text
stringlengths 54
60.6k
|
---|
<commit_before>#include <config.h>
#include <assert.h>
#include <boost/assert.hpp>
#include <boost/multi_array/multi_array_ref.hpp>
#include <dune/common/exceptions.hh>
#include <dune/fem/misc/mpimanager.hh>
#include <dune/stuff/common/logging.hh>
#include <dune/stuff/common/profiler.hh>
#include <dune/stuff/common/ranges.hh>
#include <dune/stuff/common/float_cmp.hh>
#include <dune/stuff/grid/information.hh>
#include <algorithm>
#include <iterator>
#include <ostream>
#include <utility>
#include <memory>
#include <dune/multiscale/tools/misc.hh>
#include <dune/grid/common/gridfactory.hh>
#include <dune/stuff/grid/structuredgridfactory.hh>
#include <Eigen/Core>
#include "subgrid-list.hh"
namespace Dune {
namespace Multiscale {
namespace MsFEM {
LocalGridList::LocalGridList(MsFEMTraits::MacroMicroGridSpecifierType& specifier, bool silent /*= true*/)
: coarseSpace_(specifier.coarseSpace())
, specifier_(specifier)
, silent_(silent)
, coarseGridLeafIndexSet_(coarseSpace_.gridPart().grid().leafIndexSet())
, fineToCoarseMap_(Fem::MPIManager::size()) {
DSC::Profiler::ScopedTiming st("msfem.subgrid_list");
createSubGrids();
}
LocalGridList::~LocalGridList() {}
/** Get the subgrid belonging to a given coarse cell index.
*
* @param[in] coarseCellIndex The index of a coarse cell.
* @return Returns the subgrid belonging to the coarse cell with the given index.
*/
MsFEMTraits::LocalGridType& LocalGridList::getSubGrid(std::size_t coarseCellIndex) {
auto found = subGridList_.find(coarseCellIndex);
BOOST_ASSERT_MSG(found != subGridList_.end(), "There is no subgrid for the index you provided!");
assert(found->second);
return *(found->second);
} // getSubGrid
/** Get the subgrid belonging to a given coarse cell index.
*
* @param[in] coarseCellIndex The index of a coarse cell.
* @return Returns the subgrid belonging to the coarse cell with the given index.
*/
const MsFEMTraits::LocalGridType& LocalGridList::getSubGrid(std::size_t coarseCellIndex) const {
auto found = subGridList_.find(coarseCellIndex);
BOOST_ASSERT_MSG(found != subGridList_.end(), "There is no subgrid for the index you provided!");
assert(found->second);
return *(found->second);
} // getSubGrid
/** Get the subgrid belonging to a given coarse cell.
*
* @param[in] coarseCell The coarse cell.
* @return Returns the subgrid belonging to the given coarse cell.
*/
const MsFEMTraits::LocalGridType& LocalGridList::getSubGrid(const CoarseEntityType& entity) const {
const int index = coarseGridLeafIndexSet_.index(entity);
return getSubGrid(index);
} // getSubGrid
/** Get the subgrid belonging to a given coarse cell.
*
* @param[in] coarseCell The coarse cell.
* @return Returns the subgrid belonging to the given coarse cell.
*/
MsFEMTraits::LocalGridType& LocalGridList::getSubGrid(const CoarseEntityType& entity) {
const int index = coarseGridLeafIndexSet_.index(entity);
return getSubGrid(index);
} // getSubGrid
// given the id of a subgrid, return the entity seed for the 'base coarse entity'
// (i.e. the coarse entity that the subgrid was constructed from by enrichment )
const LocalGridList::CoarseEntitySeedType &LocalGridList::get_coarse_entity_seed(std::size_t i) const {
// the following returns the mapped element for index i if present,
// if not, an out-of-range exception is thrown
assert(false);//need to eliminate narrowing conversion
return subgrid_id_to_base_coarse_entity_.at(i);
}
// only required for oversampling strategies with constraints (e.g strategy 2 or 3):
// for each given subgrid index return the vecor of ALL coarse nodes (global coordinates) that are in the subgrid,
// this also includes the coarse nodes on the boundary of U(T), even if this is a global Dirichlet node!
const LocalGridList::CoarseNodeVectorType& LocalGridList::getCoarseNodeVector(std::size_t i) const {
if (DSC_CONFIG_GET("msfem.oversampling_strategy", 1) == 1)
DUNE_THROW(Dune::InvalidStateException, "Method 'getCoarseNodeVector' of class 'LocalGridList' should not be used in\
combination with oversampling strategy 1. Check your implementation!");
if (i >= specifier_.getNumOfCoarseEntities()) {
DUNE_THROW(Dune::RangeError, "Error. Subgrid-Index too large.");
}
return coarse_node_store_[i];
} // getSubGrid
// only required for oversampling strategy 3:
// this method only differs from the method 'getCoarseNodeVector' if the oversampling patch
// cannot be excluively described by a union of coarse grid elements.
// According to the definition of the LOD 'not full coarse layers' require that the averaging
// property of the weighted Clement operator is also applied to those coarse nodes, where
// the corresponding basis function has a nonempty intersection with the patch
const LocalGridList::CoarseNodeVectorType& LocalGridList::getExtendedCoarseNodeVector(std::size_t i) const {
if ((DSC_CONFIG_GET("msfem.oversampling_strategy", 1) == 1) || (DSC_CONFIG_GET("msfem.oversampling_strategy", 1) == 2))
DUNE_THROW(Dune::InvalidStateException,
"Method 'getExtendendCoarseNodeVector' of class 'LocalGridList' should not be used in\
combination with oversampling strategy 1 or 2. Check your implementation!");
if (i >= specifier_.getNumOfCoarseEntities()) {
DUNE_THROW(Dune::RangeError, "Error. Subgrid-Index too large.");
}
return extended_coarse_node_store_[i];
} // getSubGrid
// get number of sub grids
std::size_t LocalGridList::size() const { return specifier_.getNumOfCoarseEntities(); }
MsFEM::MsFEMTraits::LocalGridPartType LocalGridList::gridPart(std::size_t i) { return LocalGridPartType(getSubGrid(i)); }
bool LocalGridList::covers(const CoarseEntityType &coarse_entity, const LocalEntityType &local_entity) {
const auto& center = local_entity.geometry().center();
const auto& coarse_geo = coarse_entity.geometry();
const auto center_local = coarse_geo.local(center);
const auto& reference_element = Stuff::Grid::reference_element(coarse_entity);
return reference_element.checkInside(center_local);
}
void LocalGridList::createSubGrids() {
// DSC_PROFILER ("msfem.subgrid_list.create");
DSC_LOG_INFO << "Starting creation of subgrids." << std::endl << std::endl;
// the number of coarse grid entities (of codim 0).
const auto number_of_coarse_grid_entities = specifier_.getNumOfCoarseEntities();
const auto oversampling_strategy = DSC_CONFIG_GET("msfem.oversampling_strategy", 1);
if ((oversampling_strategy == 2) || (oversampling_strategy == 3)) {
coarse_node_store_ = CoarseGridNodeStorageType(number_of_coarse_grid_entities, CoarseNodeVectorType());
extended_coarse_node_store_ = CoarseGridNodeStorageType(number_of_coarse_grid_entities, CoarseNodeVectorType());
}
// ! ----------- create subgrids --------------------
typedef StructuredGridFactory<LocalGridType> FactoryType;
// :: createCubeGrid(const FieldVector<ctype,dimworld>& lowerLeft,
// const FieldVector<ctype,dimworld>& upperRight,
// const array<unsigned int,dim>& elements)
// loop to initialize subgrids (and to initialize the coarse node vector):
// -----------------------------------------------------------
for (const auto& coarse_entity : coarseSpace_) {
// make sure we only create subgrids for interior coarse elements, not
// for overlap or ghost elements
assert(coarse_entity.partitionType() == Dune::InteriorEntity);
const auto coarse_index = coarseGridLeafIndexSet_.index(coarse_entity);
// make sure we did not create a subgrid for the current coarse entity so far
assert(subGridList_.find(coarse_index) == subGridList_.end());
subgrid_id_to_base_coarse_entity_.insert(std::make_pair(coarse_index, std::move(coarse_entity.seed())));
const auto dimension = DSG::dimensions<CommonTraits::GridType>(coarse_entity);
const int dim_world = LocalGridType::dimensionworld;
typedef FieldVector<typename LocalGridType::ctype, dim_world> CoordType;
CoordType lowerLeft(0);
CoordType upperRight(0);
array<unsigned int,dim_world> elemens;
for(const auto i : DSC::valueRange(dim_world))
{
elemens[i] = DSC_CONFIG_GET("msfem.micro_cells_per_macrocell_dim", 8);
lowerLeft[i] = dimension.coord_limits[i].min();
upperRight[i] = dimension.coord_limits[i].max();
}
boost::format sp("Subgrid %d from (%f,%f) to (%f,%f) created.\n");
DSC_LOG_INFO << sp % coarse_index % lowerLeft[0] % lowerLeft[1] % upperRight[0] % upperRight[1];
subGridList_[coarse_index] = FactoryType::createCubeGrid(lowerLeft, upperRight, elemens);
if ((oversampling_strategy == 2) || (oversampling_strategy == 3)) {
assert(coarse_index >= 0 && coarse_index < coarse_node_store_.size() &&
"Index set is not suitable for the current implementation!");
for (int c = 0; c < coarse_entity.geometry().corners(); ++c) {
coarse_node_store_[coarse_index].emplace_back(coarse_entity.geometry().corner(c));
extended_coarse_node_store_[coarse_index].emplace_back(coarse_entity.geometry().corner(c));
}
}
}
}
} // namespace MsFEM {
} // namespace Multiscale {
} // namespace Dune {
<commit_msg>create local grids with oversampling<commit_after>#include <config.h>
#include <assert.h>
#include <boost/assert.hpp>
#include <boost/multi_array/multi_array_ref.hpp>
#include <dune/common/exceptions.hh>
#include <dune/fem/misc/mpimanager.hh>
#include <dune/stuff/common/logging.hh>
#include <dune/stuff/common/profiler.hh>
#include <dune/stuff/common/ranges.hh>
#include <dune/stuff/common/float_cmp.hh>
#include <dune/stuff/grid/information.hh>
#include <algorithm>
#include <iterator>
#include <ostream>
#include <utility>
#include <memory>
#include <dune/multiscale/tools/misc.hh>
#include <dune/grid/common/gridfactory.hh>
#include <dune/stuff/grid/structuredgridfactory.hh>
#include <Eigen/Core>
#include "subgrid-list.hh"
namespace Dune {
namespace Multiscale {
namespace MsFEM {
LocalGridList::LocalGridList(MsFEMTraits::MacroMicroGridSpecifierType& specifier, bool silent /*= true*/)
: coarseSpace_(specifier.coarseSpace())
, specifier_(specifier)
, silent_(silent)
, coarseGridLeafIndexSet_(coarseSpace_.gridPart().grid().leafIndexSet())
, fineToCoarseMap_(Fem::MPIManager::size()) {
DSC::Profiler::ScopedTiming st("msfem.subgrid_list");
createSubGrids();
}
LocalGridList::~LocalGridList() {}
/** Get the subgrid belonging to a given coarse cell index.
*
* @param[in] coarseCellIndex The index of a coarse cell.
* @return Returns the subgrid belonging to the coarse cell with the given index.
*/
MsFEMTraits::LocalGridType& LocalGridList::getSubGrid(std::size_t coarseCellIndex) {
auto found = subGridList_.find(coarseCellIndex);
BOOST_ASSERT_MSG(found != subGridList_.end(), "There is no subgrid for the index you provided!");
assert(found->second);
return *(found->second);
} // getSubGrid
/** Get the subgrid belonging to a given coarse cell index.
*
* @param[in] coarseCellIndex The index of a coarse cell.
* @return Returns the subgrid belonging to the coarse cell with the given index.
*/
const MsFEMTraits::LocalGridType& LocalGridList::getSubGrid(std::size_t coarseCellIndex) const {
auto found = subGridList_.find(coarseCellIndex);
BOOST_ASSERT_MSG(found != subGridList_.end(), "There is no subgrid for the index you provided!");
assert(found->second);
return *(found->second);
} // getSubGrid
/** Get the subgrid belonging to a given coarse cell.
*
* @param[in] coarseCell The coarse cell.
* @return Returns the subgrid belonging to the given coarse cell.
*/
const MsFEMTraits::LocalGridType& LocalGridList::getSubGrid(const CoarseEntityType& entity) const {
const int index = coarseGridLeafIndexSet_.index(entity);
return getSubGrid(index);
} // getSubGrid
/** Get the subgrid belonging to a given coarse cell.
*
* @param[in] coarseCell The coarse cell.
* @return Returns the subgrid belonging to the given coarse cell.
*/
MsFEMTraits::LocalGridType& LocalGridList::getSubGrid(const CoarseEntityType& entity) {
const int index = coarseGridLeafIndexSet_.index(entity);
return getSubGrid(index);
} // getSubGrid
// given the id of a subgrid, return the entity seed for the 'base coarse entity'
// (i.e. the coarse entity that the subgrid was constructed from by enrichment )
const LocalGridList::CoarseEntitySeedType &LocalGridList::get_coarse_entity_seed(std::size_t i) const {
// the following returns the mapped element for index i if present,
// if not, an out-of-range exception is thrown
assert(false);//need to eliminate narrowing conversion
return subgrid_id_to_base_coarse_entity_.at(i);
}
// only required for oversampling strategies with constraints (e.g strategy 2 or 3):
// for each given subgrid index return the vecor of ALL coarse nodes (global coordinates) that are in the subgrid,
// this also includes the coarse nodes on the boundary of U(T), even if this is a global Dirichlet node!
const LocalGridList::CoarseNodeVectorType& LocalGridList::getCoarseNodeVector(std::size_t i) const {
if (DSC_CONFIG_GET("msfem.oversampling_strategy", 1) == 1)
DUNE_THROW(Dune::InvalidStateException, "Method 'getCoarseNodeVector' of class 'LocalGridList' should not be used in\
combination with oversampling strategy 1. Check your implementation!");
if (i >= specifier_.getNumOfCoarseEntities()) {
DUNE_THROW(Dune::RangeError, "Error. Subgrid-Index too large.");
}
return coarse_node_store_[i];
} // getSubGrid
// only required for oversampling strategy 3:
// this method only differs from the method 'getCoarseNodeVector' if the oversampling patch
// cannot be excluively described by a union of coarse grid elements.
// According to the definition of the LOD 'not full coarse layers' require that the averaging
// property of the weighted Clement operator is also applied to those coarse nodes, where
// the corresponding basis function has a nonempty intersection with the patch
const LocalGridList::CoarseNodeVectorType& LocalGridList::getExtendedCoarseNodeVector(std::size_t i) const {
if ((DSC_CONFIG_GET("msfem.oversampling_strategy", 1) == 1) || (DSC_CONFIG_GET("msfem.oversampling_strategy", 1) == 2))
DUNE_THROW(Dune::InvalidStateException,
"Method 'getExtendendCoarseNodeVector' of class 'LocalGridList' should not be used in\
combination with oversampling strategy 1 or 2. Check your implementation!");
if (i >= specifier_.getNumOfCoarseEntities()) {
DUNE_THROW(Dune::RangeError, "Error. Subgrid-Index too large.");
}
return extended_coarse_node_store_[i];
} // getSubGrid
// get number of sub grids
std::size_t LocalGridList::size() const { return specifier_.getNumOfCoarseEntities(); }
MsFEM::MsFEMTraits::LocalGridPartType LocalGridList::gridPart(std::size_t i) { return LocalGridPartType(getSubGrid(i)); }
bool LocalGridList::covers(const CoarseEntityType &coarse_entity, const LocalEntityType &local_entity) {
const auto& center = local_entity.geometry().center();
const auto& coarse_geo = coarse_entity.geometry();
const auto center_local = coarse_geo.local(center);
const auto& reference_element = Stuff::Grid::reference_element(coarse_entity);
return reference_element.checkInside(center_local);
}
void LocalGridList::createSubGrids() {
// DSC_PROFILER ("msfem.subgrid_list.create");
DSC_LOG_INFO << "Starting creation of subgrids." << std::endl << std::endl;
// the number of coarse grid entities (of codim 0).
const auto number_of_coarse_grid_entities = specifier_.getNumOfCoarseEntities();
const auto oversampling_strategy = DSC_CONFIG_GET("msfem.oversampling_strategy", 1);
if ((oversampling_strategy == 2) || (oversampling_strategy == 3)) {
coarse_node_store_ = CoarseGridNodeStorageType(number_of_coarse_grid_entities, CoarseNodeVectorType());
extended_coarse_node_store_ = CoarseGridNodeStorageType(number_of_coarse_grid_entities, CoarseNodeVectorType());
}
typedef StructuredGridFactory<LocalGridType> FactoryType;
const auto oversampling_layer = DSC_CONFIG_GET("msfem.oversampling_strategy", 1);
const auto coarse_dimensions = DSG::dimensions<CommonTraits::GridType>(coarseSpace_.gridPart().grid());
for (const auto& coarse_entity : coarseSpace_) {
// make sure we only create subgrids for interior coarse elements, not
// for overlap or ghost elements
assert(coarse_entity.partitionType() == Dune::InteriorEntity);
const auto coarse_index = coarseGridLeafIndexSet_.index(coarse_entity);
// make sure we did not create a subgrid for the current coarse entity so far
assert(subGridList_.find(coarse_index) == subGridList_.end());
subgrid_id_to_base_coarse_entity_.insert(std::make_pair(coarse_index, std::move(coarse_entity.seed())));
const auto dimensions = DSG::dimensions<CommonTraits::GridType>(coarse_entity);
const int dim_world = LocalGridType::dimensionworld;
typedef FieldVector<typename LocalGridType::ctype, dim_world> CoordType;
CoordType lowerLeft(0);
CoordType upperRight(0);
array<unsigned int,dim_world> elemens;
for(const auto i : DSC::valueRange(dim_world))
{
elemens[i] = DSC_CONFIG_GET("msfem.micro_cells_per_macrocell_dim", 8);
const auto min = dimensions.coord_limits[i].min();
const auto max = dimensions.coord_limits[i].max();
const auto coarse_min = coarse_dimensions.coord_limits[i].min();
const auto coarse_max = coarse_dimensions.coord_limits[i].max();
const auto delta = max - min;
lowerLeft[i] = std::max(min - oversampling_layer * delta, coarse_min);
upperRight[i] = std::min(max + oversampling_layer * delta, coarse_max);
}
boost::format sp("Subgrid %d from (%f,%f) to (%f,%f) created.\n");
DSC_LOG_INFO << sp % coarse_index % lowerLeft[0] % lowerLeft[1] % upperRight[0] % upperRight[1];
subGridList_[coarse_index] = FactoryType::createCubeGrid(lowerLeft, upperRight, elemens);
if ((oversampling_strategy == 2) || (oversampling_strategy == 3)) {
assert(coarse_index >= 0 && coarse_index < coarse_node_store_.size() &&
"Index set is not suitable for the current implementation!");
for (int c = 0; c < coarse_entity.geometry().corners(); ++c) {
coarse_node_store_[coarse_index].emplace_back(coarse_entity.geometry().corner(c));
extended_coarse_node_store_[coarse_index].emplace_back(coarse_entity.geometry().corner(c));
}
}
}
}
} // namespace MsFEM {
} // namespace Multiscale {
} // namespace Dune {
<|endoftext|> |
<commit_before><commit_msg>check error<commit_after><|endoftext|> |
<commit_before>/*
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "gluonobjectfactory.h"
#include "gluonobject.h"
#include "component.h"
#include "asset.h"
#include <QtCore/QDebug>
#include <QDir>
#include <QApplication>
#include <QPluginLoader>
using namespace Gluon;
template<> GluonObjectFactory* KSingleton<GluonObjectFactory>::m_instance = 0;
void
GluonObjectFactory::registerObjectType(GluonObject * newObjectType)
{
if(newObjectType)
{
qDebug() << "Registering object type" << newObjectType->metaObject()->className();
objectTypes[newObjectType->metaObject()->className()] = newObjectType;
}
}
GluonObject *
GluonObjectFactory::instantiateObjectByName(const QString& objectTypeName)
{
QString fullObjectTypeName = QString("Gluon::") + objectTypeName;
if(objectTypes.find(fullObjectTypeName) != objectTypes.end())
{
return objectTypes.value(fullObjectTypeName)->instantiate();
}
return 0;
}
void
GluonObjectFactory::loadPlugins()
{
QDir pluginDir(QApplication::applicationDirPath());
#if defined(Q_OS_WIN)
if (pluginDir.dirName().tolower() == "debug" || pluginDir.dirName().tolower() == "release")
pluginDir.cdUp();
#elif defined(Q_OS_MAC)
if (pluginDir.dirName() == "MacOS")
{
pluginDir.cdUp();
pluginDir.cdUp();
pluginDir.cdUp();
}
#endif
if(!pluginDir.cd("plugins"))
pluginDir.cd("/home/leinir/Documents/Uni/msc/btcomponents/build");
qDebug() << "Looking for pluggable components in:" << pluginDir.absolutePath();
qDebug() << "Found" << (pluginDir.count() - 2) << "potential plugins. Attempting to load:";
foreach (QString fileName, pluginDir.entryList(QDir::Files))
{
QPluginLoader loader(pluginDir.absoluteFilePath(fileName));
if(Component* loaded = qobject_cast<Component*>(loader.instance()))
m_pluggedComponents.append(loaded);
else if(Asset* loaded = qobject_cast<Asset*>(loader.instance()))
m_pluggedAssets.append(loaded);
else
qDebug() << loader.errorString();
}
}
#include "gluonobjectfactory.moc"
<commit_msg>Sane plugin search locations ftw!<commit_after>/*
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "gluonobjectfactory.h"
#include "gluonobject.h"
#include "component.h"
#include "asset.h"
#include <QtCore/QDebug>
#include <QDir>
#include <QApplication>
#include <QPluginLoader>
using namespace Gluon;
template<> GluonObjectFactory* KSingleton<GluonObjectFactory>::m_instance = 0;
void
GluonObjectFactory::registerObjectType(GluonObject * newObjectType)
{
if(newObjectType)
{
qDebug() << "Registering object type" << newObjectType->metaObject()->className();
objectTypes[newObjectType->metaObject()->className()] = newObjectType;
}
}
GluonObject *
GluonObjectFactory::instantiateObjectByName(const QString& objectTypeName)
{
QString fullObjectTypeName = QString("Gluon::") + objectTypeName;
if(objectTypes.find(fullObjectTypeName) != objectTypes.end())
{
return objectTypes.value(fullObjectTypeName)->instantiate();
}
return 0;
}
void
GluonObjectFactory::loadPlugins()
{
QList<QDir> pluginDirs;
QDir pluginDir(QApplication::applicationDirPath());
#if defined(Q_OS_WIN)
if (pluginDir.dirName().tolower() == "debug" || pluginDir.dirName().tolower() == "release")
pluginDir.cdUp();
#elif defined(Q_OS_MAC)
if (pluginDir.dirName() == "MacOS")
{
pluginDir.cdUp();
pluginDir.cdUp();
pluginDir.cdUp();
}
#endif
if(pluginDir.cd("plugins"))
pluginDirs.append(pluginDir);
if(pluginDir.cd("/usr/lib/gluon"))
pluginDirs.append(pluginDir);
// Always look in the current dir
pluginDirs.append(QDir::current());
if(pluginDir.cd(QDir::homePath() + "/gluonplugins"))
pluginDirs.append(pluginDir);
qDebug() << "Number of plugin locations:" << pluginDirs.count();
foreach(const QDir &theDir, pluginDirs)
{
qDebug() << "Looking for pluggable components in:" << theDir.absolutePath();
qDebug() << "Found" << (theDir.count() - 2) << "potential plugins. Attempting to load:";
foreach (QString fileName, theDir.entryList(QDir::Files))
{
QPluginLoader loader(theDir.absoluteFilePath(fileName));
if(Component* loaded = qobject_cast<Component*>(loader.instance()))
m_pluggedComponents.append(loaded);
else if(Asset* loaded = qobject_cast<Asset*>(loader.instance()))
m_pluggedAssets.append(loaded);
else
qDebug() << loader.errorString();
}
}
}
#include "gluonobjectfactory.moc"
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2016 Jan Grulich
*
* This library 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 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include "gnomehintssettings.h"
#include <QDir>
#include <QString>
#include <QPalette>
#include <QMainWindow>
#include <QApplication>
#include <QGuiApplication>
#include <QDialogButtonBox>
#include <QToolBar>
#include <QLoggingCategory>
#include <gtk-3.0/gtk/gtksettings.h>
Q_LOGGING_CATEGORY(QGnomePlatform, "qt.qpa.qgnomeplatform")
GnomeHintsSettings::GnomeHintsSettings()
: QObject(0)
, m_gtkThemeDarkVariant(false)
, m_palette(nullptr)
, m_settings(g_settings_new("org.gnome.desktop.interface"))
{
gtk_init(nullptr, nullptr);
// Get current theme and variant
// g_object_get(gtk_settings_get_default(), "gtk-theme-name", &m_gtkTheme, NULL);
m_gtkTheme = g_settings_get_string(m_settings, "gtk-theme");
g_object_get(gtk_settings_get_default(), "gtk-application-prefer-dark-theme", &m_gtkThemeDarkVariant, NULL);
if (!m_gtkTheme) {
qCWarning(QGnomePlatform) << "Couldn't get current gtk theme!";
} else {
qCDebug(QGnomePlatform) << "Theme name: " << m_gtkTheme;
qCDebug(QGnomePlatform) << "Dark version: " << (m_gtkThemeDarkVariant ? "yes" : "no");
}
gint cursorBlinkTime = g_settings_get_int(m_settings, "cursor-blink-time");
// g_object_get(gtk_settings_get_default(), "gtk-cursor-blink-time", &cursorBlinkTime, NULL);
if (cursorBlinkTime >= 100) {
qCDebug(QGnomePlatform) << "Cursor blink time: " << cursorBlinkTime;
m_hints[QPlatformTheme::CursorFlashTime] = cursorBlinkTime;
} else {
m_hints[QPlatformTheme::CursorFlashTime] = 1200;
}
gint doubleClickTime = 400;
g_object_get(gtk_settings_get_default(), "gtk-double-click-time", &doubleClickTime, NULL);
qCDebug(QGnomePlatform) << "Double click time: " << doubleClickTime;
m_hints[QPlatformTheme::MouseDoubleClickInterval] = doubleClickTime;
guint longPressTime = 500;
g_object_get(gtk_settings_get_default(), "gtk-long-press-time", &longPressTime, NULL);
qCDebug(QGnomePlatform) << "Long press time: " << longPressTime;
m_hints[QPlatformTheme::MousePressAndHoldInterval] = longPressTime;
gint doubleClickDistance = 5;
g_object_get(gtk_settings_get_default(), "gtk-double-click-distance", &doubleClickDistance, NULL);
qCDebug(QGnomePlatform) << "Double click distance: " << doubleClickDistance;
m_hints[QPlatformTheme::MouseDoubleClickDistance] = doubleClickDistance;
gint startDragDistance = 8;
g_object_get(gtk_settings_get_default(), "gtk-dnd-drag-threshold", &startDragDistance, NULL);
qCDebug(QGnomePlatform) << "Dnd drag threshold: " << startDragDistance;
m_hints[QPlatformTheme::StartDragDistance] = startDragDistance;
guint passwordMaskDelay = 0;
g_object_get(gtk_settings_get_default(), "gtk-entry-password-hint-timeout", &passwordMaskDelay, NULL);
qCDebug(QGnomePlatform) << "Password hint timeout: " << passwordMaskDelay;
m_hints[QPlatformTheme::PasswordMaskDelay] = passwordMaskDelay;
gchar *systemIconTheme = g_settings_get_string(m_settings, "icon-theme");
// g_object_get(gtk_settings_get_default(), "gtk-icon-theme-name", &systemIconTheme, NULL);
if (systemIconTheme) {
qCDebug(QGnomePlatform) << "Icon theme: " << systemIconTheme;
m_hints[QPlatformTheme::SystemIconThemeName] = systemIconTheme;
free(systemIconTheme);
} else {
m_hints[QPlatformTheme::SystemIconThemeName] = "Adwaita";
}
m_hints[QPlatformTheme::SystemIconFallbackThemeName] = "Adwaita";
m_hints[QPlatformTheme::IconThemeSearchPaths] = xdgIconThemePaths();
QStringList styleNames;
styleNames << QStringLiteral("adwaita")
// Avoid using gtk+ style as it uses gtk2 and we use gtk3 which is causing a crash
// << QStringLiteral("gtk+")
<< QStringLiteral("fusion")
<< QStringLiteral("windows");
m_hints[QPlatformTheme::StyleNames] = styleNames;
m_hints[QPlatformTheme::DialogButtonBoxLayout] = QDialogButtonBox::GnomeLayout;
m_hints[QPlatformTheme::DialogButtonBoxButtonsHaveIcons] = true;
m_hints[QPlatformTheme::KeyboardScheme] = QPlatformTheme::GnomeKeyboardScheme;
m_hints[QPlatformTheme::IconPixmapSizes] = QVariant::fromValue(QList<int>() << 512 << 256 << 128 << 64 << 32 << 22 << 16 << 8);
m_hints[QPlatformTheme::PasswordMaskCharacter] = QVariant(QChar(0x2022));
// Watch for changes
g_signal_connect(m_settings, "changed::gtk-theme", G_CALLBACK(gsettingPropertyChanged), this);
g_signal_connect(m_settings, "changed::icon-theme", G_CALLBACK(gsettingPropertyChanged), this);
g_signal_connect(m_settings, "changed::cursor-blink-time", G_CALLBACK(gsettingPropertyChanged), this);
g_signal_connect(m_settings, "changed::font-name", G_CALLBACK(gsettingPropertyChanged), this);
g_signal_connect(m_settings, "changed::monospace-font-name", G_CALLBACK(gsettingPropertyChanged), this);
g_signal_connect(m_settings, "changed::text-scaling-factor", G_CALLBACK(gsettingPropertyChanged), this);
// g_signal_connect(gtk_settings_get_default(), "notify::gtk-theme-name", G_CALLBACK(gtkThemeChanged), this);
/* Other theme hints */
// KeyboardInputInterval, StartDragTime, KeyboardAutoRepeatRate, StartDragVelocity, DropShadow,
// MaximumScrollBarDragDistance, ItemViewActivateItemOnSingleClick, WindowAutoPlacement, DialogButtonBoxButtonsHaveIcons
// UseFullScreenForPopupMenu, UiEffects, SpellCheckUnderlineStyle, TabFocusBehavior, TabAllWidgets, PasswordMaskCharacter
// DialogSnapToDefaultButton, ContextMenuOnMouseRelease, WheelScrollLines
// TODO TextCursorWidth, ToolButtonStyle, ToolBarIconSize
// Load fonts
loadFonts();
// Load palette
loadPalette();
}
GnomeHintsSettings::~GnomeHintsSettings()
{
qDeleteAll(m_fonts);
delete m_palette;
}
void GnomeHintsSettings::gsettingPropertyChanged(GSettings *settings, gchar *key, GnomeHintsSettings *gnomeHintsSettings)
{
Q_UNUSED(settings);
const QString changedProperty = key;
if (changedProperty == QLatin1String("gtk-theme")) {
gnomeHintsSettings->themeChanged();
} else if (changedProperty == QLatin1String("icon-theme")) {
gnomeHintsSettings->iconsChanged();
} else if (changedProperty == QLatin1String("cursor-blink-time")) {
gnomeHintsSettings->cursorBlinkTimeChanged();
} else if (changedProperty == QLatin1String("font-name")) {
gnomeHintsSettings->fontChanged();
} else if (changedProperty == QLatin1String("monospace-font-name")) {
gnomeHintsSettings->fontChanged();
} else if (changedProperty == QLatin1String("text-scaling-factor")) {
gnomeHintsSettings->fontChanged();
} else {
qCDebug(QGnomePlatform) << "GSetting property change: " << key;
}
}
void GnomeHintsSettings::cursorBlinkTimeChanged()
{
gint cursorBlinkTime = g_settings_get_int(m_settings, "cursor-blink-time");
if (cursorBlinkTime >= 100) {
qCDebug(QGnomePlatform) << "Cursor blink time changed to: " << cursorBlinkTime;
m_hints[QPlatformTheme::CursorFlashTime] = cursorBlinkTime;
} else {
qCDebug(QGnomePlatform) << "Cursor blink time changed to: 1200";
m_hints[QPlatformTheme::CursorFlashTime] = 1200;
}
//If we are not a QApplication, means that we are a QGuiApplication, then we do nothing.
if (!qobject_cast<QApplication *>(QCoreApplication::instance())) {
return;
}
QWidgetList widgets = QApplication::allWidgets();
Q_FOREACH (QWidget *widget, widgets) {
if (qobject_cast<QToolBar *>(widget) || qobject_cast<QMainWindow *>(widget)) {
QEvent event(QEvent::StyleChange);
QApplication::sendEvent(widget, &event);
}
}
}
void GnomeHintsSettings::fontChanged()
{
loadFonts();
if (qobject_cast<QApplication *>(QCoreApplication::instance())) {
QApplication::setFont(*m_fonts[QPlatformTheme::SystemFont]);
QWidgetList widgets = QApplication::allWidgets();
Q_FOREACH (QWidget *widget, widgets) {
widget->setFont(*m_fonts[QPlatformTheme::SystemFont]);
}
} else {
QGuiApplication::setFont(*m_fonts[QPlatformTheme::SystemFont]);
}
}
void GnomeHintsSettings::iconsChanged()
{
gchar *systemIconTheme = g_settings_get_string(m_settings, "icon-theme");
if (systemIconTheme) {
qCDebug(QGnomePlatform) << "Icon theme changed to: " << systemIconTheme;
m_hints[QPlatformTheme::SystemIconThemeName] = systemIconTheme;
free(systemIconTheme);
} else {
qCDebug(QGnomePlatform) << "Icon theme changed to: Adwaita";
m_hints[QPlatformTheme::SystemIconThemeName] = "Adwaita";
}
//If we are not a QApplication, means that we are a QGuiApplication, then we do nothing.
if (!qobject_cast<QApplication *>(QCoreApplication::instance())) {
return;
}
QWidgetList widgets = QApplication::allWidgets();
Q_FOREACH (QWidget *widget, widgets) {
if (qobject_cast<QToolBar *>(widget) || qobject_cast<QMainWindow *>(widget)) {
QEvent event(QEvent::StyleChange);
QApplication::sendEvent(widget, &event);
}
}
}
void GnomeHintsSettings::themeChanged()
{
loadPalette();
// QApplication::setPalette and QGuiApplication::setPalette are different functions
// and non virtual. Call the correct one
if (qobject_cast<QApplication *>(QCoreApplication::instance())) {
QApplication::setPalette(*m_palette);
} else if (qobject_cast<QGuiApplication *>(QCoreApplication::instance())) {
QGuiApplication::setPalette(*m_palette);
}
}
void GnomeHintsSettings::loadFonts()
{
gdouble scaling = g_settings_get_double(m_settings, "text-scaling-factor");
qCDebug(QGnomePlatform) << "Font scaling: " << scaling;
const QStringList fontTypes { "font-name", "monospace-font-name" };
Q_FOREACH (const QString fontType, fontTypes) {
gchar *fontName = g_settings_get_string(m_settings, fontType.toStdString().c_str());
if (!fontName) {
qCWarning(QGnomePlatform) << "Couldn't get " << fontType;
} else {
QString fontNameString(fontName);
QRegExp re("(.+)[ \t]+([0-9]+)");
int fontSize;
if (re.indexIn(fontNameString) == 0) {
fontSize = re.cap(2).toInt();
if (fontType == QLatin1String("font-name")) {
m_fonts[QPlatformTheme::SystemFont] = new QFont(re.cap(1), fontSize * scaling, QFont::Normal);
qCDebug(QGnomePlatform) << "Font name: " << re.cap(1) << " (size " << fontSize << ")";
} else if (fontType == QLatin1String("monospace-font-name")) {
m_fonts[QPlatformTheme::FixedFont] = new QFont(re.cap(1), fontSize * scaling, QFont::Normal);
qCDebug(QGnomePlatform) << "Monospace font name: " << re.cap(1) << " (size " << fontSize << ")";
}
} else {
if (fontType == QLatin1String("font-name")) {
m_fonts[QPlatformTheme::SystemFont] = new QFont(fontNameString);
qCDebug(QGnomePlatform) << "Font name: " << fontNameString;
} else if (fontType == QLatin1String("monospace-font-name")) {
m_fonts[QPlatformTheme::FixedFont] = new QFont(fontNameString);
qCDebug(QGnomePlatform) << "Monospace font name: " << fontNameString;
}
}
free(fontName);
}
}
}
void GnomeHintsSettings::loadPalette()
{
if (m_palette) {
delete m_palette;
m_palette = nullptr;
}
m_palette = new QPalette();
// GtkCssProvider *gtkCssProvider = gtk_css_provider_get_named(themeName, preferDark ? "dark" : NULL);
//
// if (!gtkCssProvider) {
// qCDebug(QGnomePlatform) << "Couldn't load current gtk css provider!";
// return;
// }
// qCDebug(QGnomePlatform) << gtk_css_provider_to_string(gtkCssProvider);
}
QStringList GnomeHintsSettings::xdgIconThemePaths() const
{
QStringList paths;
const QFileInfo homeIconDir(QDir::homePath() + QStringLiteral("/.icons"));
if (homeIconDir.isDir()) {
paths << homeIconDir.absoluteFilePath();
}
QString xdgDirString = QFile::decodeName(qgetenv("XDG_DATA_DIRS"));
if (xdgDirString.isEmpty()) {
xdgDirString = QStringLiteral("/usr/local/share:/usr/share");
}
Q_FOREACH (const QString &xdgDir, xdgDirString.split(QLatin1Char(':'))) {
const QFileInfo xdgIconsDir(xdgDir + QStringLiteral("/icons"));
if (xdgIconsDir.isDir()) {
paths << xdgIconsDir.absoluteFilePath();
}
}
return paths;
}
<commit_msg>Fix font scaling<commit_after>/*
* Copyright (C) 2016 Jan Grulich
*
* This library 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 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include "gnomehintssettings.h"
#include <QDir>
#include <QString>
#include <QPalette>
#include <QMainWindow>
#include <QApplication>
#include <QGuiApplication>
#include <QDialogButtonBox>
#include <QToolBar>
#include <QLoggingCategory>
#include <gtk-3.0/gtk/gtksettings.h>
Q_LOGGING_CATEGORY(QGnomePlatform, "qt.qpa.qgnomeplatform")
GnomeHintsSettings::GnomeHintsSettings()
: QObject(0)
, m_gtkThemeDarkVariant(false)
, m_palette(nullptr)
, m_settings(g_settings_new("org.gnome.desktop.interface"))
{
gtk_init(nullptr, nullptr);
// Get current theme and variant
// g_object_get(gtk_settings_get_default(), "gtk-theme-name", &m_gtkTheme, NULL);
m_gtkTheme = g_settings_get_string(m_settings, "gtk-theme");
g_object_get(gtk_settings_get_default(), "gtk-application-prefer-dark-theme", &m_gtkThemeDarkVariant, NULL);
if (!m_gtkTheme) {
qCWarning(QGnomePlatform) << "Couldn't get current gtk theme!";
} else {
qCDebug(QGnomePlatform) << "Theme name: " << m_gtkTheme;
qCDebug(QGnomePlatform) << "Dark version: " << (m_gtkThemeDarkVariant ? "yes" : "no");
}
gint cursorBlinkTime = g_settings_get_int(m_settings, "cursor-blink-time");
// g_object_get(gtk_settings_get_default(), "gtk-cursor-blink-time", &cursorBlinkTime, NULL);
if (cursorBlinkTime >= 100) {
qCDebug(QGnomePlatform) << "Cursor blink time: " << cursorBlinkTime;
m_hints[QPlatformTheme::CursorFlashTime] = cursorBlinkTime;
} else {
m_hints[QPlatformTheme::CursorFlashTime] = 1200;
}
gint doubleClickTime = 400;
g_object_get(gtk_settings_get_default(), "gtk-double-click-time", &doubleClickTime, NULL);
qCDebug(QGnomePlatform) << "Double click time: " << doubleClickTime;
m_hints[QPlatformTheme::MouseDoubleClickInterval] = doubleClickTime;
guint longPressTime = 500;
g_object_get(gtk_settings_get_default(), "gtk-long-press-time", &longPressTime, NULL);
qCDebug(QGnomePlatform) << "Long press time: " << longPressTime;
m_hints[QPlatformTheme::MousePressAndHoldInterval] = longPressTime;
gint doubleClickDistance = 5;
g_object_get(gtk_settings_get_default(), "gtk-double-click-distance", &doubleClickDistance, NULL);
qCDebug(QGnomePlatform) << "Double click distance: " << doubleClickDistance;
m_hints[QPlatformTheme::MouseDoubleClickDistance] = doubleClickDistance;
gint startDragDistance = 8;
g_object_get(gtk_settings_get_default(), "gtk-dnd-drag-threshold", &startDragDistance, NULL);
qCDebug(QGnomePlatform) << "Dnd drag threshold: " << startDragDistance;
m_hints[QPlatformTheme::StartDragDistance] = startDragDistance;
guint passwordMaskDelay = 0;
g_object_get(gtk_settings_get_default(), "gtk-entry-password-hint-timeout", &passwordMaskDelay, NULL);
qCDebug(QGnomePlatform) << "Password hint timeout: " << passwordMaskDelay;
m_hints[QPlatformTheme::PasswordMaskDelay] = passwordMaskDelay;
gchar *systemIconTheme = g_settings_get_string(m_settings, "icon-theme");
// g_object_get(gtk_settings_get_default(), "gtk-icon-theme-name", &systemIconTheme, NULL);
if (systemIconTheme) {
qCDebug(QGnomePlatform) << "Icon theme: " << systemIconTheme;
m_hints[QPlatformTheme::SystemIconThemeName] = systemIconTheme;
free(systemIconTheme);
} else {
m_hints[QPlatformTheme::SystemIconThemeName] = "Adwaita";
}
m_hints[QPlatformTheme::SystemIconFallbackThemeName] = "Adwaita";
m_hints[QPlatformTheme::IconThemeSearchPaths] = xdgIconThemePaths();
QStringList styleNames;
styleNames << QStringLiteral("adwaita")
// Avoid using gtk+ style as it uses gtk2 and we use gtk3 which is causing a crash
// << QStringLiteral("gtk+")
<< QStringLiteral("fusion")
<< QStringLiteral("windows");
m_hints[QPlatformTheme::StyleNames] = styleNames;
m_hints[QPlatformTheme::DialogButtonBoxLayout] = QDialogButtonBox::GnomeLayout;
m_hints[QPlatformTheme::DialogButtonBoxButtonsHaveIcons] = true;
m_hints[QPlatformTheme::KeyboardScheme] = QPlatformTheme::GnomeKeyboardScheme;
m_hints[QPlatformTheme::IconPixmapSizes] = QVariant::fromValue(QList<int>() << 512 << 256 << 128 << 64 << 32 << 22 << 16 << 8);
m_hints[QPlatformTheme::PasswordMaskCharacter] = QVariant(QChar(0x2022));
// Watch for changes
g_signal_connect(m_settings, "changed::gtk-theme", G_CALLBACK(gsettingPropertyChanged), this);
g_signal_connect(m_settings, "changed::icon-theme", G_CALLBACK(gsettingPropertyChanged), this);
g_signal_connect(m_settings, "changed::cursor-blink-time", G_CALLBACK(gsettingPropertyChanged), this);
g_signal_connect(m_settings, "changed::font-name", G_CALLBACK(gsettingPropertyChanged), this);
g_signal_connect(m_settings, "changed::monospace-font-name", G_CALLBACK(gsettingPropertyChanged), this);
g_signal_connect(m_settings, "changed::text-scaling-factor", G_CALLBACK(gsettingPropertyChanged), this);
// g_signal_connect(gtk_settings_get_default(), "notify::gtk-theme-name", G_CALLBACK(gtkThemeChanged), this);
/* Other theme hints */
// KeyboardInputInterval, StartDragTime, KeyboardAutoRepeatRate, StartDragVelocity, DropShadow,
// MaximumScrollBarDragDistance, ItemViewActivateItemOnSingleClick, WindowAutoPlacement, DialogButtonBoxButtonsHaveIcons
// UseFullScreenForPopupMenu, UiEffects, SpellCheckUnderlineStyle, TabFocusBehavior, TabAllWidgets, PasswordMaskCharacter
// DialogSnapToDefaultButton, ContextMenuOnMouseRelease, WheelScrollLines
// TODO TextCursorWidth, ToolButtonStyle, ToolBarIconSize
// Load fonts
loadFonts();
// Load palette
loadPalette();
}
GnomeHintsSettings::~GnomeHintsSettings()
{
qDeleteAll(m_fonts);
delete m_palette;
}
void GnomeHintsSettings::gsettingPropertyChanged(GSettings *settings, gchar *key, GnomeHintsSettings *gnomeHintsSettings)
{
Q_UNUSED(settings);
const QString changedProperty = key;
if (changedProperty == QLatin1String("gtk-theme")) {
gnomeHintsSettings->themeChanged();
} else if (changedProperty == QLatin1String("icon-theme")) {
gnomeHintsSettings->iconsChanged();
} else if (changedProperty == QLatin1String("cursor-blink-time")) {
gnomeHintsSettings->cursorBlinkTimeChanged();
} else if (changedProperty == QLatin1String("font-name")) {
gnomeHintsSettings->fontChanged();
} else if (changedProperty == QLatin1String("monospace-font-name")) {
gnomeHintsSettings->fontChanged();
} else if (changedProperty == QLatin1String("text-scaling-factor")) {
gnomeHintsSettings->fontChanged();
} else {
qCDebug(QGnomePlatform) << "GSetting property change: " << key;
}
}
void GnomeHintsSettings::cursorBlinkTimeChanged()
{
gint cursorBlinkTime = g_settings_get_int(m_settings, "cursor-blink-time");
if (cursorBlinkTime >= 100) {
qCDebug(QGnomePlatform) << "Cursor blink time changed to: " << cursorBlinkTime;
m_hints[QPlatformTheme::CursorFlashTime] = cursorBlinkTime;
} else {
qCDebug(QGnomePlatform) << "Cursor blink time changed to: 1200";
m_hints[QPlatformTheme::CursorFlashTime] = 1200;
}
//If we are not a QApplication, means that we are a QGuiApplication, then we do nothing.
if (!qobject_cast<QApplication *>(QCoreApplication::instance())) {
return;
}
QWidgetList widgets = QApplication::allWidgets();
Q_FOREACH (QWidget *widget, widgets) {
if (qobject_cast<QToolBar *>(widget) || qobject_cast<QMainWindow *>(widget)) {
QEvent event(QEvent::StyleChange);
QApplication::sendEvent(widget, &event);
}
}
}
void GnomeHintsSettings::fontChanged()
{
loadFonts();
if (qobject_cast<QApplication *>(QCoreApplication::instance())) {
QApplication::setFont(*m_fonts[QPlatformTheme::SystemFont]);
QWidgetList widgets = QApplication::allWidgets();
Q_FOREACH (QWidget *widget, widgets) {
widget->setFont(*m_fonts[QPlatformTheme::SystemFont]);
}
} else {
QGuiApplication::setFont(*m_fonts[QPlatformTheme::SystemFont]);
}
}
void GnomeHintsSettings::iconsChanged()
{
gchar *systemIconTheme = g_settings_get_string(m_settings, "icon-theme");
if (systemIconTheme) {
qCDebug(QGnomePlatform) << "Icon theme changed to: " << systemIconTheme;
m_hints[QPlatformTheme::SystemIconThemeName] = systemIconTheme;
free(systemIconTheme);
} else {
qCDebug(QGnomePlatform) << "Icon theme changed to: Adwaita";
m_hints[QPlatformTheme::SystemIconThemeName] = "Adwaita";
}
//If we are not a QApplication, means that we are a QGuiApplication, then we do nothing.
if (!qobject_cast<QApplication *>(QCoreApplication::instance())) {
return;
}
QWidgetList widgets = QApplication::allWidgets();
Q_FOREACH (QWidget *widget, widgets) {
if (qobject_cast<QToolBar *>(widget) || qobject_cast<QMainWindow *>(widget)) {
QEvent event(QEvent::StyleChange);
QApplication::sendEvent(widget, &event);
}
}
}
void GnomeHintsSettings::themeChanged()
{
loadPalette();
// QApplication::setPalette and QGuiApplication::setPalette are different functions
// and non virtual. Call the correct one
if (qobject_cast<QApplication *>(QCoreApplication::instance())) {
QApplication::setPalette(*m_palette);
} else if (qobject_cast<QGuiApplication *>(QCoreApplication::instance())) {
QGuiApplication::setPalette(*m_palette);
}
}
void GnomeHintsSettings::loadFonts()
{
gdouble scaling = g_settings_get_double(m_settings, "text-scaling-factor");
qCDebug(QGnomePlatform) << "Font scaling: " << scaling;
const QStringList fontTypes { "font-name", "monospace-font-name" };
Q_FOREACH (const QString fontType, fontTypes) {
gchar *fontName = g_settings_get_string(m_settings, fontType.toStdString().c_str());
if (!fontName) {
qCWarning(QGnomePlatform) << "Couldn't get " << fontType;
} else {
QString fontNameString(fontName);
QRegExp re("(.+)[ \t]+([0-9]+)");
int fontSize;
if (re.indexIn(fontNameString) == 0) {
fontSize = re.cap(2).toInt();
QFont* font = new QFont(re.cap(1));
font->setPointSizeF(fontSize * scaling);
if (fontType == QLatin1String("font-name")) {
m_fonts[QPlatformTheme::SystemFont] = font;
qCDebug(QGnomePlatform) << "Font name: " << re.cap(1) << " (size " << fontSize << ")";
} else if (fontType == QLatin1String("monospace-font-name")) {
m_fonts[QPlatformTheme::FixedFont] = font;
qCDebug(QGnomePlatform) << "Monospace font name: " << re.cap(1) << " (size " << fontSize << ")";
}
} else {
if (fontType == QLatin1String("font-name")) {
m_fonts[QPlatformTheme::SystemFont] = new QFont(fontNameString);
qCDebug(QGnomePlatform) << "Font name: " << fontNameString;
} else if (fontType == QLatin1String("monospace-font-name")) {
m_fonts[QPlatformTheme::FixedFont] = new QFont(fontNameString);
qCDebug(QGnomePlatform) << "Monospace font name: " << fontNameString;
}
}
free(fontName);
}
}
}
void GnomeHintsSettings::loadPalette()
{
if (m_palette) {
delete m_palette;
m_palette = nullptr;
}
m_palette = new QPalette();
// GtkCssProvider *gtkCssProvider = gtk_css_provider_get_named(themeName, preferDark ? "dark" : NULL);
//
// if (!gtkCssProvider) {
// qCDebug(QGnomePlatform) << "Couldn't load current gtk css provider!";
// return;
// }
// qCDebug(QGnomePlatform) << gtk_css_provider_to_string(gtkCssProvider);
}
QStringList GnomeHintsSettings::xdgIconThemePaths() const
{
QStringList paths;
const QFileInfo homeIconDir(QDir::homePath() + QStringLiteral("/.icons"));
if (homeIconDir.isDir()) {
paths << homeIconDir.absoluteFilePath();
}
QString xdgDirString = QFile::decodeName(qgetenv("XDG_DATA_DIRS"));
if (xdgDirString.isEmpty()) {
xdgDirString = QStringLiteral("/usr/local/share:/usr/share");
}
Q_FOREACH (const QString &xdgDir, xdgDirString.split(QLatin1Char(':'))) {
const QFileInfo xdgIconsDir(xdgDir + QStringLiteral("/icons"));
if (xdgIconsDir.isDir()) {
paths << xdgIconsDir.absoluteFilePath();
}
}
return paths;
}
<|endoftext|> |
<commit_before><commit_msg>Improve auto detection correct category in serializationinfo.<commit_after><|endoftext|> |
<commit_before>#ifndef _TRACER_H
#define _TRACER_H
#include <string>
#include <map>
#include <vector>
#include <boost/interprocess/containers/container/flat_map.hpp>
#include <boost/regex.hpp>
using std::string;
using std::map;
using std::vector;
#define TRACER_ENABLED 1
#define HEAP 1
#define STACK 2
#define READ 1
#define WRITE 2
#define NOTE 3
#ifdef TRACER_ENABLED
namespace pwiz {
namespace chemistry {
struct MZTolerance;
}
namespace util {
class IntegerSet;
}
}
namespace freicore {
class PeakPreData;
struct BaseSpectrum;
struct PrecursorMassHypothesis;
enum MassType;
namespace myrimatch {
struct Spectrum;
struct PeakInfo;
struct SpectraList;
enum MzToleranceRule;
}
}
typedef boost::container::flat_map<double, freicore::myrimatch::PeakInfo> PeakSpectrumData;
void tracer_dump(const string *x);
void tracer_dump(const vector<string> *x);
void tracer_dump(const map<string, string> *x);
void tracer_dump(const vector<double> *x);
void tracer_dump(const vector<float> *x);
void tracer_dump(const vector<int> *x);
void tracer_dump(const size_t *x);
void tracer_dump(const int *x);
void tracer_dump(const float *x);
void tracer_dump(const double *x);
void tracer_dump(const char *x);
void tracer_dump(const bool *x);
void tracer_dump(const pwiz::util::IntegerSet *x);
void tracer_dump(const boost::regex *x);
void tracer_dump(const freicore::PeakPreData *x);
void tracer_dump(const freicore::myrimatch::SpectraList *x);
void tracer_dump(const freicore::myrimatch::Spectrum *x);
void tracer_dump(const freicore::BaseSpectrum *x);
void tracer_dump(const vector<string> *x);
void tracer_dump(const freicore::PrecursorMassHypothesis *x);
void tracer_dump(const vector<freicore::PrecursorMassHypothesis> *x);
void tracer_dump(const pwiz::chemistry::MZTolerance *x);
void tracer_dump(const freicore::MassType *x);
void tracer_dump(const freicore::myrimatch::MzToleranceRule *x);
void tracer_dump(const PeakSpectrumData *x);
const char * tracer_id(const freicore::myrimatch::Spectrum *x);
const char * tracer_id(const freicore::BaseSpectrum *x);
const char * tracer_id(void *ptr);
#define TRACER(variable, operation, heap, note) { cout << "[TRACER]" << '\t' << "dump" << '\t'; tracer_dump(&(variable)); cout << '\t' << #variable << '\t' << heap << '\t' << operation << '\t' << note << '\t' << __FILE__ << '\t' << __LINE__ << '\n'; }
#define TRACER_P(variable, type, representation, operation, heap, note) { cout << "[TRACER]" << '\t' << "dump" << '\t' << &(variable) << '\t' << type << '\t' << representation << '\t' << #variable << '\t' << heap << '\t' << operation << '\t' << note << '\t' << __FILE__ << '\t' << __LINE__ << '\n'; }
// Reference a variable in an operation, do not dump all its info
#define TRACER_REF(variable, operation, heap, note) { cout << "[TRACER]" << '\t' << "ref" << '\t' << &(variable) << '\t' << #variable << '\t' << heap << '\t' << operation << '\t' << note << '\t' << __FILE__ << '\t' << __LINE__ << '\n'; }
#define TRACER_UNLINK(variable) { cout << "[TRACER]" << '\t' << "unlink" << '\t' << &(variable) << '\t' << #variable << '\t' __FILE__ << '\t' << __LINE__ << '\n'; }
// Start operation of a given name
#define TRACER_OP_START(name) { cout << "[TRACER]" << '\t' << "op_start" << '\t' << name << '\t' << __FILE__ << '\t' << __LINE__ << '\n'; }
// End operation of a given name
#define TRACER_OP_END(name) { cout << "[TRACER]" << '\t' << "op_end" << '\t' << name << '\t' << __FILE__ << '\t' << __LINE__ << '\n'; }
#define TRACER_METHOD_START(name) TRACER_BI; TRACER_OP_START(name); TRACER(*this, READ, HEAP, tracer_id(this));
#define TRACER_METHOD_END(name) TRACER_OP_END(name); TRACER_BO;
#define TRACER_S2S(variable) lexical_cast<string>(variable)
// Defines scope of stack variables
#define TRACER_BI { cout << "[TRACER]" << '\t' << "block_in" << '\n'; }
#define TRACER_BO { cout << "[TRACER]" << '\t' << "block_out" << '\n'; }
#else // !TRACER_ENABLED
#define TRACER(variable, operation, heap, note)
#define TRACER_R(variable, type, representation, operation, heap, note)
#define TRACER_UNLINK(variable)
#define TRACER_OP_START(name)
#define TRACER_OP_END(name)
#define TRACER_S2S(variable)
#define TRACER_BI
#define TRACER_BO
#endif // TRACER_ENABLED
#endif<commit_msg>Toward serialization of structs and arrays<commit_after>#ifndef _TRACER_H
#define _TRACER_H
#include <string>
#include <map>
#include <vector>
#include <boost/interprocess/containers/container/flat_map.hpp>
#include <boost/regex.hpp>
using std::string;
using std::map;
using std::vector;
#define TRACER_ENABLED 1
#define HEAP 1
#define STACK 2
#define READ 1
#define WRITE 2
#define NOTE 3
#ifdef TRACER_ENABLED
namespace pwiz {
namespace chemistry {
struct MZTolerance;
}
namespace util {
class IntegerSet;
}
namespace proteome {
class Peptide;
class Digestion;
class Modification;
class ModificationMap;
}
}
namespace freicore {
class PeakPreData;
struct BaseSpectrum;
struct PrecursorMassHypothesis;
enum MassType;
namespace myrimatch {
struct Spectrum;
struct PeakInfo;
struct SpectraList;
enum MzToleranceRule;
struct SearchResult;
}
}
typedef boost::container::flat_map<double, freicore::myrimatch::PeakInfo> PeakSpectrumData;
void tracer_dump(const string *x);
void tracer_dump(const vector<string> *x);
void tracer_dump(const map<string, string> *x);
void tracer_dump(const vector<double> *x);
void tracer_dump(const vector<float> *x);
void tracer_dump(const vector<int> *x);
void tracer_dump(const size_t *x);
void tracer_dump(const int *x);
void tracer_dump(const float *x);
void tracer_dump(const double *x);
void tracer_dump(const char *x);
void tracer_dump(const bool *x);
void tracer_dump(const pwiz::util::IntegerSet *x);
void tracer_dump(const boost::regex *x);
void tracer_dump(const freicore::PeakPreData *x);
void tracer_dump(const freicore::myrimatch::SpectraList *x);
void tracer_dump(const freicore::myrimatch::Spectrum *x);
void tracer_dump(const freicore::BaseSpectrum *x);
void tracer_dump(const vector<string> *x);
void tracer_dump(const freicore::PrecursorMassHypothesis *x);
void tracer_dump(const vector<freicore::PrecursorMassHypothesis> *x);
void tracer_dump(const pwiz::chemistry::MZTolerance *x);
void tracer_dump(const freicore::MassType *x);
void tracer_dump(const freicore::myrimatch::MzToleranceRule *x);
void tracer_dump(const PeakSpectrumData *x);
const char * tracer_id(const freicore::myrimatch::Spectrum *x);
const char * tracer_id(const freicore::BaseSpectrum *x);
const char * tracer_id(void *ptr);
#define TRACER(variable, operation, heap, note) { cout << "[TRACER]" << '\t' << "dump" << '\t' << #variable << '\t' << heap << '\t' << operation << '\t' << note << '\t' << __FILE__ << '\t' << __LINE__ << '\t'; tracer_dump(&(variable)); cout << '\n'; }
#define TRACER_P(variable, type, representation, operation, heap, note) { cout << "[TRACER]" << '\t' << "dump" << '\t' << &(variable) << '\t' << type << '\t' << representation << '\t' << #variable << '\t' << heap << '\t' << operation << '\t' << note << '\t' << __FILE__ << '\t' << __LINE__ << '\n'; }
// Reference a variable in an operation, do not dump all its info
#define TRACER_REF(variable, operation, heap, note) { cout << "[TRACER]" << '\t' << "ref" << '\t' << &(variable) << '\t' << #variable << '\t' << heap << '\t' << operation << '\t' << note << '\t' << __FILE__ << '\t' << __LINE__ << '\n'; }
#define TRACER_UNLINK(variable) { cout << "[TRACER]" << '\t' << "unlink" << '\t' << &(variable) << '\t' << #variable << '\t' __FILE__ << '\t' << __LINE__ << '\n'; }
// Start operation of a given name
#define TRACER_OP_START(name) { cout << "[TRACER]" << '\t' << "op_start" << '\t' << name << '\t' << __FILE__ << '\t' << __LINE__ << '\n'; }
// End operation of a given name
#define TRACER_OP_END(name) { cout << "[TRACER]" << '\t' << "op_end" << '\t' << name << '\t' << __FILE__ << '\t' << __LINE__ << '\n'; }
#define TRACER_METHOD_START(name) TRACER_BI; TRACER_OP_START(name); TRACER(*this, READ, HEAP, tracer_id(this));
#define TRACER_METHOD_END(name) TRACER_OP_END(name); TRACER_BO;
#define TRACER_S2S(variable) lexical_cast<string>(variable)
// Defines scope of stack variables
#define TRACER_BI { cout << "[TRACER]" << '\t' << "block_in" << '\n'; }
#define TRACER_BO { cout << "[TRACER]" << '\t' << "block_out" << '\n'; }
#else // !TRACER_ENABLED
#define TRACER(variable, operation, heap, note)
#define TRACER_R(variable, type, representation, operation, heap, note)
#define TRACER_UNLINK(variable)
#define TRACER_OP_START(name)
#define TRACER_OP_END(name)
#define TRACER_S2S(variable)
#define TRACER_BI
#define TRACER_BO
#endif // TRACER_ENABLED
#endif<|endoftext|> |
<commit_before><commit_msg>Added <chrono><commit_after><|endoftext|> |
<commit_before>/*
* Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "level_indicator.h"
namespace webrtc {
// Array for adding smothing to level changes (ad-hoc).
WebRtc_UWord32 perm[] =
{0,1,2,3,4,4,5,5,5,5,6,6,6,6,6,7,7,7,7,8,8,8,9,9,9,9,9,9,9,9,9,9,9};
LevelIndicator::LevelIndicator()
: _max(0),
_count(0),
_currentLevel(0)
{
}
LevelIndicator::~LevelIndicator()
{
}
// Level is based on the highest absolute value for all samples.
void LevelIndicator::ComputeLevel(const WebRtc_Word16* speech,
const WebRtc_UWord16 nrOfSamples)
{
WebRtc_Word32 min = 0;
for(WebRtc_UWord32 i = 0; i < nrOfSamples; i++)
{
if(_max < speech[i])
{
_max = speech[i];
}
if(min > speech[i])
{
min = speech[i];
}
}
// Absolute max value.
if(-min > _max)
{
_max = -min;
}
if(_count == TICKS_BEFORE_CALCULATION)
{
// Highest sample value maps directly to a level.
WebRtc_Word32 position = _max / 1000;
if ((position == 0) &&
(_max > 250))
{
position = 1;
}
_currentLevel = perm[position];
// The max value is decayed and stored so that it can be reused to slow
// down decreases in level.
_max = _max >> 1;
_count = 0;
} else {
_count++;
}
}
WebRtc_Word32 LevelIndicator::GetLevel()
{
return _currentLevel;
}
} // namespace webrtc
<commit_msg>Fixed webrtc::perm variable.<commit_after>/*
* Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "level_indicator.h"
namespace webrtc {
// Array for adding smothing to level changes (ad-hoc).
const WebRtc_UWord32 perm[] =
{0,1,2,3,4,4,5,5,5,5,6,6,6,6,6,7,7,7,7,8,8,8,9,9,9,9,9,9,9,9,9,9,9};
LevelIndicator::LevelIndicator()
: _max(0),
_count(0),
_currentLevel(0)
{
}
LevelIndicator::~LevelIndicator()
{
}
// Level is based on the highest absolute value for all samples.
void LevelIndicator::ComputeLevel(const WebRtc_Word16* speech,
const WebRtc_UWord16 nrOfSamples)
{
WebRtc_Word32 min = 0;
for(WebRtc_UWord32 i = 0; i < nrOfSamples; i++)
{
if(_max < speech[i])
{
_max = speech[i];
}
if(min > speech[i])
{
min = speech[i];
}
}
// Absolute max value.
if(-min > _max)
{
_max = -min;
}
if(_count == TICKS_BEFORE_CALCULATION)
{
// Highest sample value maps directly to a level.
WebRtc_Word32 position = _max / 1000;
if ((position == 0) &&
(_max > 250))
{
position = 1;
}
_currentLevel = perm[position];
// The max value is decayed and stored so that it can be reused to slow
// down decreases in level.
_max = _max >> 1;
_count = 0;
} else {
_count++;
}
}
WebRtc_Word32 LevelIndicator::GetLevel()
{
return _currentLevel;
}
} // namespace webrtc
<|endoftext|> |
<commit_before><commit_msg>DS21SM: increase TX rate<commit_after><|endoftext|> |
<commit_before>/*******************************************************************************
Licensed to the OpenCOR team under one or more contributor license agreements.
See the NOTICE.txt file distributed with this work for additional information
regarding copyright ownership. The OpenCOR team licenses this file to you under
the Apache License, Version 2.0 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
*******************************************************************************/
//==============================================================================
// Lexer for the pretty CellML format
//==============================================================================
#include "prettycellmlviewlexer.h"
#include "qscintillawidget.h"
//==============================================================================
#include <QRegularExpression>
//==============================================================================
namespace OpenCOR {
namespace PrettyCellMLView {
//==============================================================================
PrettyCellmlViewLexer::PrettyCellmlViewLexer(QObject *pParent) :
QsciLexerCustom(pParent),
mFullText(QString())
{
// Some initialisations
mKeywords = QStringList() << "as" << "comp" << "def" << "enddef" << "model" << "unit";
mCellmlKeywords = QStringList() << "base"
<< "ampere" << "candela" << "coulomb" << "joule" << "kelvin" << "kilogram" << "liter" << "litre" << "lumen" << "meter" << "metre" << "mole" << "newton" << "second" << "steradian" << "volt" << "watt" << "weber";
mParameterKeywords = QStringList() << "pref" << "expo" << "mult" << "off";
mParameterValueKeywords = QStringList() << "milli";
}
//==============================================================================
const char * PrettyCellmlViewLexer::language() const
{
// Return the language for our lexer
return "Pretty CellML";
}
//==============================================================================
QString PrettyCellmlViewLexer::description(int pStyle) const
{
// Return the given style's description
switch (pStyle) {
case Default:
return QObject::tr("Default");
case Comment:
return QObject::tr("Comment");
case Keyword:
return QObject::tr("Keyword");
case CellmlKeyword:
return QObject::tr("CellML keyword");
case Number:
return QObject::tr("Number");
case ParameterGroup:
return QObject::tr("Parameter group");
case ParameterKeyword:
return QObject::tr("Parameter keyword");
case ParameterValueKeyword:
return QObject::tr("Parameter value keyword");
case ParameterNumber:
return QObject::tr("Parameter number");
}
return QString();
}
//==============================================================================
QColor PrettyCellmlViewLexer::color(int pStyle) const
{
// Return the given style's colour
switch (pStyle) {
case Default:
case ParameterGroup:
return QColor(0x1f, 0x1f, 0x1f);
case Comment:
return QColor(0x00, 0x7f, 0x00);
case Keyword:
case ParameterKeyword:
return QColor(0x00, 0x00, 0x7f);
case CellmlKeyword:
case ParameterValueKeyword:
return QColor(0x7f, 0x00, 0x7f);
case Number:
case ParameterNumber:
return QColor(0x7f, 0x7f, 0x00);
}
return QsciLexerCustom::color(pStyle);
}
//==============================================================================
QFont PrettyCellmlViewLexer::font(int pStyle) const
{
// Return the given style's colour
QFont res = QsciLexer::font(pStyle);
switch (pStyle) {
case ParameterGroup:
case ParameterKeyword:
case ParameterValueKeyword:
case ParameterNumber:
res.setItalic(true);
break;
}
return res;
}
//==============================================================================
void PrettyCellmlViewLexer::styleText(int pStart, int pEnd)
{
// Make sure that we have an editor
if (!editor())
return;
// Retrieve the text to style
char *data = new char[pEnd-pStart+1];
editor()->SendScintilla(QsciScintilla::SCI_GETTEXTRANGE, pStart, pEnd, data);
QString text = QString(data);
delete[] data;
if (text.isEmpty())
return;
// Effectively style our text
mFullText = editor()->text();
doStyleText(pStart, pEnd, text, false);
}
//==============================================================================
void PrettyCellmlViewLexer::doStyleText(int pStart, int pEnd, QString pText,
bool pParameterGroup)
{
// Make sure that we are given some text to style
if (pText.trimmed().isEmpty())
return;
// Check whether a /* XXX */ comment started before or at the beginning of
// the given text
static const QString StartCommentString = "/*";
static const QString EndCommentString = "*/";
static const int StartCommentLength = StartCommentString.length();
static const int EndCommentLength = EndCommentString.length();
int commentStartPosition = mFullText.lastIndexOf(StartCommentString, pStart+StartCommentLength);
if (commentStartPosition != -1) {
// A /* XXX */ comment started before or at the beginning of the given
// text, so now look for where it ends
int commentEndPosition = mFullText.indexOf(EndCommentString, commentStartPosition+StartCommentLength);
if (commentEndPosition == -1)
commentEndPosition = mFullText.length();
if ((commentStartPosition <= pStart) && (pStart <= commentEndPosition)) {
// The beginning of the given text is a comment, so style it
int realEnd = commentEndPosition+EndCommentLength;
int end = qMin(pEnd, realEnd);
startStyling(pStart, 0x1f);
setStyling(end-pStart, Comment);
// Style everything that is behind the comment, if anything
if (end == realEnd)
doStyleText(end, pEnd, pText.right(pEnd-end), pParameterGroup);
return;
}
}
// Check whether a parameter group started before or at the beginning of the
// given text
static const QString StartParameterGroupString = "{";
static const QString EndParameterGroupString = "}";
static const int StartParameterGroupLength = StartParameterGroupString.length();
static const int EndParameterGroupLength = EndParameterGroupString.length();
int parameterGroupStartPosition = mFullText.lastIndexOf(StartParameterGroupString, pStart+StartParameterGroupLength);
if (parameterGroupStartPosition != -1) {
// A parameter group started before or at the beginning of the given
// text, so now look for where it ends
int parameterGroupEndPosition = mFullText.indexOf(EndParameterGroupString, parameterGroupStartPosition+StartParameterGroupLength);
if (parameterGroupEndPosition == -1)
parameterGroupEndPosition = mFullText.length();
if ((parameterGroupStartPosition <= pStart) && (pStart <= parameterGroupEndPosition)) {
// The beginning of the given text is a parameter group, so style
// everything that is behind the parameter group, if anything
int realEnd = parameterGroupEndPosition+EndParameterGroupLength;
int end = qMin(pEnd, realEnd);
bool hasEnd = end == realEnd;
if (hasEnd)
doStyleText(end, pEnd, pText.right(pEnd-end), pParameterGroup);
// Style the beginning and the end of the parameter group
bool hasBeginning = !pText.left(StartParameterGroupLength).compare(StartParameterGroupString);
if (hasBeginning) {
startStyling(pStart, 0x1f);
setStyling(StartParameterGroupLength, ParameterGroup);
}
if (hasEnd) {
startStyling(end-EndParameterGroupLength, 0x1f);
setStyling(EndParameterGroupLength, ParameterGroup);
}
// Now style the contents of the parameter group
pStart += hasBeginning?StartParameterGroupLength:0;
pEnd = end-(hasEnd?EndParameterGroupLength:0);
pText = pText.mid(pStart, pEnd-pStart);
pParameterGroup = true;
}
}
// Check whether the given text contains a // comment
static const QString CommentString = "//";
int commentPosition = pText.indexOf(CommentString);
if (commentPosition != -1) {
// There is a // comment to style, so first style everything that is
// before the // comment
doStyleText(pStart, pStart+commentPosition, pText.left(commentPosition),
pParameterGroup);
// Now, style everything that is after the // comment, if anything, by
// looking for the end of the line on which the // comment is
QString eolString = qobject_cast<QScintillaSupport::QScintillaWidget *>(editor())->eolString();
int eolStringLength = eolString.length();
int eolPosition = pText.indexOf(eolString, commentPosition+eolStringLength);
if (eolPosition != -1) {
int start = pStart+eolPosition+eolStringLength;
doStyleText(start, pEnd, pText.right(pEnd-start), pParameterGroup);
}
// Style the // comment itself
int start = pStart+commentPosition;
startStyling(start, 0x1f);
setStyling(((eolPosition == -1)?pEnd:pStart+eolPosition)-start, Comment);
return;
}
// Check whether the given text contains a /* XXX */ comment
commentStartPosition = pText.indexOf(StartCommentString);
if (commentStartPosition != -1) {
// There is a /* XXX */ comment to style, so first style everything that
// is before it
doStyleText(pStart, pStart+commentStartPosition,
pText.left(commentStartPosition), pParameterGroup);
// Now style everything from the comment onwards
// Note: to style everything from the comment onwards means that we will
// find that a /* XXX */ comment starts at the beginning of the
// 'new' given text...
doStyleText(pStart+commentStartPosition, pEnd,
pText.right(pEnd-pStart-commentStartPosition),
pParameterGroup);
return;
}
// Check whether the given text contains a parameter group
parameterGroupStartPosition = pText.indexOf(StartParameterGroupString);
if (parameterGroupStartPosition != -1) {
// There is a parameter group, so first style everything that is before
// it
doStyleText(pStart, pStart+parameterGroupStartPosition,
pText.left(parameterGroupStartPosition), pParameterGroup);
// Now style everything from the parameter group onwards
// Note: to style everything from the parameter group onwards means that
// we will find that a parameter group starts at the beginning of
// the 'new' given text...
doStyleText(pStart+parameterGroupStartPosition, pEnd,
pText.right(pEnd-pStart-parameterGroupStartPosition),
pParameterGroup);
return;
}
// Use a default style for the given text
startStyling(pStart, 0x1f);
setStyling(pEnd-pStart, pParameterGroup?ParameterGroup:Default);
// Check whether the given text contains keywords from various categories
doStyleTextKeyword(pStart, pText, mKeywords, pParameterGroup?ParameterGroup:Keyword);
doStyleTextKeyword(pStart, pText, mCellmlKeywords, pParameterGroup?ParameterGroup:CellmlKeyword);
doStyleTextKeyword(pStart, pText, mParameterKeywords, pParameterGroup?ParameterKeyword:Default);
doStyleTextKeyword(pStart, pText, mParameterValueKeywords, pParameterGroup?ParameterValueKeyword:Default);
}
//==============================================================================
void PrettyCellmlViewLexer::doStyleTextKeyword(int pStart,
const QString &pText,
const QStringList pKeywords,
const int &pKeywordStyle)
{
// Check whether the given text contains some of the given keywords
foreach (const QString &keyword, pKeywords) {
QRegularExpressionMatchIterator regExMatchIter = QRegularExpression("\\b"+keyword+"\\b").globalMatch(pText);
while (regExMatchIter.hasNext()) {
QRegularExpressionMatch regExMatch = regExMatchIter.next();
// We found a keyword, so style it as such
startStyling(pStart+regExMatch.capturedStart(), 0x1f);
setStyling(regExMatch.capturedLength(), pKeywordStyle);
}
}
}
//==============================================================================
} // namespace PrettyCellMLView
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================
<commit_msg>Some minor cleaning up [ci skip].<commit_after>/*******************************************************************************
Licensed to the OpenCOR team under one or more contributor license agreements.
See the NOTICE.txt file distributed with this work for additional information
regarding copyright ownership. The OpenCOR team licenses this file to you under
the Apache License, Version 2.0 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
*******************************************************************************/
//==============================================================================
// Lexer for the pretty CellML format
//==============================================================================
#include "prettycellmlviewlexer.h"
#include "qscintillawidget.h"
//==============================================================================
#include <QRegularExpression>
//==============================================================================
namespace OpenCOR {
namespace PrettyCellMLView {
//==============================================================================
PrettyCellmlViewLexer::PrettyCellmlViewLexer(QObject *pParent) :
QsciLexerCustom(pParent),
mFullText(QString())
{
// Some initialisations
mKeywords = QStringList() << "as" << "comp" << "def" << "enddef" << "model" << "unit";
mCellmlKeywords = QStringList() << "base"
<< "ampere" << "candela" << "coulomb" << "joule" << "kelvin" << "kilogram" << "liter" << "litre" << "lumen" << "meter" << "metre" << "mole" << "newton" << "second" << "steradian" << "volt" << "watt" << "weber";
mParameterKeywords = QStringList() << "pref" << "expo" << "mult" << "off";
mParameterValueKeywords = QStringList() << "milli";
}
//==============================================================================
const char * PrettyCellmlViewLexer::language() const
{
// Return the language for our lexer
return "Pretty CellML";
}
//==============================================================================
QString PrettyCellmlViewLexer::description(int pStyle) const
{
// Return the given style's description
switch (pStyle) {
case Default:
return QObject::tr("Default");
case Comment:
return QObject::tr("Comment");
case Keyword:
return QObject::tr("Keyword");
case CellmlKeyword:
return QObject::tr("CellML keyword");
case Number:
return QObject::tr("Number");
case ParameterGroup:
return QObject::tr("Parameter group");
case ParameterKeyword:
return QObject::tr("Parameter keyword");
case ParameterValueKeyword:
return QObject::tr("Parameter value keyword");
case ParameterNumber:
return QObject::tr("Parameter number");
}
return QString();
}
//==============================================================================
QColor PrettyCellmlViewLexer::color(int pStyle) const
{
// Return the given style's colour
switch (pStyle) {
case Default:
case ParameterGroup:
return QColor(0x1f, 0x1f, 0x1f);
case Comment:
return QColor(0x00, 0x7f, 0x00);
case Keyword:
case ParameterKeyword:
return QColor(0x00, 0x00, 0x7f);
case CellmlKeyword:
case ParameterValueKeyword:
return QColor(0x7f, 0x00, 0x7f);
case Number:
case ParameterNumber:
return QColor(0x7f, 0x7f, 0x00);
}
return QsciLexerCustom::color(pStyle);
}
//==============================================================================
QFont PrettyCellmlViewLexer::font(int pStyle) const
{
// Return the given style's colour
QFont res = QsciLexer::font(pStyle);
switch (pStyle) {
case ParameterGroup:
case ParameterKeyword:
case ParameterValueKeyword:
case ParameterNumber:
res.setItalic(true);
break;
}
return res;
}
//==============================================================================
void PrettyCellmlViewLexer::styleText(int pStart, int pEnd)
{
// Make sure that we have an editor
if (!editor())
return;
// Retrieve the text to style
char *data = new char[pEnd-pStart+1];
editor()->SendScintilla(QsciScintilla::SCI_GETTEXTRANGE, pStart, pEnd, data);
QString text = QString(data);
delete[] data;
if (text.isEmpty())
return;
// Effectively style our text
mFullText = editor()->text();
doStyleText(pStart, pEnd, text, false);
}
//==============================================================================
void PrettyCellmlViewLexer::doStyleText(int pStart, int pEnd, QString pText,
bool pParameterGroup)
{
// Make sure that we are given some text to style
if (pText.trimmed().isEmpty())
return;
// Check whether a /* XXX */ comment started before or at the beginning of
// the given text
static const QString StartCommentString = "/*";
static const QString EndCommentString = "*/";
static const int StartCommentLength = StartCommentString.length();
static const int EndCommentLength = EndCommentString.length();
int commentStartPosition = mFullText.lastIndexOf(StartCommentString, pStart+StartCommentLength);
if (commentStartPosition != -1) {
// A /* XXX */ comment started before or at the beginning of the given
// text, so now look for where it ends
int commentEndPosition = mFullText.indexOf(EndCommentString, commentStartPosition+StartCommentLength);
if (commentEndPosition == -1) {
// The comment doesn't end as such, so consider that it 'ends' at
// the of the full text
commentEndPosition = mFullText.length();
}
if ((commentStartPosition <= pStart) && (pStart <= commentEndPosition)) {
// The beginning of the given text is a comment, so style it
int realEnd = commentEndPosition+EndCommentLength;
int end = qMin(pEnd, realEnd);
startStyling(pStart, 0x1f);
setStyling(end-pStart, Comment);
// Style everything that is behind the comment, if anything
if (end == realEnd)
doStyleText(end, pEnd, pText.right(pEnd-end), pParameterGroup);
return;
}
}
// Check whether a parameter group started before or at the beginning of the
// given text
static const QString StartParameterGroupString = "{";
static const QString EndParameterGroupString = "}";
static const int StartParameterGroupLength = StartParameterGroupString.length();
static const int EndParameterGroupLength = EndParameterGroupString.length();
int parameterGroupStartPosition = mFullText.lastIndexOf(StartParameterGroupString, pStart+StartParameterGroupLength);
if (parameterGroupStartPosition != -1) {
// A parameter group started before or at the beginning of the given
// text, so now look for where it ends
int parameterGroupEndPosition = mFullText.indexOf(EndParameterGroupString, parameterGroupStartPosition+StartParameterGroupLength);
if (parameterGroupEndPosition == -1)
parameterGroupEndPosition = mFullText.length();
if ((parameterGroupStartPosition <= pStart) && (pStart <= parameterGroupEndPosition)) {
// The beginning of the given text is a parameter group, so style
// everything that is behind the parameter group, if anything
int realEnd = parameterGroupEndPosition+EndParameterGroupLength;
int end = qMin(pEnd, realEnd);
bool hasEnd = end == realEnd;
if (hasEnd)
doStyleText(end, pEnd, pText.right(pEnd-end), pParameterGroup);
// Style the beginning and the end of the parameter group
bool hasBeginning = !pText.left(StartParameterGroupLength).compare(StartParameterGroupString);
if (hasBeginning) {
startStyling(pStart, 0x1f);
setStyling(StartParameterGroupLength, ParameterGroup);
}
if (hasEnd) {
startStyling(end-EndParameterGroupLength, 0x1f);
setStyling(EndParameterGroupLength, ParameterGroup);
}
// Now style the contents of the parameter group
pStart += hasBeginning?StartParameterGroupLength:0;
pEnd = end-(hasEnd?EndParameterGroupLength:0);
pText = pText.mid(pStart, pEnd-pStart);
pParameterGroup = true;
}
}
// Check whether the given text contains a // comment
static const QString CommentString = "//";
int commentPosition = pText.indexOf(CommentString);
if (commentPosition != -1) {
// There is a // comment to style, so first style everything that is
// before it
doStyleText(pStart, pStart+commentPosition, pText.left(commentPosition),
pParameterGroup);
// Now, style everything that is after the // comment, if anything, by
// looking for the end of the line on which the // comment is
QString eolString = qobject_cast<QScintillaSupport::QScintillaWidget *>(editor())->eolString();
int eolStringLength = eolString.length();
int eolPosition = pText.indexOf(eolString, commentPosition+eolStringLength);
if (eolPosition != -1) {
int start = pStart+eolPosition+eolStringLength;
doStyleText(start, pEnd, pText.right(pEnd-start), pParameterGroup);
}
// Style the // comment itself
int start = pStart+commentPosition;
startStyling(start, 0x1f);
setStyling(((eolPosition == -1)?pEnd:pStart+eolPosition)-start, Comment);
return;
}
// Check whether the given text contains a /* XXX */ comment
commentStartPosition = pText.indexOf(StartCommentString);
if (commentStartPosition != -1) {
// There is a /* XXX */ comment to style, so first style everything that
// is before it
doStyleText(pStart, pStart+commentStartPosition,
pText.left(commentStartPosition), pParameterGroup);
// Now style everything from the comment onwards
// Note: to style everything from the comment onwards means that we will
// find that a /* XXX */ comment starts at the beginning of the
// 'new' given text...
doStyleText(pStart+commentStartPosition, pEnd,
pText.right(pEnd-pStart-commentStartPosition),
pParameterGroup);
return;
}
// Check whether the given text contains a parameter group
parameterGroupStartPosition = pText.indexOf(StartParameterGroupString);
if (parameterGroupStartPosition != -1) {
// There is a parameter group, so first style everything that is before
// it
doStyleText(pStart, pStart+parameterGroupStartPosition,
pText.left(parameterGroupStartPosition), pParameterGroup);
// Now style everything from the parameter group onwards
// Note: to style everything from the parameter group onwards means that
// we will find that a parameter group starts at the beginning of
// the 'new' given text...
doStyleText(pStart+parameterGroupStartPosition, pEnd,
pText.right(pEnd-pStart-parameterGroupStartPosition),
pParameterGroup);
return;
}
// Use a default style for the given text
startStyling(pStart, 0x1f);
setStyling(pEnd-pStart, pParameterGroup?ParameterGroup:Default);
// Check whether the given text contains keywords from various categories
doStyleTextKeyword(pStart, pText, mKeywords, pParameterGroup?ParameterGroup:Keyword);
doStyleTextKeyword(pStart, pText, mCellmlKeywords, pParameterGroup?ParameterGroup:CellmlKeyword);
doStyleTextKeyword(pStart, pText, mParameterKeywords, pParameterGroup?ParameterKeyword:Default);
doStyleTextKeyword(pStart, pText, mParameterValueKeywords, pParameterGroup?ParameterValueKeyword:Default);
}
//==============================================================================
void PrettyCellmlViewLexer::doStyleTextKeyword(int pStart,
const QString &pText,
const QStringList pKeywords,
const int &pKeywordStyle)
{
// Check whether the given text contains some of the given keywords
foreach (const QString &keyword, pKeywords) {
QRegularExpressionMatchIterator regExMatchIter = QRegularExpression("\\b"+keyword+"\\b").globalMatch(pText);
while (regExMatchIter.hasNext()) {
QRegularExpressionMatch regExMatch = regExMatchIter.next();
// We found a keyword, so style it as such
startStyling(pStart+regExMatch.capturedStart(), 0x1f);
setStyling(regExMatch.capturedLength(), pKeywordStyle);
}
}
}
//==============================================================================
} // namespace PrettyCellMLView
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================
<|endoftext|> |
<commit_before>#include <iostream>
#include <vector>
#include <fstream>
#include <string>
#include <algorithm>
#include <cmath>
#include <boost/lexical_cast.hpp>
#include "Point.hpp"
#include "Function.hpp"
#include "SymbolicRegressionSolver.hpp"
#include "Config.hpp"
#define OPTIMISE_CONFIG
int amountOfSimulationsToPerform = 1;
SymbolicRegressionSolver::Config config{};
Function fn{parse("+ 1 x").statement, "x"};
int initialPoint = -10;
int endPoint = 10;
int stepSize = 1;
std::istream& operator>>(std::istream& is, SymbolicRegressionSolver::Config& config);
std::ostream& operator<<(std::ostream& os, const SymbolicRegressionSolver::Config& config);
void parseArguments(int argc, char *argv[]);
void printValidFlags()
{
std::cout << "-c <configuration-file> (TODO)\n";
std::cout << "-f <function>\n";
std::cout << "-i <initial-point>\n";
std::cout << "-e <end-point>\n";
std::cout << "-s <step size>\n";
std::cout << "-r <amount of times to redo simulation>\n";
}
int main(int argc, char *argv[])
{
parseArguments(argc, argv);
#ifdef VERBOSE_LOG
std::clog << "function: " << fn << '\n';
std::clog << "initial point: " << initialPoint << '\n';
std::clog << "end point: " << endPoint << '\n';
std::clog << "step size: " << stepSize << '\n';
#endif // VERBOSE_LOG
std::vector<Point> points;
points.reserve((endPoint - initialPoint)/stepSize);
VariableMap map;
for(int i = initialPoint; i <= endPoint; i += stepSize)
{
points.emplace_back(i, fn(map, i));
}
SymbolicRegressionSolver solver{config, points};
enum Direction { HIGHER, LOWER } dir = LOWER;
auto& variableToModify = solver.config().mutationPercent;
auto bestConfigOption = variableToModify;
double bestAverage;
size_t bestTotalSolutions = 0;
{
auto solutions = solver.solve();
bestAverage = solver.currentGeneration();
bestTotalSolutions = solutions.size();
solver.reset();
}
variableToModify /= 2;
while(std::abs(variableToModify - bestConfigOption) > 0.001)
{
/*
std::cout << "bestConfigOpt = " << bestConfigOption << '\n';
std::cout << "variable to modify = " << variableToModify << '\n';
*/
double currentAverage = 0;
size_t totalSolutions = 0;
for(int i = 1; i < amountOfSimulationsToPerform; ++i)
{
auto solutions = solver.solve();
totalSolutions += solutions.size();
currentAverage += solver.currentGeneration();
#ifndef OPTIMISE_CONFIG
for(auto& solution : solutions)
{
/*
result.averageGen += solver.currentGeneration();
result.minGen = result.minGen == -1 ? solver.currentGeneration() : std::min(result.minGen, solver.currentGeneration());
result.maxGen = result.maxGen == -1 ? solver.currentGeneration() : std::max(result.maxGen, solver.currentGeneration());
*/
std::cout << solver.currentGeneration() << ",";
std::cout << solution.fitnessLevel << ",";
std::cout << solution.mutated << ",";
std::cout << solution.mated << '\n';
}
#endif // OPTIMISE_CONFIG
solver.reset();
}
currentAverage /= totalSolutions;
/*
std::cout << "currentAverage= " << currentAverage << '\n';
std::cout << "bestAverage= " << bestAverage << '\n';
std::cout << "total solutions= " << totalSolutions << '\n';
std::cout << "best total solutions= " << bestTotalSolutions << '\n';
*/
if((totalSolutions > bestTotalSolutions &&
std::abs(static_cast<int>(totalSolutions - bestTotalSolutions)) >= amountOfSimulationsToPerform / 10.0) ||
currentAverage <= bestAverage)
{
bestAverage = currentAverage;
bestTotalSolutions = totalSolutions;
bestConfigOption = variableToModify;
//dir = LOWER;
//std::cout << "[IMPORTANT]: beat previous best\n";
}
else
{
dir = static_cast<Direction>(!static_cast<bool>(dir));
//dir = HIGHER;
}
//std::cout << "\n\n";
if(dir == HIGHER)
{
variableToModify = (bestConfigOption + variableToModify) / 2;
}
else
{
variableToModify /= 2;
}
}
variableToModify = bestConfigOption;
std::cout << "optimal var: " << bestConfigOption << '\n';
/*
std::cout << "optimal config is: \n";
std::cout << solver.config() << '\n';
*/
return 0;
}
void parseArguments(int argc, char *argv[])
{
for(int i = 1; i < argc; ++i)
{
auto command = argv[i];
auto commandSize = strlen(command);
if(command[0] != '-')
{
std::cout << "Invalid format: " << command << ".\n";
std::cout << "Flags must be prefixed with \"-\" (without quotes).\n";
std::exit(-2);
break;
}
if(commandSize == 1 || commandSize > 2)
{
std::cout << "Invalid flag: \"" << command << "\"\n";
printValidFlags();
std::exit(-5);
}
if(i + 1 >= argc)
{
std::cout << "please provide info with a flag...\n";
printValidFlags();
std::exit(-6);
}
switch(command[1])
{
// assign function
case 'f':
{
std::string functionAsString;
for(int j = i + 1; j < argc && argv[j][0] != '-'; ++j, ++i)
{
functionAsString += argv[j];
}
fn = parse(functionAsString).statement;
}
break;
case 'i':
{
std::string str = argv[++i];
initialPoint = boost::lexical_cast<int>(str);
}
break;
case 'e':
{
std::string str = argv[++i];
endPoint = boost::lexical_cast<int>(str);
}
break;
case 's':
{
std::string str = argv[++i];
stepSize = boost::lexical_cast<int>(str);
}
break;
case 'r':
{
std::string str = argv[++i];
amountOfSimulationsToPerform = boost::lexical_cast<int>(str);
}
break;
case 'c':
{
try
{
std::string filepath = argv[++i];
std::ifstream file;
file.exceptions(std::ifstream::failbit | std::ifstream::badbit);
file.open(filepath);
file >> config; // read the config
}
catch(boost::bad_lexical_cast& e)
{
std::cerr << e.what();
std::exit(5);
}
catch(std::exception& e)
{
std::cerr << e.what();
std::exit(6);
}
}
break;
default:
std::cout << "Invalid flag\n";
printValidFlags();
std::exit(-4);
break;
}
}
}
namespace
{
std::string obtainValue(const std::string& line)
{
return std::string(line.begin() + line.find_last_of('=') + 1, line.end());
}
template <class T>
void read(std::string& buffer, std::istream& is, T& value)
{
std::getline(is, buffer);
auto stringValue = obtainValue(buffer);
stringValue.erase(std::remove_if(stringValue.begin(), stringValue.end(), [](char c) { return std::isspace(c); }), stringValue.end());
value = boost::lexical_cast<T>(stringValue);
}
}
std::istream& operator>>(std::istream& is, SymbolicRegressionSolver::Config& config)
{
std::string buffer;
read(buffer, is, config.initialPopulation);
read(buffer, is, config.maxGenerations);
read(buffer, is, config.initialMaxDepth);
read(buffer, is, config.maxSolutionDepth);
read(buffer, is, config.keepPercentage);
read(buffer, is, config.mutationPercent);
read(buffer, is, config.matePercent);
// have to do this separately for const dist
int a, b;
read(buffer, is, a);
read(buffer, is, b);
config.constantDist = decltype(config.constantDist){a, b};
read(buffer, is, config.solutionCriterea);
read(buffer, is, config.chanceToChangeConstant);
read(buffer, is, config.chanceToChangeVar);
int nearestNeighbour = 0;
read(buffer, is, nearestNeighbour);
config.nearestNeighbourOption = static_cast<decltype(config.nearestNeighbourOption)>(nearestNeighbour);
read(buffer, is, config.chanceToUseNearestNeighbour);
read(buffer, is, config.stepSize);
int refillOption = 0;
read(buffer, is, refillOption);
config.populationRefillOption = static_cast<decltype(config.populationRefillOption)>(refillOption);
return is;
}
<commit_msg>Let's brute force this mother<commit_after>#include <iostream>
#include <vector>
#include <fstream>
#include <string>
#include <algorithm>
#include <cmath>
#include <boost/lexical_cast.hpp>
#include "Point.hpp"
#include "Function.hpp"
#include "SymbolicRegressionSolver.hpp"
#include "Config.hpp"
#define OPTIMISE_CONFIG
int amountOfSimulationsToPerform = 1;
SymbolicRegressionSolver::Config config{};
Function fn{parse("+ 1 x").statement, "x"};
int initialPoint = -10;
int endPoint = 10;
int stepSize = 1;
std::istream& operator>>(std::istream& is, SymbolicRegressionSolver::Config& config);
std::ostream& operator<<(std::ostream& os, const SymbolicRegressionSolver::Config& config);
void parseArguments(int argc, char *argv[]);
void printValidFlags()
{
std::cout << "-c <configuration-file> (TODO)\n";
std::cout << "-f <function>\n";
std::cout << "-i <initial-point>\n";
std::cout << "-e <end-point>\n";
std::cout << "-s <step size>\n";
std::cout << "-r <amount of times to redo simulation>\n";
}
int main(int argc, char *argv[])
{
parseArguments(argc, argv);
#ifdef VERBOSE_LOG
std::clog << "function: " << fn << '\n';
std::clog << "initial point: " << initialPoint << '\n';
std::clog << "end point: " << endPoint << '\n';
std::clog << "step size: " << stepSize << '\n';
#endif // VERBOSE_LOG
std::vector<Point> points;
points.reserve((endPoint - initialPoint)/stepSize);
VariableMap map;
for(int i = initialPoint; i <= endPoint; i += stepSize)
{
points.emplace_back(i, fn(map, i));
}
SymbolicRegressionSolver solver{config, points};
auto& variableToModify = solver.config().mutationPercent;
variableToModify = 0;
#ifdef OPTIMISE_CONFIG
for(; variableToModify <= 1; variableToModify += 0.1)
{
double currentAverage = 0;
size_t totalSolutions = 0;
#endif // OPTIMISE_CONFIG
for(int i = 1; i < amountOfSimulationsToPerform; ++i)
{
auto solutions = solver.solve();
totalSolutions += solutions.size();
currentAverage += solver.currentGeneration();
#ifndef OPTIMISE_CONFIG
for(auto& solution : solutions)
{
std::cout << solver.currentGeneration() << ",";
std::cout << solution.fitnessLevel << ",";
std::cout << solution.mutated << ",";
std::cout << solution.mated << '\n';
}
#endif // OPTIMISE_CONFIG
solver.reset();
}
#ifdef OPTIMISE_CONFIG
currentAverage /= totalSolutions;
std::cout << variableToModify << ", " << currentAverage << ", " << totalSolutions << '\n';
}
#endif // OPTIMISE_CONFIG
return 0;
}
void parseArguments(int argc, char *argv[])
{
for(int i = 1; i < argc; ++i)
{
auto command = argv[i];
auto commandSize = strlen(command);
if(command[0] != '-')
{
std::cout << "Invalid format: " << command << ".\n";
std::cout << "Flags must be prefixed with \"-\" (without quotes).\n";
std::exit(-2);
break;
}
if(commandSize == 1 || commandSize > 2)
{
std::cout << "Invalid flag: \"" << command << "\"\n";
printValidFlags();
std::exit(-5);
}
if(i + 1 >= argc)
{
std::cout << "please provide info with a flag...\n";
printValidFlags();
std::exit(-6);
}
switch(command[1])
{
// assign function
case 'f':
{
std::string functionAsString;
for(int j = i + 1; j < argc && argv[j][0] != '-'; ++j, ++i)
{
functionAsString += argv[j];
}
fn = parse(functionAsString).statement;
}
break;
case 'i':
{
std::string str = argv[++i];
initialPoint = boost::lexical_cast<int>(str);
}
break;
case 'e':
{
std::string str = argv[++i];
endPoint = boost::lexical_cast<int>(str);
}
break;
case 's':
{
std::string str = argv[++i];
stepSize = boost::lexical_cast<int>(str);
}
break;
case 'r':
{
std::string str = argv[++i];
amountOfSimulationsToPerform = boost::lexical_cast<int>(str);
}
break;
case 'c':
{
try
{
std::string filepath = argv[++i];
std::ifstream file;
file.exceptions(std::ifstream::failbit | std::ifstream::badbit);
file.open(filepath);
file >> config; // read the config
}
catch(boost::bad_lexical_cast& e)
{
std::cerr << e.what();
std::exit(5);
}
catch(std::exception& e)
{
std::cerr << e.what();
std::exit(6);
}
}
break;
default:
std::cout << "Invalid flag\n";
printValidFlags();
std::exit(-4);
break;
}
}
}
namespace
{
std::string obtainValue(const std::string& line)
{
return std::string(line.begin() + line.find_last_of('=') + 1, line.end());
}
template <class T>
void read(std::string& buffer, std::istream& is, T& value)
{
std::getline(is, buffer);
auto stringValue = obtainValue(buffer);
stringValue.erase(std::remove_if(stringValue.begin(), stringValue.end(), [](char c) { return std::isspace(c); }), stringValue.end());
value = boost::lexical_cast<T>(stringValue);
}
}
std::istream& operator>>(std::istream& is, SymbolicRegressionSolver::Config& config)
{
std::string buffer;
read(buffer, is, config.initialPopulation);
read(buffer, is, config.maxGenerations);
read(buffer, is, config.initialMaxDepth);
read(buffer, is, config.maxSolutionDepth);
read(buffer, is, config.keepPercentage);
read(buffer, is, config.mutationPercent);
read(buffer, is, config.matePercent);
// have to do this separately for const dist
int a, b;
read(buffer, is, a);
read(buffer, is, b);
config.constantDist = decltype(config.constantDist){a, b};
read(buffer, is, config.solutionCriterea);
read(buffer, is, config.chanceToChangeConstant);
read(buffer, is, config.chanceToChangeVar);
int nearestNeighbour = 0;
read(buffer, is, nearestNeighbour);
config.nearestNeighbourOption = static_cast<decltype(config.nearestNeighbourOption)>(nearestNeighbour);
read(buffer, is, config.chanceToUseNearestNeighbour);
read(buffer, is, config.stepSize);
int refillOption = 0;
read(buffer, is, refillOption);
config.populationRefillOption = static_cast<decltype(config.populationRefillOption)>(refillOption);
return is;
}
<|endoftext|> |
<commit_before>/*******************************************************************************
Licensed to the OpenCOR team under one or more contributor license agreements.
See the NOTICE.txt file distributed with this work for additional information
regarding copyright ownership. The OpenCOR team licenses this file to you under
the Apache License, Version 2.0 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
*******************************************************************************/
//==============================================================================
// Single cell view widget
//==============================================================================
#include "cellmlfilemanager.h"
#include "collapsiblewidget.h"
#include "singlecellviewcontentswidget.h"
#include "singlecellviewinformationwidget.h"
#include "singlecellviewsimulationwidget.h"
#include "singlecellviewwidget.h"
//==============================================================================
#include <QApplication>
#include <QDesktopWidget>
#include <QIcon>
#include <QLayout>
#include <QSettings>
//==============================================================================
namespace OpenCOR {
namespace SingleCellView {
//==============================================================================
SingleCellViewWidget::SingleCellViewWidget(SingleCellViewPlugin *pPlugin,
QWidget *pParent) :
ViewWidget(pParent),
mPlugin(pPlugin),
mSettingsGroup(QString()),
mSimulationWidgetSizes(QIntList()),
mContentsWidgetSizes(QIntList()),
mCollapsibleWidgetCollapsed(QMap<int, bool>()),
mSimulationWidget(0),
mSimulationWidgets(QMap<QString, SingleCellViewSimulationWidget *>())
{
}
//==============================================================================
static const auto SettingsSizes = QStringLiteral("Sizes");
static const auto SettingsContentsSizes = QStringLiteral("ContentsSizes");
//==============================================================================
void SingleCellViewWidget::loadSettings(QSettings *pSettings)
{
// Normally, we would retrieve the simulation widget's settings, but
// mSimulationWidget is not set at this stage. So, instead, we keep track of
// our settings' group and load them when initialising ourselves (see
// initialize())...
mSettingsGroup = pSettings->group();
// Retrieve the sizes of our simulation widget and of its contents widget
QVariantList defaultContentsSizes = QVariantList() << 0.25*qApp->desktop()->screenGeometry().width()
<< 0.75*qApp->desktop()->screenGeometry().width();
mSimulationWidgetSizes = qVariantListToIntList(pSettings->value(SettingsSizes).toList());
mContentsWidgetSizes = qVariantListToIntList(pSettings->value(SettingsContentsSizes, defaultContentsSizes).toList());
}
//==============================================================================
void SingleCellViewWidget::saveSettings(QSettings *pSettings) const
{
// Keep track of the sizes of our simulation widget and those of its
// contents widget
pSettings->setValue(SettingsSizes, qIntListToVariantList(mSimulationWidgetSizes));
pSettings->setValue(SettingsContentsSizes, qIntListToVariantList(mContentsWidgetSizes));
}
//==============================================================================
void SingleCellViewWidget::retranslateUi()
{
// Retranslate our simulation widgets
foreach (SingleCellViewSimulationWidget *simulationWidget, mSimulationWidgets)
simulationWidget->retranslateUi();
}
//==============================================================================
bool SingleCellViewWidget::contains(const QString &pFileName) const
{
// Return whether we know about the given file
return mSimulationWidgets.contains(pFileName);
}
//==============================================================================
void SingleCellViewWidget::initialize(const QString &pFileName)
{
// Retrieve the simulation widget associated with the given file, if any
SingleCellViewSimulationWidget *oldSimulationWidget = mSimulationWidget;
SingleCellViewContentsWidget *contentsWidget = 0;
Core::CollapsibleWidget *collapsibleWidget = 0;
mSimulationWidget = mSimulationWidgets.value(pFileName);
if (!mSimulationWidget) {
// No simulation widget exists for the given file, so create one
mSimulationWidget = new SingleCellViewSimulationWidget(mPlugin, pFileName, this);
// Keep track of various things related our simulation widget and its
// children
contentsWidget = mSimulationWidget->contentsWidget();
collapsibleWidget = contentsWidget->informationWidget()->collapsibleWidget();
connect(mSimulationWidget, SIGNAL(splitterMoved(const QIntList &)),
this, SLOT(simulationWidgetSplitterMoved(const QIntList &)));
connect(contentsWidget, SIGNAL(splitterMoved(const QIntList &)),
this, SLOT(contentsWidgetSplitterMoved(const QIntList &)));
connect(collapsibleWidget, SIGNAL(collapsed(const int &, const bool &)),
this, SLOT(collapsibleWidgetCollapsed(const int &, const bool &)));
// Keep track of our editing widget and add it to ourselves
mSimulationWidgets.insert(pFileName, mSimulationWidget);
layout()->addWidget(mSimulationWidget);
// Load our simulation widget's settings and those of some of its
// contents' children, if needed
QSettings settings;
settings.beginGroup(mSettingsGroup);
mSimulationWidget->loadSettings(&settings);
// Back up some settings, if this is our first simulation widget
if (mSimulationWidgets.count() == 1)
backupSettings(mSimulationWidget);
settings.endGroup();
// Initialise our simulation widget
mSimulationWidget->initialize();
} else {
contentsWidget = mSimulationWidget->contentsWidget();
collapsibleWidget = contentsWidget->informationWidget()->collapsibleWidget();
}
// Update our new simualtion widget and its children, if needed
mSimulationWidget->setSizes(mSimulationWidgetSizes);
contentsWidget->setSizes(mContentsWidgetSizes);
// Set (restore) some settings, if this is not our first (created)
// simulation widget (the first one is already properly set)
if (mSimulationWidgets.count() > 1)
restoreSettings(mSimulationWidget);
// Hide our previous simulation widget and show our new one
mSimulationWidget->show();
if (oldSimulationWidget && (mSimulationWidget != oldSimulationWidget))
oldSimulationWidget->hide();
// Set our focus proxy to our 'new' simulation widget and make sure that the
// latter immediately gets the focus
setFocusProxy(mSimulationWidget);
mSimulationWidget->setFocus();
}
//==============================================================================
void SingleCellViewWidget::finalize(const QString &pFileName)
{
// Remove the simulation widget, should there be one for the given file
SingleCellViewSimulationWidget *simulationWidget = mSimulationWidgets.value(pFileName);
if (simulationWidget) {
// There is a simulation widget for the given file name, so save its
// settings and those of some of its contents' children, if needed
QSettings settings;
settings.beginGroup(mSettingsGroup);
// Set (restore) some settings, if this is our last simulation
// widget (this is in case we close OpenCOR after having modified a
// simulation widget that is not the last one to be finalised)
if (mSimulationWidgets.count() == 1)
restoreSettings(simulationWidget);
simulationWidget->saveSettings(&settings);
settings.endGroup();
// Finalise our simulation widget
simulationWidget->finalize();
// Now, we can delete it and remove it from our list
delete simulationWidget;
mSimulationWidgets.remove(pFileName);
// Finally, reset our memory of the simulation widget, if needed
if (simulationWidget == mSimulationWidget)
mSimulationWidget = 0;
}
}
//==============================================================================
QIcon SingleCellViewWidget::fileTabIcon(const QString &pFileName) const
{
// Return, if possible, the tab icon for the given file
SingleCellViewSimulationWidget *simulationWidget = mSimulationWidgets.value(pFileName);
if (simulationWidget) {
return simulationWidget->fileTabIcon();
} else {
static const QIcon NoIcon = QIcon();
return NoIcon;
}
}
//==============================================================================
bool SingleCellViewWidget::saveFile(const QString &pOldFileName,
const QString &pNewFileName)
{
// Save the given file, if possible
SingleCellViewSimulationWidget *simulationWidget = mSimulationWidgets.value(pOldFileName);
if (simulationWidget)
return simulationWidget->saveFile(pOldFileName, pNewFileName);
else
return false;
}
//==============================================================================
void SingleCellViewWidget::fileOpened(const QString &pFileName)
{
// Keep track, if possible, of the fact that a file has been opened
SingleCellViewSimulationWidget *simulationWidget = mSimulationWidgets.value(pFileName);
if (simulationWidget)
simulationWidget->fileOpened(pFileName);
}
//==============================================================================
void SingleCellViewWidget::filePermissionsChanged(const QString &pFileName)
{
// Keep track, if possible, of the fact that a file has been un/locked
SingleCellViewSimulationWidget *simulationWidget = mSimulationWidgets.value(pFileName);
if (simulationWidget)
simulationWidget->filePermissionsChanged();
}
//==============================================================================
void SingleCellViewWidget::fileModified(const QString &pFileName)
{
// Keep track, if possible, of the fact that a file has been un/locked
SingleCellViewSimulationWidget *simulationWidget = mSimulationWidgets.value(pFileName);
if (simulationWidget)
simulationWidget->fileModified(pFileName);
}
//==============================================================================
void SingleCellViewWidget::fileReloaded(const QString &pFileName)
{
// The given file has been reloaded, so reload it, should it be managed
SingleCellViewSimulationWidget *simulationWidget = mSimulationWidgets.value(pFileName);
if (simulationWidget)
simulationWidget->fileReloaded(pFileName);
}
//==============================================================================
void SingleCellViewWidget::fileRenamed(const QString &pOldFileName,
const QString &pNewFileName)
{
// The given file has been renamed, so update our simulation widgets mapping
SingleCellViewSimulationWidget *simulationWidget = mSimulationWidgets.value(pOldFileName);
if (simulationWidget) {
mSimulationWidgets.insert(pNewFileName, simulationWidget);
mSimulationWidgets.remove(pOldFileName);
}
}
//==============================================================================
void SingleCellViewWidget::fileClosed(const QString &pFileName)
{
// The given file has been closed, so let our our simulation widgets know
// about it
foreach (SingleCellViewSimulationWidget *simulationWidget, mSimulationWidgets.values())
simulationWidget->fileClosed(pFileName);
}
//==============================================================================
void SingleCellViewWidget::simulationWidgetSplitterMoved(const QIntList &pSizes)
{
// The splitter of our simulation widget has moved, so keep track of its new
// sizes
mSimulationWidgetSizes = pSizes;
}
//==============================================================================
void SingleCellViewWidget::contentsWidgetSplitterMoved(const QIntList &pSizes)
{
// The splitter of our contents widget has moved, so keep track of its new
// sizes
mContentsWidgetSizes = pSizes;
}
//==============================================================================
void SingleCellViewWidget::collapsibleWidgetCollapsed(const int &pIndex,
const bool &pCollapsed)
{
// One of the widgets in our collapsible widget has been collapsed or
// expanded, so keep track of that fact
mCollapsibleWidgetCollapsed.insert(pIndex, pCollapsed);
}
//==============================================================================
void SingleCellViewWidget::backupSettings(SingleCellViewSimulationWidget *pSimulationWidget)
{
// Back up some of the given simulation's contents' children's settings
Core::CollapsibleWidget *collapsibleWidget = pSimulationWidget->contentsWidget()->informationWidget()->collapsibleWidget();
for (int i = 0, iMax = collapsibleWidget->count(); i < iMax; ++i)
mCollapsibleWidgetCollapsed.insert(i, collapsibleWidget->isCollapsed(i));
}
//==============================================================================
void SingleCellViewWidget::restoreSettings(SingleCellViewSimulationWidget *pSimulationWidget)
{
// Restore some of the given simulation's contents' children's settings
Core::CollapsibleWidget *collapsibleWidget = pSimulationWidget->contentsWidget()->informationWidget()->collapsibleWidget();
foreach (const int &index, mCollapsibleWidgetCollapsed.keys())
collapsibleWidget->setCollapsed(index, mCollapsibleWidgetCollapsed.value(index));
}
//==============================================================================
} // namespace SingleCellView
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================
<commit_msg>Single Cell view: some work on making the view more file specific (#590) [ci skip].<commit_after>/*******************************************************************************
Licensed to the OpenCOR team under one or more contributor license agreements.
See the NOTICE.txt file distributed with this work for additional information
regarding copyright ownership. The OpenCOR team licenses this file to you under
the Apache License, Version 2.0 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
*******************************************************************************/
//==============================================================================
// Single cell view widget
//==============================================================================
#include "cellmlfilemanager.h"
#include "collapsiblewidget.h"
#include "singlecellviewcontentswidget.h"
#include "singlecellviewinformationwidget.h"
#include "singlecellviewsimulationwidget.h"
#include "singlecellviewwidget.h"
//==============================================================================
#include <QApplication>
#include <QDesktopWidget>
#include <QIcon>
#include <QLayout>
#include <QSettings>
//==============================================================================
namespace OpenCOR {
namespace SingleCellView {
//==============================================================================
SingleCellViewWidget::SingleCellViewWidget(SingleCellViewPlugin *pPlugin,
QWidget *pParent) :
ViewWidget(pParent),
mPlugin(pPlugin),
mSettingsGroup(QString()),
mSimulationWidgetSizes(QIntList()),
mContentsWidgetSizes(QIntList()),
mCollapsibleWidgetCollapsed(QMap<int, bool>()),
mSimulationWidget(0),
mSimulationWidgets(QMap<QString, SingleCellViewSimulationWidget *>())
{
}
//==============================================================================
static const auto SettingsSizes = QStringLiteral("Sizes");
static const auto SettingsContentsSizes = QStringLiteral("ContentsSizes");
//==============================================================================
void SingleCellViewWidget::loadSettings(QSettings *pSettings)
{
// Normally, we would retrieve the simulation widget's settings, but
// mSimulationWidget is not set at this stage. So, instead, we keep track of
// our settings' group and load them when initialising ourselves (see
// initialize())...
mSettingsGroup = pSettings->group();
// Retrieve the sizes of our simulation widget and of its contents widget
QVariantList defaultContentsSizes = QVariantList() << 0.25*qApp->desktop()->screenGeometry().width()
<< 0.75*qApp->desktop()->screenGeometry().width();
mSimulationWidgetSizes = qVariantListToIntList(pSettings->value(SettingsSizes).toList());
mContentsWidgetSizes = qVariantListToIntList(pSettings->value(SettingsContentsSizes, defaultContentsSizes).toList());
}
//==============================================================================
void SingleCellViewWidget::saveSettings(QSettings *pSettings) const
{
// Keep track of the sizes of our simulation widget and those of its
// contents widget
pSettings->setValue(SettingsSizes, qIntListToVariantList(mSimulationWidgetSizes));
pSettings->setValue(SettingsContentsSizes, qIntListToVariantList(mContentsWidgetSizes));
}
//==============================================================================
void SingleCellViewWidget::retranslateUi()
{
// Retranslate our simulation widgets
foreach (SingleCellViewSimulationWidget *simulationWidget, mSimulationWidgets)
simulationWidget->retranslateUi();
}
//==============================================================================
bool SingleCellViewWidget::contains(const QString &pFileName) const
{
// Return whether we know about the given file
return mSimulationWidgets.contains(pFileName);
}
//==============================================================================
void SingleCellViewWidget::initialize(const QString &pFileName)
{
// Retrieve the simulation widget associated with the given file, if any
SingleCellViewSimulationWidget *oldSimulationWidget = mSimulationWidget;
SingleCellViewContentsWidget *contentsWidget = 0;
Core::CollapsibleWidget *collapsibleWidget = 0;
mSimulationWidget = mSimulationWidgets.value(pFileName);
if (!mSimulationWidget) {
// No simulation widget exists for the given file, so create one
mSimulationWidget = new SingleCellViewSimulationWidget(mPlugin, pFileName, this);
// Keep track of our editing widget and add it to ourselves
mSimulationWidgets.insert(pFileName, mSimulationWidget);
layout()->addWidget(mSimulationWidget);
// Load our simulation widget's settings and those of some of its
// contents' children, if needed
QSettings settings;
settings.beginGroup(mSettingsGroup);
mSimulationWidget->loadSettings(&settings);
// Back up some settings, if this is our first simulation widget
if (mSimulationWidgets.count() == 1)
backupSettings(mSimulationWidget);
settings.endGroup();
// Initialise our simulation widget
mSimulationWidget->initialize();
// Keep track of various things related our simulation widget and its
// children
contentsWidget = mSimulationWidget->contentsWidget();
collapsibleWidget = contentsWidget->informationWidget()->collapsibleWidget();
connect(mSimulationWidget, SIGNAL(splitterMoved(const QIntList &)),
this, SLOT(simulationWidgetSplitterMoved(const QIntList &)));
connect(contentsWidget, SIGNAL(splitterMoved(const QIntList &)),
this, SLOT(contentsWidgetSplitterMoved(const QIntList &)));
connect(collapsibleWidget, SIGNAL(collapsed(const int &, const bool &)),
this, SLOT(collapsibleWidgetCollapsed(const int &, const bool &)));
} else {
contentsWidget = mSimulationWidget->contentsWidget();
collapsibleWidget = contentsWidget->informationWidget()->collapsibleWidget();
}
// Update our new simualtion widget and its children, if needed
mSimulationWidget->setSizes(mSimulationWidgetSizes);
contentsWidget->setSizes(mContentsWidgetSizes);
// Set (restore) some settings, if this is not our first (created)
// simulation widget (the first one is already properly set)
if (mSimulationWidgets.count() > 1)
restoreSettings(mSimulationWidget);
// Hide our previous simulation widget and show our new one
mSimulationWidget->show();
if (oldSimulationWidget && (mSimulationWidget != oldSimulationWidget))
oldSimulationWidget->hide();
// Set our focus proxy to our 'new' simulation widget and make sure that the
// latter immediately gets the focus
setFocusProxy(mSimulationWidget);
mSimulationWidget->setFocus();
}
//==============================================================================
void SingleCellViewWidget::finalize(const QString &pFileName)
{
// Remove the simulation widget, should there be one for the given file
SingleCellViewSimulationWidget *simulationWidget = mSimulationWidgets.value(pFileName);
if (simulationWidget) {
// There is a simulation widget for the given file name, so save its
// settings and those of some of its contents' children, if needed
QSettings settings;
settings.beginGroup(mSettingsGroup);
// Set (restore) some settings, if this is our last simulation
// widget (this is in case we close OpenCOR after having modified a
// simulation widget that is not the last one to be finalised)
if (mSimulationWidgets.count() == 1)
restoreSettings(simulationWidget);
simulationWidget->saveSettings(&settings);
settings.endGroup();
// Finalise our simulation widget
simulationWidget->finalize();
// Now, we can delete it and remove it from our list
delete simulationWidget;
mSimulationWidgets.remove(pFileName);
// Finally, reset our memory of the simulation widget, if needed
if (simulationWidget == mSimulationWidget)
mSimulationWidget = 0;
}
}
//==============================================================================
QIcon SingleCellViewWidget::fileTabIcon(const QString &pFileName) const
{
// Return, if possible, the tab icon for the given file
SingleCellViewSimulationWidget *simulationWidget = mSimulationWidgets.value(pFileName);
if (simulationWidget) {
return simulationWidget->fileTabIcon();
} else {
static const QIcon NoIcon = QIcon();
return NoIcon;
}
}
//==============================================================================
bool SingleCellViewWidget::saveFile(const QString &pOldFileName,
const QString &pNewFileName)
{
// Save the given file, if possible
SingleCellViewSimulationWidget *simulationWidget = mSimulationWidgets.value(pOldFileName);
if (simulationWidget)
return simulationWidget->saveFile(pOldFileName, pNewFileName);
else
return false;
}
//==============================================================================
void SingleCellViewWidget::fileOpened(const QString &pFileName)
{
// Keep track, if possible, of the fact that a file has been opened
SingleCellViewSimulationWidget *simulationWidget = mSimulationWidgets.value(pFileName);
if (simulationWidget)
simulationWidget->fileOpened(pFileName);
}
//==============================================================================
void SingleCellViewWidget::filePermissionsChanged(const QString &pFileName)
{
// Keep track, if possible, of the fact that a file has been un/locked
SingleCellViewSimulationWidget *simulationWidget = mSimulationWidgets.value(pFileName);
if (simulationWidget)
simulationWidget->filePermissionsChanged();
}
//==============================================================================
void SingleCellViewWidget::fileModified(const QString &pFileName)
{
// Keep track, if possible, of the fact that a file has been un/locked
SingleCellViewSimulationWidget *simulationWidget = mSimulationWidgets.value(pFileName);
if (simulationWidget)
simulationWidget->fileModified(pFileName);
}
//==============================================================================
void SingleCellViewWidget::fileReloaded(const QString &pFileName)
{
// The given file has been reloaded, so reload it, should it be managed
SingleCellViewSimulationWidget *simulationWidget = mSimulationWidgets.value(pFileName);
if (simulationWidget)
simulationWidget->fileReloaded(pFileName);
}
//==============================================================================
void SingleCellViewWidget::fileRenamed(const QString &pOldFileName,
const QString &pNewFileName)
{
// The given file has been renamed, so update our simulation widgets mapping
SingleCellViewSimulationWidget *simulationWidget = mSimulationWidgets.value(pOldFileName);
if (simulationWidget) {
mSimulationWidgets.insert(pNewFileName, simulationWidget);
mSimulationWidgets.remove(pOldFileName);
}
}
//==============================================================================
void SingleCellViewWidget::fileClosed(const QString &pFileName)
{
// The given file has been closed, so let our our simulation widgets know
// about it
foreach (SingleCellViewSimulationWidget *simulationWidget, mSimulationWidgets.values())
simulationWidget->fileClosed(pFileName);
}
//==============================================================================
void SingleCellViewWidget::simulationWidgetSplitterMoved(const QIntList &pSizes)
{
// The splitter of our simulation widget has moved, so keep track of its new
// sizes
mSimulationWidgetSizes = pSizes;
}
//==============================================================================
void SingleCellViewWidget::contentsWidgetSplitterMoved(const QIntList &pSizes)
{
// The splitter of our contents widget has moved, so keep track of its new
// sizes
mContentsWidgetSizes = pSizes;
}
//==============================================================================
void SingleCellViewWidget::collapsibleWidgetCollapsed(const int &pIndex,
const bool &pCollapsed)
{
// One of the widgets in our collapsible widget has been collapsed or
// expanded, so keep track of that fact
mCollapsibleWidgetCollapsed.insert(pIndex, pCollapsed);
}
//==============================================================================
void SingleCellViewWidget::backupSettings(SingleCellViewSimulationWidget *pSimulationWidget)
{
// Back up some of the given simulation's contents' children's settings
Core::CollapsibleWidget *collapsibleWidget = pSimulationWidget->contentsWidget()->informationWidget()->collapsibleWidget();
for (int i = 0, iMax = collapsibleWidget->count(); i < iMax; ++i)
mCollapsibleWidgetCollapsed.insert(i, collapsibleWidget->isCollapsed(i));
}
//==============================================================================
void SingleCellViewWidget::restoreSettings(SingleCellViewSimulationWidget *pSimulationWidget)
{
// Restore some of the given simulation's contents' children's settings
Core::CollapsibleWidget *collapsibleWidget = pSimulationWidget->contentsWidget()->informationWidget()->collapsibleWidget();
foreach (const int &index, mCollapsibleWidgetCollapsed.keys())
collapsibleWidget->setCollapsed(index, mCollapsibleWidgetCollapsed.value(index));
}
//==============================================================================
} // namespace SingleCellView
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================
<|endoftext|> |
<commit_before>/*
Resembla: Word-based Japanese similar sentence search library
https://github.com/tuem/resembla
Copyright 2017 Takashi Uemura
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "text_classification_feature_extractor.hpp"
#include "../../string_util.hpp"
#include "../../csv_reader.hpp"
namespace resembla {
TextClassificationFeatureExtractor::TextClassificationFeatureExtractor(
const std::string& mecab_options, const std::string& dict_path, const std::string& model_path):
tagger(MeCab::createTagger(mecab_options.c_str())),
model(svm_load_model(model_path.c_str()))
{
for(const auto& columns: CsvReader<>(dict_path, 2)){
dictionary[columns[1]] = std::stoi(columns[0]);
}
}
Feature::text_type TextClassificationFeatureExtractor::operator()(const string_type& text) const
{
auto nodes = toNodes(text);
double s;
{
std::lock_guard<std::mutex> lock(mutex_model);
s = svm_predict(model, &nodes[0]);
}
return Feature::toText(s);
}
std::vector<svm_node> TextClassificationFeatureExtractor::toNodes(const string_type& text) const
{
const auto text_string = cast_string<std::string>(text);
BoW bow;
{
std::lock_guard<std::mutex> lock(mutex_tagger);
for(const auto* node = tagger->parseToNode(text_string.c_str()); node; node = node->next){
// skip BOS/EOS nodes
if(node->stat == MECAB_BOS_NODE || node->stat == MECAB_EOS_NODE){
continue;
}
auto i = dictionary.find(std::string(node->surface, node->surface + node->length));
if(i == dictionary.end()){
continue;
}
auto j = bow.find(i->second);
if(j == bow.end()){
bow[i->second] = 1;
}
else{
++j->second;
}
}
}
std::vector<svm_node> nodes(bow.size() + 1);
size_t i = 0;
for(const auto& j: bow){
nodes[i].index = j.first;
nodes[i].value = static_cast<double>(j.second);
++i;
}
nodes[i].index = -1; // end of features
return nodes;
}
}
<commit_msg>return 0 if no word in document exists in dictionary<commit_after>/*
Resembla: Word-based Japanese similar sentence search library
https://github.com/tuem/resembla
Copyright 2017 Takashi Uemura
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "text_classification_feature_extractor.hpp"
#include "../../string_util.hpp"
#include "../../csv_reader.hpp"
namespace resembla {
TextClassificationFeatureExtractor::TextClassificationFeatureExtractor(
const std::string& mecab_options, const std::string& dict_path, const std::string& model_path):
tagger(MeCab::createTagger(mecab_options.c_str())),
model(svm_load_model(model_path.c_str()))
{
for(const auto& columns: CsvReader<>(dict_path, 2)){
dictionary[columns[1]] = std::stoi(columns[0]);
}
}
Feature::text_type TextClassificationFeatureExtractor::operator()(const string_type& text) const
{
auto nodes = toNodes(text);
double s = 0.0;
if(!nodes.empty()){
{
std::lock_guard<std::mutex> lock(mutex_model);
s = svm_predict(model, &nodes[0]);
}
}
return Feature::toText(s);
}
std::vector<svm_node> TextClassificationFeatureExtractor::toNodes(const string_type& text) const
{
const auto text_string = cast_string<std::string>(text);
BoW bow;
{
std::lock_guard<std::mutex> lock(mutex_tagger);
for(const auto* node = tagger->parseToNode(text_string.c_str()); node; node = node->next){
// skip BOS/EOS nodes
if(node->stat == MECAB_BOS_NODE || node->stat == MECAB_EOS_NODE){
continue;
}
auto i = dictionary.find(std::string(node->surface, node->surface + node->length));
if(i == dictionary.end()){
continue;
}
auto j = bow.find(i->second);
if(j == bow.end()){
bow[i->second] = 1;
}
else{
++j->second;
}
}
}
std::vector<svm_node> nodes(bow.size() + 1);
size_t i = 0;
for(const auto& j: bow){
nodes[i].index = j.first;
nodes[i].value = static_cast<double>(j.second);
++i;
}
nodes[i].index = -1; // end of features
return nodes;
}
}
<|endoftext|> |
<commit_before>/*
Metaballs Demo
Copyright (C) 1999 by Denis Dmitriev
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <stdarg.h>
#include <string.h>
#include "cssysdef.h"
#include "csutil/scf.h"
#include "meta.h"
#include "igraph3d.h"
#include "igraph2d.h"
#include "csutil/inifile.h"
#include "isystem.h"
#include "csengine/pol2d.h"
#include "csengine/polygon.h"
IMPLEMENT_FACTORY (csMetaBalls)
EXPORT_CLASS_TABLE (metaball)
EXPORT_CLASS (csMetaBalls, "crystalspace.graphics.metaballs",
"Metaball renderer for crystal space")
EXPORT_CLASS_TABLE_END
IMPLEMENT_IBASE (csMetaBalls)
IMPLEMENTS_INTERFACE (iPlugIn)
IMPLEMENTS_INTERFACE (iMetaBalls)
IMPLEMENT_IBASE_END
#define MAP_RESOLUTION 256
static float asin_table[2*MAP_RESOLUTION+1];
csMetaBalls::csMetaBalls (iBase *iParent)
{
CONSTRUCT_IBASE (iParent);
th = NULL;
poly = new G3DPolygonDPFX ();
memset(poly, 0, sizeof(*poly));
poly->num = 3;
alpha = frame = 0;
}
csMetaBalls::~csMetaBalls ()
{
delete [] triangles_array;
delete [] meta_balls;
delete poly;
}
float csMetaBalls::map (float x)
{
return asin_table[(int)(MAP_RESOLUTION*(1+x))];
}
void csMetaBalls::InitTables(void)
{
for (int i = -MAP_RESOLUTION, j = 0; i <= MAP_RESOLUTION; i++, j++)
{
float c = 1.0 * i / MAP_RESOLUTION;
switch(env_mapping)
{
case TRUE_ENV_MAP:
asin_table[j] = env_map_mult * (0.5+asin(c)/M_PI);
break;
case FAKE_ENV_MAP:
asin_table[j] = 0.5 * env_map_mult * (1 + c);
break;
}
}
}
bool csMetaBalls::Initialize (iSystem *sys)
{
Sys = sys;
return true;
}
void csMetaBalls::SetContext (iGraphics3D *g3d)
{
G3D = g3d;
G2D = G3D->GetDriver2D ();
}
void csMetaBalls::SetNumberMetaBalls (int number)
{
if ((number < 1) || (number == num_meta_balls))
return;
num_meta_balls = number;
delete [] meta_balls;
meta_balls = new MetaBall [num_meta_balls];
}
void csMetaBalls::SetQualityEnvironmentMapping (bool toggle)
{
env_mapping = toggle;
InitTables ();
}
void csMetaBalls::SetEnvironmentMappingFactor (float env_mult)
{
env_map_mult = env_mult;
InitTables ();
}
void csMetaBalls::SetMetaBallDefaults (csIniFile *Config)
{
this->Config = Config;
// Read the config here: earlier than Sys->Initialize we can't
mp.d_alpha = Config->GetFloat ("MetaBalls", "INITIAL_SPEED", 0.03);
num_meta_balls = Config->GetInt ("MetaBalls", "NUM_META_BALLS", 3);
mp.iso_level = Config->GetFloat ("MetaBalls", "ISO_LEVEL", 1.0);
max_triangles = Config->GetInt ("MetaBalls", "MAX_TRIANGLES", 2000);
env_map_mult = Config->GetFloat ("MetaBalls", "ENV_MAP_MULTIPLIER", 1.0);
env_mapping = Config->GetYesNo ("MetaBalls", "USE_TRUE_ENV_MAP", true)
? TRUE_ENV_MAP : FAKE_ENV_MAP;
meta_balls = new MetaBall[num_meta_balls];
triangles_array = new Triangle[max_triangles];
mp.charge = Config->GetFloat ("MetaBalls", "CHARGE", 3.5);
InitTables();
}
void LitVertex(const csVector3 &n, G3DTexturedVertex &c)
{
if (n.z > 0)
c.r = c.g = c.b = 0;
else
{
float l = n.z*n.z;
c.r = c.g = c.b = l;
}
}
void csMetaBalls::DrawSomething(void)
{
int i,j;
int h_height = G2D->GetHeight () / 2;
int h_width = G2D->GetWidth () / 2;
for (i = 0; i < num_meta_balls; i++)
{
float m = fmod((i + 1) / 3.0, 1.5) + 0.5;
csVector3 &c = meta_balls[i].center;
c.x = 4 * m * sin (m * alpha + i * M_PI / 4);
c.y = 3 * m * cos (1.4 * m * alpha + m * M_PI / 6);
c.z = 11 + 2 * sin (m * alpha * 1.3214);
}
CalculateMetaBalls();
for (i = 0; i < triangles_tesselated; i++)
{
Triangle& t = triangles_array[i];
for (j = 0; j < 3; j++)
{
int m = 2 - j;
// Projecting.
poly->vertices[j].sx = h_width + h_height * t.p[m].x / (1 + t.p[m].z);
poly->vertices[j].sy = h_height * (1 + t.p[m].y / (1 + t.p[m].z));
// Computing normal at point.
csVector3 n(0, 0, 0);
for(int k = 0; k < num_meta_balls; k++)
{
csVector3 rv(t.p[m].x - meta_balls[k].center.x,
t.p[m].y - meta_balls[k].center.y,
t.p[m].z - meta_balls[k].center.z);
float r = rv.Norm();
float c = mp.charge / (r*r*r);
n += rv * c;
}
// Lighting
if (n.z > 0)
break;
n = n.Unit();
LitVertex (n, poly->vertices[j]);
// Environment mapping.
poly->vertices[j].u = map (n.x);
poly->vertices[j].v = map (n.y);
poly->vertices[j].z = 1 / t.p[m].z;
}
// We really want to draw this triangle
if (j == 3)
G3D->DrawPolygonFX (*poly);
}
}
bool csMetaBalls::Draw ()
{
// Tell 3D driver we're going to display 3D things.
alpha += mp.d_alpha;
poly->txt_handle = th;
G3D->StartPolygonFX(th, CS_FX_COPY | CS_FX_GOURAUD);
G3D->SetRenderState (G3DRENDERSTATE_ZBUFFERMODE, CS_ZBUF_USE);
DrawSomething();
G3D->FinishPolygonFX();
return true;
}
<commit_msg><commit_after>/*
Metaballs Demo
Copyright (C) 1999 by Denis Dmitriev
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <stdarg.h>
#include <string.h>
#include "cssysdef.h"
#include "csutil/scf.h"
#include "meta.h"
#include "igraph3d.h"
#include "igraph2d.h"
#include "csutil/inifile.h"
#include "isystem.h"
#include "csengine/pol2d.h"
#include "csengine/polygon.h"
IMPLEMENT_FACTORY (csMetaBalls)
EXPORT_CLASS_TABLE (metaball)
EXPORT_CLASS (csMetaBalls, "crystalspace.graphics.metaballs",
"Metaball renderer for crystal space")
EXPORT_CLASS_TABLE_END
IMPLEMENT_IBASE (csMetaBalls)
IMPLEMENTS_INTERFACE (iPlugIn)
IMPLEMENTS_INTERFACE (iMetaBalls)
IMPLEMENT_IBASE_END
#define MAP_RESOLUTION 256
static float asin_table[2*MAP_RESOLUTION+1];
csMetaBalls::csMetaBalls (iBase *iParent)
{
CONSTRUCT_IBASE (iParent);
th = NULL;
poly = new G3DPolygonDPFX ();
memset(poly, 0, sizeof(*poly));
poly->num = 3;
alpha = frame = 0;
triangles_array = NULL;
meta_balls = NULL;
}
csMetaBalls::~csMetaBalls ()
{
delete [] triangles_array;
delete [] meta_balls;
delete poly;
}
float csMetaBalls::map (float x)
{
return asin_table[(int)(MAP_RESOLUTION*(1+x))];
}
void csMetaBalls::InitTables(void)
{
for (int i = -MAP_RESOLUTION, j = 0; i <= MAP_RESOLUTION; i++, j++)
{
float c = 1.0 * i / MAP_RESOLUTION;
switch(env_mapping)
{
case TRUE_ENV_MAP:
asin_table[j] = env_map_mult * (0.5+asin(c)/M_PI);
break;
case FAKE_ENV_MAP:
asin_table[j] = 0.5 * env_map_mult * (1 + c);
break;
}
}
}
bool csMetaBalls::Initialize (iSystem *sys)
{
Sys = sys;
return true;
}
void csMetaBalls::SetContext (iGraphics3D *g3d)
{
G3D = g3d;
G2D = G3D->GetDriver2D ();
}
void csMetaBalls::SetNumberMetaBalls (int number)
{
if ((number < 1) || (number == num_meta_balls))
return;
num_meta_balls = number;
delete [] meta_balls;
meta_balls = new MetaBall [num_meta_balls];
}
void csMetaBalls::SetQualityEnvironmentMapping (bool toggle)
{
env_mapping = toggle;
InitTables ();
}
void csMetaBalls::SetEnvironmentMappingFactor (float env_mult)
{
env_map_mult = env_mult;
InitTables ();
}
void csMetaBalls::SetMetaBallDefaults (csIniFile *Config)
{
this->Config = Config;
// Read the config here: earlier than Sys->Initialize we can't
mp.d_alpha = Config->GetFloat ("MetaBalls", "INITIAL_SPEED", 0.03);
num_meta_balls = Config->GetInt ("MetaBalls", "NUM_META_BALLS", 3);
mp.iso_level = Config->GetFloat ("MetaBalls", "ISO_LEVEL", 1.0);
max_triangles = Config->GetInt ("MetaBalls", "MAX_TRIANGLES", 2000);
env_map_mult = Config->GetFloat ("MetaBalls", "ENV_MAP_MULTIPLIER", 1.0);
env_mapping = Config->GetYesNo ("MetaBalls", "USE_TRUE_ENV_MAP", true)
? TRUE_ENV_MAP : FAKE_ENV_MAP;
meta_balls = new MetaBall[num_meta_balls];
triangles_array = new Triangle[max_triangles];
mp.charge = Config->GetFloat ("MetaBalls", "CHARGE", 3.5);
InitTables();
}
void LitVertex(const csVector3 &n, G3DTexturedVertex &c)
{
if (n.z > 0)
c.r = c.g = c.b = 0;
else
{
float l = n.z*n.z;
c.r = c.g = c.b = l;
}
}
void csMetaBalls::DrawSomething(void)
{
int i,j;
int h_height = G2D->GetHeight () / 2;
int h_width = G2D->GetWidth () / 2;
for (i = 0; i < num_meta_balls; i++)
{
float m = fmod((i + 1) / 3.0, 1.5) + 0.5;
csVector3 &c = meta_balls[i].center;
c.x = 4 * m * sin (m * alpha + i * M_PI / 4);
c.y = 3 * m * cos (1.4 * m * alpha + m * M_PI / 6);
c.z = 11 + 2 * sin (m * alpha * 1.3214);
}
CalculateMetaBalls();
for (i = 0; i < triangles_tesselated; i++)
{
Triangle& t = triangles_array[i];
for (j = 0; j < 3; j++)
{
int m = 2 - j;
// Projecting.
poly->vertices[j].sx = h_width + h_height * t.p[m].x / (1 + t.p[m].z);
poly->vertices[j].sy = h_height * (1 + t.p[m].y / (1 + t.p[m].z));
// Computing normal at point.
csVector3 n(0, 0, 0);
for(int k = 0; k < num_meta_balls; k++)
{
csVector3 rv(t.p[m].x - meta_balls[k].center.x,
t.p[m].y - meta_balls[k].center.y,
t.p[m].z - meta_balls[k].center.z);
float r = rv.Norm();
float c = mp.charge / (r*r*r);
n += rv * c;
}
// Lighting
if (n.z > 0)
break;
n = n.Unit();
LitVertex (n, poly->vertices[j]);
// Environment mapping.
poly->vertices[j].u = map (n.x);
poly->vertices[j].v = map (n.y);
poly->vertices[j].z = 1 / t.p[m].z;
}
// We really want to draw this triangle
if (j == 3)
G3D->DrawPolygonFX (*poly);
}
}
bool csMetaBalls::Draw ()
{
// Tell 3D driver we're going to display 3D things.
alpha += mp.d_alpha;
poly->txt_handle = th;
G3D->StartPolygonFX(th, CS_FX_COPY | CS_FX_GOURAUD);
G3D->SetRenderState (G3DRENDERSTATE_ZBUFFERMODE, CS_ZBUF_USE);
DrawSomething();
G3D->FinishPolygonFX();
return true;
}
<|endoftext|> |
<commit_before>#include "BigFix/DataRef.h"
#include "BigFix/DateTime.h"
#include "BigFix/Error.h"
#include <gtest/gtest.h>
using namespace BigFix;
TEST( DateTimeTest, DefaultIsTheEpoch )
{
DateTime time;
EXPECT_EQ( 1970ul, time.Year() );
EXPECT_EQ( 1ul, time.Month() );
EXPECT_EQ( 1ul, time.Day() );
EXPECT_EQ( 0ul, time.Hour() );
EXPECT_EQ( 0ul, time.Minute() );
EXPECT_EQ( 0ul, time.Second() );
}
TEST( DateTimeTest, FromString )
{
DateTime time( DataRef( "Sun, 11 Mar 1984 08:23:42 +0000" ) );
EXPECT_EQ( 1984ul, time.Year() );
EXPECT_EQ( 3ul, time.Month() );
EXPECT_EQ( 11ul, time.Day() );
EXPECT_EQ( 8ul, time.Hour() );
EXPECT_EQ( 23ul, time.Minute() );
EXPECT_EQ( 42ul, time.Second() );
}
TEST( DateTimeTest, ToString )
{
EXPECT_EQ(
"Sun, 11 Mar 1984 08:23:42 +0000",
DateTime( DataRef( "Sun, 11 Mar 1984 08:23:42 +0000" ) ).ToString() );
}
TEST( DateTimeTest, FromConstructor )
{
EXPECT_EQ(
"Sun, 11 Mar 1984 08:23:42 +0000",
DateTime( 1984, 3, 11, 1, 8, 23, 42 ).ToString() );
}
TEST( DateTimeTest, ThrowsOnInvalidDates )
{
EXPECT_THROW( DateTime( DataRef( "hodor" ) ), Error );
EXPECT_THROW( DateTime( DataRef( "Xxx, 11 Mar 1984 08:23:42 +0000" ) ),
Error );
EXPECT_THROW( DateTime( DataRef( "Sun, 11 Xxx 1984 08:23:42 +0000" ) ),
Error );
}
<commit_msg>Appease the code coverage gods<commit_after>#include "BigFix/DataRef.h"
#include "BigFix/DateTime.h"
#include "BigFix/Error.h"
#include <gtest/gtest.h>
using namespace BigFix;
TEST( DateTimeTest, DefaultIsTheEpoch )
{
DateTime time;
EXPECT_EQ( 1970ul, time.Year() );
EXPECT_EQ( 1ul, time.Month() );
EXPECT_EQ( 1ul, time.Day() );
EXPECT_EQ( 0ul, time.Hour() );
EXPECT_EQ( 0ul, time.Minute() );
EXPECT_EQ( 0ul, time.Second() );
}
TEST( DateTimeTest, FromString )
{
DateTime time( DataRef( "Sun, 11 Mar 1984 08:23:42 +0000" ) );
EXPECT_EQ( 1984ul, time.Year() );
EXPECT_EQ( 3ul, time.Month() );
EXPECT_EQ( 11ul, time.Day() );
EXPECT_EQ( 8ul, time.Hour() );
EXPECT_EQ( 23ul, time.Minute() );
EXPECT_EQ( 42ul, time.Second() );
}
TEST( DateTimeTest, ToString )
{
EXPECT_EQ(
"Sun, 11 Mar 1984 08:23:42 +0000",
DateTime( DataRef( "Sun, 11 Mar 1984 08:23:42 +0000" ) ).ToString() );
}
TEST( DateTimeTest, FromConstructor )
{
EXPECT_EQ(
"Sun, 11 Mar 1984 08:23:42 +0000",
DateTime( 1984, 3, 11, 1, 8, 23, 42 ).ToString() );
}
TEST( DateTimeTest, ThrowsOnInvalidDates )
{
DataRef badLength( "hodor" );
DataRef badDay( "Xxx, 11 Mar 1984 08:23:42 +0000" );
DataRef badMonth( "Sun, 11 Xxx 1984 08:23:42 +0000" );
EXPECT_THROW( DateTime date( badLength ), Error );
EXPECT_THROW( DateTime date( badDay ), Error );
EXPECT_THROW( DateTime date( badMonth ), Error );
}
<|endoftext|> |
<commit_before><commit_msg>INTEGRATION: CWS vgbugs07 (1.39.50); FILE MERGED 2007/06/04 13:26:12 vg 1.39.50.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after><|endoftext|> |
<commit_before>/* * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* BSD 3-Clause License
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Code by Cassius Fiorin - cafiorin@gmail.com
http://pinballhomemade.blogspot.com.br
* * * * * * * * * * * * * * * * * * * * * * * * * * * * */
// TestPinb.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "OOP\Pinball.h"
#include "OOP\PinballObject.h"
#include "OOP\HardwareSerial.h"
#include "OOP\Input.h"
#include "OOP\Output.h"
#include "OOP\SlingShot.h"
#include "OOP\Bumper.h"
#include "OOP\KickoutHole.h"
#include "OOP\Utils.h"
void InitObjectsToPinballMaster(Pinball *pPinball)
{
PinballObject *pInput1 = new Input("input1", pPinball, 1);
Output *pOutput = new Output("output", pPinball, 2);
SlingShot *pSling = new SlingShot("sling", pPinball, 3, 4, 5);
Bumper *pBumper = new Bumper("bumper", pPinball, 6, 7);
KickoutHole *pHole = new KickoutHole("hole", pPinball, 8, 9);
pOutput->TurnOnByTimer(500);
}
void InitObjectsToPinballSlave(Pinball *pPinball)
{
}
int ikeyCount = 0;
char szKey[80];
int Ard = 0;
void PrintReadKey()
{
int x = 70;
int y = 20;
clrbox(x, y, x + 15, y + 2, BLACK);
setcolor(WHITE);
box(x, y, x + 15, y + 2, y + 7, y + 7, "Key");
gotoxy(x + 2, y + 1);
printf("Read Key :");
}
int ReadKey()
{
if (_kbhit())
{
char ch = _getch();
if (ch >= '0' && ch <= '9')
{
szKey[ikeyCount] = ch;
ikeyCount++;
szKey[ikeyCount] = 0;
}
else if (ch == 27)
{
return -2;
}
else if (ch == 13)
{
int sw = atoi(szKey);
ikeyCount = 0;
szKey[ikeyCount] = 0;
PrintReadKey();
return sw;
}
PrintReadKey();
printf("%s", szKey);
}
return -1;
}
int main()
{
HardwareSerial *serial = new HardwareSerial();
Pinball *pPinballMaster = new Pinball("Master", serial, true);
InitObjectsToPinballMaster(pPinballMaster);
HardwareSerial *serial2 = new HardwareSerial(100);
Pinball *pPinballSlave = new Pinball("Slave", serial2);
InitObjectsToPinballSlave(pPinballMaster);
pPinballMaster->Init();
pPinballSlave->Init();
PrintReadKey();
int ch = 0;
do
{
ch = ReadKey();
if (ch != -2 && ch != -1)
{
pPinballMaster->Loop(ch);
pPinballSlave->Loop(ch);
gotoxy(72 + 10 + ikeyCount, 21);
}
} while (ch != -2);
delete pPinballMaster;
delete pPinballSlave;
return 0;
}
<commit_msg>Fixed Loop and change to accept keys more than 200 to second Arduino<commit_after>/* * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* BSD 3-Clause License
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Code by Cassius Fiorin - cafiorin@gmail.com
http://pinballhomemade.blogspot.com.br
* * * * * * * * * * * * * * * * * * * * * * * * * * * * */
// TestPinb.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "OOP\Pinball.h"
#include "OOP\PinballObject.h"
#include "OOP\HardwareSerial.h"
#include "OOP\Input.h"
#include "OOP\Output.h"
#include "OOP\SlingShot.h"
#include "OOP\Bumper.h"
#include "OOP\KickoutHole.h"
#include "OOP\Utils.h"
void InitObjectsToPinballMaster(Pinball *pPinball)
{
PinballObject *pInput1 = new Input("input1", pPinball, 1);
Output *pOutput = new Output("output", pPinball, 2);
SlingShot *pSling = new SlingShot("sling", pPinball, 3, 4, 5);
Bumper *pBumper = new Bumper("bumper", pPinball, 6, 7);
KickoutHole *pHole = new KickoutHole("hole", pPinball, 8, 9);
pOutput->TurnOnByTimer(500);
}
void InitObjectsToPinballSlave(Pinball *pPinball)
{
SlingShot *pSling = new SlingShot("sling2", pPinball, 1, 2, 3);
}
int ikeyCount = 0;
char szKey[80];
int Ard = 0;
void PrintReadKey()
{
int x = 70;
int y = 20;
clrbox(x, y, x + 15, y + 2, BLACK);
setcolor(WHITE);
box(x, y, x + 15, y + 2, y + 7, y + 7, "Key");
gotoxy(x + 2, y + 1);
printf("Read Key :");
}
int ReadKey()
{
if (_kbhit())
{
char ch = _getch();
if (ch >= '0' && ch <= '9')
{
szKey[ikeyCount] = ch;
ikeyCount++;
szKey[ikeyCount] = 0;
}
else if (ch == 27)
{
return -2;
}
else if (ch == 13)
{
int sw = atoi(szKey);
ikeyCount = 0;
szKey[ikeyCount] = 0;
PrintReadKey();
return sw;
}
PrintReadKey();
printf("%s", szKey);
}
return -1;
}
int main()
{
HardwareSerial *serial = new HardwareSerial();
Pinball *pPinballMaster = new Pinball("Master", serial, true);
InitObjectsToPinballMaster(pPinballMaster);
HardwareSerial *serial2 = new HardwareSerial(100);
Pinball *pPinballSlave = new Pinball("Slave", serial2);
InitObjectsToPinballSlave(pPinballSlave);
pPinballMaster->Init();
pPinballSlave->Init();
PrintReadKey();
int ch = 0;
do
{
ch = ReadKey();
if (ch != -2 && ch != -1)
{
if (ch > 200)
{
pPinballSlave->Loop(ch-200);
}
else
{
pPinballMaster->Loop(ch);
}
gotoxy(72 + 10 + ikeyCount, 21);
}
else
{
pPinballMaster->Loop(0);
pPinballSlave->Loop(0);
}
} while (ch != -2);
delete pPinballMaster;
delete pPinballSlave;
return 0;
}
<|endoftext|> |
<commit_before><commit_msg>INTEGRATION: CWS swdrawpositioning (1.1.2); FILE ADDED 2004/06/01 12:01:09 od 1.1.2.3: #i26791# classes <SwAnchoredObject> and <SwAnchoredDrawObject> - method to set and convert positioning attributes. 2004/04/23 07:23:56 od 1.1.2.2: #i26791# - adjustments for the unification of the positioning of Writer fly frames and drawing objects 2004/04/07 08:58:17 od 1.1.2.1: #i26791# new class <SwAnchoredObject> for the unification of the positioning of Writer fly frames and drawing objects.<commit_after><|endoftext|> |
<commit_before>#ifndef URI_HH
#define URI_HH
#include <string>
#include <utility>
#include <vector>
#include <stdexcept>
#include <algorithm>
#include <sstream>
#include <boost/algorithm/string.hpp>
/* TODO:
* Normalization and Comparison
* http://tools.ietf.org/html/rfc3986#section-6
*/
struct uri {
std::string scheme;
std::string userinfo;
std::string host;
std::string path;
std::string query;
std::string fragment;
unsigned int port;
uri() : port(0) {}
uri(const std::string &uri_str) {
const char *error_at = NULL;
if (!parse(uri_str.c_str(), uri_str.size(), &error_at)) {
if (error_at) {
throw std::runtime_error(error_at);
} else {
throw std::runtime_error("uri parser error");
}
}
}
int parse(const char *buf, size_t len, const char **error_at = NULL);
void clear() {
scheme.clear();
userinfo.clear();
host.clear();
path.clear();
query.clear();
fragment.clear();
port = 0;
}
void normalize();
std::string compose(bool path_only=false);
void transform(uri &base, uri &relative);
static std::string encode(const std::string& src);
static std::string decode(const std::string& src);
template <typename T> struct query_match {
query_match(const T &k_) : k(k_) {}
const T &k;
bool operator()(const std::pair<T, T> &i) {
return i.first == k;
}
};
typedef std::vector<std::pair<std::string, std::string> > query_params;
query_params parse_query();
static query_params::iterator find_param(query_params &p, const std::string &k) {
return std::find_if(p.begin(), p.end(), query_match<std::string>(k));
}
static void remove_param(query_params &p, const std::string &k) {
query_params::iterator nend = std::remove_if(p.begin(), p.end(), query_match<std::string>(k));
p.erase(nend, p.end());
}
static std::string params_to_query(const query_params &pms) {
if (pms.empty()) return "";
std::stringstream ss;
ss << "?";
query_params::const_iterator it = pms.begin();
while (it!=pms.end()) {
ss << it->first << "=" << it->second;
++it;
if (it != pms.end()) {
ss << "&";
}
}
return ss.str();
}
struct match_char {
char c;
match_char(char c) : c(c) {}
bool operator()(char x) const { return x == c; }
};
typedef std::vector<std::string> split_vector;
split_vector path_splits() {
split_vector splits;
boost::split(splits, path, match_char('/'));
return splits;
}
};
#endif // URI_HH
<commit_msg>add uri::get_param<commit_after>#ifndef URI_HH
#define URI_HH
#include <string>
#include <utility>
#include <vector>
#include <stdexcept>
#include <algorithm>
#include <sstream>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
/* TODO:
* Normalization and Comparison
* http://tools.ietf.org/html/rfc3986#section-6
*/
struct uri {
std::string scheme;
std::string userinfo;
std::string host;
std::string path;
std::string query;
std::string fragment;
unsigned int port;
uri() : port(0) {}
uri(const std::string &uri_str) {
const char *error_at = NULL;
if (!parse(uri_str.c_str(), uri_str.size(), &error_at)) {
if (error_at) {
throw std::runtime_error(error_at);
} else {
throw std::runtime_error("uri parser error");
}
}
}
int parse(const char *buf, size_t len, const char **error_at = NULL);
void clear() {
scheme.clear();
userinfo.clear();
host.clear();
path.clear();
query.clear();
fragment.clear();
port = 0;
}
void normalize();
std::string compose(bool path_only=false);
void transform(uri &base, uri &relative);
static std::string encode(const std::string& src);
static std::string decode(const std::string& src);
template <typename T> struct query_match {
query_match(const T &k_) : k(k_) {}
const T &k;
bool operator()(const std::pair<T, T> &i) {
return i.first == k;
}
};
typedef std::vector<std::pair<std::string, std::string> > query_params;
query_params parse_query();
static query_params::iterator find_param(query_params &p, const std::string &k) {
return std::find_if(p.begin(), p.end(), query_match<std::string>(k));
}
template <typename ParamT> static bool get_param(query_params &p, const std::string &k, ParamT &v) {
auto i = std::find_if(p.begin(), p.end(), query_match<std::string>(k));
if (i != p.end()) {
try {
v = boost::lexical_cast<ParamT>(i->second);
return true;
} catch (boost::bad_lexical_cast &e) {}
}
return false;
}
static void remove_param(query_params &p, const std::string &k) {
query_params::iterator nend = std::remove_if(p.begin(), p.end(), query_match<std::string>(k));
p.erase(nend, p.end());
}
static std::string params_to_query(const query_params &pms) {
if (pms.empty()) return "";
std::stringstream ss;
ss << "?";
query_params::const_iterator it = pms.begin();
while (it!=pms.end()) {
ss << it->first << "=" << it->second;
++it;
if (it != pms.end()) {
ss << "&";
}
}
return ss.str();
}
struct match_char {
char c;
match_char(char c) : c(c) {}
bool operator()(char x) const { return x == c; }
};
typedef std::vector<std::string> split_vector;
split_vector path_splits() {
split_vector splits;
boost::split(splits, path, match_char('/'));
return splits;
}
};
#endif // URI_HH
<|endoftext|> |
<commit_before>/* Copyright (c) 2008-2019 the MRtrix3 contributors.
*
* 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/.
*
* Covered Software is provided under this License on an "as is"
* basis, without warranty of any kind, either expressed, implied, or
* statutory, including, without limitation, warranties that the
* Covered Software is free of defects, merchantable, fit for a
* particular purpose or non-infringing.
* See the Mozilla Public License v. 2.0 for more details.
*
* For more details, see http://www.mrtrix.org/.
*/
#include "command.h"
#include "datatype.h"
#include "header.h"
#include "image.h"
#include "mrtrix.h"
#include "stride.h"
#include "types.h"
#include "algo/loop.h"
#include "algo/min_max.h"
#include "colourmap.h"
using namespace MR;
using namespace App;
vector<std::string> colourmap_choices_std;
vector<const char*> colourmap_choices_cstr;
void usage ()
{
const ColourMap::Entry* entry = ColourMap::maps;
do {
if (strcmp(entry->name, "Complex"))
colourmap_choices_std.push_back (lowercase (entry->name));
++entry;
} while (entry->name);
colourmap_choices_cstr.reserve (colourmap_choices_std.size() + 1);
for (const auto& s : colourmap_choices_std)
colourmap_choices_cstr.push_back (s.c_str());
colourmap_choices_cstr.push_back (nullptr);
AUTHOR = "Robert E. Smith (robert.smith@florey.edu.au)";
SYNOPSIS = "Apply a colour map to an image";
DESCRIPTION
+ "Under typical usage, this command will receive as input ad 3D greyscale image, and "
"output a 4D image with 3 volumes corresponding to red-green-blue components; "
"other use cases are possible, and are described in more detail below."
+ "By default, the command will automatically determine the maximum and minimum "
"intensities of the input image, and use that information to set the upper and "
"lower bounds of the applied colourmap. This behaviour can be overridden by manually "
"specifying these bounds using the -upper and -lower options respectively.";
ARGUMENTS
+ Argument ("input", "the input image").type_image_in()
+ Argument ("map", "the colourmap to apply; choices are: " + join(colourmap_choices_std, ",")).type_choice (colourmap_choices_cstr.data())
+ Argument ("output", "the output image").type_image_out();
OPTIONS
+ Option ("upper", "manually set the upper intensity of the colour mapping")
+ Argument ("value").type_float()
+ Option ("lower", "manually set the lower intensity of the colour mapping")
+ Argument ("value").type_float()
+ Option ("colour", "set the target colour for use of the 'colour' map (three comma-separated floating-point values)")
+ Argument ("values").type_sequence_float();
}
void run ()
{
Header H_in = Header::open (argument[0]);
const ColourMap::Entry colourmap = ColourMap::maps[argument[1]];
Eigen::Vector3 fixed_colour (NaN, NaN, NaN);
if (colourmap.is_colour) {
if (!(H_in.ndim() == 3 || (H_in.ndim() == 4 && H_in.size(3) == 1)))
throw Exception ("For applying a fixed colour, command expects a 3D image as input");
auto opt = get_options ("colour");
if (!opt.size())
throw Exception ("For \'colour\' colourmap, target colour must be specified using the -colour option");
const auto values = parse_floats (opt[0][0]);
if (values.size() != 3)
throw Exception ("Target colour must be specified as a comma-separated list of three values");
fixed_colour = Eigen::Vector3 (values.data());
if (fixed_colour.minCoeff() < 0.0)
throw Exception ("Values for fixed colour provided via -colour option cannot be negative");
} else if (colourmap.is_rgb) {
if (!(H_in.ndim() == 4 && H_in.size(3) == 3))
throw Exception ("\'rgb\' colourmap only applies to 4D images with 3 volumes");
if (get_options ("lower").size()) {
WARN ("Option -lower ignored: not compatible with \'rgb\' colourmap (a minimum of 0.0 is assumed)");
}
} else {
if (!(H_in.ndim() == 3 || (H_in.ndim() == 4 && H_in.size(3) == 1)))
throw Exception ("For standard colour maps, command expects a 3D image as input");
if (get_options ("colour").size()) {
WARN ("Option -colour ignored: only applies if \'colour\' colourmap is used");
}
}
auto in = H_in.get_image<float>();
float lower = int(argument[1]) == 6 ? 0.0 : get_option_value ("lower", NaN);
float upper = get_option_value ("upper", NaN);
if (!std::isfinite (lower) || !std::isfinite (upper)) {
float image_min = NaN, image_max = NaN;
min_max (in, image_min, image_max);
if (int(argument[1]) == 6) { // RGB
image_max = std::max (MR::abs (image_min), MR::abs (image_max));
} else {
if (!std::isfinite (lower)) {
if (!std::isfinite (image_min))
throw Exception ("Unable to determine minimum value from image");
lower = image_min;
}
}
if (!std::isfinite (upper)) {
if (!std::isfinite (image_max))
throw Exception ("Unable to determine maximum value from image");
upper = image_max;
}
}
const float multiplier = 1.0f / (upper - lower);
auto scale = [&] (const float value) { return std::max (0.0f, std::min (1.0f, multiplier * (value - lower))); };
Header H_out (H_in);
H_out.ndim() = 4;
H_out.size(3) = 3;
Stride::set (H_out, Stride::contiguous_along_axis (3, H_out));
H_out.datatype() = DataType::Float32;
H_out.datatype().set_byte_order_native();
auto out = Image<float>::create (argument[2], H_out);
if (colourmap.is_colour) {
assert (fixed_colour.allFinite());
for (auto l_outer = Loop ("Applying fixed RGB colour to greyscale image", H_in) (in, out); l_outer; ++l_outer) {
const float amplitude = std::max (0.0f, std::min (1.0f, scale (in.value())));
for (auto l_inner = Loop(3) (out); l_inner; ++l_inner)
out.value() = amplitude * fixed_colour[out.index(3)];
}
} else if (colourmap.is_rgb) {
for (auto l_outer = Loop ("Scaling RGB colour image", H_in) (in, out); l_outer; ++l_outer)
out.value() = scale (in.value());
} else {
const ColourMap::Entry::basic_map_fn& map_fn = colourmap.basic_mapping;
for (auto l_outer = Loop ("Mapping intensities to RGB colours", H_in) (in, out); l_outer; ++l_outer) {
const Eigen::Array3f colour = map_fn (scale (in.value()));
for (auto l_inner = Loop(3) (out); l_inner; ++l_inner)
out.value() = colour[out.index(3)];
}
}
}
<commit_msg>mrcolour: avoid hard-coded index for RGB scheme<commit_after>/* Copyright (c) 2008-2019 the MRtrix3 contributors.
*
* 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/.
*
* Covered Software is provided under this License on an "as is"
* basis, without warranty of any kind, either expressed, implied, or
* statutory, including, without limitation, warranties that the
* Covered Software is free of defects, merchantable, fit for a
* particular purpose or non-infringing.
* See the Mozilla Public License v. 2.0 for more details.
*
* For more details, see http://www.mrtrix.org/.
*/
#include "command.h"
#include "datatype.h"
#include "header.h"
#include "image.h"
#include "mrtrix.h"
#include "stride.h"
#include "types.h"
#include "algo/loop.h"
#include "algo/min_max.h"
#include "colourmap.h"
using namespace MR;
using namespace App;
vector<std::string> colourmap_choices_std;
vector<const char*> colourmap_choices_cstr;
void usage ()
{
const ColourMap::Entry* entry = ColourMap::maps;
do {
if (strcmp(entry->name, "Complex"))
colourmap_choices_std.push_back (lowercase (entry->name));
++entry;
} while (entry->name);
colourmap_choices_cstr.reserve (colourmap_choices_std.size() + 1);
for (const auto& s : colourmap_choices_std)
colourmap_choices_cstr.push_back (s.c_str());
colourmap_choices_cstr.push_back (nullptr);
AUTHOR = "Robert E. Smith (robert.smith@florey.edu.au)";
SYNOPSIS = "Apply a colour map to an image";
DESCRIPTION
+ "Under typical usage, this command will receive as input ad 3D greyscale image, and "
"output a 4D image with 3 volumes corresponding to red-green-blue components; "
"other use cases are possible, and are described in more detail below."
+ "By default, the command will automatically determine the maximum and minimum "
"intensities of the input image, and use that information to set the upper and "
"lower bounds of the applied colourmap. This behaviour can be overridden by manually "
"specifying these bounds using the -upper and -lower options respectively.";
ARGUMENTS
+ Argument ("input", "the input image").type_image_in()
+ Argument ("map", "the colourmap to apply; choices are: " + join(colourmap_choices_std, ",")).type_choice (colourmap_choices_cstr.data())
+ Argument ("output", "the output image").type_image_out();
OPTIONS
+ Option ("upper", "manually set the upper intensity of the colour mapping")
+ Argument ("value").type_float()
+ Option ("lower", "manually set the lower intensity of the colour mapping")
+ Argument ("value").type_float()
+ Option ("colour", "set the target colour for use of the 'colour' map (three comma-separated floating-point values)")
+ Argument ("values").type_sequence_float();
}
void run ()
{
Header H_in = Header::open (argument[0]);
const ColourMap::Entry colourmap = ColourMap::maps[argument[1]];
Eigen::Vector3 fixed_colour (NaN, NaN, NaN);
if (colourmap.is_colour) {
if (!(H_in.ndim() == 3 || (H_in.ndim() == 4 && H_in.size(3) == 1)))
throw Exception ("For applying a fixed colour, command expects a 3D image as input");
auto opt = get_options ("colour");
if (!opt.size())
throw Exception ("For \'colour\' colourmap, target colour must be specified using the -colour option");
const auto values = parse_floats (opt[0][0]);
if (values.size() != 3)
throw Exception ("Target colour must be specified as a comma-separated list of three values");
fixed_colour = Eigen::Vector3 (values.data());
if (fixed_colour.minCoeff() < 0.0)
throw Exception ("Values for fixed colour provided via -colour option cannot be negative");
} else if (colourmap.is_rgb) {
if (!(H_in.ndim() == 4 && H_in.size(3) == 3))
throw Exception ("\'rgb\' colourmap only applies to 4D images with 3 volumes");
if (get_options ("lower").size()) {
WARN ("Option -lower ignored: not compatible with \'rgb\' colourmap (a minimum of 0.0 is assumed)");
}
} else {
if (!(H_in.ndim() == 3 || (H_in.ndim() == 4 && H_in.size(3) == 1)))
throw Exception ("For standard colour maps, command expects a 3D image as input");
if (get_options ("colour").size()) {
WARN ("Option -colour ignored: only applies if \'colour\' colourmap is used");
}
}
auto in = H_in.get_image<float>();
float lower = colourmap.is_rgb ? 0.0 : get_option_value ("lower", NaN);
float upper = get_option_value ("upper", NaN);
if (!std::isfinite (lower) || !std::isfinite (upper)) {
float image_min = NaN, image_max = NaN;
min_max (in, image_min, image_max);
if (colourmap.is_rgb) { // RGB
image_max = std::max (MR::abs (image_min), MR::abs (image_max));
} else {
if (!std::isfinite (lower)) {
if (!std::isfinite (image_min))
throw Exception ("Unable to determine minimum value from image");
lower = image_min;
}
}
if (!std::isfinite (upper)) {
if (!std::isfinite (image_max))
throw Exception ("Unable to determine maximum value from image");
upper = image_max;
}
}
const float multiplier = 1.0f / (upper - lower);
auto scale = [&] (const float value) { return std::max (0.0f, std::min (1.0f, multiplier * (value - lower))); };
Header H_out (H_in);
H_out.ndim() = 4;
H_out.size(3) = 3;
Stride::set (H_out, Stride::contiguous_along_axis (3, H_out));
H_out.datatype() = DataType::Float32;
H_out.datatype().set_byte_order_native();
auto out = Image<float>::create (argument[2], H_out);
if (colourmap.is_colour) {
assert (fixed_colour.allFinite());
for (auto l_outer = Loop ("Applying fixed RGB colour to greyscale image", H_in) (in, out); l_outer; ++l_outer) {
const float amplitude = std::max (0.0f, std::min (1.0f, scale (in.value())));
for (auto l_inner = Loop(3) (out); l_inner; ++l_inner)
out.value() = amplitude * fixed_colour[out.index(3)];
}
} else if (colourmap.is_rgb) {
for (auto l_outer = Loop ("Scaling RGB colour image", H_in) (in, out); l_outer; ++l_outer)
out.value() = scale (in.value());
} else {
const ColourMap::Entry::basic_map_fn& map_fn = colourmap.basic_mapping;
for (auto l_outer = Loop ("Mapping intensities to RGB colours", H_in) (in, out); l_outer; ++l_outer) {
const Eigen::Array3f colour = map_fn (scale (in.value()));
for (auto l_inner = Loop(3) (out); l_inner; ++l_inner)
out.value() = colour[out.index(3)];
}
}
}
<|endoftext|> |
<commit_before>#include <QLocalServer>
#include <QLocalSocket>
#include <QtCore/QEventLoop>
#include <QtCore/QVariant>
#include <QtTest/QtTest>
#include "json/qjsondocument.h"
#include "qjsonrpcservice.h"
#include "qjsonrpcmessage.h"
class TestQJsonRpcServiceProvider: public QObject
{
Q_OBJECT
private Q_SLOTS:
void initTestCase();
void cleanupTestCase();
void init();
void cleanup();
void testServiceProviderNoParameter();
void testServiceProviderSingleParameter();
void testServiceProviderMultiparameter();
void testServiceProviderInvalidArgs();
void testServiceProviderMethodNotFound();
};
class TestService : public QJsonRpcService
{
Q_OBJECT
public:
TestService(QObject *parent = 0)
: QJsonRpcService(parent)
{
}
~TestService()
{
}
QString serviceName() const
{
return QString("service");
}
public Q_SLOTS:
void noParam() const
{
}
QString singleParam(const QString &string) const
{
return string;
}
QString multipleParam(const QString &first,
const QString &second,
const QString &third) const
{
return first + second + third;
}
};
void TestQJsonRpcServiceProvider::initTestCase()
{
qRegisterMetaType<QJsonRpcMessage>("QJsonRpcMessage");
}
void TestQJsonRpcServiceProvider::cleanupTestCase()
{
}
void TestQJsonRpcServiceProvider::init()
{
}
void TestQJsonRpcServiceProvider::cleanup()
{
}
void TestQJsonRpcServiceProvider::testServiceProviderNoParameter()
{
// Initialize the service provider.
QEventLoop loop;
TestService service;
QLocalServer localServer;
QVERIFY(localServer.listen("test"));
QJsonRpcServiceProvider serviceProvider(&localServer);
serviceProvider.addService(&service);
// Connect to the socket.
QLocalSocket socket;
socket.connectToServer("test");
QJsonRpcServiceSocket serviceSocket(&socket, this);
QSignalSpy spyMessageReceived(&serviceSocket,
SIGNAL(messageReceived(QJsonRpcMessage)));
QJsonRpcMessage request = QJsonRpcMessage::createRequest("service.noParam");
QJsonRpcServiceReply *reply = serviceSocket.sendMessage(request);
connect(&serviceSocket, SIGNAL(messageReceived(QJsonRpcMessage)), &loop, SLOT(quit()));
connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
loop.exec();
QJsonRpcMessage response = reply->response();
QCOMPARE(spyMessageReceived.count(), 0);
QVERIFY(response.errorCode() == 0);
QCOMPARE(request.id(), response.id());
}
void TestQJsonRpcServiceProvider::testServiceProviderSingleParameter()
{
// Initialize the service provider.
QEventLoop loop;
TestService service;
QLocalServer localServer;
QVERIFY(localServer.listen("test"));
QJsonRpcServiceProvider serviceProvider(&localServer);
serviceProvider.addService(&service);
// Connect to the socket.
QLocalSocket socket;
socket.connectToServer("test");
QJsonRpcServiceSocket serviceSocket(&socket, this);
QSignalSpy spyMessageReceived(&serviceSocket,
SIGNAL(messageReceived(QJsonRpcMessage)));
QJsonRpcMessage request = QJsonRpcMessage::createRequest("service.singleParam", QString("single"));
QJsonRpcServiceReply *reply = serviceSocket.sendMessage(request);
connect(&serviceSocket, SIGNAL(messageReceived(QJsonRpcMessage)), &loop, SLOT(quit()));
connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
loop.exec();
QJsonRpcMessage response = reply->response();
QCOMPARE(spyMessageReceived.count(), 0);
QVERIFY(response.errorCode() == 0);
QCOMPARE(request.id(), response.id());
QVERIFY(response.result() == QString("single"));
}
void TestQJsonRpcServiceProvider::testServiceProviderMultiparameter()
{
// Initialize the service provider.
QEventLoop loop;
TestService service;
QLocalServer localServer;
QVERIFY(localServer.listen("test"));
QJsonRpcServiceProvider serviceProvider(&localServer);
serviceProvider.addService(&service);
// Connect to the socket.
QLocalSocket socket;
socket.connectToServer("test");
QJsonRpcServiceSocket serviceSocket(&socket, this);
QSignalSpy spyMessageReceived(&serviceSocket,
SIGNAL(messageReceived(QJsonRpcMessage)));
QJsonRpcMessage request = QJsonRpcMessage::createRequest("service.multipleParam",
QVariantList() << QVariant(QString("a"))
<< QVariant(QString("b"))
<< QVariant(QString("c")));
QJsonRpcServiceReply *reply = serviceSocket.sendMessage(request);
connect(&serviceSocket, SIGNAL(messageReceived(QJsonRpcMessage)), &loop, SLOT(quit()));
connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
loop.exec();
QJsonRpcMessage response = reply->response();
QCOMPARE(spyMessageReceived.count(), 0);
QVERIFY(response.errorCode() == 0);
QCOMPARE(request.id(), response.id());
QVERIFY(response.result() == QString("abc"));
}
void TestQJsonRpcServiceProvider::testServiceProviderInvalidArgs()
{
// Initialize the service provider.
QEventLoop loop;
TestService service;
QLocalServer localServer;
QVERIFY(localServer.listen("test"));
QJsonRpcServiceProvider serviceProvider(&localServer);
serviceProvider.addService(&service);
// Connect to the socket.
QLocalSocket socket;
socket.connectToServer("test");
QJsonRpcServiceSocket serviceSocket(&socket, this);
QSignalSpy spyMessageReceived(&serviceSocket,
SIGNAL(messageReceived(QJsonRpcMessage)));
QJsonRpcMessage request = QJsonRpcMessage::createRequest("service.noParam",
QVariantList() << false);
QJsonRpcServiceReply *reply = serviceSocket.sendMessage(request);
connect(&serviceSocket, SIGNAL(messageReceived(QJsonRpcMessage)), &loop, SLOT(quit()));
connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
loop.exec();
QCOMPARE(spyMessageReceived.count(), 1);
if (spyMessageReceived.count() == 1) {
QVariant message = spyMessageReceived.takeFirst().at(0);
QJsonRpcMessage error = message.value<QJsonRpcMessage>();
QCOMPARE(request.id(), error.id());
QVERIFY(error.errorCode() == QJsonRpc::InvalidParams);
}
}
void TestQJsonRpcServiceProvider::testServiceProviderMethodNotFound()
{
// Initialize the service provider.
QEventLoop loop;
TestService service;
QLocalServer localServer;
QVERIFY(localServer.listen("test"));
QJsonRpcServiceProvider serviceProvider(&localServer);
serviceProvider.addService(&service);
// Connect to the socket.
QLocalSocket socket;
socket.connectToServer("test");
QJsonRpcServiceSocket serviceSocket(&socket, this);
QSignalSpy spyMessageReceived(&serviceSocket,
SIGNAL(messageReceived(QJsonRpcMessage)));
QJsonRpcMessage request = QJsonRpcMessage::createRequest("service.doesNotExist");
QJsonRpcServiceReply *reply = serviceSocket.sendMessage(request);
connect(&serviceSocket, SIGNAL(messageReceived(QJsonRpcMessage)), &loop, SLOT(quit()));
connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
loop.exec();
QCOMPARE(spyMessageReceived.count(), 1);
if (spyMessageReceived.count() == 1) {
QVariant message = spyMessageReceived.takeFirst().at(0);
QJsonRpcMessage error = message.value<QJsonRpcMessage>();
QCOMPARE(request.id(), error.id());
QVERIFY(error.errorCode() == QJsonRpc::MethodNotFound);
}
}
QTEST_MAIN(TestQJsonRpcServiceProvider)
#include "tst_qjsonrpcserviceprovider.moc"
<commit_msg>duplicated tests for tcp support<commit_after>#include <QLocalServer>
#include <QLocalSocket>
#include <QTcpServer>
#include <QTcpSocket>
#include <QtCore/QEventLoop>
#include <QtCore/QVariant>
#include <QtTest/QtTest>
#include "json/qjsondocument.h"
#include "qjsonrpcservice.h"
#include "qjsonrpcmessage.h"
class TestQJsonRpcServiceProvider: public QObject
{
Q_OBJECT
private Q_SLOTS:
void initTestCase();
void cleanupTestCase();
void init();
void cleanup();
// Local Server
void testLocalServiceProviderNoParameter();
void testLocalServiceProviderSingleParameter();
void testLocalServiceProviderMultiparameter();
void testLocalServiceProviderInvalidArgs();
void testLocalServiceProviderMethodNotFound();
// TCP Server
void testTcpServiceProviderNoParameter();
void testTcpServiceProviderSingleParameter();
void testTcpServiceProviderMultiparameter();
void testTcpServiceProviderInvalidArgs();
void testTcpServiceProviderMethodNotFound();
};
class TestService : public QJsonRpcService
{
Q_OBJECT
public:
TestService(QObject *parent = 0)
: QJsonRpcService(parent)
{
}
~TestService()
{
}
QString serviceName() const
{
return QString("service");
}
public Q_SLOTS:
void noParam() const
{
}
QString singleParam(const QString &string) const
{
return string;
}
QString multipleParam(const QString &first,
const QString &second,
const QString &third) const
{
return first + second + third;
}
};
void TestQJsonRpcServiceProvider::initTestCase()
{
qRegisterMetaType<QJsonRpcMessage>("QJsonRpcMessage");
}
void TestQJsonRpcServiceProvider::cleanupTestCase()
{
}
void TestQJsonRpcServiceProvider::init()
{
}
void TestQJsonRpcServiceProvider::cleanup()
{
}
void TestQJsonRpcServiceProvider::testLocalServiceProviderNoParameter()
{
// Initialize the service provider.
QEventLoop loop;
TestService service;
QLocalServer localServer;
QVERIFY(localServer.listen("test"));
QJsonRpcServiceProvider serviceProvider(&localServer);
serviceProvider.addService(&service);
// Connect to the socket.
QLocalSocket socket;
socket.connectToServer("test");
QVERIFY(socket.waitForConnected());
QJsonRpcServiceSocket serviceSocket(&socket, this);
QSignalSpy spyMessageReceived(&serviceSocket,
SIGNAL(messageReceived(QJsonRpcMessage)));
QJsonRpcMessage request = QJsonRpcMessage::createRequest("service.noParam");
QJsonRpcServiceReply *reply = serviceSocket.sendMessage(request);
connect(&serviceSocket, SIGNAL(messageReceived(QJsonRpcMessage)), &loop, SLOT(quit()));
connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
loop.exec();
QJsonRpcMessage response = reply->response();
QCOMPARE(spyMessageReceived.count(), 0);
QVERIFY(response.errorCode() == 0);
QCOMPARE(request.id(), response.id());
}
void TestQJsonRpcServiceProvider::testLocalServiceProviderSingleParameter()
{
// Initialize the service provider.
QEventLoop loop;
TestService service;
QLocalServer localServer;
QVERIFY(localServer.listen("test"));
QJsonRpcServiceProvider serviceProvider(&localServer);
serviceProvider.addService(&service);
// Connect to the socket.
QLocalSocket socket;
socket.connectToServer("test");
QVERIFY(socket.waitForConnected());
QJsonRpcServiceSocket serviceSocket(&socket, this);
QSignalSpy spyMessageReceived(&serviceSocket,
SIGNAL(messageReceived(QJsonRpcMessage)));
QJsonRpcMessage request = QJsonRpcMessage::createRequest("service.singleParam", QString("single"));
QJsonRpcServiceReply *reply = serviceSocket.sendMessage(request);
connect(&serviceSocket, SIGNAL(messageReceived(QJsonRpcMessage)), &loop, SLOT(quit()));
connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
loop.exec();
QJsonRpcMessage response = reply->response();
QCOMPARE(spyMessageReceived.count(), 0);
QVERIFY(response.errorCode() == 0);
QCOMPARE(request.id(), response.id());
QVERIFY(response.result() == QString("single"));
}
void TestQJsonRpcServiceProvider::testLocalServiceProviderMultiparameter()
{
// Initialize the service provider.
QEventLoop loop;
TestService service;
QLocalServer localServer;
QVERIFY(localServer.listen("test"));
QJsonRpcServiceProvider serviceProvider(&localServer);
serviceProvider.addService(&service);
// Connect to the socket.
QLocalSocket socket;
socket.connectToServer("test");
QVERIFY(socket.waitForConnected());
QJsonRpcServiceSocket serviceSocket(&socket, this);
QSignalSpy spyMessageReceived(&serviceSocket,
SIGNAL(messageReceived(QJsonRpcMessage)));
QJsonRpcMessage request = QJsonRpcMessage::createRequest("service.multipleParam",
QVariantList() << QVariant(QString("a"))
<< QVariant(QString("b"))
<< QVariant(QString("c")));
QJsonRpcServiceReply *reply = serviceSocket.sendMessage(request);
connect(&serviceSocket, SIGNAL(messageReceived(QJsonRpcMessage)), &loop, SLOT(quit()));
connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
loop.exec();
QJsonRpcMessage response = reply->response();
QCOMPARE(spyMessageReceived.count(), 0);
QVERIFY(response.errorCode() == 0);
QCOMPARE(request.id(), response.id());
QVERIFY(response.result() == QString("abc"));
}
void TestQJsonRpcServiceProvider::testLocalServiceProviderInvalidArgs()
{
// Initialize the service provider.
QEventLoop loop;
TestService service;
QLocalServer localServer;
QVERIFY(localServer.listen("test"));
QJsonRpcServiceProvider serviceProvider(&localServer);
serviceProvider.addService(&service);
// Connect to the socket.
QLocalSocket socket;
socket.connectToServer("test");
QVERIFY(socket.waitForConnected());
QJsonRpcServiceSocket serviceSocket(&socket, this);
QSignalSpy spyMessageReceived(&serviceSocket,
SIGNAL(messageReceived(QJsonRpcMessage)));
QJsonRpcMessage request = QJsonRpcMessage::createRequest("service.noParam",
QVariantList() << false);
QJsonRpcServiceReply *reply = serviceSocket.sendMessage(request);
connect(&serviceSocket, SIGNAL(messageReceived(QJsonRpcMessage)), &loop, SLOT(quit()));
connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
loop.exec();
QCOMPARE(spyMessageReceived.count(), 1);
if (spyMessageReceived.count() == 1) {
QVariant message = spyMessageReceived.takeFirst().at(0);
QJsonRpcMessage error = message.value<QJsonRpcMessage>();
QCOMPARE(request.id(), error.id());
QVERIFY(error.errorCode() == QJsonRpc::InvalidParams);
}
}
void TestQJsonRpcServiceProvider::testLocalServiceProviderMethodNotFound()
{
// Initialize the service provider.
QEventLoop loop;
TestService service;
QLocalServer localServer;
QVERIFY(localServer.listen("test"));
QJsonRpcServiceProvider serviceProvider(&localServer);
serviceProvider.addService(&service);
// Connect to the socket.
QLocalSocket socket;
socket.connectToServer("test");
QVERIFY(socket.waitForConnected());
QJsonRpcServiceSocket serviceSocket(&socket, this);
QSignalSpy spyMessageReceived(&serviceSocket,
SIGNAL(messageReceived(QJsonRpcMessage)));
QJsonRpcMessage request = QJsonRpcMessage::createRequest("service.doesNotExist");
QJsonRpcServiceReply *reply = serviceSocket.sendMessage(request);
connect(&serviceSocket, SIGNAL(messageReceived(QJsonRpcMessage)), &loop, SLOT(quit()));
connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
loop.exec();
QCOMPARE(spyMessageReceived.count(), 1);
if (spyMessageReceived.count() == 1) {
QVariant message = spyMessageReceived.takeFirst().at(0);
QJsonRpcMessage error = message.value<QJsonRpcMessage>();
QCOMPARE(request.id(), error.id());
QVERIFY(error.errorCode() == QJsonRpc::MethodNotFound);
}
}
void TestQJsonRpcServiceProvider::testTcpServiceProviderNoParameter()
{
// Initialize the service provider.
QEventLoop loop;
TestService service;
QTcpServer tcpServer;
QVERIFY(tcpServer.listen(QHostAddress::LocalHost, 5555));
QJsonRpcServiceProvider serviceProvider(&tcpServer);
serviceProvider.addService(&service);
// Connect to the socket.
QTcpSocket socket;
socket.connectToHost(QHostAddress::LocalHost, 5555);
QVERIFY(socket.waitForConnected());
QJsonRpcServiceSocket serviceSocket(&socket, this);
QSignalSpy spyMessageReceived(&serviceSocket,
SIGNAL(messageReceived(QJsonRpcMessage)));
QJsonRpcMessage request = QJsonRpcMessage::createRequest("service.noParam");
QJsonRpcServiceReply *reply = serviceSocket.sendMessage(request);
connect(&serviceSocket, SIGNAL(messageReceived(QJsonRpcMessage)), &loop, SLOT(quit()));
connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
loop.exec();
QJsonRpcMessage response = reply->response();
QCOMPARE(spyMessageReceived.count(), 0);
QVERIFY(response.errorCode() == 0);
QCOMPARE(request.id(), response.id());
}
void TestQJsonRpcServiceProvider::testTcpServiceProviderSingleParameter()
{
// Initialize the service provider.
QEventLoop loop;
TestService service;
QTcpServer tcpServer;
QVERIFY(tcpServer.listen(QHostAddress::LocalHost, 5555));
QJsonRpcServiceProvider serviceProvider(&tcpServer);
serviceProvider.addService(&service);
// Connect to the socket.
QTcpSocket socket;
socket.connectToHost(QHostAddress::LocalHost, 5555);
QVERIFY(socket.waitForConnected());
QJsonRpcServiceSocket serviceSocket(&socket, this);
QSignalSpy spyMessageReceived(&serviceSocket,
SIGNAL(messageReceived(QJsonRpcMessage)));
QJsonRpcMessage request = QJsonRpcMessage::createRequest("service.singleParam", QString("single"));
QJsonRpcServiceReply *reply = serviceSocket.sendMessage(request);
connect(&serviceSocket, SIGNAL(messageReceived(QJsonRpcMessage)), &loop, SLOT(quit()));
connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
loop.exec();
QJsonRpcMessage response = reply->response();
QCOMPARE(spyMessageReceived.count(), 0);
QVERIFY(response.errorCode() == 0);
QCOMPARE(request.id(), response.id());
QVERIFY(response.result() == QString("single"));
}
void TestQJsonRpcServiceProvider::testTcpServiceProviderMultiparameter()
{
// Initialize the service provider.
QEventLoop loop;
TestService service;
QTcpServer tcpServer;
QVERIFY(tcpServer.listen(QHostAddress::LocalHost, 5555));
QJsonRpcServiceProvider serviceProvider(&tcpServer);
serviceProvider.addService(&service);
// Connect to the socket.
QTcpSocket socket;
socket.connectToHost(QHostAddress::LocalHost, 5555);
QVERIFY(socket.waitForConnected());
QJsonRpcServiceSocket serviceSocket(&socket, this);
QSignalSpy spyMessageReceived(&serviceSocket,
SIGNAL(messageReceived(QJsonRpcMessage)));
QJsonRpcMessage request = QJsonRpcMessage::createRequest("service.multipleParam",
QVariantList() << QVariant(QString("a"))
<< QVariant(QString("b"))
<< QVariant(QString("c")));
QJsonRpcServiceReply *reply = serviceSocket.sendMessage(request);
connect(&serviceSocket, SIGNAL(messageReceived(QJsonRpcMessage)), &loop, SLOT(quit()));
connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
loop.exec();
QJsonRpcMessage response = reply->response();
QCOMPARE(spyMessageReceived.count(), 0);
QVERIFY(response.errorCode() == 0);
QCOMPARE(request.id(), response.id());
QVERIFY(response.result() == QString("abc"));
}
void TestQJsonRpcServiceProvider::testTcpServiceProviderInvalidArgs()
{
// Initialize the service provider.
QEventLoop loop;
TestService service;
QTcpServer tcpServer;
QVERIFY(tcpServer.listen(QHostAddress::LocalHost, 5555));
QJsonRpcServiceProvider serviceProvider(&tcpServer);
serviceProvider.addService(&service);
// Connect to the socket.
QTcpSocket socket;
socket.connectToHost(QHostAddress::LocalHost, 5555);
QVERIFY(socket.waitForConnected());
QJsonRpcServiceSocket serviceSocket(&socket, this);
QSignalSpy spyMessageReceived(&serviceSocket,
SIGNAL(messageReceived(QJsonRpcMessage)));
QJsonRpcMessage request = QJsonRpcMessage::createRequest("service.noParam",
QVariantList() << false);
QJsonRpcServiceReply *reply = serviceSocket.sendMessage(request);
connect(&serviceSocket, SIGNAL(messageReceived(QJsonRpcMessage)), &loop, SLOT(quit()));
connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
loop.exec();
QCOMPARE(spyMessageReceived.count(), 1);
if (spyMessageReceived.count() == 1) {
QVariant message = spyMessageReceived.takeFirst().at(0);
QJsonRpcMessage error = message.value<QJsonRpcMessage>();
QCOMPARE(request.id(), error.id());
QVERIFY(error.errorCode() == QJsonRpc::InvalidParams);
}
}
void TestQJsonRpcServiceProvider::testTcpServiceProviderMethodNotFound()
{
// Initialize the service provider.
QEventLoop loop;
TestService service;
QTcpServer tcpServer;
QVERIFY(tcpServer.listen(QHostAddress::LocalHost, 5555));
QJsonRpcServiceProvider serviceProvider(&tcpServer);
serviceProvider.addService(&service);
// Connect to the socket.
QTcpSocket socket;
socket.connectToHost(QHostAddress::LocalHost, 5555);
QVERIFY(socket.waitForConnected());
QJsonRpcServiceSocket serviceSocket(&socket, this);
QSignalSpy spyMessageReceived(&serviceSocket,
SIGNAL(messageReceived(QJsonRpcMessage)));
QJsonRpcMessage request = QJsonRpcMessage::createRequest("service.doesNotExist");
QJsonRpcServiceReply *reply = serviceSocket.sendMessage(request);
connect(&serviceSocket, SIGNAL(messageReceived(QJsonRpcMessage)), &loop, SLOT(quit()));
connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
loop.exec();
QCOMPARE(spyMessageReceived.count(), 1);
if (spyMessageReceived.count() == 1) {
QVariant message = spyMessageReceived.takeFirst().at(0);
QJsonRpcMessage error = message.value<QJsonRpcMessage>();
QCOMPARE(request.id(), error.id());
QVERIFY(error.errorCode() == QJsonRpc::MethodNotFound);
}
}
QTEST_MAIN(TestQJsonRpcServiceProvider)
#include "tst_qjsonrpcserviceprovider.moc"
<|endoftext|> |
<commit_before>#include "rb_tree.h"
#include <stack>
void RB_Tree::Insert(TreeNode* z){
TreeNode* y = NULL;
TreeNode* x = root;
while(x!=NULL){
y=x;
if(z->data<x->data)
x=x->lchild;
else if(z->data>x->data)
x=x->rchild;
}
z->parent=y;
if(NULL==y){
root=z;
}else if(z->data<y->data){
y->lchild=z;
}else{
y->rchild=z;
}
z->lchild=NULL;
z->rchild=NULL;
z->color = RED;
InsertFixup(z);
}
/*--fixup case:-------------------------------------------------------------------
* 1. 如果当前结点的父结点是红色且祖父结点的另一个子结点(叔叔结点)是红色
* 2. 当前结点的父结点是红色,叔叔结点是黑色,当前结点是其父结点的右子
* 3. 当前结点的父结点是红色,叔叔结点是黑色,当前结点是其父结点的左子
*-----------------------------------------------------------------------------*/
void RB_Tree::InsertFixup(TreeNode* z){
TreeNode* y;
if(z->parent==NULL){
root->color=BLACK;
return;
}
while(z->parent!=NULL && z->parent->color==RED){
if(NULL == z->parent->parent) break;
if(z->parent==z->parent->parent->lchild){
y=z->parent->parent->rchild;
if(y!=NULL && y->color==RED){ // case 1
z->parent->color=BLACK;
y->color=BLACK;
z->parent->parent->color=RED;
z=z->parent->parent;
}else{
if(z==z->parent->rchild){// case 2
z=z->parent;
LeftRotate(z);
}
// case 3
z->parent->color=BLACK;
z->parent->parent->color=RED;
RightRotate(z->parent->parent);
}
}else{
y=z->parent->parent->lchild;
if(y!=NULL && y->color==RED){
z->parent->color=BLACK;
y->color=BLACK;
z->parent->parent->color=RED;
z=z->parent->parent;
}else{
if(z==z->parent->lchild){
z=z->parent;
RightRotate(z);
}
z->parent->color=BLACK;
z->parent->parent->color=RED;
LeftRotate(z->parent->parent);
}
}
}
root->color=BLACK;
}
void RB_Tree::LeftRotate(TreeNode* x){
TreeNode* y=x->rchild;
x->rchild=y->lchild;
if(y->lchild!=NULL){
y->lchild->parent=x;
}
y->parent=x->parent;
if(x->parent==NULL){
root=y;
}else if(x==x->parent->lchild) x->parent->lchild=y;
else x->parent->rchild=y;
y->lchild=x;
x->parent=y;
}
void RB_Tree::RightRotate(TreeNode* x){
TreeNode* y=x->lchild;
x->lchild=y->rchild;
if(y->rchild!=NULL){
y->rchild->parent=x;
}
y->parent=x->parent;
if(x->parent==NULL){
root=y;
}else if(x==x->parent->lchild) x->parent->lchild=y;
else x->parent->rchild=y;
y->rchild=x;
x->parent=y;
}
/*-----------------------------------------------------------------------------
* 1. 没有儿子,即为叶结点。直接把父结点的对应儿子指针设为NULL,删除儿子结点就OK了。
* 2. 只有一个儿子。那么把父结点的相应儿子指针指向儿子的独生子,删除儿子结点也OK了。
* 3. 有两个儿子。我们可以选择左儿子中的最大元素或者右儿子中的最小元素放到待删除
* 结点的位置,就可以保证结构的不变。
*-----------------------------------------------------------------------------*/
TreeNode* RB_Tree::Delete(TreeNode* z){
TreeNode* y;
TreeNode* x=NULL;
if(z->lchild == NULL || z->rchild == NULL) y=z;
else y=TreeSuccessor(z);
if(y->lchild != NULL) x=y->lchild;
else if(y->rchild!=NULL) x=y->rchild;
if(NULL != x) x->parent=y->parent;
if(y->parent == NULL) root=x;
else if(y==y->parent->lchild) y->parent->lchild=x;
else y->parent->rchild=x;
if(y!=z) z->data=y->data;
if(y->color==BLACK) DeleteFixup(x);
return y;
}
TreeNode* RB_Tree::Delete(int data){
return Delete(Search(root, data));
}
TreeNode* RB_Tree::Search(TreeNode* n, int data){
if(data==n->data) return n;
if(data<n->data) return Search(n->lchild, data);
return Search(n->rchild, data);
}
/*-----------------------------------------------------------------------------
* 1. 当前结点是黑+黑且兄弟结点为红色(此时父结点和兄弟结点的子结点分为黑)
* 2. 当前结点是黑加黑且兄弟是黑色且兄弟结点的两个子结点全为黑色
* 3. 当前结点颜色是黑+黑,兄弟结点是黑色,兄弟的左子是红色,右子是黑色
* 4. 当前结点颜色是黑-黑色,它的兄弟结点是黑色,但是兄弟结点的右子是红色,
* 兄弟结点左子的颜色任意
*-----------------------------------------------------------------------------*/
void RB_Tree::DeleteFixup(TreeNode* x){
if(NULL == x) return;
TreeNode* y;
while(x!=root && x->color==BLACK){
if(NULL == x->parent) break;
if(x==x->parent->lchild){
y=x->parent->rchild;
if(y->color==RED){// case 1
y->color=BLACK;
x->parent->color=RED;
LeftRotate(x->parent);
y=x->parent->rchild;
}
if(NULL == y->lchild && NULL == y->rchild) break;
if(y->lchild->color==BLACK && y->rchild->color==BLACK){ // case 2
y->color=RED;
x=x->parent;
}else{
if( y->lchild->color== RED && y->rchild->color==BLACK){// case 3
y->lchild->color=BLACK;
y->color=RED;
RightRotate(y);
y=x->parent->rchild;
}
// case 4
y->color=x->parent->color;
x->parent->color=BLACK;
y->rchild->color=BLACK;
LeftRotate(x->parent);
x=root;
}
}else{
y=x->parent->lchild;
if(y->color==RED){
y->color=BLACK;
x->parent->color=RED;
RightRotate(x->parent);
y=x->parent->lchild;
}
if(NULL == y->lchild && NULL == y->rchild) break;
if(y->lchild->color == BLACK && y->rchild->color==BLACK){
y->color=RED;
x=x->parent;
}else{
if(y->lchild->color==BLACK){
y->color=RED;
y->rchild->color=BLACK;
LeftRotate(y);
y=x->parent->lchild;
}
y->color=x->parent->color;
x->parent->color=BLACK;
y->lchild->color=BLACK;
RightRotate(x->parent);
x=root;
}
}
}
x->color=BLACK;
}
TreeNode* RB_Tree::TreeSuccessor(TreeNode* x){
if(x->rchild!=NULL) return TreeMinimum(x->rchild);
TreeNode* y=x->parent;
while(y!=NULL && x==y->rchild){
x=y;
y=y->parent;
}
return y;
}
TreeNode* RB_Tree::TreeMinimum(TreeNode* x){
while(x->lchild!=NULL) x=x->lchild;
return x;
}
void RB_Tree::Traverse(TreeNode* n, int order){
if(NULL == n) return;
// pre
if(order==-1) cout << n->data << "(" << n->color << ") ";
if(n->lchild){
Traverse(n->lchild, order);
}
// in
if(order==0) cout << n->data << "(" << n->color << ") ";
if(n->rchild){
Traverse(n->rchild, order);
}
// beh
if(order==1) cout << n->data << "(" << n->color << ") ";
}
void RB_Tree::InOrderTraverse(){
stack<TreeNode*> stk;
TreeNode* p = root;
while(p!=NULL || !stk.empty()){
while(p!=NULL){
stk.push(p);
p=p->lchild;
}
if(!stk.empty()){
cout << stk.top()->data << "(" << stk.top()->color << ")" << " ";
p=stk.top()->rchild;
stk.pop();
}
}
}
/*-----------------------------------------------------------------------------
* 9
* 4 14
* 1 6 12 18
* 0 2 5 7 11 13 16 19
* 3 8 10 15 17
*-----------------------------------------------------------------------------*/
int main(){
int arr[20]={12,1,9,2,0,11,7,19,4,15,18,5,14,13,10,16,6,3,8,17};
RB_Tree rb = RB_Tree();
for(int i=0;i<20;i++) rb.Insert(new TreeNode(arr[i]));
rb.InOrderTraverse();
cout << endl;
cout << "pre:" << endl;
rb.Traverse(rb.root, -1);
cout << endl;
cout << "in:" << endl;
rb.Traverse(rb.root, 0);
cout << endl;
cout << "beh:" << endl;
rb.Traverse(rb.root, 1);
cout << endl;
return 0;
}
<commit_msg>IMP..<commit_after>#include "rb_tree.h"
#include <stack>
void RB_Tree::Insert(TreeNode* z){
TreeNode* y = NULL;
TreeNode* x = root;
while(x!=NULL){
y=x;
if(z->data<x->data)
x=x->lchild;
else if(z->data>x->data)
x=x->rchild;
}
z->parent=y;
if(NULL==y){
root=z;
}else if(z->data<y->data){
y->lchild=z;
}else{
y->rchild=z;
}
z->lchild=NULL;
z->rchild=NULL;
z->color = RED;
InsertFixup(z);
}
/*--fixup case:-------------------------------------------------------------------
* 1. 如果当前结点的父结点是红色且祖父结点的另一个子结点(叔叔结点)是红色
* 2. 当前结点的父结点是红色,叔叔结点是黑色,当前结点是其父结点的右子
* 3. 当前结点的父结点是红色,叔叔结点是黑色,当前结点是其父结点的左子
*-----------------------------------------------------------------------------*/
void RB_Tree::InsertFixup(TreeNode* z){
TreeNode* y;
if(z->parent==NULL){
root->color=BLACK;
return;
}
while(z->parent!=NULL && z->parent->color==RED){
if(NULL == z->parent->parent) break;
if(z->parent==z->parent->parent->lchild){
y=z->parent->parent->rchild;
if(y!=NULL && y->color==RED){ // case 1
z->parent->color=BLACK;
y->color=BLACK;
z->parent->parent->color=RED;
z=z->parent->parent;
}else{
if(z==z->parent->rchild){// case 2
z=z->parent;
LeftRotate(z);
}
// case 3
z->parent->color=BLACK;
z->parent->parent->color=RED;
RightRotate(z->parent->parent);
}
}else{
y=z->parent->parent->lchild;
if(y!=NULL && y->color==RED){
z->parent->color=BLACK;
y->color=BLACK;
z->parent->parent->color=RED;
z=z->parent->parent;
}else{
if(z==z->parent->lchild){
z=z->parent;
RightRotate(z);
}
z->parent->color=BLACK;
z->parent->parent->color=RED;
LeftRotate(z->parent->parent);
}
}
}
root->color=BLACK;
}
void RB_Tree::LeftRotate(TreeNode* x){
TreeNode* y=x->rchild;
x->rchild=y->lchild;
if(y->lchild!=NULL){
y->lchild->parent=x;
}
y->parent=x->parent;
if(x->parent==NULL){
root=y;
}else if(x==x->parent->lchild) x->parent->lchild=y;
else x->parent->rchild=y;
y->lchild=x;
x->parent=y;
}
void RB_Tree::RightRotate(TreeNode* x){
TreeNode* y=x->lchild;
x->lchild=y->rchild;
if(y->rchild!=NULL){
y->rchild->parent=x;
}
y->parent=x->parent;
if(x->parent==NULL){
root=y;
}else if(x==x->parent->lchild) x->parent->lchild=y;
else x->parent->rchild=y;
y->rchild=x;
x->parent=y;
}
/*-----------------------------------------------------------------------------
* 1. 没有儿子,即为叶结点。直接把父结点的对应儿子指针设为NULL,删除儿子结点就OK了。
* 2. 只有一个儿子。那么把父结点的相应儿子指针指向儿子的独生子,删除儿子结点也OK了。
* 3. 有两个儿子。我们可以选择左儿子中的最大元素或者右儿子中的最小元素放到待删除
* 结点的位置,就可以保证结构的不变。
*-----------------------------------------------------------------------------*/
TreeNode* RB_Tree::Delete(TreeNode* z){
TreeNode* x, *y;
if(z->lchild == NULL || z->rchild == NULL) y=z;
else y=TreeSuccessor(z);
if(y->lchild != NULL) x=y->lchild;
else x=y->rchild;
if(NULL != x) x->parent=y->parent;
if(y->parent == NULL) root=x;
else if(y==y->parent->lchild) y->parent->lchild=x;
else y->parent->rchild=x;
if(y!=z) z->data=y->data;
if(y->color==BLACK) DeleteFixup(x);
return y;
}
TreeNode* RB_Tree::Delete(int data){
return Delete(Search(root, data));
}
TreeNode* RB_Tree::Search(TreeNode* n, int data){
if(data==n->data) return n;
if(data<n->data) return Search(n->lchild, data);
return Search(n->rchild, data);
}
/*-----------------------------------------------------------------------------
* 1. 当前结点是黑+黑且兄弟结点为红色(此时父结点和兄弟结点的子结点分为黑)
* 2. 当前结点是黑加黑且兄弟是黑色且兄弟结点的两个子结点全为黑色
* 3. 当前结点颜色是黑+黑,兄弟结点是黑色,兄弟的左子是红色,右子是黑色
* 4. 当前结点颜色是黑-黑色,它的兄弟结点是黑色,但是兄弟结点的右子是红色,
* 兄弟结点左子的颜色任意
*-----------------------------------------------------------------------------*/
void RB_Tree::DeleteFixup(TreeNode* x){
if(NULL == x) return;
TreeNode* y;
while(x!=root && x->color==BLACK){
if(NULL == x->parent) break;
if(x==x->parent->lchild){
y=x->parent->rchild;
if(y->color==RED){// case 1
y->color=BLACK;
x->parent->color=RED;
LeftRotate(x->parent);
y=x->parent->rchild;
}
if(NULL == y->lchild && NULL == y->rchild) break;
if(y->lchild->color==BLACK && y->rchild->color==BLACK){ // case 2
y->color=RED;
x=x->parent;
}else{
if( y->lchild->color== RED && y->rchild->color==BLACK){// case 3
y->lchild->color=BLACK;
y->color=RED;
RightRotate(y);
y=x->parent->rchild;
}
// case 4
y->color=x->parent->color;
x->parent->color=BLACK;
y->rchild->color=BLACK;
LeftRotate(x->parent);
x=root;
}
}else{
y=x->parent->lchild;
if(y->color==RED){
y->color=BLACK;
x->parent->color=RED;
RightRotate(x->parent);
y=x->parent->lchild;
}
if(NULL == y->lchild && NULL == y->rchild) break;
if(y->lchild->color == BLACK && y->rchild->color==BLACK){
y->color=RED;
x=x->parent;
}else{
if(y->lchild->color==BLACK){
y->color=RED;
y->rchild->color=BLACK;
LeftRotate(y);
y=x->parent->lchild;
}
y->color=x->parent->color;
x->parent->color=BLACK;
y->lchild->color=BLACK;
RightRotate(x->parent);
x=root;
}
}
}
x->color=BLACK;
}
TreeNode* RB_Tree::TreeSuccessor(TreeNode* x){
if(x->rchild!=NULL) return TreeMinimum(x->rchild);
TreeNode* y=x->parent;
while(y!=NULL && x==y->rchild){
x=y;
y=y->parent;
}
return y;
}
TreeNode* RB_Tree::TreeMinimum(TreeNode* x){
while(x->lchild!=NULL) x=x->lchild;
return x;
}
void RB_Tree::Traverse(TreeNode* n, int order){
if(NULL == n) return;
// pre
if(order==-1) cout << n->data << "(" << n->color << ") ";
if(n->lchild){
Traverse(n->lchild, order);
}
// in
if(order==0) cout << n->data << "(" << n->color << ") ";
if(n->rchild){
Traverse(n->rchild, order);
}
// beh
if(order==1) cout << n->data << "(" << n->color << ") ";
}
void RB_Tree::InOrderTraverse(){
stack<TreeNode*> stk;
TreeNode* p = root;
while(p!=NULL || !stk.empty()){
while(p!=NULL){
stk.push(p);
p=p->lchild;
}
if(!stk.empty()){
cout << stk.top()->data << "(" << stk.top()->color << ")" << " ";
p=stk.top()->rchild;
stk.pop();
}
}
}
/*-----------------------------------------------------------------------------
* 9
* 4 14
* 1 6 12 18
* 0 2 5 7 11 13 16 19
* 3 8 10 15 17
*-----------------------------------------------------------------------------*/
int main(){
int arr[20]={12,1,9,2,0,11,7,19,4,15,18,5,14,13,10,16,6,3,8,17};
RB_Tree rb = RB_Tree();
for(int i=0;i<20;i++) rb.Insert(new TreeNode(arr[i]));
rb.InOrderTraverse();
cout << endl;
cout << "pre:" << endl;
rb.Traverse(rb.root, -1);
cout << endl;
cout << "in:" << endl;
rb.Traverse(rb.root, 0);
cout << endl;
cout << "beh:" << endl;
rb.Traverse(rb.root, 1);
cout << endl;
return 0;
}
<|endoftext|> |
<commit_before>#include <vector>
#include <string>
#include <sstream>
#include <cstring>
#include <boost/range/iterator_range.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/python.hpp>
#include <boost/python/extract.hpp>
#include <boost/python/numeric.hpp>
#include <boost/python/raw_function.hpp>
#include <boost/python/stl_iterator.hpp>
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include "numpy_boost_python.hpp"
#include <amgcl/runtime.hpp>
#include <amgcl/make_solver.hpp>
#include <amgcl/relaxation/as_preconditioner.hpp>
#include <amgcl/preconditioner/cpr.hpp>
#include <amgcl/preconditioner/simple.hpp>
#include <amgcl/adapter/crs_tuple.hpp>
namespace amgcl {
#ifdef AMGCL_PROFILING
profiler<> prof;
#endif
namespace backend {
template <>
struct is_builtin_vector< numpy_boost<double,1> > : boost::true_type {};
}
}
//---------------------------------------------------------------------------
boost::property_tree::ptree make_ptree(const boost::python::dict &args) {
using namespace boost::python;
boost::property_tree::ptree p;
for(stl_input_iterator<tuple> arg(args.items()), end; arg != end; ++arg) {
const char *name = extract<const char*>((*arg)[0]);
const char *type = extract<const char*>((*arg)[1].attr("__class__").attr("__name__"));
if (strcmp(type, "int") == 0)
p.put(name, extract<int>((*arg)[1]));
else
p.put(name, extract<float>((*arg)[1]));
}
return p;
}
//---------------------------------------------------------------------------
struct make_solver {
make_solver(
amgcl::runtime::coarsening::type coarsening,
amgcl::runtime::relaxation::type relaxation,
amgcl::runtime::solver::type solver,
const boost::python::dict &prm,
const numpy_boost<int, 1> &ptr,
const numpy_boost<int, 1> &col,
const numpy_boost<double, 1> &val
)
: n(ptr.num_elements() - 1)
{
boost::property_tree::ptree pt = make_ptree(prm);
pt.put("amg.coarsening.type", coarsening);
pt.put("amg.relaxation.type", relaxation);
pt.put("solver.type", solver);
S = boost::make_shared<Solver>(boost::tie(n, ptr, col, val), pt);
}
PyObject* solve(const numpy_boost<double, 1> &rhs) const {
numpy_boost<double, 1> x(&n);
BOOST_FOREACH(double &v, x) v = 0;
cnv = (*S)(rhs, x);
PyObject *result = x.py_ptr();
Py_INCREF(result);
return result;
}
PyObject* solve(
const numpy_boost<int, 1> &ptr,
const numpy_boost<int, 1> &col,
const numpy_boost<double, 1> &val,
const numpy_boost<double, 1> &rhs
) const
{
numpy_boost<double, 1> x(&n);
BOOST_FOREACH(double &v, x) v = 0;
cnv = (*S)(boost::tie(n, ptr, col, val), rhs, x);
PyObject *result = x.py_ptr();
Py_INCREF(result);
return result;
}
int iterations() const {
return boost::get<0>(cnv);
}
double residual() const {
return boost::get<1>(cnv);
}
std::string repr() const {
std::ostringstream buf;
buf << "pyamgcl solver\n" << S->precond();
return buf.str();
}
private:
typedef amgcl::make_solver<
amgcl::runtime::amg<
amgcl::backend::builtin<double>
>,
amgcl::runtime::iterative_solver<
amgcl::backend::builtin<double>
>
> Solver;
int n;
boost::shared_ptr< Solver > S;
mutable boost::tuple<int, double> cnv;
};
//---------------------------------------------------------------------------
struct make_preconditioner {
make_preconditioner(
amgcl::runtime::coarsening::type coarsening,
amgcl::runtime::relaxation::type relaxation,
const boost::python::dict &prm,
const numpy_boost<int, 1> &ptr,
const numpy_boost<int, 1> &col,
const numpy_boost<double, 1> &val
)
: n(ptr.num_elements() - 1)
{
boost::property_tree::ptree pt = make_ptree(prm);
pt.put("coarsening.type", coarsening);
pt.put("relaxation.type", relaxation);
P = boost::make_shared<Preconditioner>(boost::tie(n, ptr, col, val), pt);
}
PyObject* apply(const numpy_boost<double, 1> &rhs) const {
numpy_boost<double, 1> x(&n);
P->apply(rhs, x);
PyObject *result = x.py_ptr();
Py_INCREF(result);
return result;
}
std::string repr() const {
std::ostringstream buf;
buf << "pyamgcl preconditioner\n" << (*P);
return buf.str();
}
private:
int n;
typedef amgcl::runtime::amg< amgcl::backend::builtin<double> > Preconditioner;
boost::shared_ptr<Preconditioner> P;
};
//---------------------------------------------------------------------------
struct make_cpr {
make_cpr(
const boost::python::dict &prm,
const numpy_boost<int, 1> &ptr,
const numpy_boost<int, 1> &col,
const numpy_boost<double, 1> &val,
const numpy_boost<int, 1> &pm
)
: n(ptr.num_elements() - 1)
{
boost::property_tree::ptree pt(make_ptree(prm));
pt.put("pmask", static_cast<const void*>(pm.data()));
pt.put("pmask_size", n);
P = boost::make_shared<CPR>(boost::tie(n, ptr, col, val), pt);
}
PyObject* apply(const numpy_boost<double, 1> &rhs) const {
numpy_boost<double, 1> x(&n);
P->apply(rhs, x);
PyObject *result = x.py_ptr();
Py_INCREF(result);
return result;
}
private:
int n;
typedef amgcl::preconditioner::cpr<
amgcl::amg<
amgcl::backend::builtin<double>,
amgcl::coarsening::smoothed_aggregation,
amgcl::relaxation::spai0
>,
amgcl::relaxation::as_preconditioner<
amgcl::backend::builtin<double>,
amgcl::relaxation::ilu0
>
> CPR;
boost::shared_ptr<CPR> P;
};
//---------------------------------------------------------------------------
struct make_simple {
make_simple(
const boost::python::dict &prm,
const numpy_boost<int, 1> &ptr,
const numpy_boost<int, 1> &col,
const numpy_boost<double, 1> &val,
const numpy_boost<int, 1> &pm
)
: n(ptr.num_elements() - 1)
{
boost::property_tree::ptree pt(make_ptree(prm));
pt.put("pmask", static_cast<const void*>(pm.data()));
pt.put("pmask_size", n);
P = boost::make_shared<SIMPLE>(boost::tie(n, ptr, col, val), pt);
}
PyObject* apply(const numpy_boost<double, 1> &rhs) const {
numpy_boost<double, 1> x(&n);
P->apply(rhs, x);
PyObject *result = x.py_ptr();
Py_INCREF(result);
return result;
}
private:
int n;
typedef
amgcl::preconditioner::simple<
amgcl::amg<
amgcl::backend::builtin<double>,
amgcl::coarsening::smoothed_aggregation,
amgcl::relaxation::spai0
>,
amgcl::relaxation::as_preconditioner<
amgcl::backend::builtin<double>,
amgcl::relaxation::ilu0
>
> SIMPLE;
boost::shared_ptr<SIMPLE> P;
};
#if PY_MAJOR_VERSION >= 3
void*
#else
void
#endif
call_import_array() {
import_array();
return NUMPY_IMPORT_ARRAY_RETVAL;
}
//---------------------------------------------------------------------------
BOOST_PYTHON_MODULE(pyamgcl_ext)
{
using namespace boost::python;
docstring_options docopts(true, true, false);
enum_<amgcl::runtime::coarsening::type>("coarsening", "coarsening kinds")
.value("ruge_stuben", amgcl::runtime::coarsening::ruge_stuben)
.value("aggregation", amgcl::runtime::coarsening::aggregation)
.value("smoothed_aggregation", amgcl::runtime::coarsening::smoothed_aggregation)
.value("smoothed_aggr_emin", amgcl::runtime::coarsening::smoothed_aggr_emin)
;
enum_<amgcl::runtime::relaxation::type>("relaxation", "relaxation schemes")
.value("damped_jacobi", amgcl::runtime::relaxation::damped_jacobi)
.value("gauss_seidel", amgcl::runtime::relaxation::gauss_seidel)
.value("multicolor_gauss_seidel", amgcl::runtime::relaxation::multicolor_gauss_seidel)
.value("chebyshev", amgcl::runtime::relaxation::chebyshev)
.value("spai0", amgcl::runtime::relaxation::spai0)
.value("ilu0", amgcl::runtime::relaxation::ilu0)
;
enum_<amgcl::runtime::solver::type>("solver_type", "iterative solvers")
.value("cg", amgcl::runtime::solver::cg)
.value("bicgstab", amgcl::runtime::solver::bicgstab)
.value("bicgstabl", amgcl::runtime::solver::bicgstabl)
.value("gmres", amgcl::runtime::solver::gmres)
;
call_import_array();
numpy_boost_python_register_type<int, 1>();
numpy_boost_python_register_type<double, 1>();
PyObject* (make_solver::*s1)(
const numpy_boost<double, 1>&
) const = &make_solver::solve;
PyObject* (make_solver::*s2)(
const numpy_boost<int, 1>&,
const numpy_boost<int, 1>&,
const numpy_boost<double, 1>&,
const numpy_boost<double, 1>&
) const = &make_solver::solve;
class_<make_solver, boost::noncopyable>(
"make_solver",
"Creates iterative solver preconditioned by AMG",
init<
amgcl::runtime::coarsening::type,
amgcl::runtime::relaxation::type,
amgcl::runtime::solver::type,
const dict&,
const numpy_boost<int, 1>&,
const numpy_boost<int, 1>&,
const numpy_boost<double, 1>&
>(
args(
"coarsening",
"relaxation",
"iterative_solver",
"params",
"indptr",
"indices",
"values"
),
"Creates iterative solver preconditioned by AMG"
)
)
.def("__repr__", &make_solver::repr)
.def("__call__", s1, args("rhs"),
"Solves the problem for the given RHS")
.def("__call__", s2, args("ptr", "col", "val", "rhs"),
"Solves the problem for the given matrix and the RHS")
.def("iterations", &make_solver::iterations,
"Returns iterations made during last solve")
.def("residual", &make_solver::residual,
"Returns relative error achieved during last solve")
;
class_<make_preconditioner, boost::noncopyable>(
"make_preconditioner",
"Creates AMG hierarchy to be used as a preconditioner",
init<
amgcl::runtime::coarsening::type,
amgcl::runtime::relaxation::type,
const dict&,
const numpy_boost<int, 1>&,
const numpy_boost<int, 1>&,
const numpy_boost<double, 1>&
>(
args(
"coarsening",
"relaxation",
"params",
"indptr",
"indices",
"values"
),
"Creates AMG hierarchy to be used as a preconditioner"
)
)
.def("__repr__", &make_preconditioner::repr)
.def("__call__", &make_preconditioner::apply,
"Apply preconditioner to the given vector")
;
class_<make_cpr, boost::noncopyable>(
"make_cpr",
"Creates CPR preconditioner",
init<
const dict&,
const numpy_boost<int, 1>&,
const numpy_boost<int, 1>&,
const numpy_boost<double, 1>&,
const numpy_boost<int, 1>&
>(
args(
"params",
"indptr",
"indices",
"values",
"pmask"
),
"Creates CPR preconditioner"
)
)
.def("__call__", &make_cpr::apply,
"Apply preconditioner to the given vector")
;
class_<make_simple, boost::noncopyable>(
"make_simple",
"Creates SIMPLE preconditioner",
init<
const dict&,
const numpy_boost<int, 1>&,
const numpy_boost<int, 1>&,
const numpy_boost<double, 1>&,
const numpy_boost<int, 1>&
>(
args(
"params",
"indptr",
"indices",
"values",
"pmask"
),
"Creates SIMPLE preconditioner"
)
)
.def("__call__", &make_simple::apply,
"Apply preconditioner to the given vector")
;
}
<commit_msg>Drop two stage preconditioners from python interface<commit_after>#include <vector>
#include <string>
#include <sstream>
#include <cstring>
#include <boost/range/iterator_range.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/python.hpp>
#include <boost/python/extract.hpp>
#include <boost/python/numeric.hpp>
#include <boost/python/raw_function.hpp>
#include <boost/python/stl_iterator.hpp>
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include "numpy_boost_python.hpp"
#include <amgcl/runtime.hpp>
#include <amgcl/make_solver.hpp>
#include <amgcl/adapter/crs_tuple.hpp>
namespace amgcl {
#ifdef AMGCL_PROFILING
profiler<> prof;
#endif
namespace backend {
template <>
struct is_builtin_vector< numpy_boost<double,1> > : boost::true_type {};
}
}
//---------------------------------------------------------------------------
boost::property_tree::ptree make_ptree(const boost::python::dict &args) {
using namespace boost::python;
boost::property_tree::ptree p;
for(stl_input_iterator<tuple> arg(args.items()), end; arg != end; ++arg) {
const char *name = extract<const char*>((*arg)[0]);
const char *type = extract<const char*>((*arg)[1].attr("__class__").attr("__name__"));
if (strcmp(type, "int") == 0)
p.put(name, extract<int>((*arg)[1]));
else
p.put(name, extract<float>((*arg)[1]));
}
return p;
}
//---------------------------------------------------------------------------
struct make_solver {
make_solver(
amgcl::runtime::coarsening::type coarsening,
amgcl::runtime::relaxation::type relaxation,
amgcl::runtime::solver::type solver,
const boost::python::dict &prm,
const numpy_boost<int, 1> &ptr,
const numpy_boost<int, 1> &col,
const numpy_boost<double, 1> &val
)
: n(ptr.num_elements() - 1)
{
boost::property_tree::ptree pt = make_ptree(prm);
pt.put("amg.coarsening.type", coarsening);
pt.put("amg.relaxation.type", relaxation);
pt.put("solver.type", solver);
S = boost::make_shared<Solver>(boost::tie(n, ptr, col, val), pt);
}
PyObject* solve(const numpy_boost<double, 1> &rhs) const {
numpy_boost<double, 1> x(&n);
BOOST_FOREACH(double &v, x) v = 0;
cnv = (*S)(rhs, x);
PyObject *result = x.py_ptr();
Py_INCREF(result);
return result;
}
PyObject* solve(
const numpy_boost<int, 1> &ptr,
const numpy_boost<int, 1> &col,
const numpy_boost<double, 1> &val,
const numpy_boost<double, 1> &rhs
) const
{
numpy_boost<double, 1> x(&n);
BOOST_FOREACH(double &v, x) v = 0;
cnv = (*S)(boost::tie(n, ptr, col, val), rhs, x);
PyObject *result = x.py_ptr();
Py_INCREF(result);
return result;
}
int iterations() const {
return boost::get<0>(cnv);
}
double residual() const {
return boost::get<1>(cnv);
}
std::string repr() const {
std::ostringstream buf;
buf << "pyamgcl solver\n" << S->precond();
return buf.str();
}
private:
typedef amgcl::make_solver<
amgcl::runtime::amg<
amgcl::backend::builtin<double>
>,
amgcl::runtime::iterative_solver<
amgcl::backend::builtin<double>
>
> Solver;
int n;
boost::shared_ptr< Solver > S;
mutable boost::tuple<int, double> cnv;
};
//---------------------------------------------------------------------------
struct make_preconditioner {
make_preconditioner(
amgcl::runtime::coarsening::type coarsening,
amgcl::runtime::relaxation::type relaxation,
const boost::python::dict &prm,
const numpy_boost<int, 1> &ptr,
const numpy_boost<int, 1> &col,
const numpy_boost<double, 1> &val
)
: n(ptr.num_elements() - 1)
{
boost::property_tree::ptree pt = make_ptree(prm);
pt.put("coarsening.type", coarsening);
pt.put("relaxation.type", relaxation);
P = boost::make_shared<Preconditioner>(boost::tie(n, ptr, col, val), pt);
}
PyObject* apply(const numpy_boost<double, 1> &rhs) const {
numpy_boost<double, 1> x(&n);
P->apply(rhs, x);
PyObject *result = x.py_ptr();
Py_INCREF(result);
return result;
}
std::string repr() const {
std::ostringstream buf;
buf << "pyamgcl preconditioner\n" << (*P);
return buf.str();
}
private:
int n;
typedef amgcl::runtime::amg< amgcl::backend::builtin<double> > Preconditioner;
boost::shared_ptr<Preconditioner> P;
};
#if PY_MAJOR_VERSION >= 3
void*
#else
void
#endif
call_import_array() {
import_array();
return NUMPY_IMPORT_ARRAY_RETVAL;
}
//---------------------------------------------------------------------------
BOOST_PYTHON_MODULE(pyamgcl_ext)
{
using namespace boost::python;
docstring_options docopts(true, true, false);
enum_<amgcl::runtime::coarsening::type>("coarsening", "coarsening kinds")
.value("ruge_stuben", amgcl::runtime::coarsening::ruge_stuben)
.value("aggregation", amgcl::runtime::coarsening::aggregation)
.value("smoothed_aggregation", amgcl::runtime::coarsening::smoothed_aggregation)
.value("smoothed_aggr_emin", amgcl::runtime::coarsening::smoothed_aggr_emin)
;
enum_<amgcl::runtime::relaxation::type>("relaxation", "relaxation schemes")
.value("damped_jacobi", amgcl::runtime::relaxation::damped_jacobi)
.value("gauss_seidel", amgcl::runtime::relaxation::gauss_seidel)
.value("multicolor_gauss_seidel", amgcl::runtime::relaxation::multicolor_gauss_seidel)
.value("chebyshev", amgcl::runtime::relaxation::chebyshev)
.value("spai0", amgcl::runtime::relaxation::spai0)
.value("ilu0", amgcl::runtime::relaxation::ilu0)
;
enum_<amgcl::runtime::solver::type>("solver_type", "iterative solvers")
.value("cg", amgcl::runtime::solver::cg)
.value("bicgstab", amgcl::runtime::solver::bicgstab)
.value("bicgstabl", amgcl::runtime::solver::bicgstabl)
.value("gmres", amgcl::runtime::solver::gmres)
;
call_import_array();
numpy_boost_python_register_type<int, 1>();
numpy_boost_python_register_type<double, 1>();
PyObject* (make_solver::*s1)(
const numpy_boost<double, 1>&
) const = &make_solver::solve;
PyObject* (make_solver::*s2)(
const numpy_boost<int, 1>&,
const numpy_boost<int, 1>&,
const numpy_boost<double, 1>&,
const numpy_boost<double, 1>&
) const = &make_solver::solve;
class_<make_solver, boost::noncopyable>(
"make_solver",
"Creates iterative solver preconditioned by AMG",
init<
amgcl::runtime::coarsening::type,
amgcl::runtime::relaxation::type,
amgcl::runtime::solver::type,
const dict&,
const numpy_boost<int, 1>&,
const numpy_boost<int, 1>&,
const numpy_boost<double, 1>&
>(
args(
"coarsening",
"relaxation",
"iterative_solver",
"params",
"indptr",
"indices",
"values"
),
"Creates iterative solver preconditioned by AMG"
)
)
.def("__repr__", &make_solver::repr)
.def("__call__", s1, args("rhs"),
"Solves the problem for the given RHS")
.def("__call__", s2, args("ptr", "col", "val", "rhs"),
"Solves the problem for the given matrix and the RHS")
.def("iterations", &make_solver::iterations,
"Returns iterations made during last solve")
.def("residual", &make_solver::residual,
"Returns relative error achieved during last solve")
;
class_<make_preconditioner, boost::noncopyable>(
"make_preconditioner",
"Creates AMG hierarchy to be used as a preconditioner",
init<
amgcl::runtime::coarsening::type,
amgcl::runtime::relaxation::type,
const dict&,
const numpy_boost<int, 1>&,
const numpy_boost<int, 1>&,
const numpy_boost<double, 1>&
>(
args(
"coarsening",
"relaxation",
"params",
"indptr",
"indices",
"values"
),
"Creates AMG hierarchy to be used as a preconditioner"
)
)
.def("__repr__", &make_preconditioner::repr)
.def("__call__", &make_preconditioner::apply,
"Apply preconditioner to the given vector")
;
}
<|endoftext|> |
<commit_before>#ifndef __INSTANCE_SELECTION_HPP__
#define __INSTANCE_SELECTION_HPP__
#define repeat(N) for(int i = 0; i < N; ++i)
#define TEST_PRIVATE_ATTRIBUTES 0 // 1 => enable testing in private members of the classes
#define N_THREADS 100
// Metaheuristics flags
#define LOCAL_SEARCH 0
#define ITERATED_LOCAL_SEARCH 1
#define GRASP 2
// #include "classifiers.hpp"
#include <cassert>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <iostream>
using std::make_pair;
#include <vector>
using std::vector;
#include <set>
using std::multiset;
#include <unordered_map>
using std::unordered_map;
#include <map>
using std::map;
#include <iostream>
using std::cout;
using std::endl;
using std::ostream;
using std::flush;
#include <algorithm>
using std::min_element;
using std::max_element;
#include <string>
using std::string;
#include <thread>
using std::thread;
#include <mutex>
using std::mutex;
#include <array>
using std::array;
#if TEST_PRIVATE_ATTRIBUTES
#include "gtest-1.7.0/include/gtest/gtest.h"
#endif
#include <ctime>
using std::clock_t;
using std::clock;
#include "point_instances.hpp"
// Forward declaration
#include "testing.hpp"
// Class to measure time. The objects will serve as "function decorators"
class MeasureTime {
public:
MeasureTime(string fn) {
function_name_ = fn;
begin_ = clock();
result_ = NULL;
print_ = true;
++deepness;
}
MeasureTime(string fn, Result *result) {
function_name_ = fn;
begin_ = clock();
result_ = result;
print_ = true;
++deepness;
}
MeasureTime(string fn, Result *result, bool print) {
function_name_ = fn;
begin_ = clock();
result_ = result;
print_ = print;
++deepness;
}
~MeasureTime() {
double elapsed_time = double(clock() - begin_) / CLOCKS_PER_SEC;
if (print_) {
repeat(deepness) { cout << "-"; }
cout << function_name_ << " : "
<< elapsed_time << " seconds\n" << flush;
}
if (result_ != NULL) {
result_->addTime(elapsed_time);
}
--deepness;
}
private:
clock_t begin_;
string function_name_;
static int deepness;
Result *result_;
bool print_;
};
// Template class to handle IS/PS solution representation
// Template arguments:
// * Point: Representation of the classification problem points
// * Class: Representation of the classification problem classes
template <typename Point, typename Class>
class PopulationMap {
public:
// Empty constructor
PopulationMap() { }
// Copy constructor
PopulationMap(const PopulationMap& obj) {
points_to_toggle_ = obj.points_to_toggle_;
selected_points_ = obj.selected_points_;
unselected_points_ = obj.unselected_points_;
correctness_weight_ = obj.correctness_weight_;
error_rate_ = obj.error_rate_;
evaluate_ = obj.evaluate_;
classify_ = obj.classify_;
resolve_ = obj.resolve_;
}
// Map <flag, metaheuristic function>
typedef PopulationMap<Point, Class> (*Metaheuristic)(const PopulationMap<Point,Class>&, int);
typedef unordered_map<int, Metaheuristic> MetaHeuristicMap;
// Function pointers typedefs
typedef Class (*Classifier)(Point, const multiset<Point>&);
typedef float (*Evaluator)(float, float, float);
// Just for styling
typedef int MetaheuristicType;
// Constructor without:
// * weight specification : default 0.5
// * resolver function : default LocalSearch
PopulationMap(multiset<Point> data, int points_to_toggle,
Classifier cls, Evaluator eval) : points_to_toggle_ ( points_to_toggle ),
selected_points_ ( data ),
correctness_weight_ ( 0.5 ),
classify_ (cls),
evaluate_ (eval),
resolve_ (LOCAL_SEARCH) {
}
// Constructor without:
// * resolver function : default LocalSearch
PopulationMap(multiset<Point> data, int points_to_toggle,
float correctness_weight, Classifier cls, Evaluator eval)
: points_to_toggle_ ( points_to_toggle ),
selected_points_ ( data ),
correctness_weight_ ( correctness_weight ),
classify_ (cls),
evaluate_ (eval),
resolve_ (LOCAL_SEARCH) {
}
// Constructor without:
// * weight specification : default 0.5
PopulationMap(multiset<Point> data, int points_to_toggle,
Classifier cls, Evaluator eval, MetaheuristicType mht)
: points_to_toggle_ ( points_to_toggle ),
selected_points_ ( data ),
correctness_weight_ ( 0.5 ),
classify_ (cls),
evaluate_ (eval),
resolve_ (mhm[mht]) {
}
// Constructor with all arguments
PopulationMap(multiset<Point> data, int points_to_toggle,
float correctness_weight, Classifier cls,
Evaluator eval, MetaheuristicType mht)
: points_to_toggle_ ( points_to_toggle ),
selected_points_ ( data ),
correctness_weight_ ( correctness_weight ),
classify_ (cls),
evaluate_ (eval),
resolve_ (mhm[mht]) {
}
// Initial solution to the Map
void InitialSolution() {
// Greedy
MCNN();
}
// Resolve method that calls the metaheuristic function
PopulationMap<Point, Class> resolve() { return resolve_(*this, 1000); }
void CNN() {
// Decorator to measure time
//MeasureTime mt("CNN");
srand(time(NULL));
// Start with the empty set C `selected_points_`
unselected_points_ = selected_points_;
selected_points_.clear();
auto random_point_iterator =
std::next(std::begin(unselected_points_),
std::rand() % unselected_points_.size());
Point point = *random_point_iterator;
selected_points_.insert(point);
unselected_points_.erase(point);
bool changed = true;
while (changed) {
changed = false;
for (auto curr = unselected_points_.begin(); curr != unselected_points_.end(); ) {
Point p = *curr;
curr++;
if (p.ClassLabel() != classify_(p, selected_points_)) {
selected_points_.insert(p);
unselected_points_.erase(p);
changed = true;
}
}
}
}
void MCNN() {
//MeasureTime mt("MCNN");
srand(time(NULL));
// Start with the empty set C `selected_points_`
unselected_points_ = selected_points_;
selected_points_.clear();
vector< vector<Point> > classes_values(g_max_label);
vector< bool > class_represented(g_max_label);
// Separate points by classes
for (auto p : selected_points_) {
classes_values[p.ClassLabel()].push_back(p);
}
// Pick a random representative from each class
for (auto cv : classes_values) {
// Maybe the class didn't exist
if (cv.size() > 0) {
Point p = cv[rand() % cv.size()];
selected_points_.insert(p);
unselected_points_.erase(p);
}
}
bool changed = true;
while (changed) {
multiset<Point> points_to_move;
changed = false;
// Classify all the unselected points
for (Point p : unselected_points_) {
// Store the ones wrongly classified
if (p.ClassLabel() != classify_(p, selected_points_)) {
points_to_move.insert(p);
changed = true;
}
}
for (int i; i < g_max_label; ++i) {
class_represented[i] = false;
}
// Get a representative of each class of all the wrongly classified points
for (Point p : points_to_move) {
if (!class_represented[p.ClassLabel()]) {
class_represented[p.ClassLabel()] = true;
selected_points_.insert(p);
unselected_points_.erase(p);
}
}
}
}
void RNN() {
//MeasureTime mt("RNN");
CNN();
multiset<Point> all(selected_points_);
all.insert(unselected_points_.begin(), unselected_points_.end());
multiset<Point> selected_points_copy = selected_points_;
for (Point p : selected_points_copy) {
selected_points_.erase(p);
for (Point i : all) {
// If it classifies wrongly, insert it again
if (i.ClassLabel() != classify_(i, selected_points_)) {
selected_points_.insert(p);
break;
}
}
}
}
void RandomSolution() {
// Decorator to measure time
//MeasureTime mt("RandomSolution");
srand(time(NULL));
multiset<Point> data(selected_points_);
data.insert(unselected_points_.begin(), unselected_points_.end());
// Clear both sets
selected_points_.clear();
unselected_points_.clear();
// First we randomize the selected_points
for (auto itr = data.begin(); itr != data.end(); ++itr) {
int use_in_solution = rand() % 2;
if (use_in_solution == 1) {
selected_points_.insert(*itr);
} else {
unselected_points_.insert(*itr);
}
}
}
// Function that modifies the map to generate a new neighbor solution map
void NeighborhoodOperator(void) {
//MeasureTime mt("NeighborhoodOperator");
// This function may toggle the same point more than once
repeat(points_to_toggle_) {
// We choose either selected_points_ or unselected_points_ (random)
// If any of them is empty, the we take the other one
int random_to_pick_set = rand() % 2;
if (selected_points_.empty()) {
random_to_pick_set = 0;
} else if (unselected_points_.empty()) {
random_to_pick_set = 1;
}
Point random_point = GetRandomPoint(random_to_pick_set);
//Point random_point = GetBestPoint(random_to_pick_set);
toggle(random_point, random_to_pick_set);
}
}
Point GetRandomPoint(int random_to_pick_set) {
const multiset<Point>& set_to_use = (random_to_pick_set == 1 ? selected_points_
: unselected_points_);
auto random_point_iterator =
std::next(std::begin(set_to_use),
std::rand() % set_to_use.size());
return *random_point_iterator;
}
// Function that evaluates the current map's quality
float EvaluateQuality(void) const {
// Decorator to measure time
//MeasureTime mt("EvaluateQuality");
float classification_correctness = RunClassifier(selected_points_, unselected_points_);
float reduction_percentage = GetReductionPercentage();
return evaluate_(classification_correctness, reduction_percentage, correctness_weight_);
}
pair<float,float> SolutionStatistics() {
return make_pair(RunClassifier(selected_points_, unselected_points_), GetReductionPercentage());
}
multiset<Point> selected_points() const { return selected_points_; }
multiset<Point> unselected_points() const { return unselected_points_; }
int TotalSize() const { return selected_points_.size() + unselected_points_.size(); }
int SelectedPointsSize() const { return selected_points_.size(); }
int UnselectedPointsSize() const { return unselected_points_.size(); }
private:
// Toggles points between selected and unselected points sets.
void toggle(Point p, int set_to_use) {
if (set_to_use == 1) {
selected_points_.erase(p);
unselected_points_.insert(p);
} else {
unselected_points_.erase(p);
selected_points_.insert(p);
}
}
// Thread function to be used in parallel
void ClassifyPoint(int thread, const Point& p, const multiset<Point>& training_set) const {
if (p.ClassLabel() == classify_(p, training_set)) {
++good_classifications_[thread];
}
}
// Returns the percentage of correct classified points (from 0 to 1)
// TODO: Consider to multiply by 100 the percentage
float RunClassifier(const multiset<Point>& training_set,
const multiset<Point>& testing_set) const {
//MeasureTime mt("RunClassifier");
if (testing_set.empty()) {
return 0.0;
}
// XXX: PARALLELISM IS SLOWER
//memset(good_classifications_, 0, sizeof(good_classifications_));
//thread classifiers[N_THREADS];
//auto fun_ptr = &PopulationMap<Point, Class, classify, fitness>::ClassifyPoint;
//// TODO: Parallelize this for
//auto p = testing_set.begin();
//for (int t = 0; p != testing_set.end(); ++p, t = (t + 1) % N_THREADS) {
//classifiers[t] = thread(fun_ptr, this, t, *p, training_set);
//// Wait all threads N_THREAD threads are used
//if (t == N_THREADS - 1) {
//for (int w = 0; w < N_THREADS; ++w) {
//classifiers[w].join();
//}
//}
//}
//// Collect the well classified points
//int correct = 0;
//for (int w = 0; w < N_THREADS; ++w) {
//if (classifiers[w].joinable()) {
//classifiers[w].join();
//}
//correct += good_classifications_[w];
/*}*/
int correct = 0;
// TODO: Parallelize this for
for (const Point& p: testing_set) {
if (p.ClassLabel() == classify_(p, training_set)) {
++correct;
}
}
return float(correct) / testing_set.size();
}
float GetReductionPercentage() const {
return float(unselected_points_.size()) / (unselected_points_.size() +
selected_points_.size());
}
friend class BallonPointTest;
#ifndef TEST_PRIVATE_ATTRIBUTES
FRIEND_TEST(BallonPointTest, TogglingPoints);
FRIEND_TEST(BallonPointTest, FitnessFunction);
#endif
// Class private members
// XXX: IF NEW ATTRIBUTES ARE ADDED, ADD TO COPY CONSTRUCTOR
int points_to_toggle_;
multiset<Point> selected_points_;
multiset<Point> unselected_points_;
float correctness_weight_;
float error_rate_;
Classifier classify_;
Evaluator evaluate_;
Metaheuristic resolve_;
mutable int good_classifications_[N_THREADS];
static MetaHeuristicMap mhm;
};
#endif
<commit_msg>MCNN working correctly (not tested)<commit_after>#ifndef __INSTANCE_SELECTION_HPP__
#define __INSTANCE_SELECTION_HPP__
#define repeat(N) for(int i = 0; i < N; ++i)
#define TEST_PRIVATE_ATTRIBUTES 0 // 1 => enable testing in private members of the classes
#define N_THREADS 100
// Metaheuristics flags
#define LOCAL_SEARCH 0
#define ITERATED_LOCAL_SEARCH 1
#define GRASP 2
// #include "classifiers.hpp"
#include <cassert>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <iostream>
using std::make_pair;
#include <vector>
using std::vector;
#include <set>
using std::multiset;
#include <unordered_map>
using std::unordered_map;
#include <map>
using std::map;
#include <iostream>
using std::cout;
using std::endl;
using std::ostream;
using std::flush;
#include <algorithm>
using std::min_element;
using std::max_element;
#include <string>
using std::string;
#include <thread>
using std::thread;
#include <mutex>
using std::mutex;
#include <array>
using std::array;
#if TEST_PRIVATE_ATTRIBUTES
#include "gtest-1.7.0/include/gtest/gtest.h"
#endif
#include <ctime>
using std::clock_t;
using std::clock;
#include "point_instances.hpp"
// Forward declaration
#include "testing.hpp"
// Class to measure time. The objects will serve as "function decorators"
class MeasureTime {
public:
MeasureTime(string fn) {
function_name_ = fn;
begin_ = clock();
result_ = NULL;
print_ = true;
++deepness;
}
MeasureTime(string fn, Result *result) {
function_name_ = fn;
begin_ = clock();
result_ = result;
print_ = true;
++deepness;
}
MeasureTime(string fn, Result *result, bool print) {
function_name_ = fn;
begin_ = clock();
result_ = result;
print_ = print;
++deepness;
}
~MeasureTime() {
double elapsed_time = double(clock() - begin_) / CLOCKS_PER_SEC;
if (print_) {
repeat(deepness) { cout << "-"; }
cout << function_name_ << " : "
<< elapsed_time << " seconds\n" << flush;
}
if (result_ != NULL) {
result_->addTime(elapsed_time);
}
--deepness;
}
private:
clock_t begin_;
string function_name_;
static int deepness;
Result *result_;
bool print_;
};
// Template class to handle IS/PS solution representation
// Template arguments:
// * Point: Representation of the classification problem points
// * Class: Representation of the classification problem classes
template <typename Point, typename Class>
class PopulationMap {
public:
// Empty constructor
PopulationMap() { }
// Copy constructor
PopulationMap(const PopulationMap& obj) {
points_to_toggle_ = obj.points_to_toggle_;
selected_points_ = obj.selected_points_;
unselected_points_ = obj.unselected_points_;
correctness_weight_ = obj.correctness_weight_;
error_rate_ = obj.error_rate_;
evaluate_ = obj.evaluate_;
classify_ = obj.classify_;
resolve_ = obj.resolve_;
}
// Map <flag, metaheuristic function>
typedef PopulationMap<Point, Class> (*Metaheuristic)(const PopulationMap<Point,Class>&, int);
typedef unordered_map<int, Metaheuristic> MetaHeuristicMap;
// Function pointers typedefs
typedef Class (*Classifier)(Point, const multiset<Point>&);
typedef float (*Evaluator)(float, float, float);
// Just for styling
typedef int MetaheuristicType;
// Constructor without:
// * weight specification : default 0.5
// * resolver function : default LocalSearch
PopulationMap(multiset<Point> data, int points_to_toggle,
Classifier cls, Evaluator eval) : points_to_toggle_ ( points_to_toggle ),
selected_points_ ( data ),
correctness_weight_ ( 0.5 ),
classify_ (cls),
evaluate_ (eval),
resolve_ (LOCAL_SEARCH) {
}
// Constructor without:
// * resolver function : default LocalSearch
PopulationMap(multiset<Point> data, int points_to_toggle,
float correctness_weight, Classifier cls, Evaluator eval)
: points_to_toggle_ ( points_to_toggle ),
selected_points_ ( data ),
correctness_weight_ ( correctness_weight ),
classify_ (cls),
evaluate_ (eval),
resolve_ (LOCAL_SEARCH) {
}
// Constructor without:
// * weight specification : default 0.5
PopulationMap(multiset<Point> data, int points_to_toggle,
Classifier cls, Evaluator eval, MetaheuristicType mht)
: points_to_toggle_ ( points_to_toggle ),
selected_points_ ( data ),
correctness_weight_ ( 0.5 ),
classify_ (cls),
evaluate_ (eval),
resolve_ (mhm[mht]) {
}
// Constructor with all arguments
PopulationMap(multiset<Point> data, int points_to_toggle,
float correctness_weight, Classifier cls,
Evaluator eval, MetaheuristicType mht)
: points_to_toggle_ ( points_to_toggle ),
selected_points_ ( data ),
correctness_weight_ ( correctness_weight ),
classify_ (cls),
evaluate_ (eval),
resolve_ (mhm[mht]) {
}
// Initial solution to the Map
void InitialSolution() {
// Greedy
MCNN();
}
// Resolve method that calls the metaheuristic function
PopulationMap<Point, Class> resolve() { return resolve_(*this, 1000); }
void CNN() {
// Decorator to measure time
//MeasureTime mt("CNN");
srand(time(NULL));
// Start with the empty set C `selected_points_`
unselected_points_ = selected_points_;
selected_points_.clear();
auto random_point_iterator =
std::next(std::begin(unselected_points_),
std::rand() % unselected_points_.size());
Point point = *random_point_iterator;
selected_points_.insert(point);
unselected_points_.erase(point);
bool changed = true;
while (changed) {
changed = false;
for (auto curr = unselected_points_.begin(); curr != unselected_points_.end(); ) {
Point p = *curr;
curr++;
if (p.ClassLabel() != classify_(p, selected_points_)) {
selected_points_.insert(p);
unselected_points_.erase(p);
changed = true;
}
}
}
}
void MCNN() {
// MeasureTime mt("MCNN");
srand(time(NULL));
// Start with the empty set C `selected_points_`
unselected_points_ = selected_points_;
selected_points_.clear();
int classes_n = g_max_label + 1;
vector< vector<Point> > class_values(classes_n);
vector< bool > class_represented(classes_n);
// Separate points by classes
for (auto p : unselected_points_) {
class_values[p.ClassLabel()].push_back(p);
}
// Pick a random representative from each class
for (auto cv : class_values) {
// Maybe the class didn't exist
if (cv.size() > 0) {
Point p = cv[rand() % cv.size()];
selected_points_.insert(p);
unselected_points_.erase(p);
}
}
bool changed = true;
while (changed) {
multiset<Point> points_to_move;
changed = false;
// Classify all the unselected points
for (Point p : unselected_points_) {
// Store the ones wrongly classified
if (p.ClassLabel() != classify_(p, selected_points_)) {
points_to_move.insert(p);
changed = true;
}
}
for (int i = 0; i < classes_n; ++i) {
class_represented[i] = false;
}
// Get a representative of each class of all the wrongly classified points
for (Point p : points_to_move) {
if (!class_represented[p.ClassLabel()]) {
class_represented[p.ClassLabel()] = true;
selected_points_.insert(p);
unselected_points_.erase(p);
}
}
}
}
void RNN() {
//MeasureTime mt("RNN");
CNN();
multiset<Point> all(selected_points_);
all.insert(unselected_points_.begin(), unselected_points_.end());
multiset<Point> selected_points_copy = selected_points_;
for (Point p : selected_points_copy) {
selected_points_.erase(p);
for (Point i : all) {
// If it classifies wrongly, insert it again
if (i.ClassLabel() != classify_(i, selected_points_)) {
selected_points_.insert(p);
break;
}
}
}
}
void RandomSolution() {
// Decorator to measure time
//MeasureTime mt("RandomSolution");
srand(time(NULL));
multiset<Point> data(selected_points_);
data.insert(unselected_points_.begin(), unselected_points_.end());
// Clear both sets
selected_points_.clear();
unselected_points_.clear();
// First we randomize the selected_points
for (auto itr = data.begin(); itr != data.end(); ++itr) {
int use_in_solution = rand() % 2;
if (use_in_solution == 1) {
selected_points_.insert(*itr);
} else {
unselected_points_.insert(*itr);
}
}
}
// Function that modifies the map to generate a new neighbor solution map
void NeighborhoodOperator(void) {
//MeasureTime mt("NeighborhoodOperator");
// This function may toggle the same point more than once
repeat(points_to_toggle_) {
// We choose either selected_points_ or unselected_points_ (random)
// If any of them is empty, the we take the other one
int random_to_pick_set = rand() % 2;
if (selected_points_.empty()) {
random_to_pick_set = 0;
} else if (unselected_points_.empty()) {
random_to_pick_set = 1;
}
Point random_point = GetRandomPoint(random_to_pick_set);
//Point random_point = GetBestPoint(random_to_pick_set);
toggle(random_point, random_to_pick_set);
}
}
Point GetRandomPoint(int random_to_pick_set) {
const multiset<Point>& set_to_use = (random_to_pick_set == 1 ? selected_points_
: unselected_points_);
auto random_point_iterator =
std::next(std::begin(set_to_use),
std::rand() % set_to_use.size());
return *random_point_iterator;
}
// Function that evaluates the current map's quality
float EvaluateQuality(void) const {
// Decorator to measure time
//MeasureTime mt("EvaluateQuality");
float classification_correctness = RunClassifier(selected_points_, unselected_points_);
float reduction_percentage = GetReductionPercentage();
return evaluate_(classification_correctness, reduction_percentage, correctness_weight_);
}
pair<float,float> SolutionStatistics() {
return make_pair(RunClassifier(selected_points_, unselected_points_), GetReductionPercentage());
}
multiset<Point> selected_points() const { return selected_points_; }
multiset<Point> unselected_points() const { return unselected_points_; }
int TotalSize() const { return selected_points_.size() + unselected_points_.size(); }
int SelectedPointsSize() const { return selected_points_.size(); }
int UnselectedPointsSize() const { return unselected_points_.size(); }
private:
// Toggles points between selected and unselected points sets.
void toggle(Point p, int set_to_use) {
if (set_to_use == 1) {
selected_points_.erase(p);
unselected_points_.insert(p);
} else {
unselected_points_.erase(p);
selected_points_.insert(p);
}
}
// Thread function to be used in parallel
void ClassifyPoint(int thread, const Point& p, const multiset<Point>& training_set) const {
if (p.ClassLabel() == classify_(p, training_set)) {
++good_classifications_[thread];
}
}
// Returns the percentage of correct classified points (from 0 to 1)
// TODO: Consider to multiply by 100 the percentage
float RunClassifier(const multiset<Point>& training_set,
const multiset<Point>& testing_set) const {
//MeasureTime mt("RunClassifier");
if (testing_set.empty()) {
return 0.0;
}
// XXX: PARALLELISM IS SLOWER
//memset(good_classifications_, 0, sizeof(good_classifications_));
//thread classifiers[N_THREADS];
//auto fun_ptr = &PopulationMap<Point, Class, classify, fitness>::ClassifyPoint;
//// TODO: Parallelize this for
//auto p = testing_set.begin();
//for (int t = 0; p != testing_set.end(); ++p, t = (t + 1) % N_THREADS) {
//classifiers[t] = thread(fun_ptr, this, t, *p, training_set);
//// Wait all threads N_THREAD threads are used
//if (t == N_THREADS - 1) {
//for (int w = 0; w < N_THREADS; ++w) {
//classifiers[w].join();
//}
//}
//}
//// Collect the well classified points
//int correct = 0;
//for (int w = 0; w < N_THREADS; ++w) {
//if (classifiers[w].joinable()) {
//classifiers[w].join();
//}
//correct += good_classifications_[w];
/*}*/
int correct = 0;
// TODO: Parallelize this for
for (const Point& p: testing_set) {
if (p.ClassLabel() == classify_(p, training_set)) {
++correct;
}
}
return float(correct) / testing_set.size();
}
float GetReductionPercentage() const {
return float(unselected_points_.size()) / (unselected_points_.size() +
selected_points_.size());
}
friend class BallonPointTest;
#ifndef TEST_PRIVATE_ATTRIBUTES
FRIEND_TEST(BallonPointTest, TogglingPoints);
FRIEND_TEST(BallonPointTest, FitnessFunction);
#endif
// Class private members
// XXX: IF NEW ATTRIBUTES ARE ADDED, ADD TO COPY CONSTRUCTOR
int points_to_toggle_;
multiset<Point> selected_points_;
multiset<Point> unselected_points_;
float correctness_weight_;
float error_rate_;
Classifier classify_;
Evaluator evaluate_;
Metaheuristic resolve_;
mutable int good_classifications_[N_THREADS];
static MetaHeuristicMap mhm;
};
#endif
<|endoftext|> |
<commit_before>// Copyright 2020 Global Phasing Ltd.
#include "common.h"
#include "gemmi/elem.hpp"
#include "gemmi/resinfo.hpp"
#include "gemmi/it92.hpp"
#include "gemmi/c4322.hpp"
#include <pybind11/stl.h>
#include <pybind11/numpy.h>
namespace py = pybind11;
using namespace gemmi;
static std::vector<std::string>
expand_protein_one_letter_string(const std::string& s) {
std::vector<std::string> r;
r.reserve(s.size());
for (char c : s)
r.push_back(expand_protein_one_letter(c));
return r;
}
void add_elem(py::module& m) {
// it92.hpp
using IT92 = gemmi::IT92<double>;
py::class_<IT92::Coef>(m, "IT92Coef")
.def_property_readonly("a", [](IT92::Coef& c) -> std::array<double,4> {
return {{ c.a(0), c.a(1), c.a(2), c.a(3) }};
})
.def_property_readonly("b", [](IT92::Coef& c) -> std::array<double,4> {
return {{ c.b(0), c.b(1), c.b(2), c.b(3) }};
})
.def_property_readonly("c", &IT92::Coef::c)
.def("set_coefs", &IT92::Coef::set_coefs)
.def("calculate_sf", py::vectorize(&IT92::Coef::calculate_sf), py::arg("stol2"))
.def("calculate_density_iso",
[](const IT92::Coef &self, py::array_t<double> r2, double B) {
return py::vectorize([self,B](double r2) { return self.calculate_density_iso(r2, B); })(r2);
},
py::arg("r2"), py::arg("B"))
;
// c4322.hpp
using C4322 = gemmi::C4322<double>;
py::class_<C4322::Coef>(m, "C4322Coef")
.def_property_readonly("a", [](C4322::Coef& c) -> std::array<double,5> {
return {{ c.a(0), c.a(1), c.a(2), c.a(3), c.a(4) }};
})
.def_property_readonly("b", [](C4322::Coef& c) -> std::array<double,5> {
return {{ c.b(0), c.b(1), c.b(2), c.b(3), c.b(4) }};
})
.def("set_coefs", &C4322::Coef::set_coefs)
.def("calculate_sf", &C4322::Coef::calculate_sf, py::arg("stol2"))
.def("calculate_density_iso", &C4322::Coef::calculate_density_iso,
py::arg("r2"), py::arg("B"))
;
// elem.hpp
py::class_<Element>(m, "Element")
.def(py::init<const std::string &>())
.def(py::init<int>())
.def("__eq__",
[](const Element &a, const Element &b) { return a.elem == b.elem; },
py::is_operator())
#if PY_MAJOR_VERSION < 3 // in Py3 != is inferred from ==
.def("__ne__",
[](const Element &a, const Element &b) { return a.elem != b.elem; },
py::is_operator())
#endif
.def_property_readonly("name", &Element::name)
.def_property_readonly("weight", &Element::weight)
.def_property_readonly("covalent_r", &Element::covalent_r)
.def_property_readonly("vdw_r", &Element::vdw_r)
.def_property_readonly("atomic_number", &Element::atomic_number)
.def_property_readonly("is_hydrogen", &Element::is_hydrogen)
.def_property_readonly("is_metal", &Element::is_metal)
.def_property_readonly("it92", [](const Element& self) {
return IT92::get_ptr(self.elem);
}, py::return_value_policy::reference_internal)
.def_property_readonly("c4322", [](const Element& self) {
return C4322::get_ptr(self.elem);
}, py::return_value_policy::reference_internal)
.def("__repr__", [](const Element& self) {
return "<gemmi.Element: " + std::string(self.name()) + ">";
});
// resinfo.hpp
py::class_<ResidueInfo>(m, "ResidueInfo")
.def_readonly("one_letter_code", &ResidueInfo::one_letter_code)
.def_readonly("hydrogen_count", &ResidueInfo::hydrogen_count)
.def_readonly("weight", &ResidueInfo::weight)
.def("found", &ResidueInfo::found)
.def("is_standard", &ResidueInfo::is_standard)
.def("is_water", &ResidueInfo::is_water)
.def("is_nucleic_acid", &ResidueInfo::is_nucleic_acid)
.def("is_amino_acid", &ResidueInfo::is_amino_acid);
m.def("find_tabulated_residue", &find_tabulated_residue, py::arg("name"),
"Find chemical component information in the internal table.");
m.def("expand_protein_one_letter", &expand_protein_one_letter);
m.def("expand_protein_one_letter_string", &expand_protein_one_letter_string);
}
<commit_msg>python calculate_density_iso(): pass self by value, limit line length<commit_after>// Copyright 2020 Global Phasing Ltd.
#include "common.h"
#include "gemmi/elem.hpp"
#include "gemmi/resinfo.hpp"
#include "gemmi/it92.hpp"
#include "gemmi/c4322.hpp"
#include <pybind11/stl.h>
#include <pybind11/numpy.h>
namespace py = pybind11;
using namespace gemmi;
static std::vector<std::string>
expand_protein_one_letter_string(const std::string& s) {
std::vector<std::string> r;
r.reserve(s.size());
for (char c : s)
r.push_back(expand_protein_one_letter(c));
return r;
}
void add_elem(py::module& m) {
// it92.hpp
using IT92 = gemmi::IT92<double>;
py::class_<IT92::Coef>(m, "IT92Coef")
.def_property_readonly("a", [](IT92::Coef& c) -> std::array<double,4> {
return {{ c.a(0), c.a(1), c.a(2), c.a(3) }};
})
.def_property_readonly("b", [](IT92::Coef& c) -> std::array<double,4> {
return {{ c.b(0), c.b(1), c.b(2), c.b(3) }};
})
.def_property_readonly("c", &IT92::Coef::c)
.def("set_coefs", &IT92::Coef::set_coefs)
.def("calculate_sf", py::vectorize(&IT92::Coef::calculate_sf), py::arg("stol2"))
.def("calculate_density_iso",
[](const IT92::Coef &self, py::array_t<double> r2, double B) {
return py::vectorize([&self,B](double r2) {
return self.calculate_density_iso(r2, B);
})(r2);
}, py::arg("r2"), py::arg("B"))
;
// c4322.hpp
using C4322 = gemmi::C4322<double>;
py::class_<C4322::Coef>(m, "C4322Coef")
.def_property_readonly("a", [](C4322::Coef& c) -> std::array<double,5> {
return {{ c.a(0), c.a(1), c.a(2), c.a(3), c.a(4) }};
})
.def_property_readonly("b", [](C4322::Coef& c) -> std::array<double,5> {
return {{ c.b(0), c.b(1), c.b(2), c.b(3), c.b(4) }};
})
.def("set_coefs", &C4322::Coef::set_coefs)
.def("calculate_sf", &C4322::Coef::calculate_sf, py::arg("stol2"))
.def("calculate_density_iso", &C4322::Coef::calculate_density_iso,
py::arg("r2"), py::arg("B"))
;
// elem.hpp
py::class_<Element>(m, "Element")
.def(py::init<const std::string &>())
.def(py::init<int>())
.def("__eq__",
[](const Element &a, const Element &b) { return a.elem == b.elem; },
py::is_operator())
#if PY_MAJOR_VERSION < 3 // in Py3 != is inferred from ==
.def("__ne__",
[](const Element &a, const Element &b) { return a.elem != b.elem; },
py::is_operator())
#endif
.def_property_readonly("name", &Element::name)
.def_property_readonly("weight", &Element::weight)
.def_property_readonly("covalent_r", &Element::covalent_r)
.def_property_readonly("vdw_r", &Element::vdw_r)
.def_property_readonly("atomic_number", &Element::atomic_number)
.def_property_readonly("is_hydrogen", &Element::is_hydrogen)
.def_property_readonly("is_metal", &Element::is_metal)
.def_property_readonly("it92", [](const Element& self) {
return IT92::get_ptr(self.elem);
}, py::return_value_policy::reference_internal)
.def_property_readonly("c4322", [](const Element& self) {
return C4322::get_ptr(self.elem);
}, py::return_value_policy::reference_internal)
.def("__repr__", [](const Element& self) {
return "<gemmi.Element: " + std::string(self.name()) + ">";
});
// resinfo.hpp
py::class_<ResidueInfo>(m, "ResidueInfo")
.def_readonly("one_letter_code", &ResidueInfo::one_letter_code)
.def_readonly("hydrogen_count", &ResidueInfo::hydrogen_count)
.def_readonly("weight", &ResidueInfo::weight)
.def("found", &ResidueInfo::found)
.def("is_standard", &ResidueInfo::is_standard)
.def("is_water", &ResidueInfo::is_water)
.def("is_nucleic_acid", &ResidueInfo::is_nucleic_acid)
.def("is_amino_acid", &ResidueInfo::is_amino_acid);
m.def("find_tabulated_residue", &find_tabulated_residue, py::arg("name"),
"Find chemical component information in the internal table.");
m.def("expand_protein_one_letter", &expand_protein_one_letter);
m.def("expand_protein_one_letter_string", &expand_protein_one_letter_string);
}
<|endoftext|> |
<commit_before>
#include <togo/error/assert.hpp>
#include <togo/log/log.hpp>
#include <togo/memory/memory.hpp>
#include <togo/collection/array.hpp>
#include "../common/helpers.hpp"
using namespace togo;
#define ARRAY_ASSERTIONS(a, _size, _capacity) \
TOGO_ASSERTE(array::size(a) == _size); \
TOGO_ASSERTE(array::capacity(a) == _capacity); \
TOGO_ASSERTE(array::empty(a) == (_size == 0)); \
TOGO_ASSERTE(array::any(a) == (_size > 0))
//
signed main() {
memory_init();
TOGO_LOGF("sizeof(Array<s32>) = %zu\n", sizeof(Array<s32>));
TOGO_LOGF("alignof(Array<s32>) = %zu\n", alignof(Array<s32>));
// Invariants
Array<s32> a{memory::default_allocator()};
ARRAY_ASSERTIONS(a, 0, 0);
array::push_back(a, 42);
ARRAY_ASSERTIONS(a, 1, 8);
array::clear(a);
ARRAY_ASSERTIONS(a, 0, 8);
// Insertion
s32 count = 10;
while (count--) {
array::push_back(a, 10 - count);
}
ARRAY_ASSERTIONS(a, 10, 24);
// Access
count = 1;
for (auto const v : a) {
TOGO_ASSERTE(v == count);
TOGO_LOGF("%d ", v);
++count;
}
TOGO_LOG("\n");
for (u32 i = 0; i < array::size(a); ++i) {
TOGO_ASSERTE(a[i] == signed_cast(i + 1));
}
count = 1;
for (auto it = array::begin(a); it != array::end(a); ++it) {
TOGO_ASSERTE(*it == count);
++count;
}
// Copy
Array<s32> copy{memory::default_allocator()};
array::copy(copy, a);
TOGO_ASSERTE(array::size(copy) == array::size(a));
for (u32 i = 0; i < array::size(copy); ++i) {
TOGO_ASSERTE(copy[i] == a[i]);
}
// Removal
count = 5;
while (count--) {
array::pop_back(a);
}
ARRAY_ASSERTIONS(a, 5, 24);
count = 5;
while (count--) {
array::pop_back(a);
}
ARRAY_ASSERTIONS(a, 0, 24);
/// Removal by index
count = 4;
while (count--) {
array::push_back(a, 3 - count);
}
array::remove(a, 3);
TOGO_ASSERTE(a[0] == 0);
TOGO_ASSERTE(a[1] == 1);
TOGO_ASSERTE(a[2] == 2);
array::remove(a, 1);
TOGO_ASSERTE(a[0] == 0);
TOGO_ASSERTE(a[1] == 2);
array::remove(a, 0);
TOGO_ASSERTE(a[0] == 2);
array::remove(a, 0);
TOGO_ASSERTE(array::empty(a));
return 0;
}
<commit_msg>test/collection/array: added array::remove_over() tests.<commit_after>
#include <togo/error/assert.hpp>
#include <togo/log/log.hpp>
#include <togo/memory/memory.hpp>
#include <togo/collection/array.hpp>
#include "../common/helpers.hpp"
using namespace togo;
#define ARRAY_ASSERTIONS(a, _size, _capacity) \
TOGO_ASSERTE(array::size(a) == _size); \
TOGO_ASSERTE(array::capacity(a) == _capacity); \
TOGO_ASSERTE(array::empty(a) == (_size == 0)); \
TOGO_ASSERTE(array::any(a) == (_size > 0))
//
signed main() {
memory_init();
TOGO_LOGF("sizeof(Array<s32>) = %zu\n", sizeof(Array<s32>));
TOGO_LOGF("alignof(Array<s32>) = %zu\n", alignof(Array<s32>));
// Invariants
Array<s32> a{memory::default_allocator()};
ARRAY_ASSERTIONS(a, 0, 0);
array::push_back(a, 42);
ARRAY_ASSERTIONS(a, 1, 8);
array::clear(a);
ARRAY_ASSERTIONS(a, 0, 8);
// Insertion
s32 count = 10;
while (count--) {
array::push_back(a, 10 - count);
}
ARRAY_ASSERTIONS(a, 10, 24);
// Access
count = 1;
for (auto const v : a) {
TOGO_ASSERTE(v == count);
TOGO_LOGF("%d ", v);
++count;
}
TOGO_LOG("\n");
for (u32 i = 0; i < array::size(a); ++i) {
TOGO_ASSERTE(a[i] == signed_cast(i + 1));
}
count = 1;
for (auto it = array::begin(a); it != array::end(a); ++it) {
TOGO_ASSERTE(*it == count);
++count;
}
// Copy
Array<s32> copy{memory::default_allocator()};
array::copy(copy, a);
TOGO_ASSERTE(array::size(copy) == array::size(a));
for (u32 i = 0; i < array::size(copy); ++i) {
TOGO_ASSERTE(copy[i] == a[i]);
}
// Removal
count = 5;
while (count--) {
array::pop_back(a);
}
ARRAY_ASSERTIONS(a, 5, 24);
count = 5;
while (count--) {
array::pop_back(a);
}
ARRAY_ASSERTIONS(a, 0, 24);
/// Removal by index
count = 4;
while (count--) {
array::push_back(a, 3 - count);
}
array::remove(a, 3);
TOGO_ASSERTE(a[0] == 0);
TOGO_ASSERTE(a[1] == 1);
TOGO_ASSERTE(a[2] == 2);
array::remove(a, 1);
TOGO_ASSERTE(a[0] == 0);
TOGO_ASSERTE(a[1] == 2);
array::remove(a, 0);
TOGO_ASSERTE(a[0] == 2);
array::remove(a, 0);
TOGO_ASSERTE(array::empty(a));
// Remove-overwrite
count = 4;
while (count--) {
array::push_back(a, 3 - count);
}
array::remove_over(a, 0);
TOGO_ASSERTE(a[0] == 3);
TOGO_ASSERTE(a[1] == 1);
TOGO_ASSERTE(a[2] == 2);
array::remove_over(a, 0);
TOGO_ASSERTE(a[0] == 2);
TOGO_ASSERTE(a[1] == 1);
array::remove_over(a, 0);
TOGO_ASSERTE(a[0] == 1);
array::remove_over(a, 0);
TOGO_ASSERTE(array::empty(a));
return 0;
}
<|endoftext|> |
<commit_before>// Copyright(c) Andre Caron <andre.l.caron@gmail.com>, 2011
//
// This document is covered by the an Open Source Initiative approved license. A
// copy of the license should have been provided alongside this software package
// (see "LICENSE.txt"). If not, terms of the license are available online at
// "http://www.opensource.org/licenses/mit".
#include "Message.hpp"
#include "Error.hpp"
#include "Flags.hpp"
#include "icompare.hpp"
#include <algorithm>
#include <cstring>
#include <utility>
namespace {
struct Clear {
typedef std::pair<const std::string, std::string> Header;
void operator() ( Header& header ) const { header.second.clear(); }
};
class Matches
{
const std::string& myField;
public:
Matches ( const std::string& field )
: myField(field)
{}
bool operator() ( const std::pair<std::string,std::string>& field )
{
return (http::ieq(field.first, myField));
}
};
}
namespace http {
int Message::on_message_begin ( ::http_parser * parser )
{
Message& message = *static_cast<Message*>(parser->data);
message.myComplete = false;
message.myHeadersComplete = false;
return (0);
}
int Message::on_message_complete ( ::http_parser * parser )
{
Message& message = *static_cast<Message*>(parser->data);
message.myComplete = true;
return (0);
}
int Message::on_header_field
( ::http_parser * parser, const char * data, size_t size )
{
Message& message = *static_cast<Message*>(parser->data);
if ( !message.myCurrentValue.empty() )
{
message.myHeaders[message.myCurrentField] =
message.myCurrentValue;
message.myCurrentField.clear();
message.myCurrentValue.clear();
}
message.myCurrentField.append(data, size);
return (0);
}
int Message::on_header_value
( ::http_parser * parser, const char * data, size_t size )
{
Message& message = *static_cast<Message*>(parser->data);
message.myCurrentValue.append(data, size);
return (0);
}
int Message::on_headers_complete ( ::http_parser * parser )
{
Message& message = *static_cast<Message*>(parser->data);
if ( !message.myCurrentValue.empty() )
{
message.myHeaders[message.myCurrentField] =
message.myCurrentValue;
message.myCurrentField.clear();
message.myCurrentValue.clear();
}
message.myHeadersComplete = true;
return (0);
}
int Message::on_body
( ::http_parser * parser, const char * data, size_t size )
{
Message& message = *static_cast<Message*>(parser->data);
message.myBody.append(data, size);
return (0);
}
Message::Message ()
{
// make sure message is not seen as complete.
myComplete = false;
myHeadersComplete = false;
// select callbacks.
::memset(&mySettings, 0, sizeof(mySettings));
mySettings.on_message_complete = &Message::on_message_complete;
mySettings.on_message_begin = &Message::on_message_begin;
mySettings.on_header_field = &Message::on_header_field;
mySettings.on_header_value = &Message::on_header_value;
mySettings.on_headers_complete = &Message::on_headers_complete;
mySettings.on_body = &Message::on_body;
}
void Message::clear ()
{
// make sure message is not seen as complete.
myComplete = false;
myHeadersComplete = false;
// clear string content, while keeping memory allocated.
std::for_each(myHeaders.begin(), myHeaders.end(), Clear());
myBody.clear();
}
std::size_t Message::feed ( const void * data, ::size_t size )
{
return (feed(static_cast<const char*>(data), size));
}
std::size_t Message::feed ( const char * data, ::size_t size )
{
const ::size_t parsed =
::http_parser_execute(&myParser, &mySettings, data, size);
if ( parsed != size ) {
throw Error(HTTP_PARSER_ERRNO(&myParser));
}
return (parsed);
}
bool Message::complete () const
{
return (myComplete);
}
bool Message::headerscomplete () const
{
return (myHeadersComplete);
}
int Message::minorversion () const
{
return (myParser.http_minor);
}
const Flags Message::flags () const
{
return (Flags::of(myParser));
}
bool Message::hasheader ( const std::string& field ) const
{
const Headers::const_iterator match =
std::find_if(myHeaders.begin(), myHeaders.end(), ::Matches(field));
return ((match != myHeaders.end()) && !match->second.empty());
}
std::string Message::header ( const std::string& field ) const
{
const Headers::const_iterator match =
std::find_if(myHeaders.begin(), myHeaders.end(), ::Matches(field));
if ( match == myHeaders.end() ) {
return ("");
}
return (match->second);
}
const std::string& Message::body () const
{
return (myBody);
}
}
<commit_msg>Fixes overflow handling.<commit_after>// Copyright(c) Andre Caron <andre.l.caron@gmail.com>, 2011
//
// This document is covered by the an Open Source Initiative approved license. A
// copy of the license should have been provided alongside this software package
// (see "LICENSE.txt"). If not, terms of the license are available online at
// "http://www.opensource.org/licenses/mit".
#include "Message.hpp"
#include "Error.hpp"
#include "Flags.hpp"
#include "icompare.hpp"
#include <algorithm>
#include <cstring>
#include <utility>
namespace {
struct Clear {
typedef std::pair<const std::string, std::string> Header;
void operator() ( Header& header ) const { header.second.clear(); }
};
class Matches
{
const std::string& myField;
public:
Matches ( const std::string& field )
: myField(field)
{}
bool operator() ( const std::pair<std::string,std::string>& field )
{
return (http::ieq(field.first, myField));
}
};
}
namespace http {
int Message::on_message_begin ( ::http_parser * parser )
{
Message& message = *static_cast<Message*>(parser->data);
message.myComplete = false;
message.myHeadersComplete = false;
return (0);
}
int Message::on_message_complete ( ::http_parser * parser )
{
Message& message = *static_cast<Message*>(parser->data);
message.myComplete = true;
return (0);
}
int Message::on_header_field
( ::http_parser * parser, const char * data, size_t size )
{
Message& message = *static_cast<Message*>(parser->data);
if ( !message.myCurrentValue.empty() )
{
message.myHeaders[message.myCurrentField] =
message.myCurrentValue;
message.myCurrentField.clear();
message.myCurrentValue.clear();
}
message.myCurrentField.append(data, size);
return (0);
}
int Message::on_header_value
( ::http_parser * parser, const char * data, size_t size )
{
Message& message = *static_cast<Message*>(parser->data);
message.myCurrentValue.append(data, size);
return (0);
}
int Message::on_headers_complete ( ::http_parser * parser )
{
Message& message = *static_cast<Message*>(parser->data);
if ( !message.myCurrentValue.empty() )
{
message.myHeaders[message.myCurrentField] =
message.myCurrentValue;
message.myCurrentField.clear();
message.myCurrentValue.clear();
}
message.myHeadersComplete = true;
return (0);
}
int Message::on_body
( ::http_parser * parser, const char * data, size_t size )
{
Message& message = *static_cast<Message*>(parser->data);
message.myBody.append(data, size);
return (0);
}
Message::Message ()
{
// make sure message is not seen as complete.
myComplete = false;
myHeadersComplete = false;
// select callbacks.
::memset(&mySettings, 0, sizeof(mySettings));
mySettings.on_message_complete = &Message::on_message_complete;
mySettings.on_message_begin = &Message::on_message_begin;
mySettings.on_header_field = &Message::on_header_field;
mySettings.on_header_value = &Message::on_header_value;
mySettings.on_headers_complete = &Message::on_headers_complete;
mySettings.on_body = &Message::on_body;
}
void Message::clear ()
{
// make sure message is not seen as complete.
myComplete = false;
myHeadersComplete = false;
// clear string content, while keeping memory allocated.
std::for_each(myHeaders.begin(), myHeaders.end(), Clear());
myBody.clear();
}
std::size_t Message::feed ( const void * data, ::size_t size )
{
return (feed(static_cast<const char*>(data), size));
}
std::size_t Message::feed ( const char * data, ::size_t size )
{
return (::http_parser_execute(&myParser, &mySettings, data, size));
}
bool Message::complete () const
{
return (myComplete);
}
bool Message::headerscomplete () const
{
return (myHeadersComplete);
}
int Message::minorversion () const
{
return (myParser.http_minor);
}
const Flags Message::flags () const
{
return (Flags::of(myParser));
}
bool Message::hasheader ( const std::string& field ) const
{
const Headers::const_iterator match =
std::find_if(myHeaders.begin(), myHeaders.end(), ::Matches(field));
return ((match != myHeaders.end()) && !match->second.empty());
}
std::string Message::header ( const std::string& field ) const
{
const Headers::const_iterator match =
std::find_if(myHeaders.begin(), myHeaders.end(), ::Matches(field));
if ( match == myHeaders.end() ) {
return ("");
}
return (match->second);
}
const std::string& Message::body () const
{
return (myBody);
}
}
<|endoftext|> |
<commit_before>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#ifdef _MSC_VER
#pragma warning ( disable : 4786 )
#endif
#include "itkExceptionObject.h"
#include "itkIOCommon.h"
#include "itkDataBaseImageIO.h"
#include "itksys/SystemTools.hxx"
namespace itk
{
DataBaseImageIO::DataBaseImageIO()
{
}
DataBaseImageIO::~DataBaseImageIO()
{
}
void DataBaseImageIO::PrintSelf(std::ostream& os, Indent indent) const
{
Superclass::PrintSelf(os, indent);
}
bool DataBaseImageIO::CanReadFile( const char* filename )
{
// FIXME Implement
return true;
}
void DataBaseImageIO::ReadImageInformation()
{
// FIXME: Talk to the database, figure out what kind of image is this, and
// then populate the information below.
this->SetPixelType( SCALAR );
this->SetComponentType( UCHAR );
this->SetDimensions( 0, nx );
this->SetDimensions( 1, ny );
this->SetDimensions( 2, nz );
this->SetSpacing( 0, dx );
this->SetSpacing( 1, dy );
this->SetSpacing( 2, dz );
}
void DataBaseImageIO::Read( void * buffer)
{
// Get region from the streaming layer:
//
const unsigned int nx = this->GetDimensions( 0 );
const unsigned int ny = this->GetDimensions( 1 );
const unsigned int nz = this->GetDimensions( 2 );
ImageIORegion regionToRead = this->GetIORegion();
ImageIORegion::SizeType size = regionToRead.GetSize();
ImageIORegion::IndexType start = regionToRead.GetIndex();
const unsigned int mx = size[0];
const unsigned int my = size[1];
const unsigned int mz = size[2];
const unsigned int sx = start[0];
const unsigned int sy = start[1];
const unsigned int sz = start[2];
// FIXME: Talk to the database and get this region of extent "size", and
// begining from the "start" index.
// Put the data in this pointer below.
// The memory for it, is already allocated.
char * inptr = static_cast< char * >( buffer );
}
bool DataBaseImageIO::CanWriteFile( const char * name )
{
//
// DataBase is not implemented to write yet.
// It will be soon...
//
return false;
}
void
DataBaseImageIO
::WriteImageInformation(void)
{
// add writing here
}
/**
*
*/
void
DataBaseImageIO
::Write( const void* buffer)
{
}
/** Given a requested region, determine what could be the region that we can
* read from the file. This is called the streamable region, which will be
* smaller than the LargestPossibleRegion and greater or equal to the
RequestedRegion */
ImageIORegion
DataBaseImageIO
::GenerateStreamableReadRegionFromRequestedRegion( const ImageIORegion & requested ) const
{
// FIXME: talk to the database, figure out what is the smallest region that you can get from the database, and still fully contain the "requested"
// This will be the code if the database is a perfect streamer: meaning that it will deliver any subpiece that you ask for.
ImageIORegion streamableRegion = requested;
return streamableRegion;
// On the other extreme, an IO that does not stream, will return the LargestPossibleRegion
}
} // end namespace itk
<commit_msg>COMP: should not include itkExceptionObject.h but itkMacro.h<commit_after>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#ifdef _MSC_VER
#pragma warning ( disable : 4786 )
#endif
#include "itkMacro.h"
#include "itkIOCommon.h"
#include "itkDataBaseImageIO.h"
#include "itksys/SystemTools.hxx"
namespace itk
{
DataBaseImageIO::DataBaseImageIO()
{
}
DataBaseImageIO::~DataBaseImageIO()
{
}
void DataBaseImageIO::PrintSelf(std::ostream& os, Indent indent) const
{
Superclass::PrintSelf(os, indent);
}
bool DataBaseImageIO::CanReadFile( const char* filename )
{
// FIXME Implement
return true;
}
void DataBaseImageIO::ReadImageInformation()
{
// FIXME: Talk to the database, figure out what kind of image is this, and
// then populate the information below.
this->SetPixelType( SCALAR );
this->SetComponentType( UCHAR );
this->SetDimensions( 0, nx );
this->SetDimensions( 1, ny );
this->SetDimensions( 2, nz );
this->SetSpacing( 0, dx );
this->SetSpacing( 1, dy );
this->SetSpacing( 2, dz );
}
void DataBaseImageIO::Read( void * buffer)
{
// Get region from the streaming layer:
//
const unsigned int nx = this->GetDimensions( 0 );
const unsigned int ny = this->GetDimensions( 1 );
const unsigned int nz = this->GetDimensions( 2 );
ImageIORegion regionToRead = this->GetIORegion();
ImageIORegion::SizeType size = regionToRead.GetSize();
ImageIORegion::IndexType start = regionToRead.GetIndex();
const unsigned int mx = size[0];
const unsigned int my = size[1];
const unsigned int mz = size[2];
const unsigned int sx = start[0];
const unsigned int sy = start[1];
const unsigned int sz = start[2];
// FIXME: Talk to the database and get this region of extent "size", and
// begining from the "start" index.
// Put the data in this pointer below.
// The memory for it, is already allocated.
char * inptr = static_cast< char * >( buffer );
}
bool DataBaseImageIO::CanWriteFile( const char * name )
{
//
// DataBase is not implemented to write yet.
// It will be soon...
//
return false;
}
void
DataBaseImageIO
::WriteImageInformation(void)
{
// add writing here
}
/**
*
*/
void
DataBaseImageIO
::Write( const void* buffer)
{
}
/** Given a requested region, determine what could be the region that we can
* read from the file. This is called the streamable region, which will be
* smaller than the LargestPossibleRegion and greater or equal to the
RequestedRegion */
ImageIORegion
DataBaseImageIO
::GenerateStreamableReadRegionFromRequestedRegion( const ImageIORegion & requested ) const
{
// FIXME: talk to the database, figure out what is the smallest region that you can get from the database, and still fully contain the "requested"
// This will be the code if the database is a perfect streamer: meaning that it will deliver any subpiece that you ask for.
ImageIORegion streamableRegion = requested;
return streamableRegion;
// On the other extreme, an IO that does not stream, will return the LargestPossibleRegion
}
} // end namespace itk
<|endoftext|> |
<commit_before>///////////////////////////////////////////////////////////////////////////
//
// SneezyMUD++ 4.5 - All rights reserved, SneezyMUD Coding Team
// "fuel.cc" - Methods for TFuel class
//
// Last revision December 18, 1997.
//
///////////////////////////////////////////////////////////////////////////
#include "stdsneezy.h"
#include "obj_fuel.h"
#include "obj_light.h"
TFuel::TFuel() :
TObj(),
curFuel(0),
maxFuel(0)
{
}
TFuel::TFuel(const TFuel &a) :
TObj(a),
curFuel(a.curFuel),
maxFuel(a.maxFuel)
{
}
TFuel & TFuel::operator=(const TFuel &a)
{
if (this == &a) return *this;
TObj::operator=(a);
curFuel = a.curFuel;
maxFuel = a.maxFuel;
return *this;
}
TFuel::~TFuel()
{
}
void TFuel::addToMaxFuel(int n)
{
maxFuel += n;
}
void TFuel::setMaxFuel(int n)
{
maxFuel = n;
}
int TFuel::getMaxFuel() const
{
return maxFuel;
}
void TFuel::addToCurFuel(int n)
{
curFuel += n;
}
void TFuel::setCurFuel(int n)
{
curFuel = n;
}
int TFuel::getCurFuel() const
{
return curFuel;
}
void TFuel::describeObjectSpecifics(const TBeing *ch) const
{
double diff;
if (getMaxFuel()) {
diff = (double) ((double) getCurFuel() / (double) getMaxFuel());
ch->sendTo(COLOR_OBJECTS,
fmt("You can tell that %s has %s of its fuel left.\n\r") %
sstring(getName()).uncap() %
((diff < .20) ? "very little" : ((diff < .50) ? "some" :
((diff < .75) ? "a good bit of" : "almost all of its"))));
}
}
void TFuel::refuelMeFuel(TBeing *ch, TLight *lamp)
{
int use;
if (lamp->getMaxBurn() < 0) {
act("$p can't be refueled.", FALSE, ch, lamp, 0, TO_CHAR);
return;
}
if (lamp->getCurBurn() == lamp->getMaxBurn()) {
act("$p is already full of fuel.", FALSE, ch, lamp, 0, TO_CHAR);
return;
}
if (lamp->isLit()) {
ch->sendTo("You better not fuel that while lit, it might explode.\n\r");
return;
}
use = lamp->getMaxBurn() - lamp->getCurBurn();
use = min(use, getCurFuel());
act("$n refuels $s $o.", TRUE, ch, lamp, 0, TO_ROOM);
ch->sendTo(fmt("You refuel your %s.\n\r") % fname(lamp->name));
addToCurFuel(-use);
lamp->addToCurBurn(use);
if (getCurFuel() <= 0) {
ch->sendTo("Your fuel is all used up, and you discard it.\n\r");
if (equippedBy) {
dynamic_cast<TBeing *>(equippedBy)->unequip(eq_pos);
} else
--(*this);
delete this;
}
}
void TFuel::assignFourValues(int x1, int x2, int, int)
{
setCurFuel(x1);
setMaxFuel(x2);
}
void TFuel::getFourValues(int *x1, int *x2, int *x3, int *x4) const
{
*x1 = getCurFuel();
*x2 = getMaxFuel();
*x3 = 0;
*x4 = 0;
}
void TFuel::lowCheck()
{
if (getCurFuel() > getMaxFuel())
vlogf(LOG_LOW,fmt("fuel %s had more current fuel than max.") % getName());
TObj::lowCheck();
}
int TFuel::objectSell(TBeing *ch, TMonster *keeper)
{
keeper->doTell(ch->getName(), "I'm sorry, I don't buy back fuel.");
return TRUE;
}
sstring TFuel::statObjInfo() const
{
char buf[256];
sprintf(buf, "Refuel capability : current : %d, max : %d",
getCurFuel(), getMaxFuel());
sstring a(buf);
return a;
}
int TFuel::getVolume() const
{
int amt = TObj::getVolume();
amt *= getCurFuel();
if(getMaxFuel())
amt /= getMaxFuel();
return amt;
}
float TFuel::getTotalWeight(bool pweight) const
{
float amt = TObj::getTotalWeight(pweight);
amt *= getCurFuel();
if(getMaxFuel())
amt /= getMaxFuel();
return amt;
}
int TFuel::chiMe(TBeing *tLunatic)
{
int tMana = ::number(10, 30),
bKnown = tLunatic->getSkillLevel(SKILL_CHI),
tDamage,
tRc = DELETE_VICT;
TThing *tThing,
*tNextThing;
TBeing *tBeing;
if (tLunatic->getMana() < tMana) {
tLunatic->sendTo("You lack the chi to do this!\n\r");
return RET_STOP_PARSING;
} else
tLunatic->reconcileMana(TYPE_UNDEFINED, 0, tMana);
if (tLunatic->checkPeaceful("Violent things can not be done here and something tells you that would be violent!"))
return FALSE;
if (!tLunatic->bSuccess(bKnown, SKILL_CHI)) {
act("You fail to affect $p in any way.",
FALSE, tLunatic, this, NULL, TO_CHAR);
return true;
}
act("You focus upon $p causing it to blow up violently!",
FALSE, tLunatic, this, NULL, TO_CHAR);
act("$n concentrates upon $p, causing it to blow up violently",
TRUE, tLunatic, this, NULL, TO_ROOM);
tDamage = max(1, (::number((getCurFuel() / 2), getCurFuel()) / 10));
for (tThing = roomp->getStuff(); tThing; tThing = tNextThing) {
tNextThing = tThing->nextThing;
if (!(tBeing = dynamic_cast<TBeing *>(tThing)) || tBeing->isImmortal())
continue;
act("You are struck by the flames, caused by $n!",
FALSE, tLunatic, NULL, tBeing, TO_VICT);
if (tBeing->isPc()) {
if (tBeing->reconcileDamage(tBeing, ::number(1, tDamage), DAMAGE_FIRE) == -1) {
if (tBeing == tLunatic)
ADD_DELETE(tRc, (DELETE_THIS | RET_STOP_PARSING));
else {
delete tThing;
tThing = NULL;
}
}
} else {
if (tLunatic->reconcileDamage(tBeing, ::number(1, tDamage), DAMAGE_FIRE) == -1) {
delete tThing;
tThing = NULL;
}
}
}
return tRc;
}
<commit_msg>Added a check for roomp in TFuel::chiMe(). Hold a brick, chi it, crash the MUD.<commit_after>///////////////////////////////////////////////////////////////////////////
//
// SneezyMUD++ 4.5 - All rights reserved, SneezyMUD Coding Team
// "fuel.cc" - Methods for TFuel class
//
// Last revision December 18, 1997.
//
///////////////////////////////////////////////////////////////////////////
#include "stdsneezy.h"
#include "obj_fuel.h"
#include "obj_light.h"
TFuel::TFuel() :
TObj(),
curFuel(0),
maxFuel(0)
{
}
TFuel::TFuel(const TFuel &a) :
TObj(a),
curFuel(a.curFuel),
maxFuel(a.maxFuel)
{
}
TFuel & TFuel::operator=(const TFuel &a)
{
if (this == &a) return *this;
TObj::operator=(a);
curFuel = a.curFuel;
maxFuel = a.maxFuel;
return *this;
}
TFuel::~TFuel()
{
}
void TFuel::addToMaxFuel(int n)
{
maxFuel += n;
}
void TFuel::setMaxFuel(int n)
{
maxFuel = n;
}
int TFuel::getMaxFuel() const
{
return maxFuel;
}
void TFuel::addToCurFuel(int n)
{
curFuel += n;
}
void TFuel::setCurFuel(int n)
{
curFuel = n;
}
int TFuel::getCurFuel() const
{
return curFuel;
}
void TFuel::describeObjectSpecifics(const TBeing *ch) const
{
double diff;
if (getMaxFuel()) {
diff = (double) ((double) getCurFuel() / (double) getMaxFuel());
ch->sendTo(COLOR_OBJECTS,
fmt("You can tell that %s has %s of its fuel left.\n\r") %
sstring(getName()).uncap() %
((diff < .20) ? "very little" : ((diff < .50) ? "some" :
((diff < .75) ? "a good bit of" : "almost all of its"))));
}
}
void TFuel::refuelMeFuel(TBeing *ch, TLight *lamp)
{
int use;
if (lamp->getMaxBurn() < 0) {
act("$p can't be refueled.", FALSE, ch, lamp, 0, TO_CHAR);
return;
}
if (lamp->getCurBurn() == lamp->getMaxBurn()) {
act("$p is already full of fuel.", FALSE, ch, lamp, 0, TO_CHAR);
return;
}
if (lamp->isLit()) {
ch->sendTo("You better not fuel that while lit, it might explode.\n\r");
return;
}
use = lamp->getMaxBurn() - lamp->getCurBurn();
use = min(use, getCurFuel());
act("$n refuels $s $o.", TRUE, ch, lamp, 0, TO_ROOM);
ch->sendTo(fmt("You refuel your %s.\n\r") % fname(lamp->name));
addToCurFuel(-use);
lamp->addToCurBurn(use);
if (getCurFuel() <= 0) {
ch->sendTo("Your fuel is all used up, and you discard it.\n\r");
if (equippedBy) {
dynamic_cast<TBeing *>(equippedBy)->unequip(eq_pos);
} else
--(*this);
delete this;
}
}
void TFuel::assignFourValues(int x1, int x2, int, int)
{
setCurFuel(x1);
setMaxFuel(x2);
}
void TFuel::getFourValues(int *x1, int *x2, int *x3, int *x4) const
{
*x1 = getCurFuel();
*x2 = getMaxFuel();
*x3 = 0;
*x4 = 0;
}
void TFuel::lowCheck()
{
if (getCurFuel() > getMaxFuel())
vlogf(LOG_LOW,fmt("fuel %s had more current fuel than max.") % getName());
TObj::lowCheck();
}
int TFuel::objectSell(TBeing *ch, TMonster *keeper)
{
keeper->doTell(ch->getName(), "I'm sorry, I don't buy back fuel.");
return TRUE;
}
sstring TFuel::statObjInfo() const
{
char buf[256];
sprintf(buf, "Refuel capability : current : %d, max : %d",
getCurFuel(), getMaxFuel());
sstring a(buf);
return a;
}
int TFuel::getVolume() const
{
int amt = TObj::getVolume();
amt *= getCurFuel();
if(getMaxFuel())
amt /= getMaxFuel();
return amt;
}
float TFuel::getTotalWeight(bool pweight) const
{
float amt = TObj::getTotalWeight(pweight);
amt *= getCurFuel();
if(getMaxFuel())
amt /= getMaxFuel();
return amt;
}
int TFuel::chiMe(TBeing *tLunatic)
{
int tMana = ::number(10, 30),
bKnown = tLunatic->getSkillLevel(SKILL_CHI),
tDamage,
tRc = DELETE_VICT;
TThing *tThing,
*tNextThing;
TBeing *tBeing;
if (tLunatic->getMana() < tMana) {
tLunatic->sendTo("You lack the chi to do this!\n\r");
return RET_STOP_PARSING;
} else
tLunatic->reconcileMana(TYPE_UNDEFINED, 0, tMana);
if (tLunatic->checkPeaceful("Violent things can not be done here and something tells you that would be violent!"))
return FALSE;
if (!roomp) {
// added to prevent crashes when item is held, etc.
act("You must be more cautious to chi something so volatile.", FALSE, tLunatic, this, NULL, TO_CHAR);
return FALSE;
}
if (!tLunatic->bSuccess(bKnown, SKILL_CHI)) {
act("You fail to affect $p in any way.",
FALSE, tLunatic, this, NULL, TO_CHAR);
return true;
}
act("You focus upon $p causing it to blow up violently!",
FALSE, tLunatic, this, NULL, TO_CHAR);
act("$n concentrates upon $p, causing it to blow up violently",
TRUE, tLunatic, this, NULL, TO_ROOM);
tDamage = max(1, (::number((getCurFuel() / 2), getCurFuel()) / 10));
for (tThing = roomp->getStuff(); tThing; tThing = tNextThing) {
tNextThing = tThing->nextThing;
if (!(tBeing = dynamic_cast<TBeing *>(tThing)) || tBeing->isImmortal())
continue;
act("You are struck by the flames, caused by $n!",
FALSE, tLunatic, NULL, tBeing, TO_VICT);
if (tBeing->isPc()) {
if (tBeing->reconcileDamage(tBeing, ::number(1, tDamage), DAMAGE_FIRE) == -1) {
if (tBeing == tLunatic)
ADD_DELETE(tRc, (DELETE_THIS | RET_STOP_PARSING));
else {
delete tThing;
tThing = NULL;
}
}
} else {
if (tLunatic->reconcileDamage(tBeing, ::number(1, tDamage), DAMAGE_FIRE) == -1) {
delete tThing;
tThing = NULL;
}
}
}
return tRc;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2017-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "thrift/lib/cpp2/transport/rsocket/client/RSClientThriftChannel.h"
#include <proxygen/lib/utils/WheelTimerInstance.h>
#include <thrift/lib/cpp2/protocol/CompactProtocol.h>
#include <thrift/lib/cpp2/transport/rsocket/client/RPCSubscriber.h>
namespace apache {
namespace thrift {
using namespace apache::thrift::transport;
using namespace apache::thrift::detail;
using namespace rsocket;
using namespace yarpl::single;
using proxygen::WheelTimerInstance;
std::unique_ptr<folly::IOBuf> RSClientThriftChannel::serializeMetadata(
const RequestRpcMetadata& requestMetadata) {
CompactProtocolWriter writer;
folly::IOBufQueue queue;
writer.setOutput(&queue);
requestMetadata.write(&writer);
return queue.move();
}
std::unique_ptr<ResponseRpcMetadata> RSClientThriftChannel::deserializeMetadata(
const folly::IOBuf& buffer) {
CompactProtocolReader reader;
auto responseMetadata = std::make_unique<ResponseRpcMetadata>();
reader.setInput(&buffer);
responseMetadata->read(&reader);
return responseMetadata;
}
namespace {
// This default value should match with the
// H2ClientConnection::kDefaultTransactionTimeout's value.
static constexpr std::chrono::milliseconds kDefaultRequestTimeout =
std::chrono::milliseconds(500);
// Adds a timer that timesout if the observer could not get its onSuccess or
// onError methods being called in a specified time range, which causes onError
// method to be called.
class TimedSingleObserver : public SingleObserverBase<Payload>,
public folly::HHWheelTimer::Callback {
public:
TimedSingleObserver(
std::unique_ptr<ThriftClientCallback> callback,
std::chrono::milliseconds timeout,
ChannelCounters& counters)
: timeout_(timeout),
timer_(timeout, callback->getEventBase()),
callback_(std::move(callback)),
counters_(counters) {}
virtual ~TimedSingleObserver() {
complete();
}
void setDecrementPendingRequestCounter() {
decrementPendingRequestCounter_ = true;
}
protected:
void onSubscribe(Reference<SingleSubscription> subscription) override {
auto ref = this->ref_from_this(this);
SingleObserverBase<Payload>::onSubscribe(std::move(subscription));
auto evb = callback_->getEventBase();
evb->runInEventBaseThread([this]() {
callback_->onThriftRequestSent();
if (timeout_.count() > 0) {
timer_.scheduleTimeout(this, timeout_);
}
});
}
void onSuccess(Payload payload) override {
auto ref = this->ref_from_this(this);
auto evb = callback_->getEventBase();
evb->runInEventBaseThread([ref, payload = std::move(payload)]() mutable {
if (ref->complete()) {
ref->callback_->onThriftResponse(
payload.metadata
? RSClientThriftChannel::deserializeMetadata(*payload.metadata)
: std::make_unique<ResponseRpcMetadata>(),
std::move(payload.data));
}
});
if (SingleObserverBase<Payload>::subscription()) {
// TODO: can we get rid of calling the parent functions
SingleObserverBase<Payload>::onSuccess({});
}
}
void onError(folly::exception_wrapper ew) override {
auto ref = this->ref_from_this(this);
auto evb = callback_->getEventBase();
evb->runInEventBaseThread([ref, ew = std::move(ew)]() mutable {
if (ref->complete()) {
ref->callback_->onError(std::move(ew));
// TODO: Inspect the cases where might we end up in this function.
// 1- server closes the stream before all the messages are
// delievered.
// 2- time outs
}
});
if (SingleObserverBase<Payload>::subscription()) {
// TODO: can we get rid of calling the parent functions
SingleObserverBase<Payload>::onError({});
}
}
void timeoutExpired() noexcept override {
onError(folly::make_exception_wrapper<TTransportException>(
apache::thrift::transport::TTransportException::TIMED_OUT));
}
void callbackCanceled() noexcept override {
// nothing!
}
bool complete() {
if (alreadySignalled_) {
return false;
}
alreadySignalled_ = true;
cancelTimeout();
if (decrementPendingRequestCounter_) {
counters_.decPendingRequests();
decrementPendingRequestCounter_ = false;
}
return true;
}
private:
std::chrono::milliseconds timeout_;
// TODO: WheelTimerInstance is part of Proxygen, we need to use another timer.
WheelTimerInstance timer_;
std::unique_ptr<ThriftClientCallback> callback_;
apache::thrift::detail::ChannelCounters& counters_;
bool alreadySignalled_{false};
bool decrementPendingRequestCounter_{false};
};
} // namespace
RSClientThriftChannel::RSClientThriftChannel(
std::shared_ptr<RSocketRequester> rsRequester,
ChannelCounters& channelCounters)
: rsRequester_(std::move(rsRequester)), channelCounters_(channelCounters) {}
void RSClientThriftChannel::sendThriftRequest(
std::unique_ptr<RequestRpcMetadata> metadata,
std::unique_ptr<folly::IOBuf> payload,
std::unique_ptr<ThriftClientCallback> callback) noexcept {
DCHECK(metadata->__isset.kind);
if (!rsRequester_) {
if (callback) {
auto evb = callback->getEventBase();
evb->runInEventBaseThread([evbCallback = std::move(callback)]() mutable {
evbCallback->onError(folly::make_exception_wrapper<TTransportException>(
TTransportException::NOT_OPEN));
});
}
return;
}
metadata->seqId = 0;
metadata->__isset.seqId = true;
switch (metadata->kind) {
case RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE:
sendSingleRequestResponse(
std::move(metadata), std::move(payload), std::move(callback));
break;
case RpcKind::SINGLE_REQUEST_NO_RESPONSE:
sendSingleRequestNoResponse(
std::move(metadata), std::move(payload), std::move(callback));
break;
case RpcKind::STREAMING_REQUEST_STREAMING_RESPONSE:
channelRequest(std::move(metadata), std::move(payload));
break;
default:
LOG(FATAL) << "not implemented";
}
}
void RSClientThriftChannel::sendSingleRequestNoResponse(
std::unique_ptr<RequestRpcMetadata> requestMetadata,
std::unique_ptr<folly::IOBuf> buf,
std::unique_ptr<ThriftClientCallback> callback) noexcept {
DCHECK(requestMetadata);
if (channelCounters_.incPendingRequests()) {
auto guard =
folly::makeGuard([&] { channelCounters_.decPendingRequests(); });
rsRequester_
->fireAndForget(rsocket::Payload(
std::move(buf), serializeMetadata(*requestMetadata)))
->subscribe([] {});
} else {
LOG(ERROR) << "max number of pending requests is exceeded";
}
auto cbEvb = callback->getEventBase();
cbEvb->runInEventBaseThread(
[cb = std::move(callback)]() mutable { cb->onThriftRequestSent(); });
}
void RSClientThriftChannel::sendSingleRequestResponse(
std::unique_ptr<RequestRpcMetadata> requestMetadata,
std::unique_ptr<folly::IOBuf> buf,
std::unique_ptr<ThriftClientCallback> callback) noexcept {
DCHECK(requestMetadata);
auto timeout = kDefaultRequestTimeout;
if (requestMetadata->__isset.clientTimeoutMs) {
timeout = std::chrono::milliseconds(requestMetadata->clientTimeoutMs);
}
auto singleObserver = yarpl::make_ref<TimedSingleObserver>(
std::move(callback), timeout, channelCounters_);
if (channelCounters_.incPendingRequests()) {
singleObserver->setDecrementPendingRequestCounter();
// As we send clientTimeoutMs, queueTimeoutMs and priority values using
// RequestRpcMetadata object, there is no need for RSocket to put them to
// metadata->otherMetadata map.
rsRequester_
->requestResponse(rsocket::Payload(
std::move(buf), serializeMetadata(*requestMetadata)))
->subscribe(std::move(singleObserver));
} else {
TTransportException ex(
TTransportException::NETWORK_ERROR,
"Too many active requests on connection");
// Might be able to create another transaction soon
ex.setOptions(TTransportException::CHANNEL_IS_VALID);
yarpl::single::Singles::error<Payload>(
folly::make_exception_wrapper<TTransportException>(std::move(ex)))
->subscribe(std::move(singleObserver));
}
}
void RSClientThriftChannel::channelRequest(
std::unique_ptr<RequestRpcMetadata> metadata,
std::unique_ptr<folly::IOBuf> payload) noexcept {
auto input = yarpl::flowable::Flowables::fromPublisher<rsocket::Payload>(
[this, initialBuf = std::move(payload), metadata = std::move(metadata)](
yarpl::Reference<yarpl::flowable::Subscriber<rsocket::Payload>>
subscriber) mutable {
VLOG(3) << "Input is started to be consumed: "
<< initialBuf->cloneAsValue().moveToFbString().toStdString();
outputPromise_.setValue(yarpl::make_ref<RPCSubscriber>(
serializeMetadata(*metadata),
std::move(initialBuf),
std::move(subscriber)));
});
// Perform the rpc call
auto result = rsRequester_->requestChannel(input);
result
->map([](auto payload) -> std::unique_ptr<folly::IOBuf> {
VLOG(3) << "Request channel: "
<< payload.data->cloneAsValue().moveToFbString().toStdString();
// TODO - don't drop the headers
return std::move(payload.data);
})
->subscribe(input_);
}
// ChannelCounters' functions
static constexpr uint32_t kMaxPendingRequests =
std::numeric_limits<uint32_t>::max();
ChannelCounters::ChannelCounters()
: maxPendingRequests_(kMaxPendingRequests),
requestTimeout_(kDefaultRequestTimeout) {}
void ChannelCounters::setMaxPendingRequests(uint32_t count) {
maxPendingRequests_ = count;
}
uint32_t ChannelCounters::getMaxPendingRequests() {
return maxPendingRequests_;
}
uint32_t ChannelCounters::getPendingRequests() {
return pendingRequests_;
}
bool ChannelCounters::incPendingRequests() {
if (pendingRequests_ >= maxPendingRequests_) {
return false;
}
++pendingRequests_;
return true;
}
void ChannelCounters::decPendingRequests() {
--pendingRequests_;
}
void ChannelCounters::setRequestTimeout(std::chrono::milliseconds timeout) {
requestTimeout_ = timeout;
}
std::chrono::milliseconds ChannelCounters::getRequestTimeout() {
return requestTimeout_;
}
} // namespace thrift
} // namespace apache
<commit_msg>Remove dependency to Proxygen for the HHWheelTimerInstance<commit_after>/*
* Copyright 2017-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "thrift/lib/cpp2/transport/rsocket/client/RSClientThriftChannel.h"
#include <thrift/lib/cpp2/protocol/CompactProtocol.h>
#include <thrift/lib/cpp2/transport/rsocket/client/RPCSubscriber.h>
namespace apache {
namespace thrift {
using namespace apache::thrift::transport;
using namespace apache::thrift::detail;
using namespace rsocket;
using namespace yarpl::single;
std::unique_ptr<folly::IOBuf> RSClientThriftChannel::serializeMetadata(
const RequestRpcMetadata& requestMetadata) {
CompactProtocolWriter writer;
folly::IOBufQueue queue;
writer.setOutput(&queue);
requestMetadata.write(&writer);
return queue.move();
}
std::unique_ptr<ResponseRpcMetadata> RSClientThriftChannel::deserializeMetadata(
const folly::IOBuf& buffer) {
CompactProtocolReader reader;
auto responseMetadata = std::make_unique<ResponseRpcMetadata>();
reader.setInput(&buffer);
responseMetadata->read(&reader);
return responseMetadata;
}
namespace {
// This default value should match with the
// H2ClientConnection::kDefaultTransactionTimeout's value.
static constexpr std::chrono::milliseconds kDefaultRequestTimeout =
std::chrono::milliseconds(500);
// Adds a timer that timesout if the observer could not get its onSuccess or
// onError methods being called in a specified time range, which causes onError
// method to be called.
class TimedSingleObserver : public SingleObserver<Payload>,
public folly::HHWheelTimer::Callback {
public:
TimedSingleObserver(
std::unique_ptr<ThriftClientCallback> callback,
std::chrono::milliseconds timeout,
ChannelCounters& counters)
: callback_(std::move(callback)),
counters_(counters),
timeout_(timeout),
timer_(callback_->getEventBase()->timer()) {}
virtual ~TimedSingleObserver() {
complete();
}
void setDecrementPendingRequestCounter() {
decrementPendingRequestCounter_ = true;
}
protected:
void onSubscribe(Reference<SingleSubscription>) override {
// Note that we don't need the Subscription object.
auto evb = callback_->getEventBase();
evb->runInEventBaseThread([this]() {
callback_->onThriftRequestSent();
if (timeout_.count() > 0) {
timer_.scheduleTimeout(this, timeout_);
}
});
}
void onSuccess(Payload payload) override {
auto ref = this->ref_from_this(this);
auto evb = callback_->getEventBase();
evb->runInEventBaseThread([ref, payload = std::move(payload)]() mutable {
if (ref->complete()) {
ref->callback_->onThriftResponse(
payload.metadata
? RSClientThriftChannel::deserializeMetadata(*payload.metadata)
: std::make_unique<ResponseRpcMetadata>(),
std::move(payload.data));
}
});
}
void onError(folly::exception_wrapper ew) override {
auto ref = this->ref_from_this(this);
auto evb = callback_->getEventBase();
evb->runInEventBaseThread([ref, ew = std::move(ew)]() mutable {
if (ref->complete()) {
ref->callback_->onError(std::move(ew));
// TODO: Inspect the cases where might we end up in this function.
// 1- server closes the stream before all the messages are
// delievered.
// 2- time outs
}
});
}
void timeoutExpired() noexcept override {
onError(folly::make_exception_wrapper<TTransportException>(
apache::thrift::transport::TTransportException::TIMED_OUT));
}
void callbackCanceled() noexcept override {
// nothing!
}
bool complete() {
if (alreadySignalled_) {
return false;
}
alreadySignalled_ = true;
if (decrementPendingRequestCounter_) {
counters_.decPendingRequests();
decrementPendingRequestCounter_ = false;
}
return true;
}
private:
std::unique_ptr<ThriftClientCallback> callback_;
apache::thrift::detail::ChannelCounters& counters_;
std::chrono::milliseconds timeout_;
folly::HHWheelTimer& timer_;
bool alreadySignalled_{false};
bool decrementPendingRequestCounter_{false};
};
} // namespace
RSClientThriftChannel::RSClientThriftChannel(
std::shared_ptr<RSocketRequester> rsRequester,
ChannelCounters& channelCounters)
: rsRequester_(std::move(rsRequester)), channelCounters_(channelCounters) {}
void RSClientThriftChannel::sendThriftRequest(
std::unique_ptr<RequestRpcMetadata> metadata,
std::unique_ptr<folly::IOBuf> payload,
std::unique_ptr<ThriftClientCallback> callback) noexcept {
DCHECK(metadata->__isset.kind);
if (!rsRequester_) {
if (callback) {
auto evb = callback->getEventBase();
evb->runInEventBaseThread([evbCallback = std::move(callback)]() mutable {
evbCallback->onError(folly::make_exception_wrapper<TTransportException>(
TTransportException::NOT_OPEN));
});
}
return;
}
metadata->seqId = 0;
metadata->__isset.seqId = true;
switch (metadata->kind) {
case RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE:
sendSingleRequestResponse(
std::move(metadata), std::move(payload), std::move(callback));
break;
case RpcKind::SINGLE_REQUEST_NO_RESPONSE:
sendSingleRequestNoResponse(
std::move(metadata), std::move(payload), std::move(callback));
break;
case RpcKind::STREAMING_REQUEST_STREAMING_RESPONSE:
channelRequest(std::move(metadata), std::move(payload));
break;
default:
LOG(FATAL) << "not implemented";
}
}
void RSClientThriftChannel::sendSingleRequestNoResponse(
std::unique_ptr<RequestRpcMetadata> requestMetadata,
std::unique_ptr<folly::IOBuf> buf,
std::unique_ptr<ThriftClientCallback> callback) noexcept {
DCHECK(requestMetadata);
if (channelCounters_.incPendingRequests()) {
auto guard =
folly::makeGuard([&] { channelCounters_.decPendingRequests(); });
rsRequester_
->fireAndForget(rsocket::Payload(
std::move(buf), serializeMetadata(*requestMetadata)))
->subscribe([] {});
} else {
LOG(ERROR) << "max number of pending requests is exceeded";
}
auto cbEvb = callback->getEventBase();
cbEvb->runInEventBaseThread(
[cb = std::move(callback)]() mutable { cb->onThriftRequestSent(); });
}
void RSClientThriftChannel::sendSingleRequestResponse(
std::unique_ptr<RequestRpcMetadata> requestMetadata,
std::unique_ptr<folly::IOBuf> buf,
std::unique_ptr<ThriftClientCallback> callback) noexcept {
DCHECK(requestMetadata);
auto timeout = kDefaultRequestTimeout;
if (requestMetadata->__isset.clientTimeoutMs) {
timeout = std::chrono::milliseconds(requestMetadata->clientTimeoutMs);
}
auto singleObserver = yarpl::make_ref<TimedSingleObserver>(
std::move(callback), timeout, channelCounters_);
if (channelCounters_.incPendingRequests()) {
singleObserver->setDecrementPendingRequestCounter();
// As we send clientTimeoutMs, queueTimeoutMs and priority values using
// RequestRpcMetadata object, there is no need for RSocket to put them to
// metadata->otherMetadata map.
rsRequester_
->requestResponse(rsocket::Payload(
std::move(buf), serializeMetadata(*requestMetadata)))
->subscribe(std::move(singleObserver));
} else {
TTransportException ex(
TTransportException::NETWORK_ERROR,
"Too many active requests on connection");
// Might be able to create another transaction soon
ex.setOptions(TTransportException::CHANNEL_IS_VALID);
yarpl::single::Singles::error<Payload>(
folly::make_exception_wrapper<TTransportException>(std::move(ex)))
->subscribe(std::move(singleObserver));
}
}
void RSClientThriftChannel::channelRequest(
std::unique_ptr<RequestRpcMetadata> metadata,
std::unique_ptr<folly::IOBuf> payload) noexcept {
auto input = yarpl::flowable::Flowables::fromPublisher<rsocket::Payload>(
[this, initialBuf = std::move(payload), metadata = std::move(metadata)](
yarpl::Reference<yarpl::flowable::Subscriber<rsocket::Payload>>
subscriber) mutable {
VLOG(3) << "Input is started to be consumed: "
<< initialBuf->cloneAsValue().moveToFbString().toStdString();
outputPromise_.setValue(yarpl::make_ref<RPCSubscriber>(
serializeMetadata(*metadata),
std::move(initialBuf),
std::move(subscriber)));
});
// Perform the rpc call
auto result = rsRequester_->requestChannel(input);
result
->map([](auto payload) -> std::unique_ptr<folly::IOBuf> {
VLOG(3) << "Request channel: "
<< payload.data->cloneAsValue().moveToFbString().toStdString();
// TODO - don't drop the headers
return std::move(payload.data);
})
->subscribe(input_);
}
// ChannelCounters' functions
static constexpr uint32_t kMaxPendingRequests =
std::numeric_limits<uint32_t>::max();
ChannelCounters::ChannelCounters()
: maxPendingRequests_(kMaxPendingRequests),
requestTimeout_(kDefaultRequestTimeout) {}
void ChannelCounters::setMaxPendingRequests(uint32_t count) {
maxPendingRequests_ = count;
}
uint32_t ChannelCounters::getMaxPendingRequests() {
return maxPendingRequests_;
}
uint32_t ChannelCounters::getPendingRequests() {
return pendingRequests_;
}
bool ChannelCounters::incPendingRequests() {
if (pendingRequests_ >= maxPendingRequests_) {
return false;
}
++pendingRequests_;
return true;
}
void ChannelCounters::decPendingRequests() {
--pendingRequests_;
}
void ChannelCounters::setRequestTimeout(std::chrono::milliseconds timeout) {
requestTimeout_ = timeout;
}
std::chrono::milliseconds ChannelCounters::getRequestTimeout() {
return requestTimeout_;
}
} // namespace thrift
} // namespace apache
<|endoftext|> |
<commit_before>/** @file
traffic_ctl
@section license License
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "traffic_ctl.h"
#include "I_RecProcess.h"
#include "RecordsConfig.h"
#include "ts/I_Layout.h"
#include "ts/runroot.h"
AppVersionInfo CtrlVersionInfo;
const char *CtrlMgmtRecord::name() const { return this->ele->rec_name; }
TSRecordT CtrlMgmtRecord::type() const { return this->ele->rec_type; }
int CtrlMgmtRecord::rclass() const { return this->ele->rec_class; }
int64_t CtrlMgmtRecord::as_int() const {
switch (this->ele->rec_type) {
case TS_REC_INT:
return this->ele->valueT.int_val;
case TS_REC_COUNTER:
return this->ele->valueT.counter_val;
default:
return 0;
}
}
TSMgmtError CtrlMgmtRecord::fetch(const char *name) {
return TSRecordGet(name, this->ele);
}
TSMgmtError CtrlMgmtRecordList::match(const char *name) {
return TSRecordGetMatchMlt(name, this->list);
}
CtrlMgmtRecordValue::CtrlMgmtRecordValue(const CtrlMgmtRecord &rec) {
this->init(rec.ele->rec_type, rec.ele->valueT);
}
CtrlMgmtRecordValue::CtrlMgmtRecordValue(const TSRecordEle *ele) {
this->init(ele->rec_type, ele->valueT);
}
CtrlMgmtRecordValue::CtrlMgmtRecordValue(TSRecordT _t, TSRecordValueT _v) {
this->init(_t, _v);
}
void CtrlMgmtRecordValue::init(TSRecordT _t, TSRecordValueT _v) {
this->rec_type = _t;
switch (this->rec_type) {
case TS_REC_INT:
snprintf(this->fmt.nbuf, sizeof(this->fmt.nbuf), "%" PRId64, _v.int_val);
break;
case TS_REC_COUNTER:
snprintf(this->fmt.nbuf, sizeof(this->fmt.nbuf), "%" PRId64,
_v.counter_val);
break;
case TS_REC_FLOAT:
snprintf(this->fmt.nbuf, sizeof(this->fmt.nbuf), "%f", _v.float_val);
break;
case TS_REC_STRING:
if (strcmp(_v.string_val, "") == 0) {
this->fmt.str = "\"\"";
} else {
this->fmt.str = _v.string_val;
}
break;
default:
rec_type = TS_REC_STRING;
this->fmt.str = "(invalid)";
}
}
const char *CtrlMgmtRecordValue::c_str() const {
switch (this->rec_type) {
case TS_REC_STRING:
return this->fmt.str;
default:
return this->fmt.nbuf;
}
}
void CtrlMgmtError(TSMgmtError err, const char *fmt, ...) {
ats_scoped_str msg(TSGetErrorMessage(err));
if (fmt) {
va_list ap;
fprintf(stderr, "%s: ", program_name);
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
fprintf(stderr, ": %s\n", (const char *)msg);
} else {
fprintf(stderr, "%s: %s\n", program_name, (const char *)msg);
}
}
int CtrlSubcommandUsage(const char *name, const subcommand *cmds,
unsigned ncmds, const ArgumentDescription *desc,
unsigned ndesc) {
const char *opt = ndesc ? "[OPTIONS]" : "";
const char *sep = (ndesc && name) ? " " : "";
fprintf(stderr, "Usage: traffic_ctl %s%s%s CMD [ARGS ...]\n\nSubcommands:\n",
name ? name : "", sep, opt);
for (unsigned i = 0; i < ncmds; ++i) {
fprintf(stderr, " %-16s%s\n", cmds[i].name, cmds[i].help);
}
if (ndesc) {
usage(desc, ndesc, "\nOptions:");
}
return CTRL_EX_USAGE;
}
int CtrlCommandUsage(const char *msg, const ArgumentDescription *desc,
unsigned ndesc) {
fprintf(stderr, "Usage: traffic_ctl %s\n", msg);
if (ndesc) {
usage(desc, ndesc, "\nOptions:");
}
return CTRL_EX_USAGE;
}
bool CtrlProcessArguments(int /* argc */, const char **argv,
const ArgumentDescription *desc, unsigned ndesc) {
n_file_arguments = 0;
return process_args_ex(&CtrlVersionInfo, desc, ndesc, argv);
}
int CtrlUnimplementedCommand(unsigned /* argc */, const char **argv) {
CtrlDebug("the '%s' command is not implemented", *argv);
return CTRL_EX_UNIMPLEMENTED;
}
int CtrlGenericSubcommand(const char *name, const subcommand *cmds,
unsigned ncmds, unsigned argc, const char **argv) {
CtrlCommandLine cmdline;
// Process command line arguments and dump into variables
if (!CtrlProcessArguments(argc, argv, nullptr, 0) || n_file_arguments < 1) {
return CtrlSubcommandUsage(name, cmds, ncmds, nullptr, 0);
}
cmdline.init(n_file_arguments, file_arguments);
for (unsigned i = 0; i < ncmds; ++i) {
if (strcmp(file_arguments[0], cmds[i].name) == 0) {
return cmds[i].handler(cmdline.argc(), cmdline.argv());
}
}
return CtrlSubcommandUsage(name, cmds, ncmds, nullptr, 0);
}
static const subcommand commands[] = {
{subcommand_alarm, "alarm", "Manipulate alarms"},
{subcommand_config, "config", "Manipulate configuration records"},
{subcommand_metric, "metric", "Manipulate performance metrics"},
{subcommand_server, "server", "Stop, restart and examine the server"},
{subcommand_storage, "storage", "Manipulate cache storage"},
{subcommand_plugin, "plugin", "Interact with plugins"},
};
int main(int argc, const char **argv) {
CtrlCommandLine cmdline;
int debug = false;
CtrlVersionInfo.setup(PACKAGE_NAME, "traffic_ctl", PACKAGE_VERSION, __DATE__,
__TIME__, BUILD_MACHINE, BUILD_PERSON, "");
program_name = CtrlVersionInfo.AppStr;
ArgumentDescription argument_descriptions[] = {
{"debug", '-', "Enable debugging output", "F", &debug, nullptr, nullptr},
{"help", 'h', "Print usage information", nullptr, nullptr, nullptr,
[](const ArgumentDescription *args, unsigned nargs,
const char *arg_unused) {
CtrlSubcommandUsage(nullptr, commands, countof(commands), args, nargs);
}},
VERSION_ARGUMENT_DESCRIPTION(),
RUNROOT_ARGUMENT_DESCRIPTION(),
};
BaseLogFile *base_log_file = new BaseLogFile("stderr");
diags =
new Diags(program_name, "" /* tags */, "" /* actions */, base_log_file);
// Process command line arguments and dump into variables
if (!CtrlProcessArguments(argc, argv, argument_descriptions,
countof(argument_descriptions))) {
return CtrlSubcommandUsage(nullptr, commands, countof(commands),
argument_descriptions,
countof(argument_descriptions));
}
if (debug) {
diags->activate_taglist("traffic_ctl", DiagsTagType_Debug);
diags->config.enabled[DiagsTagType_Debug] = true;
diags->show_location = SHOW_LOCATION_DEBUG;
}
if (n_file_arguments < 1) {
return CtrlSubcommandUsage(nullptr, commands, countof(commands),
argument_descriptions,
countof(argument_descriptions));
}
runroot_handler(argv);
Layout::create();
RecProcessInit(RECM_STAND_ALONE, diags);
LibRecordsConfigInit();
ats_scoped_str rundir(RecConfigReadRuntimeDir());
// Make a best effort to connect the control socket. If it turns out we are
// just displaying help or something then it
// doesn't matter that we failed. If we end up performing some operation then
// that operation will fail and display the
// error.
TSInit(rundir, static_cast<TSInitOptionT>(TS_MGMT_OPT_NO_EVENTS |
TS_MGMT_OPT_NO_SOCK_TESTS));
for (unsigned i = 0; i < countof(commands); ++i) {
if (strcmp(file_arguments[0], commands[i].name) == 0) {
CtrlCommandLine cmdline;
cmdline.init(n_file_arguments, file_arguments);
return commands[i].handler(cmdline.argc(), cmdline.argv());
}
}
// Done with the mgmt API.
TSTerminate();
return CtrlSubcommandUsage(nullptr, commands, countof(commands),
argument_descriptions,
countof(argument_descriptions));
}
<commit_msg>Fix clang format errors.<commit_after>/** @file
traffic_ctl
@section license License
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "traffic_ctl.h"
#include "I_RecProcess.h"
#include "RecordsConfig.h"
#include "ts/I_Layout.h"
#include "ts/runroot.h"
AppVersionInfo CtrlVersionInfo;
const char *
CtrlMgmtRecord::name() const
{
return this->ele->rec_name;
}
TSRecordT
CtrlMgmtRecord::type() const
{
return this->ele->rec_type;
}
int
CtrlMgmtRecord::rclass() const
{
return this->ele->rec_class;
}
int64_t
CtrlMgmtRecord::as_int() const
{
switch (this->ele->rec_type) {
case TS_REC_INT:
return this->ele->valueT.int_val;
case TS_REC_COUNTER:
return this->ele->valueT.counter_val;
default:
return 0;
}
}
TSMgmtError
CtrlMgmtRecord::fetch(const char *name)
{
return TSRecordGet(name, this->ele);
}
TSMgmtError
CtrlMgmtRecordList::match(const char *name)
{
return TSRecordGetMatchMlt(name, this->list);
}
CtrlMgmtRecordValue::CtrlMgmtRecordValue(const CtrlMgmtRecord &rec)
{
this->init(rec.ele->rec_type, rec.ele->valueT);
}
CtrlMgmtRecordValue::CtrlMgmtRecordValue(const TSRecordEle *ele)
{
this->init(ele->rec_type, ele->valueT);
}
CtrlMgmtRecordValue::CtrlMgmtRecordValue(TSRecordT _t, TSRecordValueT _v)
{
this->init(_t, _v);
}
void
CtrlMgmtRecordValue::init(TSRecordT _t, TSRecordValueT _v)
{
this->rec_type = _t;
switch (this->rec_type) {
case TS_REC_INT:
snprintf(this->fmt.nbuf, sizeof(this->fmt.nbuf), "%" PRId64, _v.int_val);
break;
case TS_REC_COUNTER:
snprintf(this->fmt.nbuf, sizeof(this->fmt.nbuf), "%" PRId64, _v.counter_val);
break;
case TS_REC_FLOAT:
snprintf(this->fmt.nbuf, sizeof(this->fmt.nbuf), "%f", _v.float_val);
break;
case TS_REC_STRING:
if (strcmp(_v.string_val, "") == 0) {
this->fmt.str = "\"\"";
} else {
this->fmt.str = _v.string_val;
}
break;
default:
rec_type = TS_REC_STRING;
this->fmt.str = "(invalid)";
}
}
const char *
CtrlMgmtRecordValue::c_str() const
{
switch (this->rec_type) {
case TS_REC_STRING:
return this->fmt.str;
default:
return this->fmt.nbuf;
}
}
void
CtrlMgmtError(TSMgmtError err, const char *fmt, ...)
{
ats_scoped_str msg(TSGetErrorMessage(err));
if (fmt) {
va_list ap;
fprintf(stderr, "%s: ", program_name);
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
fprintf(stderr, ": %s\n", (const char *)msg);
} else {
fprintf(stderr, "%s: %s\n", program_name, (const char *)msg);
}
}
int
CtrlSubcommandUsage(const char *name, const subcommand *cmds, unsigned ncmds, const ArgumentDescription *desc, unsigned ndesc)
{
const char *opt = ndesc ? "[OPTIONS]" : "";
const char *sep = (ndesc && name) ? " " : "";
fprintf(stderr, "Usage: traffic_ctl %s%s%s CMD [ARGS ...]\n\nSubcommands:\n", name ? name : "", sep, opt);
for (unsigned i = 0; i < ncmds; ++i) {
fprintf(stderr, " %-16s%s\n", cmds[i].name, cmds[i].help);
}
if (ndesc) {
usage(desc, ndesc, "\nOptions:");
}
return CTRL_EX_USAGE;
}
int
CtrlCommandUsage(const char *msg, const ArgumentDescription *desc, unsigned ndesc)
{
fprintf(stderr, "Usage: traffic_ctl %s\n", msg);
if (ndesc) {
usage(desc, ndesc, "\nOptions:");
}
return CTRL_EX_USAGE;
}
bool
CtrlProcessArguments(int /* argc */, const char **argv, const ArgumentDescription *desc, unsigned ndesc)
{
n_file_arguments = 0;
return process_args_ex(&CtrlVersionInfo, desc, ndesc, argv);
}
int
CtrlUnimplementedCommand(unsigned /* argc */, const char **argv)
{
CtrlDebug("the '%s' command is not implemented", *argv);
return CTRL_EX_UNIMPLEMENTED;
}
int
CtrlGenericSubcommand(const char *name, const subcommand *cmds, unsigned ncmds, unsigned argc, const char **argv)
{
CtrlCommandLine cmdline;
// Process command line arguments and dump into variables
if (!CtrlProcessArguments(argc, argv, nullptr, 0) || n_file_arguments < 1) {
return CtrlSubcommandUsage(name, cmds, ncmds, nullptr, 0);
}
cmdline.init(n_file_arguments, file_arguments);
for (unsigned i = 0; i < ncmds; ++i) {
if (strcmp(file_arguments[0], cmds[i].name) == 0) {
return cmds[i].handler(cmdline.argc(), cmdline.argv());
}
}
return CtrlSubcommandUsage(name, cmds, ncmds, nullptr, 0);
}
static const subcommand commands[] = {
{subcommand_alarm, "alarm", "Manipulate alarms"},
{subcommand_config, "config", "Manipulate configuration records"},
{subcommand_metric, "metric", "Manipulate performance metrics"},
{subcommand_server, "server", "Stop, restart and examine the server"},
{subcommand_storage, "storage", "Manipulate cache storage"},
{subcommand_plugin, "plugin", "Interact with plugins"},
};
int
main(int argc, const char **argv)
{
CtrlCommandLine cmdline;
int debug = false;
CtrlVersionInfo.setup(PACKAGE_NAME, "traffic_ctl", PACKAGE_VERSION, __DATE__, __TIME__, BUILD_MACHINE, BUILD_PERSON, "");
program_name = CtrlVersionInfo.AppStr;
ArgumentDescription argument_descriptions[] = {
{"debug", '-', "Enable debugging output", "F", &debug, nullptr, nullptr},
{"help", 'h', "Print usage information", nullptr, nullptr, nullptr,
[](const ArgumentDescription *args, unsigned nargs, const char *arg_unused) {
CtrlSubcommandUsage(nullptr, commands, countof(commands), args, nargs);
}},
VERSION_ARGUMENT_DESCRIPTION(),
RUNROOT_ARGUMENT_DESCRIPTION(),
};
BaseLogFile *base_log_file = new BaseLogFile("stderr");
diags = new Diags(program_name, "" /* tags */, "" /* actions */, base_log_file);
// Process command line arguments and dump into variables
if (!CtrlProcessArguments(argc, argv, argument_descriptions, countof(argument_descriptions))) {
return CtrlSubcommandUsage(nullptr, commands, countof(commands), argument_descriptions, countof(argument_descriptions));
}
if (debug) {
diags->activate_taglist("traffic_ctl", DiagsTagType_Debug);
diags->config.enabled[DiagsTagType_Debug] = true;
diags->show_location = SHOW_LOCATION_DEBUG;
}
if (n_file_arguments < 1) {
return CtrlSubcommandUsage(nullptr, commands, countof(commands), argument_descriptions, countof(argument_descriptions));
}
runroot_handler(argv);
Layout::create();
RecProcessInit(RECM_STAND_ALONE, diags);
LibRecordsConfigInit();
ats_scoped_str rundir(RecConfigReadRuntimeDir());
// Make a best effort to connect the control socket. If it turns out we are
// just displaying help or something then it
// doesn't matter that we failed. If we end up performing some operation then
// that operation will fail and display the
// error.
TSInit(rundir, static_cast<TSInitOptionT>(TS_MGMT_OPT_NO_EVENTS | TS_MGMT_OPT_NO_SOCK_TESTS));
for (unsigned i = 0; i < countof(commands); ++i) {
if (strcmp(file_arguments[0], commands[i].name) == 0) {
CtrlCommandLine cmdline;
cmdline.init(n_file_arguments, file_arguments);
return commands[i].handler(cmdline.argc(), cmdline.argv());
}
}
// Done with the mgmt API.
TSTerminate();
return CtrlSubcommandUsage(nullptr, commands, countof(commands), argument_descriptions, countof(argument_descriptions));
}
<|endoftext|> |
<commit_before>#include "jsonRpcServer.h"
#include "lightspeed/base/framework/app.h"
#include "lightspeed/base/debug/dbglog.h"
#include "lightspeed/utils/json/jsonfast.tcc"
#include "lightspeed/base/debug/LogProvider.h"
#include "../httpserver/serverStats.h"
#include "../httpserver/httpServer.h"
namespace jsonsrv {
JsonRpcServer::JsonRpcServer()
{
setLogObject(this);
DbgLog::needRotateLogs(logRotateCounter);
}
void JsonRpcServer::init( const IniConfig &cfg )
{
IniConfig::Section sect = cfg.openSection("server");
init(sect);
}
void JsonRpcServer::init( const IniConfig::Section sect )
{
StringA clientPage;
StringA helpdir;
StringA rpclogfile;
FilePath p(App::current().getAppPathname());
FilePath clientPagePath;
FilePath helpdirPath;
FilePath rpclogfilePath;
sect.get(clientPage,"clientPage");
if (!clientPage.empty()) {
clientPagePath = p / clientPage;
}
sect.get(helpdir,"helpDir");
if (!helpdir.empty()) {
helpdirPath = p / helpdir;
}
sect.get(rpclogfile,"rpcLog");
if (!rpclogfile.empty()) {
rpclogfilePath = p / rpclogfile;
}
init(rpclogfilePath, helpdirPath, clientPagePath);
}
void JsonRpcServer::init( const FilePath &rpclogfilePath, const FilePath &helpdirPath, const FilePath &clientPagePath )
{
LogObject lg(THISLOCATION);
logFileName = rpclogfilePath;
openLog();
if (!helpdirPath.empty()) {
try {
PFolderIterator iter = IFileIOServices::getIOServices().openFolder(helpdirPath);
while (iter->getNext()) {
try {
loadHelp(iter->getFullPath());
} catch (Exception &e) {
lg.warning("Skipping help file: %1 error %2") << iter->entryName << e.getMessage();
}
}
} catch (Exception &e) {
lg.warning("Unable to open help folder: %1") << e.getMessage();
}
}
setClientPage(clientPagePath);
registerServerMethods(true);
registerStatHandler("server",RpcCall::create(this,&JsonRpcServer::rpcHttpStatHandler));
}
void JsonRpcServer::logMethod( IHttpRequest &invoker, ConstStrA methodName, JSON::INode *params, JSON::INode *context, JSON::INode *logOutput )
{
if (logfile == nil) return;
if (logRotateCounter != DbgLog::rotateCounter) {
if (DbgLog::needRotateLogs(logRotateCounter)) {
logRotate();
}
}
LogObject lg(THISLOCATION);
IHttpPeerInfo &pinfo = invoker.getIfc<IHttpPeerInfo>();
ConstStrA peerAddr = pinfo.getPeerRealAddr();
ConstStrA paramsStr;
LogBuffers &buffers = logBuffers[ITLSTable::getInstance()];
buffers.strparams.clear();
buffers.strcontext.clear();
buffers.stroutput.clear();
if (params == 0) params = JSON::getNullNode();
if (context == 0) context = JSON::getNullNode();
if (logOutput == 0) logOutput = JSON::getNullNode();
JSON::serialize(params,buffers.strparams,false);
JSON::serialize(context,buffers.strcontext,false);
JSON::serialize(logOutput,buffers.stroutput,false);;
ConstStrA resparamstr(buffers.strparams.getArray());
ConstStrA rescontextptr(buffers.strcontext.getArray());
ConstStrA resoutputptr(buffers.stroutput.getArray());
PrintTextA pr(*logfile);
AbstractLogProvider::LogTimestamp tms;
Synchronized<FastLock> _(lock);
pr("%{04}1/%{02}2/%{02}3 %{02}4:%{02}5:%{02}6 - [\"%7\",\"%8\",%9,%10,%11]\n")
<< tms.year << tms.month << tms.day
<< tms.hour << tms.min << tms.sec
<< peerAddr << methodName << resparamstr << rescontextptr << resoutputptr;
logfile->flush();
}
void JsonRpcServer::openLog()
{
if (logFileName.empty()) return;
Synchronized<FastLock> _(lock);
try {
logfile = new SeqFileOutBuff<>(logFileName,OpenFlags::append|OpenFlags::create);
} catch (...) {
}
}
void JsonRpcServer::registerMethod( ConstStrA methodName, const IRpcCall & method, ConstStrA help )
{
LogObject lg(THISLOCATION);
JsonRpc::registerMethod(methodName,method,help);
lg.progress("Server: Method registered: %1") << methodName;
}
void JsonRpcServer::registerGlobalHandler( ConstStrA methodName, const IRpcCall & method )
{
LogObject lg(THISLOCATION);
JsonRpc::registerGlobalHandler(methodName,method);
lg.progress("Server: Global handler registered: %1") << methodName;
}
void JsonRpcServer::eraseMethod( ConstStrA methodName )
{
LogObject lg(THISLOCATION);
JsonRpc::eraseMethod(methodName);
lg.progress("Server: Method removed: %1") << methodName;
}
void JsonRpcServer::eraseGlobalHandler( ConstStrA methodName )
{
LogObject lg(THISLOCATION);
JsonRpc::eraseGlobalHandler(methodName);
lg.progress("Server: Global handler removed: %1") << methodName;
}
void JsonRpcServer::registerStatHandler( ConstStrA handlerName, const IRpcCall & method )
{
LogObject lg(THISLOCATION);
JsonRpc::registerStatHandler(handlerName,method);
lg.progress("Server: Added statistics %1") << handlerName;
}
void JsonRpcServer::eraseStatHandler( ConstStrA handlerName )
{
LogObject lg(THISLOCATION);
JsonRpc::eraseStatHandler(handlerName);
lg.progress("Server: Removed statistics %1") << handlerName;
}
jsonsrv::RpcError JsonRpcServer::onException( JSON::IFactory *json, const std::exception &e )
{
return JsonRpc::onException(json,e);
}
template<typename T>
JSON::PNode JsonRpcServer::avgField( const StatBuffer<T> &b, JSON::IFactory &f, natural cnt )
{
T c = b.getAvg(cnt);
if (c.isDefined()) return f.newValue(c.getValue());
else return f.newNullNode();
}
template<typename T>
JSON::PNode JsonRpcServer::minField( const StatBuffer<T> &b, JSON::IFactory &f, natural cnt )
{
T c = b.getMin(cnt);
if (c.isDefined()) return f.newValue(c.getValue());
else return f.newNullNode();
}
template<typename T>
JSON::PNode JsonRpcServer::maxField( const StatBuffer<T> &b, JSON::IFactory &f, natural cnt )
{
T c = b.getMax(cnt);
if (c.isDefined()) return f.newValue(c.getValue());
else return f.newNullNode();
}
template<typename T>
JSON::PNode JsonRpcServer::statFields( const StatBuffer<T> &b, JSON::IFactory &f )
{
JSON::PNode a = f.newClass();
a->add("avg006",avgField(b,f,6));
a->add("avg030",avgField(b,f,30));
a->add("avg060",avgField(b,f,60));
a->add("avg300",avgField(b,f,300));
a->add("min006",minField(b,f,6));
a->add("min030",minField(b,f,30));
a->add("min060",minField(b,f,60));
a->add("min300",minField(b,f,300));
a->add("max006",maxField(b,f,6));
a->add("max030",maxField(b,f,30));
a->add("max060",maxField(b,f,60));
a->add("max300",maxField(b,f,300));
return a;
}
JSON::PNode JsonRpcServer::rpcHttpStatHandler( RpcRequest *rq )
{
JSON::IFactory &f = *(rq->jsonFactory);
const HttpServer &server = rq->httpRequest->getIfc<HttpServer>();
const HttpStats &st = server.getStats();
JSON::PNode out = rq->jsonFactory->newClass();
out->add("request", statFields(st.requests,f))
->add("threads", statFields(st.threads,f))
->add("threadsIdle", statFields(st.idleThreads,f))
->add("connections", statFields(st.connections,f))
->add("latency", statFields(st.latency,f))
->add("worktime", statFields(st.worktime,f));
return out;
}
}
<commit_msg>fixed: race condition and possible crash while accessing rpclogfile<commit_after>#include "jsonRpcServer.h"
#include "lightspeed/base/framework/app.h"
#include "lightspeed/base/debug/dbglog.h"
#include "lightspeed/utils/json/jsonfast.tcc"
#include "lightspeed/base/debug/LogProvider.h"
#include "../httpserver/serverStats.h"
#include "../httpserver/httpServer.h"
namespace jsonsrv {
JsonRpcServer::JsonRpcServer()
{
setLogObject(this);
DbgLog::needRotateLogs(logRotateCounter);
}
void JsonRpcServer::init( const IniConfig &cfg )
{
IniConfig::Section sect = cfg.openSection("server");
init(sect);
}
void JsonRpcServer::init( const IniConfig::Section sect )
{
StringA clientPage;
StringA helpdir;
StringA rpclogfile;
FilePath p(App::current().getAppPathname());
FilePath clientPagePath;
FilePath helpdirPath;
FilePath rpclogfilePath;
sect.get(clientPage,"clientPage");
if (!clientPage.empty()) {
clientPagePath = p / clientPage;
}
sect.get(helpdir,"helpDir");
if (!helpdir.empty()) {
helpdirPath = p / helpdir;
}
sect.get(rpclogfile,"rpcLog");
if (!rpclogfile.empty()) {
rpclogfilePath = p / rpclogfile;
}
init(rpclogfilePath, helpdirPath, clientPagePath);
}
void JsonRpcServer::init( const FilePath &rpclogfilePath, const FilePath &helpdirPath, const FilePath &clientPagePath )
{
LogObject lg(THISLOCATION);
logFileName = rpclogfilePath;
openLog();
if (!helpdirPath.empty()) {
try {
PFolderIterator iter = IFileIOServices::getIOServices().openFolder(helpdirPath);
while (iter->getNext()) {
try {
loadHelp(iter->getFullPath());
} catch (Exception &e) {
lg.warning("Skipping help file: %1 error %2") << iter->entryName << e.getMessage();
}
}
} catch (Exception &e) {
lg.warning("Unable to open help folder: %1") << e.getMessage();
}
}
setClientPage(clientPagePath);
registerServerMethods(true);
registerStatHandler("server",RpcCall::create(this,&JsonRpcServer::rpcHttpStatHandler));
}
void JsonRpcServer::logMethod( IHttpRequest &invoker, ConstStrA methodName, JSON::INode *params, JSON::INode *context, JSON::INode *logOutput )
{
if (logfile == nil) return;
if (logRotateCounter != DbgLog::rotateCounter) {
if (DbgLog::needRotateLogs(logRotateCounter)) {
logRotate();
}
}
LogObject lg(THISLOCATION);
IHttpPeerInfo &pinfo = invoker.getIfc<IHttpPeerInfo>();
ConstStrA peerAddr = pinfo.getPeerRealAddr();
ConstStrA paramsStr;
LogBuffers &buffers = logBuffers[ITLSTable::getInstance()];
buffers.strparams.clear();
buffers.strcontext.clear();
buffers.stroutput.clear();
if (params == 0) params = JSON::getNullNode();
if (context == 0) context = JSON::getNullNode();
if (logOutput == 0) logOutput = JSON::getNullNode();
JSON::serialize(params,buffers.strparams,false);
JSON::serialize(context,buffers.strcontext,false);
JSON::serialize(logOutput,buffers.stroutput,false);;
ConstStrA resparamstr(buffers.strparams.getArray());
ConstStrA rescontextptr(buffers.strcontext.getArray());
ConstStrA resoutputptr(buffers.stroutput.getArray());
Synchronized<FastLock> _(lock);
PrintTextA pr(*logfile);
AbstractLogProvider::LogTimestamp tms;
pr("%{04}1/%{02}2/%{02}3 %{02}4:%{02}5:%{02}6 - [\"%7\",\"%8\",%9,%10,%11]\n")
<< tms.year << tms.month << tms.day
<< tms.hour << tms.min << tms.sec
<< peerAddr << methodName << resparamstr << rescontextptr << resoutputptr;
logfile->flush();
}
void JsonRpcServer::openLog()
{
if (logFileName.empty()) return;
Synchronized<FastLock> _(lock);
try {
logfile = new SeqFileOutBuff<>(logFileName,OpenFlags::append|OpenFlags::create);
} catch (...) {
}
}
void JsonRpcServer::registerMethod( ConstStrA methodName, const IRpcCall & method, ConstStrA help )
{
LogObject lg(THISLOCATION);
JsonRpc::registerMethod(methodName,method,help);
lg.progress("Server: Method registered: %1") << methodName;
}
void JsonRpcServer::registerGlobalHandler( ConstStrA methodName, const IRpcCall & method )
{
LogObject lg(THISLOCATION);
JsonRpc::registerGlobalHandler(methodName,method);
lg.progress("Server: Global handler registered: %1") << methodName;
}
void JsonRpcServer::eraseMethod( ConstStrA methodName )
{
LogObject lg(THISLOCATION);
JsonRpc::eraseMethod(methodName);
lg.progress("Server: Method removed: %1") << methodName;
}
void JsonRpcServer::eraseGlobalHandler( ConstStrA methodName )
{
LogObject lg(THISLOCATION);
JsonRpc::eraseGlobalHandler(methodName);
lg.progress("Server: Global handler removed: %1") << methodName;
}
void JsonRpcServer::registerStatHandler( ConstStrA handlerName, const IRpcCall & method )
{
LogObject lg(THISLOCATION);
JsonRpc::registerStatHandler(handlerName,method);
lg.progress("Server: Added statistics %1") << handlerName;
}
void JsonRpcServer::eraseStatHandler( ConstStrA handlerName )
{
LogObject lg(THISLOCATION);
JsonRpc::eraseStatHandler(handlerName);
lg.progress("Server: Removed statistics %1") << handlerName;
}
jsonsrv::RpcError JsonRpcServer::onException( JSON::IFactory *json, const std::exception &e )
{
return JsonRpc::onException(json,e);
}
template<typename T>
JSON::PNode JsonRpcServer::avgField( const StatBuffer<T> &b, JSON::IFactory &f, natural cnt )
{
T c = b.getAvg(cnt);
if (c.isDefined()) return f.newValue(c.getValue());
else return f.newNullNode();
}
template<typename T>
JSON::PNode JsonRpcServer::minField( const StatBuffer<T> &b, JSON::IFactory &f, natural cnt )
{
T c = b.getMin(cnt);
if (c.isDefined()) return f.newValue(c.getValue());
else return f.newNullNode();
}
template<typename T>
JSON::PNode JsonRpcServer::maxField( const StatBuffer<T> &b, JSON::IFactory &f, natural cnt )
{
T c = b.getMax(cnt);
if (c.isDefined()) return f.newValue(c.getValue());
else return f.newNullNode();
}
template<typename T>
JSON::PNode JsonRpcServer::statFields( const StatBuffer<T> &b, JSON::IFactory &f )
{
JSON::PNode a = f.newClass();
a->add("avg006",avgField(b,f,6));
a->add("avg030",avgField(b,f,30));
a->add("avg060",avgField(b,f,60));
a->add("avg300",avgField(b,f,300));
a->add("min006",minField(b,f,6));
a->add("min030",minField(b,f,30));
a->add("min060",minField(b,f,60));
a->add("min300",minField(b,f,300));
a->add("max006",maxField(b,f,6));
a->add("max030",maxField(b,f,30));
a->add("max060",maxField(b,f,60));
a->add("max300",maxField(b,f,300));
return a;
}
JSON::PNode JsonRpcServer::rpcHttpStatHandler( RpcRequest *rq )
{
JSON::IFactory &f = *(rq->jsonFactory);
const HttpServer &server = rq->httpRequest->getIfc<HttpServer>();
const HttpStats &st = server.getStats();
JSON::PNode out = rq->jsonFactory->newClass();
out->add("request", statFields(st.requests,f))
->add("threads", statFields(st.threads,f))
->add("threadsIdle", statFields(st.idleThreads,f))
->add("connections", statFields(st.connections,f))
->add("latency", statFields(st.latency,f))
->add("worktime", statFields(st.worktime,f));
return out;
}
}
<|endoftext|> |
<commit_before><commit_msg>Bugfix: GPGPU test: add missing forward declaration.<commit_after><|endoftext|> |
<commit_before>#include "compiler/compiler.hpp"
#include "compiler/grammar.hpp"
#include "compiler/exceptions.hpp"
#include "compiler/ast.hpp"
#include "compiler/function_manager.hpp"
#include "compiler/steps.hpp"
#include "shared/opcodes.hpp"
#include <boost/spirit/home/qi/parse.hpp>
#include <vector>
#include <utility>
#include <stdexcept>
namespace perseus
{
using namespace std::string_literals;
struct compiler::impl
{
detail::token_definitions lexer;
detail::grammar parser;
detail::skip_grammar skipper;
bool linking = false;
std::vector< detail::ast::parser::file > files;
};
compiler::compiler()
: _impl( std::make_unique< compiler::impl >() )
{
}
// these are in the .cpp since they require with compiler::impl, which is only forward declared in the .hpp
compiler::~compiler() = default;
compiler::compiler( compiler&& ) = default;
compiler& compiler::operator=( compiler&& ) = default;
void compiler::reset()
{
// keep lexer, parser & skipper intact - the entire point of the compiler class is keeping their results cached
_impl->linking = false;
_impl->files.clear();
}
void compiler::parse( std::istream& source_stream, const std::string& filename )
{
detail::enhanced_istream_iterator input_it, input_end;
// TODO: add filename to file_position and track it
std::tie( input_it, input_end ) = detail::enhanced_iterators( source_stream );
detail::skip_byte_order_mark( input_it, input_end );
// I suppose unless I need tokens_it/tokens_end, I could just lex::tokenize_and_phrase_parse, but doing it manually gives me more options
detail::token_iterator tokens_it = _impl->lexer.begin( input_it, input_end );
const detail::token_iterator tokens_end = _impl->lexer.end();
detail::ast::parser::file result;
bool success = boost::spirit::qi::phrase_parse( tokens_it, tokens_end, _impl->parser, _impl->skipper, result );
if( !success )
{
// TODO: throw better error
throw syntax_error(
"Failed to parse " + filename,
tokens_it == tokens_end ? detail::file_position() : tokens_it->value().begin().get_position()
);
}
// no need to check if it == end, since the grammar contains an eoi parser.
_impl->files.emplace_back( std::move( result ) );
}
detail::processor compiler::link()
{
if( _impl->linking )
{
throw std::logic_error{ "Called compiler::link() again after failure without calling compiler::reset() first!" };
}
_impl->linking = true; // set it now in case of exceptions since we don't roll back on failure
// collect available functions
detail::function_manager function_manager;
for( auto& file_ast : _impl->files )
{
detail::extract_functions( file_ast, function_manager );
}
// generate code
// find main function
detail::code_segment code;
detail::function_manager::function_pointer main_function;
if( !function_manager.get_function( { "main"s, {} }, main_function ) )
{
throw semantic_error{ "no main() function (without parameters) defined!"s, { 0, 0 } };
}
// reserve return value space
{
auto size = get_size( main_function->second.return_type );
if( size > 0 )
{
code.push< detail::opcode >( detail::opcode::reserve );
code.push< std::uint32_t >( size );
}
}
// call main function
code.push< detail::opcode >( detail::opcode::call );
main_function->second.write_address( code );
// exit
code.push< detail::opcode >( detail::opcode::exit );
// append functions
while( !_impl->files.empty() )
{
generate_code( detail::simplify_and_annotate( std::move( _impl->files.back() ), function_manager ), code );
_impl->files.pop_back();
}
if( function_manager.has_open_address_requests() )
{
throw std::logic_error{ "Unhandled address requests?!" };
}
_impl->linking = false;
return detail::processor{ std::move( code ) };
}
}
<commit_msg>builtin print function<commit_after>#include "compiler/compiler.hpp"
#include "compiler/grammar.hpp"
#include "compiler/exceptions.hpp"
#include "compiler/ast.hpp"
#include "compiler/function_manager.hpp"
#include "compiler/steps.hpp"
#include "shared/opcodes.hpp"
#include <boost/spirit/home/qi/parse.hpp>
#include <vector>
#include <utility>
#include <stdexcept>
#include <iostream>
namespace perseus
{
using namespace std::string_literals;
struct compiler::impl
{
detail::token_definitions lexer;
detail::grammar parser;
detail::skip_grammar skipper;
bool linking = false;
std::vector< detail::ast::parser::file > files;
};
compiler::compiler()
: _impl( std::make_unique< compiler::impl >() )
{
}
// these are in the .cpp since they require with compiler::impl, which is only forward declared in the .hpp
compiler::~compiler() = default;
compiler::compiler( compiler&& ) = default;
compiler& compiler::operator=( compiler&& ) = default;
void compiler::reset()
{
// keep lexer, parser & skipper intact - the entire point of the compiler class is keeping their results cached
_impl->linking = false;
_impl->files.clear();
}
void compiler::parse( std::istream& source_stream, const std::string& filename )
{
detail::enhanced_istream_iterator input_it, input_end;
// TODO: add filename to file_position and track it
std::tie( input_it, input_end ) = detail::enhanced_iterators( source_stream );
detail::skip_byte_order_mark( input_it, input_end );
// I suppose unless I need tokens_it/tokens_end, I could just lex::tokenize_and_phrase_parse, but doing it manually gives me more options
detail::token_iterator tokens_it = _impl->lexer.begin( input_it, input_end );
const detail::token_iterator tokens_end = _impl->lexer.end();
detail::ast::parser::file result;
bool success = boost::spirit::qi::phrase_parse( tokens_it, tokens_end, _impl->parser, _impl->skipper, result );
if( !success )
{
// TODO: throw better error
throw syntax_error(
"Failed to parse " + filename,
tokens_it == tokens_end ? detail::file_position() : tokens_it->value().begin().get_position()
);
}
// no need to check if it == end, since the grammar contains an eoi parser.
_impl->files.emplace_back( std::move( result ) );
}
detail::processor compiler::link()
{
if( _impl->linking )
{
throw std::logic_error{ "Called compiler::link() again after failure without calling compiler::reset() first!" };
}
_impl->linking = true; // set it now in case of exceptions since we don't roll back on failure
detail::function_manager function_manager;
// register builtin functions
detail::function_manager::function_pointer print_i32_function, print_bool_function;
function_manager.register_function( detail::function_signature{ "print"s, { detail::type_id::i32 } }, detail::function_info{ detail::type_id::void_, false }, print_i32_function );
function_manager.register_function( detail::function_signature{ "print"s, { detail::type_id::bool_ } }, detail::function_info{ detail::type_id::void_, false }, print_bool_function );
// collect available functions
for( auto& file_ast : _impl->files )
{
detail::extract_functions( file_ast, function_manager );
}
// generate code
// entry point
// find main function
detail::code_segment code;
detail::function_manager::function_pointer main_function;
if( !function_manager.get_function( { "main"s, {} }, main_function ) )
{
throw semantic_error{ "no main() function (without parameters) defined!"s, { 0, 0 } };
}
// reserve return value space
{
auto size = get_size( main_function->second.return_type );
if( size > 0 )
{
code.push< detail::opcode >( detail::opcode::reserve );
code.push< std::uint32_t >( size );
}
}
// call main function
code.push< detail::opcode >( detail::opcode::call );
main_function->second.write_address( code );
// exit
code.push< detail::opcode >( detail::opcode::exit );
// generate builtin functions
std::vector< detail::syscall > syscalls;
auto generate_builtin_code = [ &syscalls, &code ]( detail::function_manager::function_pointer function, detail::syscall&& definition )
{
function->second.set_address( code.size(), code );
code.push< detail::opcode >( detail::opcode::syscall );
code.push< std::uint32_t >( syscalls.size() );
code.push< detail::opcode >( detail::opcode::return_ );
code.push< std::uint32_t >( function->first.parameters_size() );
syscalls.emplace_back( std::move( definition ) );
};
// print i32
generate_builtin_code( print_i32_function, []( stack& s ) {
const char* memory = s.data() + s.size() - sizeof( detail::instruction_pointer::value_type ) - detail::get_size( detail::type_id::i32 );
std::cout << *reinterpret_cast< const int* >( memory ) << std::endl;
} );
// print bool
generate_builtin_code( print_bool_function, []( stack& s ) {
const char* memory = s.data() + s.size() - sizeof( detail::instruction_pointer::value_type ) - detail::get_size( detail::type_id::bool_ );
bool value = *memory;
std::cout << std::boolalpha << value << std::endl;
} );
// append functions
while( !_impl->files.empty() )
{
generate_code( detail::simplify_and_annotate( std::move( _impl->files.back() ), function_manager ), code );
_impl->files.pop_back();
}
if( function_manager.has_open_address_requests() )
{
throw std::logic_error{ "Unhandled address requests?!" };
}
_impl->linking = false;
return detail::processor{ std::move( code ), std::move( syscalls ) };
}
}
<|endoftext|> |
<commit_before>/*
* Copyright 2015 Cloudius Systems
*/
#pragma once
#include "bytes_ostream.hh"
namespace query {
//
// Query results are serialized to the following form:
//
// <result> ::= <partition>*
// <partition> ::= <row-count> [ <partition-key> ] [ <static-row> ] <row>*
// <static-row> ::= <row>
// <row> ::= <row-length> <cell>+
// <cell> ::= <atomic-cell> | <collection-cell>
// <atomic-cell> ::= <present-byte> [ <timestamp> <ttl> ] <value>
// <collection-cell> ::= <blob>
//
// <value> ::= <blob>
// <blob> ::= <blob-length> <uint8_t>*
// <timestamp> ::= <uint64_t>
// <ttl> ::= <int32_t>
// <present-byte> ::= <int8_t>
// <row-length> ::= <uint32_t>
// <row-count> ::= <uint32_t>
// <blob-length> ::= <uint32_t>
//
// Optional elements are present according to partition_slice
//
class result {
bytes_ostream _w;
public:
class builder;
class partition_writer;
class row_writer;
friend class result_merger;
result() {}
result(bytes_ostream&& w) : _w(std::move(w)) {}
const bytes_ostream& buf() const {
return _w;
}
};
}
<commit_msg>query: Document intention behind query results format<commit_after>/*
* Copyright 2015 Cloudius Systems
*/
#pragma once
#include "bytes_ostream.hh"
namespace query {
//
// The query results are stored in a serialized from. This is in order to
// address the following problems, which a structured format has:
//
// - high level of indirection (vector of vectors of vectors of blobs), which
// is not CPU cache friendly
//
// - high allocation rate due to fine-grained object structure
//
// On replica side, the query results are probably going to be serialized in
// the transport layer anyway, so serializing the results up-front doesn't add
// net work. There is no processing of the query results on replica other than
// concatenation in case of range queries and checksum calculation. If query
// results are collected in serialized form from different cores, we can
// concatenate them without copying by simply appending the fragments into the
// packet.
//
// On coordinator side, the query results would have to be parsed from the
// transport layer buffers anyway, so the fact that iterators parse it also
// doesn't add net work, but again saves allocations and copying. The CQL
// server doesn't need complex data structures to process the results, it just
// goes over it linearly consuming it.
//
// The coordinator side could be optimized even further for CQL queries which
// do not need processing (eg. select * from cf where ...). We could make the
// replica send the query results in the format which is expected by the CQL
// binary protocol client. So in the typical case the coordinator would just
// pass the data using zero-copy to the client, prepending a header.
//
// Users which need more complex structure of query results, should
// trasnform it to such using appropriate visitors.
// TODO: insert reference to such visitors here.
//
// Query results have dynamic format. In some queries (maybe even in typical
// ones), we don't need to send partition or clustering keys back to the
// client, because they are already specified in the query request, and not
// queried for. The query results hold keys optionally.
//
// Also, meta-data like cell timestamp and ttl is optional. It is only needed
// if the query has writetime() or ttl() functions in it, which it typically
// won't have.
//
// Related headers:
// - query-result-reader.hh
// - query-result-writer.hh
//
// Query results are serialized to the following form:
//
// <result> ::= <partition>*
// <partition> ::= <row-count> [ <partition-key> ] [ <static-row> ] <row>*
// <static-row> ::= <row>
// <row> ::= <row-length> <cell>+
// <cell> ::= <atomic-cell> | <collection-cell>
// <atomic-cell> ::= <present-byte> [ <timestamp> <ttl> ] <value>
// <collection-cell> ::= <blob>
//
// <value> ::= <blob>
// <blob> ::= <blob-length> <uint8_t>*
// <timestamp> ::= <uint64_t>
// <ttl> ::= <int32_t>
// <present-byte> ::= <int8_t>
// <row-length> ::= <uint32_t>
// <row-count> ::= <uint32_t>
// <blob-length> ::= <uint32_t>
//
class result {
bytes_ostream _w;
public:
class builder;
class partition_writer;
class row_writer;
friend class result_merger;
result() {}
result(bytes_ostream&& w) : _w(std::move(w)) {}
const bytes_ostream& buf() const {
return _w;
}
};
}
<|endoftext|> |
<commit_before>/*
Copyright 2015 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "stdafx.h"
#include "UIforETW.h"
#include "Settings.h"
#include "Utility.h"
#include "afxdialogex.h"
/*
When doing Chrome profilng it is possible to ask various Chrome tracing
categories to emit ETW events. The filtered_event_group_names array
documents what categories map to what flag/keyword values.
The table below is subject to change, but probably not very frequently.
For more details see this Chrome change that added the initial version of the
ETW event filtering:
https://codereview.chromium.org/1176243016
*/
// Copied from Chrome's trace_event_etw_export_win.cc. This file can be found by
// searching for "f:trace_event_etw_export_win.cc" in https://code.google.com/p/chromium/codesearch#/.
const PCWSTR filtered_event_group_names[] =
{
L"benchmark", // 0x1
L"blink", // 0x2
L"browser", // 0x4
L"cc", // 0x8
L"evdev", // 0x10
L"gpu", // 0x20
L"input", // 0x40
L"netlog", // 0x80
L"renderer.scheduler", // 0x100
L"toplevel", // 0x200
L"v8", // 0x400
L"disabled-by-default-cc.debug", // 0x800
L"disabled-by-default-cc.debug.picture", // 0x1000
L"disabled-by-default-toplevel.flow", // 0x2000
};
// 1ULL << 61 and 1ULL << 62 are special values that indicate to Chrome to
// enable all enabled-by-default and disabled-by-default categories
// respectively.
const PCWSTR other_events_group_name = L"All enabled-by-default events"; // 0x2000000000000000
const PCWSTR disabled_other_events_group_name = L"All disabled-by-default events"; // 0x4000000000000000
uint64_t other_events_keyword_bit = 1ULL << 61;
uint64_t disabled_other_events_keyword_bit = 1ULL << 62;
// CSettings dialog
IMPLEMENT_DYNAMIC(CSettings, CDialogEx)
CSettings::CSettings(CWnd* pParent /*=NULL*/, const std::wstring& exeDir, const std::wstring& wptDir)
: CDialogEx(CSettings::IDD, pParent)
, exeDir_(exeDir)
, wptDir_(wptDir)
{
}
CSettings::~CSettings()
{
}
void CSettings::DoDataExchange(CDataExchange* pDX)
{
DDX_Control(pDX, IDC_HEAPEXE, btHeapTracingExe_);
DDX_Control(pDX, IDC_EXTRAPROVIDERS, btExtraProviders_);
DDX_Control(pDX, IDC_EXTRASTACKWALKS, btExtraStackwalks_);
DDX_Control(pDX, IDC_BUFFERSIZES, btBufferSizes_);
DDX_Control(pDX, IDC_COPYSTARTUPPROFILE, btCopyStartupProfile_);
DDX_Control(pDX, IDC_COPYSYMBOLDLLS, btCopySymbolDLLs_);
DDX_Control(pDX, IDC_CHROMEDEVELOPER, btChromeDeveloper_);
DDX_Control(pDX, IDC_AUTOVIEWTRACES, btAutoViewTraces_);
DDX_Control(pDX, IDC_HEAPSTACKS, btHeapStacks_);
DDX_Control(pDX, IDC_CHROMEDLLPATH, btChromeDllPath_);
DDX_Control(pDX, IDC_WSMONITOREDPROCESSES, btWSMonitoredProcesses_);
DDX_Control(pDX, IDC_EXPENSIVEWS, btExpensiveWSMonitoring_);
DDX_Control(pDX, IDC_VIRTUALALLOCSTACKS, btVirtualAllocStacks_);
DDX_Control(pDX, IDC_CHROME_CATEGORIES, btChromeCategories_);
CDialogEx::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CSettings, CDialogEx)
ON_BN_CLICKED(IDC_COPYSTARTUPPROFILE, &CSettings::OnBnClickedCopystartupprofile)
ON_BN_CLICKED(IDC_COPYSYMBOLDLLS, &CSettings::OnBnClickedCopysymboldlls)
ON_BN_CLICKED(IDC_CHROMEDEVELOPER, &CSettings::OnBnClickedChromedeveloper)
ON_BN_CLICKED(IDC_AUTOVIEWTRACES, &CSettings::OnBnClickedAutoviewtraces)
ON_BN_CLICKED(IDC_HEAPSTACKS, &CSettings::OnBnClickedHeapstacks)
ON_BN_CLICKED(IDC_VIRTUALALLOCSTACKS, &CSettings::OnBnClickedVirtualallocstacks)
ON_BN_CLICKED(IDC_EXPENSIVEWS, &CSettings::OnBnClickedExpensivews)
END_MESSAGE_MAP()
BOOL CSettings::OnInitDialog()
{
CDialogEx::OnInitDialog();
SetDlgItemText(IDC_HEAPEXE, heapTracingExes_.c_str());
CheckDlgButton(IDC_CHROMEDEVELOPER, bChromeDeveloper_);
CheckDlgButton(IDC_AUTOVIEWTRACES, bAutoViewTraces_);
CheckDlgButton(IDC_HEAPSTACKS, bHeapStacks_);
CheckDlgButton(IDC_VIRTUALALLOCSTACKS, bVirtualAllocStacks_);
SetDlgItemText(IDC_CHROMEDLLPATH, chromeDllPath_.c_str());
btExtraProviders_.EnableWindow(FALSE);
btExtraStackwalks_.EnableWindow(FALSE);
btBufferSizes_.EnableWindow(FALSE);
btChromeDllPath_.EnableWindow(bChromeDeveloper_);
// A 32-bit process on 64-bit Windows will not be able to read the
// full working set of 64-bit processes, so don't even try.
if (Is64BitWindows() && !Is64BitBuild())
btWSMonitoredProcesses_.EnableWindow(FALSE);
else
SetDlgItemText(IDC_WSMONITOREDPROCESSES, WSMonitoredProcesses_.c_str());
CheckDlgButton(IDC_EXPENSIVEWS, bExpensiveWSMonitoring_);
if (toolTip_.Create(this))
{
toolTip_.SetMaxTipWidth(400);
toolTip_.Activate(TRUE);
toolTip_.AddTool(&btHeapTracingExe_, L"Specify the file names of the exes to be heap traced, "
L"separated by semi-colons. "
L"Enter just the file parts (with the .exe extension) not a full path. For example, "
L"'chrome.exe;notepad.exe'. This is for use with the heap-tracing-to-file mode.");
toolTip_.AddTool(&btCopyStartupProfile_, L"Copies startup.wpaProfile files for WPA 8.1 and "
L"10 to the appropriate destinations so that the next time WPA starts up it will have "
L"reasonable analysis defaults.");
toolTip_.AddTool(&btCopySymbolDLLs_, L"Copy dbghelp.dll and symsrv.dll to the xperf directory to "
L"try to resolve slow or failed symbol loading in WPA. See "
L"https://randomascii.wordpress.com/2012/10/04/xperf-symbol-loading-pitfalls/ "
L"for details.");
toolTip_.AddTool(&btChromeDeveloper_, L"Check this to enable Chrome specific behavior such as "
L"setting the Chrome symbol server path, and preprocessing of Chrome symbols and "
L"traces.");
toolTip_.AddTool(&btAutoViewTraces_, L"Check this to have UIforETW launch the trace viewer "
L"immediately after a trace is recorded.");
toolTip_.AddTool(&btHeapStacks_, L"Check this to record call stacks on HeapAlloc, HeapRealloc, "
L"and similar calls, when doing heap traces.");
toolTip_.AddTool(&btChromeDllPath_, L"Specify the path where chrome.dll resides. This is used "
L"to register the Chrome providers if the Chrome developer option is set.");
toolTip_.AddTool(&btWSMonitoredProcesses_, L"Names of processes whose working sets will be "
L"monitored, separated by semi-colons. An empty string means no monitoring. A '*' means "
L"that all processes will be monitored. For instance 'chrome.exe;notepad.exe'");
toolTip_.AddTool(&btExpensiveWSMonitoring_, L"Check this to have private working set and PSS "
L"(proportional set size) calculated for monitored processes. This may consume "
L"dozens or hundreds of ms each time. Without this checked only full working "
L"set is calculated, which is cheap.");
toolTip_.AddTool(&btVirtualAllocStacks_, L"Check this to record call stacks on VirtualAlloc on all "
L"traces instead of just heap traces.");
}
// Initialize the list of check boxes with all of the Chrome categories which
// we can enable individually.
btChromeCategories_.SetCheckStyle(BS_AUTOCHECKBOX);
int index = 0;
for (auto category : filtered_event_group_names)
{
btChromeCategories_.AddString(category);
btChromeCategories_.SetCheck(index, (chromeKeywords_ & (1LL << index)) != 0);
++index;
}
// Manually add the two special Chrome category options.
btChromeCategories_.AddString(other_events_group_name);
btChromeCategories_.SetCheck(index, (chromeKeywords_ & other_events_keyword_bit) != 0);
++index;
btChromeCategories_.AddString(disabled_other_events_group_name);
btChromeCategories_.SetCheck(index, (chromeKeywords_ & disabled_other_events_keyword_bit) != 0);
return TRUE; // return TRUE unless you set the focus to a control
}
void CSettings::OnOK()
{
heapTracingExes_ = GetEditControlText(btHeapTracingExe_);
chromeDllPath_ = GetEditControlText(btChromeDllPath_);
WSMonitoredProcesses_ = GetEditControlText(btWSMonitoredProcesses_);
// Extract the Chrome categories settings and put the result in chromeKeywords_.
chromeKeywords_ = 0;
int index = 0;
for (/**/; index < ARRAYSIZE(filtered_event_group_names); ++index)
{
if (btChromeCategories_.GetCheck(index))
chromeKeywords_ |= 1LL << index;
}
// Manually grab values for the two special Chrome category options
if (btChromeCategories_.GetCheck(index))
chromeKeywords_ |= other_events_keyword_bit;
++index;
if (btChromeCategories_.GetCheck(index))
chromeKeywords_ |= disabled_other_events_keyword_bit;
CDialog::OnOK();
}
BOOL CSettings::PreTranslateMessage(MSG* pMsg)
{
toolTip_.RelayEvent(pMsg);
return CDialog::PreTranslateMessage(pMsg);
}
void CSettings::OnBnClickedCopystartupprofile()
{
CopyStartupProfiles(exeDir_, true);
}
void CSettings::OnBnClickedCopysymboldlls()
{
// Attempt to deal with these problems:
// https://randomascii.wordpress.com/2012/10/04/xperf-symbol-loading-pitfalls/
const wchar_t* fileNames[] =
{
L"dbghelp.dll",
L"symsrv.dll",
};
bool bIsWin64 = Is64BitWindows();
bool failed = false;
std::wstring third_party = exeDir_ + L"..\\third_party\\";
for (size_t i = 0; i < ARRAYSIZE(fileNames); ++i)
{
std::wstring source = third_party + fileNames[i];
if (bIsWin64)
source = third_party + L"x64\\" + fileNames[i];
std::wstring dest = wptDir_ + fileNames[i];
if (!CopyFile(source.c_str(), dest.c_str(), FALSE))
failed = true;
}
if (failed)
AfxMessageBox(L"Failed to copy dbghelp.dll and symsrv.dll to the WPT directory. Is WPA running?");
else
AfxMessageBox(L"Copied dbghelp.dll and symsrv.dll to the WPT directory. If this doesn't help "
L"with symbol loading then consider deleting them to restore the previous state.");
}
void CSettings::OnBnClickedChromedeveloper()
{
bChromeDeveloper_ = !bChromeDeveloper_;
btChromeDllPath_.EnableWindow(bChromeDeveloper_);
}
void CSettings::OnBnClickedAutoviewtraces()
{
bAutoViewTraces_ = !bAutoViewTraces_;
}
void CSettings::OnBnClickedHeapstacks()
{
bHeapStacks_ = !bHeapStacks_;
}
void CSettings::OnBnClickedVirtualallocstacks()
{
bVirtualAllocStacks_ = !bVirtualAllocStacks_;
}
void CSettings::OnBnClickedExpensivews()
{
bExpensiveWSMonitoring_ = !bExpensiveWSMonitoring_;
}
<commit_msg>Added tool tip for Chrome tracing categories<commit_after>/*
Copyright 2015 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "stdafx.h"
#include "UIforETW.h"
#include "Settings.h"
#include "Utility.h"
#include "afxdialogex.h"
/*
When doing Chrome profilng it is possible to ask various Chrome tracing
categories to emit ETW events. The filtered_event_group_names array
documents what categories map to what flag/keyword values.
The table below is subject to change, but probably not very frequently.
For more details see this Chrome change that added the initial version of the
ETW event filtering:
https://codereview.chromium.org/1176243016
*/
// Copied from Chrome's trace_event_etw_export_win.cc. This file can be found by
// searching for "f:trace_event_etw_export_win.cc" in https://code.google.com/p/chromium/codesearch#/.
const PCWSTR filtered_event_group_names[] =
{
L"benchmark", // 0x1
L"blink", // 0x2
L"browser", // 0x4
L"cc", // 0x8
L"evdev", // 0x10
L"gpu", // 0x20
L"input", // 0x40
L"netlog", // 0x80
L"renderer.scheduler", // 0x100
L"toplevel", // 0x200
L"v8", // 0x400
L"disabled-by-default-cc.debug", // 0x800
L"disabled-by-default-cc.debug.picture", // 0x1000
L"disabled-by-default-toplevel.flow", // 0x2000
};
// 1ULL << 61 and 1ULL << 62 are special values that indicate to Chrome to
// enable all enabled-by-default and disabled-by-default categories
// respectively.
const PCWSTR other_events_group_name = L"All enabled-by-default events"; // 0x2000000000000000
const PCWSTR disabled_other_events_group_name = L"All disabled-by-default events"; // 0x4000000000000000
uint64_t other_events_keyword_bit = 1ULL << 61;
uint64_t disabled_other_events_keyword_bit = 1ULL << 62;
// CSettings dialog
IMPLEMENT_DYNAMIC(CSettings, CDialogEx)
CSettings::CSettings(CWnd* pParent /*=NULL*/, const std::wstring& exeDir, const std::wstring& wptDir)
: CDialogEx(CSettings::IDD, pParent)
, exeDir_(exeDir)
, wptDir_(wptDir)
{
}
CSettings::~CSettings()
{
}
void CSettings::DoDataExchange(CDataExchange* pDX)
{
DDX_Control(pDX, IDC_HEAPEXE, btHeapTracingExe_);
DDX_Control(pDX, IDC_EXTRAPROVIDERS, btExtraProviders_);
DDX_Control(pDX, IDC_EXTRASTACKWALKS, btExtraStackwalks_);
DDX_Control(pDX, IDC_BUFFERSIZES, btBufferSizes_);
DDX_Control(pDX, IDC_COPYSTARTUPPROFILE, btCopyStartupProfile_);
DDX_Control(pDX, IDC_COPYSYMBOLDLLS, btCopySymbolDLLs_);
DDX_Control(pDX, IDC_CHROMEDEVELOPER, btChromeDeveloper_);
DDX_Control(pDX, IDC_AUTOVIEWTRACES, btAutoViewTraces_);
DDX_Control(pDX, IDC_HEAPSTACKS, btHeapStacks_);
DDX_Control(pDX, IDC_CHROMEDLLPATH, btChromeDllPath_);
DDX_Control(pDX, IDC_WSMONITOREDPROCESSES, btWSMonitoredProcesses_);
DDX_Control(pDX, IDC_EXPENSIVEWS, btExpensiveWSMonitoring_);
DDX_Control(pDX, IDC_VIRTUALALLOCSTACKS, btVirtualAllocStacks_);
DDX_Control(pDX, IDC_CHROME_CATEGORIES, btChromeCategories_);
CDialogEx::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CSettings, CDialogEx)
ON_BN_CLICKED(IDC_COPYSTARTUPPROFILE, &CSettings::OnBnClickedCopystartupprofile)
ON_BN_CLICKED(IDC_COPYSYMBOLDLLS, &CSettings::OnBnClickedCopysymboldlls)
ON_BN_CLICKED(IDC_CHROMEDEVELOPER, &CSettings::OnBnClickedChromedeveloper)
ON_BN_CLICKED(IDC_AUTOVIEWTRACES, &CSettings::OnBnClickedAutoviewtraces)
ON_BN_CLICKED(IDC_HEAPSTACKS, &CSettings::OnBnClickedHeapstacks)
ON_BN_CLICKED(IDC_VIRTUALALLOCSTACKS, &CSettings::OnBnClickedVirtualallocstacks)
ON_BN_CLICKED(IDC_EXPENSIVEWS, &CSettings::OnBnClickedExpensivews)
END_MESSAGE_MAP()
BOOL CSettings::OnInitDialog()
{
CDialogEx::OnInitDialog();
SetDlgItemText(IDC_HEAPEXE, heapTracingExes_.c_str());
CheckDlgButton(IDC_CHROMEDEVELOPER, bChromeDeveloper_);
CheckDlgButton(IDC_AUTOVIEWTRACES, bAutoViewTraces_);
CheckDlgButton(IDC_HEAPSTACKS, bHeapStacks_);
CheckDlgButton(IDC_VIRTUALALLOCSTACKS, bVirtualAllocStacks_);
SetDlgItemText(IDC_CHROMEDLLPATH, chromeDllPath_.c_str());
btExtraProviders_.EnableWindow(FALSE);
btExtraStackwalks_.EnableWindow(FALSE);
btBufferSizes_.EnableWindow(FALSE);
btChromeDllPath_.EnableWindow(bChromeDeveloper_);
// A 32-bit process on 64-bit Windows will not be able to read the
// full working set of 64-bit processes, so don't even try.
if (Is64BitWindows() && !Is64BitBuild())
btWSMonitoredProcesses_.EnableWindow(FALSE);
else
SetDlgItemText(IDC_WSMONITOREDPROCESSES, WSMonitoredProcesses_.c_str());
CheckDlgButton(IDC_EXPENSIVEWS, bExpensiveWSMonitoring_);
if (toolTip_.Create(this))
{
toolTip_.SetMaxTipWidth(400);
toolTip_.Activate(TRUE);
toolTip_.AddTool(&btHeapTracingExe_, L"Specify the file names of the exes to be heap traced, "
L"separated by semi-colons. "
L"Enter just the file parts (with the .exe extension) not a full path. For example, "
L"'chrome.exe;notepad.exe'. This is for use with the heap-tracing-to-file mode.");
toolTip_.AddTool(&btCopyStartupProfile_, L"Copies startup.wpaProfile files for WPA 8.1 and "
L"10 to the appropriate destinations so that the next time WPA starts up it will have "
L"reasonable analysis defaults.");
toolTip_.AddTool(&btCopySymbolDLLs_, L"Copy dbghelp.dll and symsrv.dll to the xperf directory to "
L"try to resolve slow or failed symbol loading in WPA. See "
L"https://randomascii.wordpress.com/2012/10/04/xperf-symbol-loading-pitfalls/ "
L"for details.");
toolTip_.AddTool(&btChromeDeveloper_, L"Check this to enable Chrome specific behavior such as "
L"setting the Chrome symbol server path, and preprocessing of Chrome symbols and "
L"traces.");
toolTip_.AddTool(&btAutoViewTraces_, L"Check this to have UIforETW launch the trace viewer "
L"immediately after a trace is recorded.");
toolTip_.AddTool(&btHeapStacks_, L"Check this to record call stacks on HeapAlloc, HeapRealloc, "
L"and similar calls, when doing heap traces.");
toolTip_.AddTool(&btChromeDllPath_, L"Specify the path where chrome.dll resides. This is used "
L"to register the Chrome providers if the Chrome developer option is set.");
toolTip_.AddTool(&btWSMonitoredProcesses_, L"Names of processes whose working sets will be "
L"monitored, separated by semi-colons. An empty string means no monitoring. A '*' means "
L"that all processes will be monitored. For instance 'chrome.exe;notepad.exe'");
toolTip_.AddTool(&btExpensiveWSMonitoring_, L"Check this to have private working set and PSS "
L"(proportional set size) calculated for monitored processes. This may consume "
L"dozens or hundreds of ms each time. Without this checked only full working "
L"set is calculated, which is cheap.");
toolTip_.AddTool(&btVirtualAllocStacks_, L"Check this to record call stacks on VirtualAlloc on all "
L"traces instead of just heap traces.");
toolTip_.AddTool(&btChromeCategories_, L"Check the chrome tracing categories that you want Chrome "
L"to emit ETW events for. This requires running Chrome version 45 or later, with "
L"--trace-export-events-to-etw on the command-line.");
}
// Initialize the list of check boxes with all of the Chrome categories which
// we can enable individually.
btChromeCategories_.SetCheckStyle(BS_AUTOCHECKBOX);
int index = 0;
for (auto category : filtered_event_group_names)
{
btChromeCategories_.AddString(category);
btChromeCategories_.SetCheck(index, (chromeKeywords_ & (1LL << index)) != 0);
++index;
}
// Manually add the two special Chrome category options.
btChromeCategories_.AddString(other_events_group_name);
btChromeCategories_.SetCheck(index, (chromeKeywords_ & other_events_keyword_bit) != 0);
++index;
btChromeCategories_.AddString(disabled_other_events_group_name);
btChromeCategories_.SetCheck(index, (chromeKeywords_ & disabled_other_events_keyword_bit) != 0);
return TRUE; // return TRUE unless you set the focus to a control
}
void CSettings::OnOK()
{
heapTracingExes_ = GetEditControlText(btHeapTracingExe_);
chromeDllPath_ = GetEditControlText(btChromeDllPath_);
WSMonitoredProcesses_ = GetEditControlText(btWSMonitoredProcesses_);
// Extract the Chrome categories settings and put the result in chromeKeywords_.
chromeKeywords_ = 0;
int index = 0;
for (/**/; index < ARRAYSIZE(filtered_event_group_names); ++index)
{
if (btChromeCategories_.GetCheck(index))
chromeKeywords_ |= 1LL << index;
}
// Manually grab values for the two special Chrome category options
if (btChromeCategories_.GetCheck(index))
chromeKeywords_ |= other_events_keyword_bit;
++index;
if (btChromeCategories_.GetCheck(index))
chromeKeywords_ |= disabled_other_events_keyword_bit;
CDialog::OnOK();
}
BOOL CSettings::PreTranslateMessage(MSG* pMsg)
{
toolTip_.RelayEvent(pMsg);
return CDialog::PreTranslateMessage(pMsg);
}
void CSettings::OnBnClickedCopystartupprofile()
{
CopyStartupProfiles(exeDir_, true);
}
void CSettings::OnBnClickedCopysymboldlls()
{
// Attempt to deal with these problems:
// https://randomascii.wordpress.com/2012/10/04/xperf-symbol-loading-pitfalls/
const wchar_t* fileNames[] =
{
L"dbghelp.dll",
L"symsrv.dll",
};
bool bIsWin64 = Is64BitWindows();
bool failed = false;
std::wstring third_party = exeDir_ + L"..\\third_party\\";
for (size_t i = 0; i < ARRAYSIZE(fileNames); ++i)
{
std::wstring source = third_party + fileNames[i];
if (bIsWin64)
source = third_party + L"x64\\" + fileNames[i];
std::wstring dest = wptDir_ + fileNames[i];
if (!CopyFile(source.c_str(), dest.c_str(), FALSE))
failed = true;
}
if (failed)
AfxMessageBox(L"Failed to copy dbghelp.dll and symsrv.dll to the WPT directory. Is WPA running?");
else
AfxMessageBox(L"Copied dbghelp.dll and symsrv.dll to the WPT directory. If this doesn't help "
L"with symbol loading then consider deleting them to restore the previous state.");
}
void CSettings::OnBnClickedChromedeveloper()
{
bChromeDeveloper_ = !bChromeDeveloper_;
btChromeDllPath_.EnableWindow(bChromeDeveloper_);
}
void CSettings::OnBnClickedAutoviewtraces()
{
bAutoViewTraces_ = !bAutoViewTraces_;
}
void CSettings::OnBnClickedHeapstacks()
{
bHeapStacks_ = !bHeapStacks_;
}
void CSettings::OnBnClickedVirtualallocstacks()
{
bVirtualAllocStacks_ = !bVirtualAllocStacks_;
}
void CSettings::OnBnClickedExpensivews()
{
bExpensiveWSMonitoring_ = !bExpensiveWSMonitoring_;
}
<|endoftext|> |
<commit_before><commit_msg>Fix #1447: remove invalid/empty file<commit_after><|endoftext|> |
<commit_before>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/ozone/platform/drm/gpu/hardware_display_plane_manager_atomic.h"
#include "base/bind.h"
#include "ui/ozone/platform/drm/gpu/crtc_controller.h"
#include "ui/ozone/platform/drm/gpu/drm_device.h"
#include "ui/ozone/platform/drm/gpu/hardware_display_plane_atomic.h"
#include "ui/ozone/platform/drm/gpu/scanout_buffer.h"
namespace ui {
static void AtomicPageFlipCallback(
std::vector<base::WeakPtr<CrtcController>> crtcs,
unsigned int frame,
unsigned int seconds,
unsigned int useconds) {
for (auto& crtc : crtcs) {
auto* crtc_ptr = crtc.get();
if (crtc_ptr)
crtc_ptr->OnPageFlipEvent(frame, seconds, useconds);
}
}
HardwareDisplayPlaneManagerAtomic::HardwareDisplayPlaneManagerAtomic() {
}
HardwareDisplayPlaneManagerAtomic::~HardwareDisplayPlaneManagerAtomic() {
}
bool HardwareDisplayPlaneManagerAtomic::Commit(
HardwareDisplayPlaneList* plane_list,
bool is_sync,
bool test_only) {
for (HardwareDisplayPlane* plane : plane_list->old_plane_list) {
bool found =
std::find(plane_list->plane_list.begin(), plane_list->plane_list.end(),
plane) != plane_list->plane_list.end();
if (!found) {
// This plane is being released, so we need to zero it.
plane->set_in_use(false);
HardwareDisplayPlaneAtomic* atomic_plane =
static_cast<HardwareDisplayPlaneAtomic*>(plane);
atomic_plane->SetPlaneData(plane_list->atomic_property_set.get(), 0, 0,
gfx::Rect(), gfx::Rect());
}
}
std::vector<base::WeakPtr<CrtcController>> crtcs;
for (HardwareDisplayPlane* plane : plane_list->plane_list) {
HardwareDisplayPlaneAtomic* atomic_plane =
static_cast<HardwareDisplayPlaneAtomic*>(plane);
if (crtcs.empty() || crtcs.back().get() != atomic_plane->crtc())
crtcs.push_back(atomic_plane->crtc()->AsWeakPtr());
}
if (test_only) {
for (HardwareDisplayPlane* plane : plane_list->plane_list) {
plane->set_in_use(false);
}
} else {
plane_list->plane_list.swap(plane_list->old_plane_list);
}
plane_list->plane_list.clear();
if (!drm_->CommitProperties(plane_list->atomic_property_set.get(), 0, is_sync,
test_only,
base::Bind(&AtomicPageFlipCallback, crtcs))) {
PLOG(ERROR) << "Failed to commit properties";
return false;
}
return true;
}
bool HardwareDisplayPlaneManagerAtomic::SetPlaneData(
HardwareDisplayPlaneList* plane_list,
HardwareDisplayPlane* hw_plane,
const OverlayPlane& overlay,
uint32_t crtc_id,
const gfx::Rect& src_rect,
CrtcController* crtc) {
HardwareDisplayPlaneAtomic* atomic_plane =
static_cast<HardwareDisplayPlaneAtomic*>(hw_plane);
if (!atomic_plane->SetPlaneData(plane_list->atomic_property_set.get(),
crtc_id, overlay.buffer->GetFramebufferId(),
overlay.display_bounds, src_rect)) {
LOG(ERROR) << "Failed to set plane properties";
return false;
}
atomic_plane->set_crtc(crtc);
return true;
}
scoped_ptr<HardwareDisplayPlane> HardwareDisplayPlaneManagerAtomic::CreatePlane(
uint32_t plane_id,
uint32_t possible_crtcs) {
return scoped_ptr<HardwareDisplayPlane>(
new HardwareDisplayPlaneAtomic(plane_id, possible_crtcs));
}
} // namespace ui
<commit_msg>ozone: Reallocate atomic property set<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/ozone/platform/drm/gpu/hardware_display_plane_manager_atomic.h"
#include "base/bind.h"
#include "ui/ozone/platform/drm/gpu/crtc_controller.h"
#include "ui/ozone/platform/drm/gpu/drm_device.h"
#include "ui/ozone/platform/drm/gpu/hardware_display_plane_atomic.h"
#include "ui/ozone/platform/drm/gpu/scanout_buffer.h"
namespace ui {
static void AtomicPageFlipCallback(
std::vector<base::WeakPtr<CrtcController>> crtcs,
unsigned int frame,
unsigned int seconds,
unsigned int useconds) {
for (auto& crtc : crtcs) {
auto* crtc_ptr = crtc.get();
if (crtc_ptr)
crtc_ptr->OnPageFlipEvent(frame, seconds, useconds);
}
}
HardwareDisplayPlaneManagerAtomic::HardwareDisplayPlaneManagerAtomic() {
}
HardwareDisplayPlaneManagerAtomic::~HardwareDisplayPlaneManagerAtomic() {
}
bool HardwareDisplayPlaneManagerAtomic::Commit(
HardwareDisplayPlaneList* plane_list,
bool is_sync,
bool test_only) {
std::vector<base::WeakPtr<CrtcController>> crtcs;
for (HardwareDisplayPlane* plane : plane_list->plane_list) {
HardwareDisplayPlaneAtomic* atomic_plane =
static_cast<HardwareDisplayPlaneAtomic*>(plane);
if (crtcs.empty() || crtcs.back().get() != atomic_plane->crtc())
crtcs.push_back(atomic_plane->crtc()->AsWeakPtr());
}
if (test_only) {
for (HardwareDisplayPlane* plane : plane_list->plane_list) {
plane->set_in_use(false);
}
} else {
plane_list->plane_list.swap(plane_list->old_plane_list);
}
plane_list->plane_list.clear();
if (!drm_->CommitProperties(plane_list->atomic_property_set.get(), 0, is_sync,
test_only,
base::Bind(&AtomicPageFlipCallback, crtcs))) {
PLOG(ERROR) << "Failed to commit properties";
return false;
}
plane_list->atomic_property_set.reset(drmModePropertySetAlloc());
return true;
}
bool HardwareDisplayPlaneManagerAtomic::SetPlaneData(
HardwareDisplayPlaneList* plane_list,
HardwareDisplayPlane* hw_plane,
const OverlayPlane& overlay,
uint32_t crtc_id,
const gfx::Rect& src_rect,
CrtcController* crtc) {
HardwareDisplayPlaneAtomic* atomic_plane =
static_cast<HardwareDisplayPlaneAtomic*>(hw_plane);
if (!atomic_plane->SetPlaneData(plane_list->atomic_property_set.get(),
crtc_id, overlay.buffer->GetFramebufferId(),
overlay.display_bounds, src_rect)) {
LOG(ERROR) << "Failed to set plane properties";
return false;
}
atomic_plane->set_crtc(crtc);
return true;
}
scoped_ptr<HardwareDisplayPlane> HardwareDisplayPlaneManagerAtomic::CreatePlane(
uint32_t plane_id,
uint32_t possible_crtcs) {
return scoped_ptr<HardwareDisplayPlane>(
new HardwareDisplayPlaneAtomic(plane_id, possible_crtcs));
}
} // namespace ui
<|endoftext|> |
<commit_before>// Copyright 2012 Google Inc. All Rights Reserved.
// Author: jacobsa@google.com (Aaron Jacobs)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// This file contains mostly code imported from the v8 project, at
// trunk/src/d8.cc. The original copyright notice is as follows.
// Copyright 2012 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "gjstest/internal/cpp/typed_arrays.h"
#include "base/logging.h"
using v8::Arguments;
using v8::ExternalArrayType;
using v8::FunctionTemplate;
using v8::Handle;
using v8::HandleScope;
using v8::Int32;
using v8::Local;
using v8::Object;
using v8::ObjectTemplate;
using v8::Persistent;
using v8::ReadOnly;
using v8::String;
using v8::True;
using v8::TryCatch;
using v8::Value;
using v8::kExternalByteArray;
using v8::kExternalDoubleArray;
using v8::kExternalFloatArray;
using v8::kExternalIntArray;
using v8::kExternalShortArray;
using v8::kExternalUnsignedByteArray;
using v8::kExternalUnsignedIntArray;
using v8::kExternalUnsignedShortArray;
namespace gjstest {
static const char kArrayBufferReferencePropName[] = "_is_array_buffer_";
static const char kArrayBufferMarkerPropName[] = "_array_buffer_ref_";
static size_t convertToUint(Local<Value> value_in, TryCatch* try_catch) {
if (value_in->IsUint32()) {
return value_in->Uint32Value();
}
Local<Value> number = value_in->ToNumber();
if (try_catch->HasCaught()) return 0;
CHECK(number->IsNumber());
Local<Int32> int32 = number->ToInt32();
if (try_catch->HasCaught() || int32.IsEmpty()) return 0;
int32_t raw_value = int32->Int32Value();
if (try_catch->HasCaught()) return 0;
if (raw_value < 0) {
ThrowException(String::New("Array length must not be negative."));
return 0;
}
static const int kMaxLength = 0x3fffffff;
if (raw_value > static_cast<int32_t>(kMaxLength)) {
ThrowException(
String::New("Array length exceeds maximum length."));
}
return static_cast<size_t>(raw_value);
}
static void ExternalArrayWeakCallback(Persistent<Value> object, void* data) {
HandleScope scope;
Handle<String> prop_name = String::New(kArrayBufferReferencePropName);
Handle<Object> converted_object = object->ToObject();
Local<Value> prop_value = converted_object->Get(prop_name);
if (data != NULL && !prop_value->IsObject()) {
free(data);
}
object.Dispose();
}
// Create an external array from an underlying set of data. Takes ownership of
// the data.
static Handle<Object> CreateExternalArray(
uint8_t* data,
size_t num_elements,
size_t element_size,
ExternalArrayType element_type) {
Handle<Object> result = Object::New();
// Create a weak reference to the handle that will delete the underlying data
// when it is disposed of.
Persistent<Object> persistent = Persistent<Object>::New(result);
persistent.MakeWeak(data, ExternalArrayWeakCallback);
persistent.MarkIndependent();
// Set the backing store for indexed elements.
result->SetIndexedPropertiesToExternalArrayData(
data,
element_type,
num_elements);
// Set up the length and BYTES_PER_ELEMENT properties on the result.
result->Set(
String::New("length"),
Int32::New(num_elements),
ReadOnly);
result->Set(
String::New("BYTES_PER_ELEMENT"),
Int32::New(element_size));
return result;
}
// Common constructor code for all typed arrays. The following signatures are
// supported:
//
// TypedArray(
// ArrayBuffer buffer,
// optional unsigned long byteOffset,
// optional unsigned long length)
//
// TypedArray(unsigned long length)
//
// TypedArray(type[] array)
//
static Handle<Value> CreateExternalArray(
const Arguments& args,
ExternalArrayType type,
size_t element_size) {
TryCatch try_catch;
// Of the functions that defer to this one, the only one with element_size
// equal to zero is the constructor for ArrayBuffer.
const bool is_array_buffer_construct = (element_size == 0);
if (is_array_buffer_construct) {
type = v8::kExternalByteArray;
element_size = 1;
}
// We only support these element sizes.
CHECK(
element_size == 1 ||
element_size == 2 ||
element_size == 4 ||
element_size == 8);
// We require at least one arg.
if (args.Length() == 0) {
return ThrowException(
String::New(
"Array constructor must have at least one parameter."));
}
// Is this the constructor with the following signature?
//
// TypedArray(
// ArrayBuffer buffer,
// optional unsigned long byteOffset,
// optional unsigned long length)
//
const bool first_arg_is_array_buffer =
args[0]->IsObject() &&
args[0]->ToObject()->Get(
String::New(kArrayBufferMarkerPropName))->IsTrue();
// Is this the constructor with the following signature?
//
// TypedArray(type[] array)
//
const bool first_arg_is_array = args[0]->IsArray();
// Check the number of arguments for the array buffer case.
if (first_arg_is_array_buffer && args.Length() > 3) {
return ThrowException(
String::New("Array constructor from ArrayBuffer must "
"have 1-3 parameters."));
}
// Check the number of arguments for the array case.
if (first_arg_is_array && args.Length() != 1) {
return ThrowException(
String::New("Array constructor from array must have 1 parameter."));
}
// Currently, only the following constructors are supported:
// TypedArray(unsigned long length)
// TypedArray(ArrayBuffer buffer,
// optional unsigned long byteOffset,
// optional unsigned long length)
Local<Value> length_value = (args.Length() < 3)
? (first_arg_is_array_buffer
? args[0]->ToObject()->Get(String::New("length"))
: args[0])
: args[2];
size_t length = convertToUint(length_value, &try_catch);
if (try_catch.HasCaught()) return try_catch.Exception();
void* data = NULL;
size_t offset = 0;
Handle<Object> array = Object::New();
if (first_arg_is_array_buffer) {
Handle<Object> derived_from = args[0]->ToObject();
data = derived_from->GetIndexedPropertiesExternalArrayData();
size_t array_buffer_length = convertToUint(
derived_from->Get(String::New("length")),
&try_catch);
if (try_catch.HasCaught()) return try_catch.Exception();
if (data == NULL && array_buffer_length != 0) {
return ThrowException(
String::New("ArrayBuffer doesn't have data"));
}
if (args.Length() > 1) {
offset = convertToUint(args[1], &try_catch);
if (try_catch.HasCaught()) return try_catch.Exception();
// The given byteOffset must be a multiple of the element size of the
// specific type, otherwise an exception is raised.
if (offset % element_size != 0) {
return ThrowException(
String::New("offset must be multiple of element_size"));
}
}
if (offset > array_buffer_length) {
return ThrowException(
String::New("byteOffset must be less than ArrayBuffer length."));
}
if (args.Length() == 2) {
// If length is not explicitly specified, the length of the ArrayBuffer
// minus the byteOffset must be a multiple of the element size of the
// specific type, or an exception is raised.
length = array_buffer_length - offset;
}
if (args.Length() != 3) {
if (length % element_size != 0) {
return ThrowException(
String::New("ArrayBuffer length minus the byteOffset must be a "
"multiple of the element size"));
}
length /= element_size;
}
// If a given byteOffset and length references an area beyond the end of
// the ArrayBuffer an exception is raised.
if (offset + (length * element_size) > array_buffer_length) {
return ThrowException(
String::New("length references an area beyond the end of the "
"ArrayBuffer"));
}
// Hold a reference to the ArrayBuffer so its buffer doesn't get collected.
array->Set(String::New(kArrayBufferReferencePropName), args[0], ReadOnly);
}
if (is_array_buffer_construct) {
array->Set(String::New(kArrayBufferMarkerPropName), True(), ReadOnly);
}
Persistent<Object> persistent_array = Persistent<Object>::New(array);
persistent_array.MakeWeak(data, ExternalArrayWeakCallback);
persistent_array.MarkIndependent();
if (data == NULL && length != 0) {
data = calloc(length, element_size);
if (data == NULL) {
return ThrowException(String::New("Memory allocation failed."));
}
}
array->SetIndexedPropertiesToExternalArrayData(
reinterpret_cast<uint8_t*>(data) + offset, type,
static_cast<int>(length));
array->Set(String::New("length"),
Int32::New(static_cast<int32_t>(length)), ReadOnly);
array->Set(String::New("BYTES_PER_ELEMENT"),
Int32::New(static_cast<int32_t>(element_size)));
return array;
}
Handle<Value> ArrayBuffer(const Arguments& args) {
return CreateExternalArray(args, kExternalByteArray, 0);
}
Handle<Value> Int8Array(const Arguments& args) {
return CreateExternalArray(args, kExternalByteArray, sizeof(int8_t));
}
Handle<Value> Int16Array(const Arguments& args) {
return CreateExternalArray(args, kExternalShortArray, sizeof(int16_t));
}
Handle<Value> Int32Array(const Arguments& args) {
return CreateExternalArray(args, kExternalIntArray, sizeof(int32_t));
}
Handle<Value> Uint8Array(const Arguments& args) {
return CreateExternalArray(args, kExternalUnsignedByteArray, sizeof(uint8_t));
}
Handle<Value> Uint16Array(const Arguments& args) {
return CreateExternalArray(args, kExternalUnsignedShortArray, sizeof(uint16_t));
}
Handle<Value> Uint32Array(const Arguments& args) {
return CreateExternalArray(args, kExternalUnsignedIntArray, sizeof(uint32_t));
}
Handle<Value> Float32Array(const Arguments& args) {
return CreateExternalArray(args, kExternalFloatArray, sizeof(float));
}
Handle<Value> Float64Array(const Arguments& args) {
return CreateExternalArray(args, kExternalDoubleArray, sizeof(double));
}
void ExportTypedArrays(
const Handle<ObjectTemplate>& global_template) {
global_template->Set(
String::New("ArrayBuffer"),
FunctionTemplate::New(ArrayBuffer));
// Signed integers.
global_template->Set(
String::New("Int8Array"),
FunctionTemplate::New(Int8Array));
global_template->Set(
String::New("Int16Array"),
FunctionTemplate::New(Int16Array));
global_template->Set(
String::New("Int32Array"),
FunctionTemplate::New(Int32Array));
// Unigned integers.
global_template->Set(
String::New("Uint8Array"),
FunctionTemplate::New(Uint8Array));
global_template->Set(
String::New("Uint16Array"),
FunctionTemplate::New(Uint16Array));
global_template->Set(
String::New("Uint32Array"),
FunctionTemplate::New(Uint32Array));
// Floats.
global_template->Set(
String::New("Float32Array"),
FunctionTemplate::New(Float32Array));
global_template->Set(
String::New("Float64Array"),
FunctionTemplate::New(Float64Array));
}
} // namespace gjstest
<commit_msg>Added another helper.<commit_after>// Copyright 2012 Google Inc. All Rights Reserved.
// Author: jacobsa@google.com (Aaron Jacobs)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// This file contains mostly code imported from the v8 project, at
// trunk/src/d8.cc. The original copyright notice is as follows.
// Copyright 2012 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "gjstest/internal/cpp/typed_arrays.h"
#include "base/logging.h"
using v8::Arguments;
using v8::ExternalArrayType;
using v8::FunctionTemplate;
using v8::Handle;
using v8::HandleScope;
using v8::Int32;
using v8::Local;
using v8::Object;
using v8::ObjectTemplate;
using v8::Persistent;
using v8::ReadOnly;
using v8::String;
using v8::True;
using v8::TryCatch;
using v8::Value;
using v8::kExternalByteArray;
using v8::kExternalDoubleArray;
using v8::kExternalFloatArray;
using v8::kExternalIntArray;
using v8::kExternalShortArray;
using v8::kExternalUnsignedByteArray;
using v8::kExternalUnsignedIntArray;
using v8::kExternalUnsignedShortArray;
namespace gjstest {
static const char kArrayBufferReferencePropName[] = "_is_array_buffer_";
static const char kArrayBufferMarkerPropName[] = "_array_buffer_ref_";
static size_t ConvertToUint(
const Handle<Value>& value_in,
TryCatch* try_catch) {
if (value_in->IsUint32()) {
return value_in->Uint32Value();
}
Local<Value> number = value_in->ToNumber();
if (try_catch->HasCaught()) return 0;
CHECK(number->IsNumber());
Local<Int32> int32 = number->ToInt32();
if (try_catch->HasCaught() || int32.IsEmpty()) return 0;
int32_t raw_value = int32->Int32Value();
if (try_catch->HasCaught()) return 0;
if (raw_value < 0) {
ThrowException(String::New("Array length must not be negative."));
return 0;
}
static const int kMaxLength = 0x3fffffff;
if (raw_value > static_cast<int32_t>(kMaxLength)) {
ThrowException(
String::New("Array length exceeds maximum length."));
}
return static_cast<size_t>(raw_value);
}
static void ExternalArrayWeakCallback(Persistent<Value> object, void* data) {
HandleScope scope;
Handle<String> prop_name = String::New(kArrayBufferReferencePropName);
Handle<Object> converted_object = object->ToObject();
Local<Value> prop_value = converted_object->Get(prop_name);
if (data != NULL && !prop_value->IsObject()) {
free(data);
}
object.Dispose();
}
// Create an external array from an underlying set of data. Takes ownership of
// the data.
static Handle<Object> CreateExternalArray(
uint8_t* data,
size_t num_elements,
size_t element_size,
ExternalArrayType element_type) {
Handle<Object> result = Object::New();
// Create a weak reference to the handle that will delete the underlying data
// when it is disposed of.
Persistent<Object> persistent = Persistent<Object>::New(result);
persistent.MakeWeak(data, ExternalArrayWeakCallback);
persistent.MarkIndependent();
// Set the backing store for indexed elements.
result->SetIndexedPropertiesToExternalArrayData(
data,
element_type,
num_elements);
// Set up the length and BYTES_PER_ELEMENT properties on the result.
result->Set(
String::New("length"),
Int32::New(num_elements),
ReadOnly);
result->Set(
String::New("BYTES_PER_ELEMENT"),
Int32::New(element_size));
return result;
}
// Create a typed array from an existing array buffer. The array_buffer
// reference must be non-empty, but the other two arguments are optional.
static Handle<Value> CreateExternalArrayFromArrayBuffer(
ExternalArrayType element_type,
size_t element_size,
const Handle<Object>& array_buffer,
const Handle<Value>& byte_offset_arg,
const Handle<Value>& length_arg) {
CHECK(!array_buffer.IsEmpty());
CHECK(
array_buffer->Get(String::New(kArrayBufferReferencePropName))->
IsTrue());
TryCatch try_catch;
// Figure out what the length of the existing array buffer is.
const size_t array_buffer_length =
ConvertToUint(array_buffer->Get(String::New("length")), &try_catch);
if (try_catch.HasCaught()) {
return try_catch.Exception();
}
// Figure out what the offset into the array buffer should be.
size_t byte_offset = 0;
if (!byte_offset_arg.IsEmpty()) {
byte_offset = ConvertToUint(byte_offset_arg, &try_catch);
if (try_catch.HasCaught()) {
return try_catch.Exception();
}
}
// Make sure the offset is legal.
if (byte_offset % element_size) {
return ThrowException(
String::New("Offset must be a multiple of element size."));
}
if (byte_offset > array_buffer_length) {
return ThrowException(
String::New("Offset must be less than the array buffer length."));
}
// Figure out what the length of the resulting array should be (in elements,
// not bytes)
size_t length = 0;
if (length_arg.IsEmpty()) {
// If the length arg is omitted, the array spans from the byte offset to the
// end of the array buffer. The size of the range spanned must be a multiple
// of the element size.
if ((array_buffer_length - byte_offset) % element_size) {
return ThrowException(
String::New(
"Array buffer length minus the byte offset must be a "
"multiple of the element size"));
length = (array_buffer_length - byte_offset) / element_size;
} else {
length = ConvertToUint(length_arg, &try_catch);
if (try_catch.HasCaught()) {
return try_catch.Exception();
}
}
}
// Make sure the length is legal.
if (byte_offset + (length * element_size) > array_buffer_length) {
return ThrowException(
String::New(
"length references an area beyond the end of the array buffer."));
}
// Grab the data property from the array buffer.
uint8_t* const data =
static_cast<uint8_t*>(
array_buffer->GetIndexedPropertiesExternalArrayData());
if (!data) {
return ThrowException(String::New("ArrayBuffer doesn't have data."));
}
// Create the resulting object.
const Handle<Object> result =
CreateExternalArray(
data,
length,
element_size,
element_type);
// Hold a reference to the ArrayBuffer so its buffer doesn't get collected.
result->Set(
String::New(kArrayBufferReferencePropName),
array_buffer,
ReadOnly);
return result;
}
// Common constructor code for all typed arrays. The following signatures are
// supported:
//
// TypedArray(
// ArrayBuffer buffer,
// optional unsigned long byteOffset,
// optional unsigned long length)
//
// TypedArray(unsigned long length)
//
// TypedArray(type[] array)
//
static Handle<Value> CreateExternalArray(
const Arguments& args,
ExternalArrayType type,
size_t element_size) {
TryCatch try_catch;
// Of the functions that defer to this one, the only one with element_size
// equal to zero is the constructor for ArrayBuffer.
const bool is_array_buffer_construct = (element_size == 0);
if (is_array_buffer_construct) {
type = v8::kExternalByteArray;
element_size = 1;
}
// We only support these element sizes.
CHECK(
element_size == 1 ||
element_size == 2 ||
element_size == 4 ||
element_size == 8);
// We require at least one arg.
if (args.Length() == 0) {
return ThrowException(
String::New(
"Array constructor must have at least one parameter."));
}
// Is this the constructor with the following signature?
//
// TypedArray(
// ArrayBuffer buffer,
// optional unsigned long byteOffset,
// optional unsigned long length)
//
const bool first_arg_is_array_buffer =
args[0]->IsObject() &&
args[0]->ToObject()->Get(
String::New(kArrayBufferMarkerPropName))->IsTrue();
// Is this the constructor with the following signature?
//
// TypedArray(type[] array)
//
const bool first_arg_is_array = args[0]->IsArray();
// Check the number of arguments for the array buffer case.
if (first_arg_is_array_buffer && args.Length() > 3) {
return ThrowException(
String::New("Array constructor from ArrayBuffer must "
"have 1-3 parameters."));
}
// Check the number of arguments for the array case.
if (first_arg_is_array && args.Length() != 1) {
return ThrowException(
String::New("Array constructor from array must have 1 parameter."));
}
// Currently, only the following constructors are supported:
// TypedArray(unsigned long length)
// TypedArray(ArrayBuffer buffer,
// optional unsigned long byteOffset,
// optional unsigned long length)
Local<Value> length_value = (args.Length() < 3)
? (first_arg_is_array_buffer
? args[0]->ToObject()->Get(String::New("length"))
: args[0])
: args[2];
size_t length = ConvertToUint(length_value, &try_catch);
if (try_catch.HasCaught()) return try_catch.Exception();
void* data = NULL;
size_t offset = 0;
Handle<Object> array = Object::New();
if (first_arg_is_array_buffer) {
Handle<Object> derived_from = args[0]->ToObject();
data = derived_from->GetIndexedPropertiesExternalArrayData();
size_t array_buffer_length = ConvertToUint(
derived_from->Get(String::New("length")),
&try_catch);
if (try_catch.HasCaught()) return try_catch.Exception();
if (data == NULL && array_buffer_length != 0) {
return ThrowException(
String::New("ArrayBuffer doesn't have data"));
}
if (args.Length() > 1) {
offset = ConvertToUint(args[1], &try_catch);
if (try_catch.HasCaught()) return try_catch.Exception();
// The given byteOffset must be a multiple of the element size of the
// specific type, otherwise an exception is raised.
if (offset % element_size != 0) {
return ThrowException(
String::New("offset must be multiple of element_size"));
}
}
if (offset > array_buffer_length) {
return ThrowException(
String::New("byteOffset must be less than ArrayBuffer length."));
}
if (args.Length() == 2) {
// If length is not explicitly specified, the length of the ArrayBuffer
// minus the byteOffset must be a multiple of the element size of the
// specific type, or an exception is raised.
length = array_buffer_length - offset;
}
if (args.Length() != 3) {
if (length % element_size != 0) {
return ThrowException(
String::New("ArrayBuffer length minus the byteOffset must be a "
"multiple of the element size"));
}
length /= element_size;
}
// If a given byteOffset and length references an area beyond the end of
// the ArrayBuffer an exception is raised.
if (offset + (length * element_size) > array_buffer_length) {
return ThrowException(
String::New("length references an area beyond the end of the "
"ArrayBuffer"));
}
// Hold a reference to the ArrayBuffer so its buffer doesn't get collected.
array->Set(String::New(kArrayBufferReferencePropName), args[0], ReadOnly);
}
if (is_array_buffer_construct) {
array->Set(String::New(kArrayBufferMarkerPropName), True(), ReadOnly);
}
Persistent<Object> persistent_array = Persistent<Object>::New(array);
persistent_array.MakeWeak(data, ExternalArrayWeakCallback);
persistent_array.MarkIndependent();
if (data == NULL && length != 0) {
data = calloc(length, element_size);
if (data == NULL) {
return ThrowException(String::New("Memory allocation failed."));
}
}
array->SetIndexedPropertiesToExternalArrayData(
reinterpret_cast<uint8_t*>(data) + offset, type,
static_cast<int>(length));
array->Set(String::New("length"),
Int32::New(static_cast<int32_t>(length)), ReadOnly);
array->Set(String::New("BYTES_PER_ELEMENT"),
Int32::New(static_cast<int32_t>(element_size)));
return array;
}
Handle<Value> ArrayBuffer(const Arguments& args) {
return CreateExternalArray(args, kExternalByteArray, 0);
}
Handle<Value> Int8Array(const Arguments& args) {
return CreateExternalArray(args, kExternalByteArray, sizeof(int8_t));
}
Handle<Value> Int16Array(const Arguments& args) {
return CreateExternalArray(args, kExternalShortArray, sizeof(int16_t));
}
Handle<Value> Int32Array(const Arguments& args) {
return CreateExternalArray(args, kExternalIntArray, sizeof(int32_t));
}
Handle<Value> Uint8Array(const Arguments& args) {
return CreateExternalArray(args, kExternalUnsignedByteArray, sizeof(uint8_t));
}
Handle<Value> Uint16Array(const Arguments& args) {
return CreateExternalArray(args, kExternalUnsignedShortArray, sizeof(uint16_t));
}
Handle<Value> Uint32Array(const Arguments& args) {
return CreateExternalArray(args, kExternalUnsignedIntArray, sizeof(uint32_t));
}
Handle<Value> Float32Array(const Arguments& args) {
return CreateExternalArray(args, kExternalFloatArray, sizeof(float));
}
Handle<Value> Float64Array(const Arguments& args) {
return CreateExternalArray(args, kExternalDoubleArray, sizeof(double));
}
void ExportTypedArrays(
const Handle<ObjectTemplate>& global_template) {
global_template->Set(
String::New("ArrayBuffer"),
FunctionTemplate::New(ArrayBuffer));
// Signed integers.
global_template->Set(
String::New("Int8Array"),
FunctionTemplate::New(Int8Array));
global_template->Set(
String::New("Int16Array"),
FunctionTemplate::New(Int16Array));
global_template->Set(
String::New("Int32Array"),
FunctionTemplate::New(Int32Array));
// Unigned integers.
global_template->Set(
String::New("Uint8Array"),
FunctionTemplate::New(Uint8Array));
global_template->Set(
String::New("Uint16Array"),
FunctionTemplate::New(Uint16Array));
global_template->Set(
String::New("Uint32Array"),
FunctionTemplate::New(Uint32Array));
// Floats.
global_template->Set(
String::New("Float32Array"),
FunctionTemplate::New(Float32Array));
global_template->Set(
String::New("Float64Array"),
FunctionTemplate::New(Float64Array));
}
} // namespace gjstest
<|endoftext|> |
<commit_before>//
// Created by theppsh on 17-4-13.
//
#include <iostream>
#include <iomanip>
#include "src/aes.hpp"
#include "src/triple_des.hpp"
int main(int argc,char ** args){
/**aes 加密*/
/// 128位全0的秘钥
u_char key_block[]={0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0
};
u_char plain_block[] = {0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,
0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18,
};
u_char cipher_block[16];
AES aes_test(key_block);
std::cout<<"********** aes 加密测试 **********"<<std::endl;
std::memcpy(cipher_block,plain_block,16);
aes_test.Cipher(cipher_block);
auto cout_default_flags = std::cout.flags();
for(int i=0;i<16;i++){
std::cout<<std::hex<<std::internal<<std::showbase<<std::setw(4)<<std::setfill('0')<<int(cipher_block[i])<<" ";
}
std::cout.setf(cout_default_flags);
std::cout<<std::endl;
std::cout<<std::endl;
std::cout<<"********** aes 解密测试 **********"<<std::endl;
std::memcpy(plain_block,cipher_block,16);
aes_test.InvCipher(plain_block);
for(int i=0;i<16;i++){
std::cout<<std::hex<<std::internal<<std::showbase<<std::setw(4)<<std::setfill('0')<<int(plain_block[i])<<" ";
}
std::cout<<std::endl;
std::cout.setf(cout_default_flags);
/// ***aes加密文件测试 ***
std::cout<<std::endl;
std::cout<<"******** aes 加密文件测试 ********"<<std::endl;
std::string plain_txt= "/media/C/课程与作业/网络安全/实验课/实验一/aes_and_des/resoureces/plain.txt";
std::string cipher_txt = "/media/C/课程与作业/网络安全/实验课/实验一/aes_and_des/resoureces/cipher.txt";
std::string decipher_txt = "/media/C/课程与作业/网络安全/实验课/实验一/aes_and_des/resoureces/decipher.txt";
aes_test.CipherFile(plain_txt,cipher_txt);
std::cout<<std::endl;
std::cout<<"******** 解密文件测试 ********"<<std::endl;
aes_test.InvCipherFile(cipher_txt,decipher_txt);
[](const std::string & file_path1,const std::string file_path2){
std::fstream f1,f2;
f1.open(file_path1);
f2.open(file_path2);
assert(f1.is_open());
assert(f2.is_open());
f1.seekg(0,std::ios::end);
f2.seekg(0,std::ios::end);
int f1_size = static_cast<int>(f1.tellg());
int f2_size = static_cast<int>(f2.tellg());
std::shared_ptr<char> f1_file_buffer(new char[f1_size+1]);
std::shared_ptr<char> f2_file_buffer(new char[f2_size+1]);
f1.seekg(0,std::ios::beg);
f2.seekg(0,std::ios::beg);
f1.read(f1_file_buffer.get(),f1_size);
f2.read(f2_file_buffer.get(),f2_size);
f1_file_buffer.get()[f1_size]='\0';
f2_file_buffer.get()[f2_size]='\0';
if(std::strcmp(f1_file_buffer.get(),f2_file_buffer.get())!=0){
std::cout<<"文件加密解密后的文件与原来的文件不一致"<<std::endl;
exit(0);
}else{
std::cout<<"文件加密解密通过!"<<std::endl;
}
}(plain_txt,decipher_txt);
/// aes 与 des 的加密解密的速度的测试 均加密128位即16个byete的数据
std::cout<<std::endl;
std::cout<<"******** ase & des CBC加密解密的速度的测试****** "<< std::endl;
int enc_times =100000; //加密而次数s
// 先测试 des
{
u_char des_bit_keys[64];
u_char des_sub_keys[16][48];
auto t1= std::chrono::system_clock::now();
for (int _time =0 ; _time < enc_times; _time++){
des::Char8ToBit64(key_block,des_bit_keys);
des::DES_MakeSubKeys(des_bit_keys,des_sub_keys);
_3_des::_3_DES_EncryptBlock(plain_block,key_block,key_block,key_block,cipher_block);
_3_des::_3_DES_EncryptBlock(plain_block+8,key_block,key_block,key_block,cipher_block+8); //des的块是8个字节也就是64位的。。。
_3_des::_3_DES_DecryptBlock(cipher_block,key_block,key_block,key_block,plain_block);
_3_des::_3_DES_DecryptBlock(cipher_block+8,key_block,key_block,key_block,plain_block+8);
}
auto t2 = std::chrono::system_clock::now();
float total_time = std::chrono::duration_cast<std::chrono::nanoseconds>(t2-t1).count()/1000.0f/1000.0f;
std::cout<<"加密解密128位数消息"<<enc_times<<"次, des-CBC总共花费了:"<<total_time<<" ms"<<std::endl;
std::cout<<"加密解密128位数消息"<<enc_times<<"次, des-CBC平均花费了:"<<total_time/enc_times<<" ms"<<std::endl;
}
// 再测试aes
{
auto t1 =std::chrono::system_clock::now();
for(int _time = 0; _time<enc_times;_time++){
aes_test.Cipher(plain_block);
memcpy(cipher_block,plain_block,16);
aes_test.InvCipher(cipher_block);
memcpy(plain_block,cipher_block,16);
}
auto t2 = std::chrono::system_clock::now();
float total_time = std::chrono::duration_cast<std::chrono::nanoseconds>(t2-t1).count()/1000.0f/1000.0f;
std::cout<<"加密解密128位数消息"<<enc_times<<"次, aes总共花费了:"<<total_time<<" ms"<<std::endl;
std::cout<<"加密解密128位数消息"<<enc_times<<"次, aes平均花费了:"<<total_time/enc_times<<" ms"<<std::endl;
}
return 0;
}<commit_msg>修改了aes<commit_after>//
// Created by theppsh on 17-4-13.
//
#include <iostream>
#include <iomanip>
#include "src/aes.hpp"
#include "src/triple_des.hpp"
int main(int argc,char ** args){
/**aes 加密*/
/// 128位全0的秘钥
u_char key_block[]={0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0
};
u_char plain_block[] = {0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,
0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18,
};
u_char cipher_block[16];
AES aes_test(key_block);
std::cout<<"********** aes 加密测试 **********"<<std::endl;
std::memcpy(cipher_block,plain_block,16);
aes_test.Cipher(cipher_block);
auto cout_default_flags = std::cout.flags();
for(int i=0;i<16;i++){
std::cout<<std::hex<<std::internal<<std::showbase<<std::setw(4)<<std::setfill('0')<<int(cipher_block[i])<<" ";
}
std::cout.setf(cout_default_flags);
std::cout<<std::endl;
std::cout<<std::endl;
std::cout<<"********** aes 解密测试 **********"<<std::endl;
std::memcpy(plain_block,cipher_block,16);
aes_test.InvCipher(plain_block);
for(int i=0;i<16;i++){
std::cout<<std::hex<<std::internal<<std::showbase<<std::setw(4)<<std::setfill('0')<<int(plain_block[i])<<" ";
}
std::cout<<std::endl;
std::cout.setf(cout_default_flags);
/// ***aes加密文件测试 ***
std::cout<<std::endl;
std::cout<<"******** aes 加密文件测试 ********"<<std::endl;
std::string plain_txt= "/media/C/课程与作业/网络安全/实验课/实验一/aes_and_des/resoureces/plain.txt";
std::string cipher_txt = "/media/C/课程与作业/网络安全/实验课/实验一/aes_and_des/resoureces/cipher.txt";
std::string decipher_txt = "/media/C/课程与作业/网络安全/实验课/实验一/aes_and_des/resoureces/decipher.txt";
aes_test.CipherFile(plain_txt,cipher_txt);
std::cout<<std::endl;
std::cout<<"******** 解密文件测试 ********"<<std::endl;
aes_test.InvCipherFile(cipher_txt,decipher_txt);
[](const std::string & file_path1,const std::string file_path2){
std::fstream f1,f2;
f1.open(file_path1);
f2.open(file_path2);
assert(f1.is_open());
assert(f2.is_open());
f1.seekg(0,std::ios::end);
f2.seekg(0,std::ios::end);
int f1_size = static_cast<int>(f1.tellg());
int f2_size = static_cast<int>(f2.tellg());
std::shared_ptr<char> f1_file_buffer(new char[f1_size+1]);
std::shared_ptr<char> f2_file_buffer(new char[f2_size+1]);
f1.seekg(0,std::ios::beg);
f2.seekg(0,std::ios::beg);
f1.read(f1_file_buffer.get(),f1_size);
f2.read(f2_file_buffer.get(),f2_size);
f1_file_buffer.get()[f1_size]='\0';
f2_file_buffer.get()[f2_size]='\0';
if(std::strcmp(f1_file_buffer.get(),f2_file_buffer.get())!=0){
std::cout<<"文件加密解密后的文件与原来的文件不一致"<<std::endl;
exit(0);
}else{
std::cout<<"文件加密解密通过!"<<std::endl;
}
}(plain_txt,decipher_txt);
/// aes 与 des 的加密解密的速度的测试 均加密128位即16个byete的数据
std::cout<<std::endl;
std::cout<<"******** ase & 3des ecb加密解密的速度的测试****** "<< std::endl;
int enc_times =100000; //加密而次数s
// 先测试 des
{
u_char des_bit_keys[64];
u_char des_sub_keys[16][48];
auto t1= std::chrono::system_clock::now();
for (int _time =0 ; _time < enc_times; _time++){
des::Char8ToBit64(key_block,des_bit_keys);
des::DES_MakeSubKeys(des_bit_keys,des_sub_keys);
_3_des::_3_DES_EncryptBlock(plain_block,key_block,key_block,key_block,cipher_block);
_3_des::_3_DES_EncryptBlock(plain_block+8,key_block,key_block,key_block,cipher_block+8); //des的块是8个字节也就是64位的。。。
_3_des::_3_DES_DecryptBlock(cipher_block,key_block,key_block,key_block,plain_block);
_3_des::_3_DES_DecryptBlock(cipher_block+8,key_block,key_block,key_block,plain_block+8);
}
auto t2 = std::chrono::system_clock::now();
float total_time = std::chrono::duration_cast<std::chrono::nanoseconds>(t2-t1).count()/1000.0f/1000.0f;
std::cout<<"加密解密128位数消息"<<enc_times<<"次, 3_des-ecb总共花费了:"<<total_time<<" ms"<<std::endl;
std::cout<<"加密解密128位数消息"<<enc_times<<"次, 3_des-ecb平均花费了:"<<total_time/enc_times<<" ms"<<std::endl;
}
// 再测试aes
{
auto t1 =std::chrono::system_clock::now();
for(int _time = 0; _time<enc_times;_time++){
aes_test.Cipher(plain_block);
memcpy(cipher_block,plain_block,16);
aes_test.InvCipher(cipher_block);
memcpy(plain_block,cipher_block,16);
}
auto t2 = std::chrono::system_clock::now();
float total_time = std::chrono::duration_cast<std::chrono::nanoseconds>(t2-t1).count()/1000.0f/1000.0f;
std::cout<<"加密解密128位数消息"<<enc_times<<"次, aes总共花费了:"<<total_time<<" ms"<<std::endl;
std::cout<<"加密解密128位数消息"<<enc_times<<"次, aes平均花费了:"<<total_time/enc_times<<" ms"<<std::endl;
}
return 0;
}<|endoftext|> |
<commit_before>// Copyright 2008, Google Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// 3. Neither the name of Google Inc. nor the names of its contributors may be
// used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
#include <string>
#include "kml/dom/kml22.h"
#include "kml/dom/kml_factory.h"
#include "kml/dom/schema.h"
#include "kml/base/unit_test.h"
namespace kmldom {
// <SimpleField>
class SimpleFieldTest : public CPPUNIT_NS::TestFixture {
CPPUNIT_TEST_SUITE(SimpleFieldTest);
CPPUNIT_TEST(TestType);
CPPUNIT_TEST(TestDefaults);
CPPUNIT_TEST(TestSetToDefaultValues);
CPPUNIT_TEST(TestSetGetHasClear);
CPPUNIT_TEST_SUITE_END();
public:
void setUp() {
simplefield_ = KmlFactory::GetFactory()->CreateSimpleField();
}
void tearDown() {
}
protected:
void TestType();
void TestDefaults();
void TestSetToDefaultValues();
void TestSetGetHasClear();
private:
SimpleFieldPtr simplefield_;
};
CPPUNIT_TEST_SUITE_REGISTRATION(SimpleFieldTest);
void SimpleFieldTest::TestType() {
CPPUNIT_ASSERT(Type_SimpleField == simplefield_->Type());
CPPUNIT_ASSERT(true == simplefield_->IsA(Type_SimpleField));
}
void SimpleFieldTest::TestDefaults() {
CPPUNIT_ASSERT("" == simplefield_->get_type());
CPPUNIT_ASSERT(false == simplefield_->has_type());
CPPUNIT_ASSERT("" == simplefield_->get_name());
CPPUNIT_ASSERT(false == simplefield_->has_name());
CPPUNIT_ASSERT("" == simplefield_->get_displayname());
CPPUNIT_ASSERT(false == simplefield_->has_displayname());
}
void SimpleFieldTest::TestSetToDefaultValues() {
TestDefaults();
simplefield_->set_type(simplefield_->get_type());
CPPUNIT_ASSERT(true == simplefield_->has_type());
simplefield_->set_name(simplefield_->get_name());
CPPUNIT_ASSERT(true == simplefield_->has_name());
simplefield_->set_displayname(simplefield_->get_displayname());
CPPUNIT_ASSERT(true == simplefield_->has_displayname());
}
void SimpleFieldTest::TestSetGetHasClear() {
std::string type("tom");
simplefield_->set_type(type);
CPPUNIT_ASSERT(true == simplefield_->has_type());
CPPUNIT_ASSERT(type == simplefield_->get_type());
simplefield_->clear_type();
std::string name("tom");
simplefield_->set_name(name);
CPPUNIT_ASSERT(true == simplefield_->has_name());
CPPUNIT_ASSERT(name == simplefield_->get_name());
simplefield_->clear_name();
std::string displayname("dick");
simplefield_->set_displayname(displayname);
CPPUNIT_ASSERT(true == simplefield_->has_displayname());
CPPUNIT_ASSERT(displayname == simplefield_->get_displayname());
simplefield_->clear_displayname();
TestDefaults();
}
// <Schema>
class SchemaTest : public CPPUNIT_NS::TestFixture {
CPPUNIT_TEST_SUITE(SchemaTest);
CPPUNIT_TEST(TestType);
CPPUNIT_TEST(TestDefaults);
CPPUNIT_TEST(TestSetToDefaultValues);
CPPUNIT_TEST(TestSetGetHasClear);
CPPUNIT_TEST(TestLists);
CPPUNIT_TEST_SUITE_END();
public:
void setUp() {
schema_ = KmlFactory::GetFactory()->CreateSchema();
}
void tearDown() {
}
protected:
void TestType();
void TestDefaults();
void TestSetToDefaultValues();
void TestSetGetHasClear();
void TestLists();
private:
SchemaPtr schema_;
};
CPPUNIT_TEST_SUITE_REGISTRATION(SchemaTest);
void SchemaTest::TestType() {
CPPUNIT_ASSERT(Type_Schema == schema_->Type());
CPPUNIT_ASSERT(true == schema_->IsA(Type_Schema));
}
void SchemaTest::TestDefaults() {
CPPUNIT_ASSERT("" == schema_->get_name());
CPPUNIT_ASSERT(false == schema_->has_name());
CPPUNIT_ASSERT("" == schema_->get_id());
CPPUNIT_ASSERT(false == schema_->has_id());
}
void SchemaTest::TestSetToDefaultValues() {
TestDefaults();
schema_->set_name(schema_->get_name());
CPPUNIT_ASSERT(true == schema_->has_name());
schema_->set_id(schema_->get_id());
CPPUNIT_ASSERT(true == schema_->has_id());
}
void SchemaTest::TestSetGetHasClear() {
std::string name("tom");
schema_->set_name(name);
CPPUNIT_ASSERT(true == schema_->has_name());
CPPUNIT_ASSERT(name == schema_->get_name());
schema_->clear_name();
std::string id("dick");
schema_->set_id(id);
CPPUNIT_ASSERT(true == schema_->has_id());
CPPUNIT_ASSERT(id == schema_->get_id());
schema_->clear_id();
TestDefaults();
}
void SchemaTest::TestLists() {
// Vector is empty.
CPPUNIT_ASSERT(0 == schema_->get_simplefield_array_size());
// Add three <SimpleField> elements:
schema_->add_simplefield(KmlFactory::GetFactory()->CreateSimpleField());
schema_->add_simplefield(KmlFactory::GetFactory()->CreateSimpleField());
schema_->add_simplefield(KmlFactory::GetFactory()->CreateSimpleField());
// We have three items in the array:
CPPUNIT_ASSERT(3 == schema_->get_simplefield_array_size());
for (size_t i = 0; i < schema_->get_simplefield_array_size(); ++i) {
CPPUNIT_ASSERT(
Type_SimpleField == schema_->get_simplefield_array_at(i)->Type());
}
}
} // end namespace kmldom
TEST_MAIN
<commit_msg>test that <Schema> IsA Object<commit_after>// Copyright 2008, Google Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// 3. Neither the name of Google Inc. nor the names of its contributors may be
// used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
#include "kml/dom/schema.h"
#include <string>
#include "kml/dom/kml22.h"
#include "kml/dom/kml_factory.h"
#include "kml/base/unit_test.h"
namespace kmldom {
// <SimpleField>
class SimpleFieldTest : public CPPUNIT_NS::TestFixture {
CPPUNIT_TEST_SUITE(SimpleFieldTest);
CPPUNIT_TEST(TestType);
CPPUNIT_TEST(TestDefaults);
CPPUNIT_TEST(TestSetToDefaultValues);
CPPUNIT_TEST(TestSetGetHasClear);
CPPUNIT_TEST_SUITE_END();
public:
void setUp() {
simplefield_ = KmlFactory::GetFactory()->CreateSimpleField();
}
void tearDown() {
}
protected:
void TestType();
void TestDefaults();
void TestSetToDefaultValues();
void TestSetGetHasClear();
private:
SimpleFieldPtr simplefield_;
};
CPPUNIT_TEST_SUITE_REGISTRATION(SimpleFieldTest);
void SimpleFieldTest::TestType() {
CPPUNIT_ASSERT(Type_SimpleField == simplefield_->Type());
CPPUNIT_ASSERT(true == simplefield_->IsA(Type_SimpleField));
}
void SimpleFieldTest::TestDefaults() {
CPPUNIT_ASSERT("" == simplefield_->get_type());
CPPUNIT_ASSERT(false == simplefield_->has_type());
CPPUNIT_ASSERT("" == simplefield_->get_name());
CPPUNIT_ASSERT(false == simplefield_->has_name());
CPPUNIT_ASSERT("" == simplefield_->get_displayname());
CPPUNIT_ASSERT(false == simplefield_->has_displayname());
}
void SimpleFieldTest::TestSetToDefaultValues() {
TestDefaults();
simplefield_->set_type(simplefield_->get_type());
CPPUNIT_ASSERT(true == simplefield_->has_type());
simplefield_->set_name(simplefield_->get_name());
CPPUNIT_ASSERT(true == simplefield_->has_name());
simplefield_->set_displayname(simplefield_->get_displayname());
CPPUNIT_ASSERT(true == simplefield_->has_displayname());
}
void SimpleFieldTest::TestSetGetHasClear() {
std::string type("tom");
simplefield_->set_type(type);
CPPUNIT_ASSERT(true == simplefield_->has_type());
CPPUNIT_ASSERT(type == simplefield_->get_type());
simplefield_->clear_type();
std::string name("tom");
simplefield_->set_name(name);
CPPUNIT_ASSERT(true == simplefield_->has_name());
CPPUNIT_ASSERT(name == simplefield_->get_name());
simplefield_->clear_name();
std::string displayname("dick");
simplefield_->set_displayname(displayname);
CPPUNIT_ASSERT(true == simplefield_->has_displayname());
CPPUNIT_ASSERT(displayname == simplefield_->get_displayname());
simplefield_->clear_displayname();
TestDefaults();
}
// <Schema>
class SchemaTest : public CPPUNIT_NS::TestFixture {
CPPUNIT_TEST_SUITE(SchemaTest);
CPPUNIT_TEST(TestType);
CPPUNIT_TEST(TestDefaults);
CPPUNIT_TEST(TestSetToDefaultValues);
CPPUNIT_TEST(TestSetGetHasClear);
CPPUNIT_TEST(TestLists);
CPPUNIT_TEST_SUITE_END();
public:
void setUp() {
schema_ = KmlFactory::GetFactory()->CreateSchema();
}
void tearDown() {
}
protected:
void TestType();
void TestDefaults();
void TestSetToDefaultValues();
void TestSetGetHasClear();
void TestLists();
private:
SchemaPtr schema_;
};
CPPUNIT_TEST_SUITE_REGISTRATION(SchemaTest);
void SchemaTest::TestType() {
CPPUNIT_ASSERT(Type_Schema == schema_->Type());
CPPUNIT_ASSERT(true == schema_->IsA(Type_Schema));
CPPUNIT_ASSERT(true == schema_->IsA(Type_Object));
}
void SchemaTest::TestDefaults() {
CPPUNIT_ASSERT("" == schema_->get_name());
CPPUNIT_ASSERT(false == schema_->has_name());
CPPUNIT_ASSERT("" == schema_->get_id());
CPPUNIT_ASSERT(false == schema_->has_id());
}
void SchemaTest::TestSetToDefaultValues() {
TestDefaults();
schema_->set_name(schema_->get_name());
CPPUNIT_ASSERT(true == schema_->has_name());
schema_->set_id(schema_->get_id());
CPPUNIT_ASSERT(true == schema_->has_id());
}
void SchemaTest::TestSetGetHasClear() {
std::string name("tom");
schema_->set_name(name);
CPPUNIT_ASSERT(true == schema_->has_name());
CPPUNIT_ASSERT(name == schema_->get_name());
schema_->clear_name();
std::string id("dick");
schema_->set_id(id);
CPPUNIT_ASSERT(true == schema_->has_id());
CPPUNIT_ASSERT(id == schema_->get_id());
schema_->clear_id();
TestDefaults();
}
void SchemaTest::TestLists() {
// Vector is empty.
CPPUNIT_ASSERT(0 == schema_->get_simplefield_array_size());
// Add three <SimpleField> elements:
schema_->add_simplefield(KmlFactory::GetFactory()->CreateSimpleField());
schema_->add_simplefield(KmlFactory::GetFactory()->CreateSimpleField());
schema_->add_simplefield(KmlFactory::GetFactory()->CreateSimpleField());
// We have three items in the array:
CPPUNIT_ASSERT(3 == schema_->get_simplefield_array_size());
for (size_t i = 0; i < schema_->get_simplefield_array_size(); ++i) {
CPPUNIT_ASSERT(
Type_SimpleField == schema_->get_simplefield_array_at(i)->Type());
}
}
} // end namespace kmldom
TEST_MAIN
<|endoftext|> |
<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2006-2008 Benoit Jacob <jacob.benoit.1@gmail.com>
//
// 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/.
#define EIGEN2_SUPPORT
#define EIGEN_NO_STATIC_ASSERT
#include "main.h"
#include <functional>
#ifdef min
#undef min
#endif
#ifdef max
#undef max
#endif
using namespace std;
template<typename Scalar> struct AddIfNull {
const Scalar operator() (const Scalar a, const Scalar b) const {return a<=1e-3 ? b : a;}
enum { Cost = NumTraits<Scalar>::AddCost };
};
template<typename MatrixType>
typename Eigen::internal::enable_if<!NumTraits<typename MatrixType::Scalar>::IsInteger,typename MatrixType::Scalar>::type
cwiseops_real_only(MatrixType& m1, MatrixType& m2, MatrixType& m3, MatrixType& mones)
{
typedef typename MatrixType::Scalar Scalar;
typedef typename NumTraits<Scalar>::Real RealScalar;
VERIFY_IS_APPROX(m1.cwise() / m2, m1.cwise() * (m2.cwise().inverse()));
m3 = m1.cwise().abs().cwise().sqrt();
VERIFY_IS_APPROX(m3.cwise().square(), m1.cwise().abs());
VERIFY_IS_APPROX(m1.cwise().square().cwise().sqrt(), m1.cwise().abs());
VERIFY_IS_APPROX(m1.cwise().abs().cwise().log().cwise().exp() , m1.cwise().abs());
VERIFY_IS_APPROX(m1.cwise().pow(2), m1.cwise().square());
m3 = (m1.cwise().abs().cwise()<=RealScalar(0.01)).select(mones,m1);
VERIFY_IS_APPROX(m3.cwise().pow(-1), m3.cwise().inverse());
m3 = m1.cwise().abs();
VERIFY_IS_APPROX(m3.cwise().pow(RealScalar(0.5)), m3.cwise().sqrt());
// VERIFY_IS_APPROX(m1.cwise().tan(), m1.cwise().sin().cwise() / m1.cwise().cos());
VERIFY_IS_APPROX(mones, m1.cwise().sin().cwise().square() + m1.cwise().cos().cwise().square());
m3 = m1;
m3.cwise() /= m2;
VERIFY_IS_APPROX(m3, m1.cwise() / m2);
return Scalar(0);
}
template<typename MatrixType>
typename Eigen::internal::enable_if<NumTraits<typename MatrixType::Scalar>::IsInteger,typename MatrixType::Scalar>::type
cwiseops_real_only(MatrixType& , MatrixType& , MatrixType& , MatrixType& )
{
typedef typename MatrixType::Scalar Scalar;
return 0;
}
template<typename MatrixType> void cwiseops(const MatrixType& m)
{
typedef typename MatrixType::Index Index;
typedef typename MatrixType::Scalar Scalar;
typedef typename NumTraits<Scalar>::Real RealScalar;
typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> VectorType;
Index rows = m.rows();
Index cols = m.cols();
MatrixType m1 = MatrixType::Random(rows, cols),
m2 = MatrixType::Random(rows, cols),
m3(rows, cols),
m4(rows, cols),
mzero = MatrixType::Zero(rows, cols),
mones = MatrixType::Ones(rows, cols),
identity = Matrix<Scalar, MatrixType::RowsAtCompileTime, MatrixType::RowsAtCompileTime>
::Identity(rows, rows);
VectorType vzero = VectorType::Zero(rows),
vones = VectorType::Ones(rows),
v3(rows);
Index r = internal::random<Index>(0, rows-1),
c = internal::random<Index>(0, cols-1);
Scalar s1 = internal::random<Scalar>();
// test Zero, Ones, Constant, and the set* variants
m3 = MatrixType::Constant(rows, cols, s1);
for (int j=0; j<cols; ++j)
for (int i=0; i<rows; ++i)
{
VERIFY_IS_APPROX(mzero(i,j), Scalar(0));
VERIFY_IS_APPROX(mones(i,j), Scalar(1));
VERIFY_IS_APPROX(m3(i,j), s1);
}
VERIFY(mzero.isZero());
VERIFY(mones.isOnes());
VERIFY(m3.isConstant(s1));
VERIFY(identity.isIdentity());
VERIFY_IS_APPROX(m4.setConstant(s1), m3);
VERIFY_IS_APPROX(m4.setConstant(rows,cols,s1), m3);
VERIFY_IS_APPROX(m4.setZero(), mzero);
VERIFY_IS_APPROX(m4.setZero(rows,cols), mzero);
VERIFY_IS_APPROX(m4.setOnes(), mones);
VERIFY_IS_APPROX(m4.setOnes(rows,cols), mones);
m4.fill(s1);
VERIFY_IS_APPROX(m4, m3);
VERIFY_IS_APPROX(v3.setConstant(rows, s1), VectorType::Constant(rows,s1));
VERIFY_IS_APPROX(v3.setZero(rows), vzero);
VERIFY_IS_APPROX(v3.setOnes(rows), vones);
m2 = m2.template binaryExpr<AddIfNull<Scalar> >(mones);
VERIFY_IS_APPROX(m1.cwise().pow(2), m1.cwise().abs2());
VERIFY_IS_APPROX(m1.cwise().pow(2), m1.cwise().square());
VERIFY_IS_APPROX(m1.cwise().pow(3), m1.cwise().cube());
VERIFY_IS_APPROX(m1 + mones, m1.cwise()+Scalar(1));
VERIFY_IS_APPROX(m1 - mones, m1.cwise()-Scalar(1));
m3 = m1; m3.cwise() += 1;
VERIFY_IS_APPROX(m1 + mones, m3);
m3 = m1; m3.cwise() -= 1;
VERIFY_IS_APPROX(m1 - mones, m3);
VERIFY_IS_APPROX(m2, m2.cwise() * mones);
VERIFY_IS_APPROX(m1.cwise() * m2, m2.cwise() * m1);
m3 = m1;
m3.cwise() *= m2;
VERIFY_IS_APPROX(m3, m1.cwise() * m2);
VERIFY_IS_APPROX(mones, m2.cwise()/m2);
// check min
VERIFY_IS_APPROX( m1.cwise().min(m2), m2.cwise().min(m1) );
VERIFY_IS_APPROX( m1.cwise().min(m1+mones), m1 );
VERIFY_IS_APPROX( m1.cwise().min(m1-mones), m1-mones );
// check max
VERIFY_IS_APPROX( m1.cwise().max(m2), m2.cwise().max(m1) );
VERIFY_IS_APPROX( m1.cwise().max(m1-mones), m1 );
VERIFY_IS_APPROX( m1.cwise().max(m1+mones), m1+mones );
VERIFY( (m1.cwise() == m1).all() );
VERIFY( (m1.cwise() != m2).any() );
VERIFY(!(m1.cwise() == (m1+mones)).any() );
if (rows*cols>1)
{
m3 = m1;
m3(r,c) += 1;
VERIFY( (m1.cwise() == m3).any() );
VERIFY( !(m1.cwise() == m3).all() );
}
VERIFY( (m1.cwise().min(m2).cwise() <= m2).all() );
VERIFY( (m1.cwise().max(m2).cwise() >= m2).all() );
VERIFY( (m1.cwise().min(m2).cwise() < (m1+mones)).all() );
VERIFY( (m1.cwise().max(m2).cwise() > (m1-mones)).all() );
VERIFY( (m1.cwise()<m1.unaryExpr(bind2nd(plus<Scalar>(), Scalar(1)))).all() );
VERIFY( !(m1.cwise()<m1.unaryExpr(bind2nd(minus<Scalar>(), Scalar(1)))).all() );
VERIFY( !(m1.cwise()>m1.unaryExpr(bind2nd(plus<Scalar>(), Scalar(1)))).any() );
cwiseops_real_only(m1, m2, m3, mones);
}
void test_cwiseop()
{
for(int i = 0; i < g_repeat ; i++) {
CALL_SUBTEST_1( cwiseops(Matrix<float, 1, 1>()) );
CALL_SUBTEST_2( cwiseops(Matrix4d()) );
CALL_SUBTEST_3( cwiseops(MatrixXf(internal::random<int>(1,EIGEN_TEST_MAX_SIZE), internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) );
CALL_SUBTEST_4( cwiseops(MatrixXf(internal::random<int>(1,EIGEN_TEST_MAX_SIZE), internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) );
CALL_SUBTEST_5( cwiseops(MatrixXi(internal::random<int>(1,EIGEN_TEST_MAX_SIZE), internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) );
CALL_SUBTEST_6( cwiseops(MatrixXd(internal::random<int>(1,EIGEN_TEST_MAX_SIZE), internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) );
}
}
<commit_msg>Workaround warning: assuming signed overflow does not occur when...<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2006-2008 Benoit Jacob <jacob.benoit.1@gmail.com>
//
// 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/.
#define EIGEN2_SUPPORT
#define EIGEN_NO_STATIC_ASSERT
#include "main.h"
#include <functional>
#ifdef min
#undef min
#endif
#ifdef max
#undef max
#endif
using namespace std;
template<typename Scalar> struct AddIfNull {
const Scalar operator() (const Scalar a, const Scalar b) const {return a<=1e-3 ? b : a;}
enum { Cost = NumTraits<Scalar>::AddCost };
};
template<typename MatrixType>
typename Eigen::internal::enable_if<!NumTraits<typename MatrixType::Scalar>::IsInteger,typename MatrixType::Scalar>::type
cwiseops_real_only(MatrixType& m1, MatrixType& m2, MatrixType& m3, MatrixType& mones)
{
typedef typename MatrixType::Scalar Scalar;
typedef typename NumTraits<Scalar>::Real RealScalar;
VERIFY_IS_APPROX(m1.cwise() / m2, m1.cwise() * (m2.cwise().inverse()));
m3 = m1.cwise().abs().cwise().sqrt();
VERIFY_IS_APPROX(m3.cwise().square(), m1.cwise().abs());
VERIFY_IS_APPROX(m1.cwise().square().cwise().sqrt(), m1.cwise().abs());
VERIFY_IS_APPROX(m1.cwise().abs().cwise().log().cwise().exp() , m1.cwise().abs());
VERIFY_IS_APPROX(m1.cwise().pow(2), m1.cwise().square());
m3 = (m1.cwise().abs().cwise()<=RealScalar(0.01)).select(mones,m1);
VERIFY_IS_APPROX(m3.cwise().pow(-1), m3.cwise().inverse());
m3 = m1.cwise().abs();
VERIFY_IS_APPROX(m3.cwise().pow(RealScalar(0.5)), m3.cwise().sqrt());
// VERIFY_IS_APPROX(m1.cwise().tan(), m1.cwise().sin().cwise() / m1.cwise().cos());
VERIFY_IS_APPROX(mones, m1.cwise().sin().cwise().square() + m1.cwise().cos().cwise().square());
m3 = m1;
m3.cwise() /= m2;
VERIFY_IS_APPROX(m3, m1.cwise() / m2);
return Scalar(0);
}
template<typename MatrixType>
typename Eigen::internal::enable_if<NumTraits<typename MatrixType::Scalar>::IsInteger,typename MatrixType::Scalar>::type
cwiseops_real_only(MatrixType& , MatrixType& , MatrixType& , MatrixType& )
{
typedef typename MatrixType::Scalar Scalar;
return 0;
}
template<typename MatrixType> void cwiseops(const MatrixType& m)
{
typedef typename MatrixType::Index Index;
typedef typename MatrixType::Scalar Scalar;
typedef typename NumTraits<Scalar>::Real RealScalar;
typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> VectorType;
Index rows = m.rows();
Index cols = m.cols();
MatrixType m1 = MatrixType::Random(rows, cols),
m1bis = m1,
m2 = MatrixType::Random(rows, cols),
m3(rows, cols),
m4(rows, cols),
mzero = MatrixType::Zero(rows, cols),
mones = MatrixType::Ones(rows, cols),
identity = Matrix<Scalar, MatrixType::RowsAtCompileTime, MatrixType::RowsAtCompileTime>
::Identity(rows, rows);
VectorType vzero = VectorType::Zero(rows),
vones = VectorType::Ones(rows),
v3(rows);
Index r = internal::random<Index>(0, rows-1),
c = internal::random<Index>(0, cols-1);
Scalar s1 = internal::random<Scalar>();
// test Zero, Ones, Constant, and the set* variants
m3 = MatrixType::Constant(rows, cols, s1);
for (int j=0; j<cols; ++j)
for (int i=0; i<rows; ++i)
{
VERIFY_IS_APPROX(mzero(i,j), Scalar(0));
VERIFY_IS_APPROX(mones(i,j), Scalar(1));
VERIFY_IS_APPROX(m3(i,j), s1);
}
VERIFY(mzero.isZero());
VERIFY(mones.isOnes());
VERIFY(m3.isConstant(s1));
VERIFY(identity.isIdentity());
VERIFY_IS_APPROX(m4.setConstant(s1), m3);
VERIFY_IS_APPROX(m4.setConstant(rows,cols,s1), m3);
VERIFY_IS_APPROX(m4.setZero(), mzero);
VERIFY_IS_APPROX(m4.setZero(rows,cols), mzero);
VERIFY_IS_APPROX(m4.setOnes(), mones);
VERIFY_IS_APPROX(m4.setOnes(rows,cols), mones);
m4.fill(s1);
VERIFY_IS_APPROX(m4, m3);
VERIFY_IS_APPROX(v3.setConstant(rows, s1), VectorType::Constant(rows,s1));
VERIFY_IS_APPROX(v3.setZero(rows), vzero);
VERIFY_IS_APPROX(v3.setOnes(rows), vones);
m2 = m2.template binaryExpr<AddIfNull<Scalar> >(mones);
VERIFY_IS_APPROX(m1.cwise().pow(2), m1.cwise().abs2());
VERIFY_IS_APPROX(m1.cwise().pow(2), m1.cwise().square());
VERIFY_IS_APPROX(m1.cwise().pow(3), m1.cwise().cube());
VERIFY_IS_APPROX(m1 + mones, m1.cwise()+Scalar(1));
VERIFY_IS_APPROX(m1 - mones, m1.cwise()-Scalar(1));
m3 = m1; m3.cwise() += 1;
VERIFY_IS_APPROX(m1 + mones, m3);
m3 = m1; m3.cwise() -= 1;
VERIFY_IS_APPROX(m1 - mones, m3);
VERIFY_IS_APPROX(m2, m2.cwise() * mones);
VERIFY_IS_APPROX(m1.cwise() * m2, m2.cwise() * m1);
m3 = m1;
m3.cwise() *= m2;
VERIFY_IS_APPROX(m3, m1.cwise() * m2);
VERIFY_IS_APPROX(mones, m2.cwise()/m2);
// check min
VERIFY_IS_APPROX( m1.cwise().min(m2), m2.cwise().min(m1) );
VERIFY_IS_APPROX( m1.cwise().min(m1+mones), m1 );
VERIFY_IS_APPROX( m1.cwise().min(m1-mones), m1-mones );
// check max
VERIFY_IS_APPROX( m1.cwise().max(m2), m2.cwise().max(m1) );
VERIFY_IS_APPROX( m1.cwise().max(m1-mones), m1 );
VERIFY_IS_APPROX( m1.cwise().max(m1+mones), m1+mones );
VERIFY( (m1.cwise() == m1).all() );
VERIFY( (m1.cwise() != m2).any() );
VERIFY(!(m1.cwise() == (m1+mones)).any() );
if (rows*cols>1)
{
m3 = m1;
m3(r,c) += 1;
VERIFY( (m1.cwise() == m3).any() );
VERIFY( !(m1.cwise() == m3).all() );
}
VERIFY( (m1.cwise().min(m2).cwise() <= m2).all() );
VERIFY( (m1.cwise().max(m2).cwise() >= m2).all() );
VERIFY( (m1.cwise().min(m2).cwise() < (m1+mones)).all() );
VERIFY( (m1.cwise().max(m2).cwise() > (m1-mones)).all() );
VERIFY( (m1.cwise()<m1.unaryExpr(bind2nd(plus<Scalar>(), Scalar(1)))).all() );
VERIFY( !(m1.cwise()<m1bis.unaryExpr(bind2nd(minus<Scalar>(), Scalar(1)))).all() );
VERIFY( !(m1.cwise()>m1bis.unaryExpr(bind2nd(plus<Scalar>(), Scalar(1)))).any() );
cwiseops_real_only(m1, m2, m3, mones);
}
void test_cwiseop()
{
for(int i = 0; i < g_repeat ; i++) {
CALL_SUBTEST_1( cwiseops(Matrix<float, 1, 1>()) );
CALL_SUBTEST_2( cwiseops(Matrix4d()) );
CALL_SUBTEST_3( cwiseops(MatrixXf(internal::random<int>(1,EIGEN_TEST_MAX_SIZE), internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) );
CALL_SUBTEST_4( cwiseops(MatrixXf(internal::random<int>(1,EIGEN_TEST_MAX_SIZE), internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) );
CALL_SUBTEST_5( cwiseops(MatrixXi(internal::random<int>(1,EIGEN_TEST_MAX_SIZE), internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) );
CALL_SUBTEST_6( cwiseops(MatrixXd(internal::random<int>(1,EIGEN_TEST_MAX_SIZE), internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) );
}
}
<|endoftext|> |
<commit_before>#ifndef DATASTRUCTURES_H
#define DATASTRUCTURES_H
#include <string>
#include <vector>
#include <map>
#include <string>
#include "api/BamMultiReader.h"
#include "fastahack/Fasta.h"
#include "ssw_cpp.h"
struct regionDat{
int seqidIndex ;
int start ;
int end ;
};
struct readPair{
int flag;
int count;
BamTools::BamAlignment al1;
BamTools::BamAlignment al2;
};
struct cigDat{
int Length;
char Type;
};
struct saTag{
int seqid;
int pos;
bool strand;
std::vector<cigDat> cig;
};
struct node;
struct edge;
struct edge{
node * L;
node * R;
std::map<char,int> support;
};
struct node{
int seqid ;
int pos ;
std::vector <edge *> eds ;
std::map<std::string,int> sm ;
};
struct graph{
std::map< int, std::map<int, node *> > nodes;
std::vector<edge *> edges;
};
//------------------------------- SUBROUTINE --------------------------------
/*
Function input : a node
Function does : visits all the edges and counts the support
Function returns: int (count of support)
*/
int getSupport(node * N){
int support = 0;
for(std::vector<edge *>::iterator ed = N->eds.begin() ;
ed != N->eds.end(); ed++){
support += (*ed)->support['L'];
support += (*ed)->support['H'];
support += (*ed)->support['S'];
support += (*ed)->support['I'];
support += (*ed)->support['D'];
support += (*ed)->support['V'];
support += (*ed)->support['M'];
support += (*ed)->support['R'];
support += (*ed)->support['X'];
support += (*ed)->support['A'];
}
return support;
}
class breakpoint{
private:
std::map<char, std::string > typeMap;
std::vector<std::string> refs ;
std::vector<std::string> seqNames;
char type;
std::string typeName;
int totalGraphWeight ;
bool paired;
bool bnd ;
bool masked;
long int length;
node * nodeL;
node * nodeR;
double totalCount;
double delCount ;
double insCount ;
double dupCount ;
double invCount ;
double traCount ;
void _count(node * n){
for(std::vector<edge *>::iterator ed = n->eds.begin() ;
ed != n->eds.end(); ed++){
if((*ed)->L->seqid == (*ed)->R->seqid){
delCount += (*ed)->support['H'];
delCount += (*ed)->support['D'];
delCount += (*ed)->support['S'];
insCount += (*ed)->support['I'];
insCount += (*ed)->support['R'];
insCount += (*ed)->support['L'];
invCount += (*ed)->support['M'];
invCount += (*ed)->support['A'];
invCount += (*ed)->support['V'];
dupCount += (*ed)->support['V'];
dupCount += (*ed)->support['S'];
dupCount += (*ed)->support['X'];
}
else{
traCount += (*ed)->support['H'];
traCount += (*ed)->support['D'];
traCount += (*ed)->support['S'];
traCount += (*ed)->support['I'];
traCount += (*ed)->support['R'];
traCount += (*ed)->support['L'];
traCount += (*ed)->support['M'];
traCount += (*ed)->support['A'];
traCount += (*ed)->support['V'];
traCount += (*ed)->support['S'];
traCount += (*ed)->support['X'];
}
totalCount += (*ed)->support['H'];
totalCount += (*ed)->support['D'];
totalCount += (*ed)->support['S'];
totalCount += (*ed)->support['I'];
totalCount += (*ed)->support['R'];
totalCount += (*ed)->support['L'];
totalCount += (*ed)->support['M'];
totalCount += (*ed)->support['A'];
totalCount += (*ed)->support['V'];
totalCount += (*ed)->support['V'];
totalCount += (*ed)->support['S'];
totalCount += (*ed)->support['X'];
}
}
void _processInternal(void){
if(nodeL->seqid != nodeR->seqid ){
if(nodeL->seqid > nodeR->seqid){
node * tmp;
tmp = nodeL;
nodeL = nodeR;
nodeR = tmp;
}
}
else{
if(nodeL->pos > nodeR->pos){
node * tmp;
tmp = nodeL;
nodeL = nodeR;
nodeR = tmp;
}
this->length = this->nodeR->pos - nodeL->pos;
}
}
public:
breakpoint(void): type('D')
, totalGraphWeight(0)
, paired(false)
, bnd(false)
, masked(false)
, length(0)
, nodeL(NULL)
, nodeR(NULL)
, totalCount(0)
, delCount(0)
, insCount(0)
, dupCount(0)
, invCount(0)
, traCount(0){
typeMap['D'] = "DEL";
typeMap['U'] = "DUP";
typeMap['T'] = "BND";
typeMap['I'] = "INS";
typeMap['V'] = "INV";
}
long int getLength(void){
return length;
}
void setGoodPair(bool t){
this->paired = t;
}
bool IsMasked(void){
return this->masked;
}
void unsetMasked(void){
this->masked = false;
}
void setMasked(void){
this->masked = true;
}
void setBadPair(void){
this->paired = true;
}
void setTotalSupport(int t){
this->totalCount = t;
}
bool IsBadPair(void){
return this->paired;
}
int getTotalSupport(void){
return this->totalCount;
}
bool add(node * n){
if(nodeL != NULL && nodeR != NULL){
return false;
}
if( nodeL == NULL ){
nodeL = n;
return true;
}
else{
nodeR = n;
_processInternal();
return true;
}
}
bool countSupportType(void){
if(nodeL == NULL || nodeR == NULL){
return false;
}
_count(nodeL);
_count(nodeR);
return true;
}
void calcType(void){
int maxN = delCount;
if(dupCount > maxN){
type = 'U';
maxN = dupCount;
}
if(invCount > maxN){
type = 'V';
maxN = invCount;
}
if(insCount > maxN){
type = 'I';
maxN = insCount;
}
if(traCount > maxN){
type = 'T';
maxN = traCount;
}
typeName = typeMap[type];
}
void getRefBases(FastaReference & rs, std::map<int, string> & lookup){
refs.push_back(rs.getSubSequence(lookup[nodeL->seqid],
nodeL->pos, 1));
if(nodeL->seqid != nodeR->seqid){
refs.push_back(rs.getSubSequence(lookup[nodeR->seqid],
nodeR->pos, 1));
}
seqNames.push_back(lookup[nodeL->seqid]);
seqNames.push_back(lookup[nodeR->seqid]);
}
friend std::ostream& operator<<(std::ostream& out,
const breakpoint& foo);
};
std::ostream& operator<<(std::ostream& out, const breakpoint & foo){
long int start = foo.nodeL->pos ;
long int end = foo.nodeR->pos ;
long int len = foo.length;
if(foo.type == 'I'){
end = start;
}
if(foo.type == 'D'){
len = -1*len;
}
if(foo.type != 'T' && (foo.nodeL->seqid == foo.nodeR->seqid)){
out << foo.seqNames.front() << "\t"
<< start << "\t"
<< end << "\t"
<< "D=" << foo.delCount
<< ";U=" << foo.dupCount
<< ";V=" << foo.invCount
<< ";I=" << foo.insCount
<< ";T=" << foo.traCount
<< ";REF=" << foo.refs.front();
out << ";" << foo.typeName << ";SVLEN=" << len ;
out << ";BW=" << double(getSupport(foo.nodeL)
+ getSupport(foo.nodeR))
/ double(foo.totalCount);
}
else{
out << foo.seqNames.front() << "\t"
<< foo.nodeL->pos << "\t"
<< foo.nodeL->pos << "\t"
<< "D=" << foo.delCount
<< ";U=" << foo.dupCount
<< ";V=" << foo.invCount
<< ";I=" << foo.insCount
<< ";T=" << foo.traCount
<< ";REF=" << foo.refs.front();
out << ";SVTYPE=" << foo.typeName << ";SVLEN=." ;
out << ";BW=" << double(getSupport(foo.nodeL)
+ getSupport(foo.nodeR))
/ double(foo.totalCount) ;
out << ";ALT=" << foo.refs.front() << "]"
<< foo.seqNames.back() << ":"
<< foo.nodeR->pos << "]";
out << std::endl;
out << foo.seqNames.back() << "\t"
<< foo.nodeR->pos << "\t"
<< foo.nodeR->pos << "\t"
<< "D=" << foo.delCount
<< ";U=" << foo.dupCount
<< ";V=" << foo.invCount
<< ";I=" << foo.insCount
<< ";T=" << foo.traCount
<< ";REF=" << foo.refs.back();
out << ";SVTYPE=" << foo.typeName << ";SVLEN=.";
out << ";BW=" << double(getSupport(foo.nodeL)
+ getSupport(foo.nodeR))
/ double(foo.totalCount);
out << ";ALT=" << foo.refs.back() << "]"
<< foo.seqNames.front() << ":"
<< foo.nodeL->pos << "]";
}
return out;
}
struct libraryStats{
std::map<std::string, double> mus ; // mean of insert length for each indvdual across 1e6 reads
std::map<std::string, double> sds ; // standard deviation
std::map<std::string, double> low ; // 25% of data
std::map<std::string, double> upr ; // 75% of the data
std::map<std::string, double> swm ;
std::map<std::string, double> sws ;
std::map<std::string, double> avgD;
double overallDepth;
} ;
//------------------------------- SUBROUTINE --------------------------------
/*
Function input : left and right node
Function does : return true if the left is less than the right
Function returns: bool
*/
bool sortNodesBySupport(node * L, node * R){
return (getSupport(L) > getSupport(R)) ;
}
//------------------------------- SUBROUTINE --------------------------------
/*
Function input : a left and right node
Function does : provides the rule for the sort
Function returns: bool
*/
bool sortNodesByPos(node * L, node * R){
return (L->pos < R->pos);
}
//------------------------------- SUBROUTINE --------------------------------
//------------------------------- SUBROUTINE --------------------------------
/*
Function input : edge pointer
Function does : init
Function returns: void
*/
void initEdge(edge * e){
e->L = NULL;
e->R = NULL;
// mate too close
e->support['L'] = 0;
// mate too far
e->support['H'] = 0;
// split read
e->support['S'] = 0;
// split read different strand (split)
e->support['V'] = 0;
// insertion
e->support['I'] = 0;
// deletion
e->support['D'] = 0;
// same strand too far
e->support['M'] = 0;
// same strand too close
e->support['R'] = 0;
// everted read pairs
e->support['X'] = 0;
e->support['K'] = 0;
// same strand
e->support['A'] = 0;
}
//------------------------------- SUBROUTINE --------------------------------
/*
Function input : refID (int), left position (int), graph
Function does : determine if a node is in the graph
Function returns: bool
*/
inline bool isInGraph(int refID, int pos, graph & lc){
if(lc.nodes.find(refID) == lc.nodes.end()){
return false;
}
if(lc.nodes[refID].find(pos) != lc.nodes[refID].end()){
return true;
}
return false;
}
//------------------------------- SUBROUTINE --------------------------------
/*
Function input : two node pointer
Function does : finds if nodes are directly connected
Function returns: bool
*/
bool connectedNode(node * left, node * right){
for(std::vector<edge *>::iterator l = left->eds.begin();
l != left->eds.end(); l++){
if(((*l)->L->pos == right->pos
|| (*l)->R->pos == right->pos)
&& (*l)->R->seqid == right->seqid ){
return true;
}
}
return false;
}
//------------------------------- SUBROUTINE --------------------------------
/*
Function input : a vector of edge pointers
Function does : does a tree terversal and joins nodes
Function returns: NA
*/
bool findEdge(std::vector<edge *> & eds, edge ** e, int pos){
for(std::vector<edge *>::iterator it = eds.begin(); it != eds.end(); it++){
if((*it)->L->pos == pos || (*it)->R->pos == pos ){
(*e) = (*it);
return true;
}
}
return false;
}
//------------------------------- SUBROUTINE --------------------------------
/*
Function input : a vector of node pointers, and a postion
Function does : removes edges that contain a position
Function returns: NA
*/
void removeEdges(std::vector<node *> & tree, int pos){
for(std::vector<node *>::iterator rm = tree.begin();
rm != tree.end(); rm++){
std::vector<edge *> tmp;
for(std::vector<edge *>::iterator e = (*rm)->eds.begin();
e != (*rm)->eds.end(); e++){
if( (*e)->L->pos != pos && (*e)->R->pos != pos ){
tmp.push_back((*e));
}
else{
}
}
(*rm)->eds.clear();
(*rm)->eds.insert((*rm)->eds.end(), tmp.begin(), tmp.end());
}
}
#endif
<commit_msg>SR < MQ0 and threaded<commit_after>#ifndef DATASTRUCTURES_H
#define DATASTRUCTURES_H
#include <string>
#include <vector>
#include <map>
#include <string>
#include "api/BamMultiReader.h"
#include "fastahack/Fasta.h"
#include "ssw_cpp.h"
struct regionDat{
int seqidIndex ;
int start ;
int end ;
};
struct readPair{
int flag;
int count;
BamTools::BamAlignment al1;
BamTools::BamAlignment al2;
};
struct cigDat{
int Length;
char Type;
};
struct saTag{
int seqid;
int pos;
bool strand;
int mapQ;
int NM;
std::vector<cigDat> cig;
};
struct node;
struct edge;
struct edge{
node * L;
node * R;
std::map<char,int> support;
};
struct node{
int seqid ;
int pos ;
std::vector <edge *> eds ;
std::map<std::string,int> sm ;
};
struct graph{
std::map< int, std::map<int, node *> > nodes;
std::vector<edge *> edges;
};
//------------------------------- SUBROUTINE --------------------------------
/*
Function input : a node
Function does : visits all the edges and counts the support
Function returns: int (count of support)
*/
int getSupport(node * N){
int support = 0;
for(std::vector<edge *>::iterator ed = N->eds.begin() ;
ed != N->eds.end(); ed++){
support += (*ed)->support['L'];
support += (*ed)->support['H'];
support += (*ed)->support['S'];
support += (*ed)->support['I'];
support += (*ed)->support['D'];
support += (*ed)->support['V'];
support += (*ed)->support['M'];
support += (*ed)->support['R'];
support += (*ed)->support['X'];
support += (*ed)->support['A'];
}
return support;
}
class breakpoint{
private:
std::map<char, std::string > typeMap;
std::vector<std::string> refs ;
std::vector<std::string> seqNames;
char type;
std::string typeName;
int totalGraphWeight ;
bool paired;
bool bnd ;
bool masked;
long int length;
node * nodeL;
node * nodeR;
double totalCount;
double delCount ;
double insCount ;
double dupCount ;
double invCount ;
double traCount ;
void _count(node * n){
for(std::vector<edge *>::iterator ed = n->eds.begin() ;
ed != n->eds.end(); ed++){
if((*ed)->L->seqid == (*ed)->R->seqid){
delCount += (*ed)->support['H'];
delCount += (*ed)->support['D'];
delCount += (*ed)->support['S'];
insCount += (*ed)->support['I'];
insCount += (*ed)->support['R'];
insCount += (*ed)->support['L'];
invCount += (*ed)->support['M'];
invCount += (*ed)->support['A'];
invCount += (*ed)->support['V'];
dupCount += (*ed)->support['V'];
dupCount += (*ed)->support['S'];
dupCount += (*ed)->support['X'];
}
else{
traCount += (*ed)->support['H'];
traCount += (*ed)->support['D'];
traCount += (*ed)->support['S'];
traCount += (*ed)->support['I'];
traCount += (*ed)->support['R'];
traCount += (*ed)->support['L'];
traCount += (*ed)->support['M'];
traCount += (*ed)->support['A'];
traCount += (*ed)->support['V'];
traCount += (*ed)->support['S'];
traCount += (*ed)->support['X'];
}
totalCount += (*ed)->support['H'];
totalCount += (*ed)->support['D'];
totalCount += (*ed)->support['S'];
totalCount += (*ed)->support['I'];
totalCount += (*ed)->support['R'];
totalCount += (*ed)->support['L'];
totalCount += (*ed)->support['M'];
totalCount += (*ed)->support['A'];
totalCount += (*ed)->support['V'];
totalCount += (*ed)->support['V'];
totalCount += (*ed)->support['S'];
totalCount += (*ed)->support['X'];
}
}
void _processInternal(void){
if(nodeL->seqid != nodeR->seqid ){
if(nodeL->seqid > nodeR->seqid){
node * tmp;
tmp = nodeL;
nodeL = nodeR;
nodeR = tmp;
}
}
else{
if(nodeL->pos > nodeR->pos){
node * tmp;
tmp = nodeL;
nodeL = nodeR;
nodeR = tmp;
}
this->length = this->nodeR->pos - nodeL->pos;
}
}
public:
breakpoint(void): type('D')
, totalGraphWeight(0)
, paired(false)
, bnd(false)
, masked(false)
, length(0)
, nodeL(NULL)
, nodeR(NULL)
, totalCount(0)
, delCount(0)
, insCount(0)
, dupCount(0)
, invCount(0)
, traCount(0){
typeMap['D'] = "DEL";
typeMap['U'] = "DUP";
typeMap['T'] = "BND";
typeMap['I'] = "INS";
typeMap['V'] = "INV";
}
long int getLength(void){
return length;
}
void setGoodPair(bool t){
this->paired = t;
}
bool IsMasked(void){
return this->masked;
}
void unsetMasked(void){
this->masked = false;
}
void setMasked(void){
this->masked = true;
}
void setBadPair(void){
this->paired = true;
}
void setTotalSupport(int t){
this->totalCount = t;
}
bool IsBadPair(void){
return this->paired;
}
int getTotalSupport(void){
return this->totalCount;
}
bool add(node * n){
if(nodeL != NULL && nodeR != NULL){
return false;
}
if( nodeL == NULL ){
nodeL = n;
return true;
}
else{
nodeR = n;
_processInternal();
return true;
}
}
bool countSupportType(void){
if(nodeL == NULL || nodeR == NULL){
return false;
}
_count(nodeL);
_count(nodeR);
return true;
}
void calcType(void){
int maxN = delCount;
if(dupCount > maxN){
type = 'U';
maxN = dupCount;
}
if(invCount > maxN){
type = 'V';
maxN = invCount;
}
if(insCount > maxN){
type = 'I';
maxN = insCount;
}
if(traCount > maxN){
type = 'T';
maxN = traCount;
}
typeName = typeMap[type];
}
void getRefBases(std::string & reffile, std::map<int, string> & lookup){
FastaReference rs;
rs.open(reffile);
refs.push_back(rs.getSubSequence(lookup[nodeL->seqid],
nodeL->pos, 1));
if(nodeL->seqid != nodeR->seqid){
refs.push_back(rs.getSubSequence(lookup[nodeR->seqid],
nodeR->pos, 1));
}
seqNames.push_back(lookup[nodeL->seqid]);
seqNames.push_back(lookup[nodeR->seqid]);
}
friend std::ostream& operator<<(std::ostream& out,
const breakpoint& foo);
};
std::ostream& operator<<(std::ostream& out, const breakpoint & foo){
long int start = foo.nodeL->pos ;
long int end = foo.nodeR->pos ;
long int len = foo.length;
if(foo.type == 'I'){
end = start;
}
if(foo.type == 'D'){
len = -1*len;
}
if(foo.type != 'T' && (foo.nodeL->seqid == foo.nodeR->seqid)){
out << foo.seqNames.front() << "\t"
<< start << "\t"
<< end << "\t"
<< "D=" << foo.delCount
<< ";U=" << foo.dupCount
<< ";V=" << foo.invCount
<< ";I=" << foo.insCount
<< ";T=" << foo.traCount
<< ";REF=" << foo.refs.front();
out << ";" << foo.typeName << ";SVLEN=" << len ;
out << ";BW=" << double(getSupport(foo.nodeL)
+ getSupport(foo.nodeR))
/ double(foo.totalCount);
}
else{
out << foo.seqNames.front() << "\t"
<< foo.nodeL->pos << "\t"
<< foo.nodeL->pos << "\t"
<< "D=" << foo.delCount
<< ";U=" << foo.dupCount
<< ";V=" << foo.invCount
<< ";I=" << foo.insCount
<< ";T=" << foo.traCount
<< ";REF=" << foo.refs.front();
out << ";SVTYPE=" << foo.typeName << ";SVLEN=." ;
out << ";BW=" << double(getSupport(foo.nodeL)
+ getSupport(foo.nodeR))
/ double(foo.totalCount) ;
out << ";ALT=" << foo.refs.front() << "]"
<< foo.seqNames.back() << ":"
<< foo.nodeR->pos << "]";
out << std::endl;
out << foo.seqNames.back() << "\t"
<< foo.nodeR->pos << "\t"
<< foo.nodeR->pos << "\t"
<< "D=" << foo.delCount
<< ";U=" << foo.dupCount
<< ";V=" << foo.invCount
<< ";I=" << foo.insCount
<< ";T=" << foo.traCount
<< ";REF=" << foo.refs.back();
out << ";SVTYPE=" << foo.typeName << ";SVLEN=.";
out << ";BW=" << double(getSupport(foo.nodeL)
+ getSupport(foo.nodeR))
/ double(foo.totalCount);
out << ";ALT=" << foo.refs.back() << "]"
<< foo.seqNames.front() << ":"
<< foo.nodeL->pos << "]";
}
return out;
}
struct libraryStats{
std::map<std::string, double> mus ; // mean of insert length for each indvdual across 1e6 reads
std::map<std::string, double> sds ; // standard deviation
std::map<std::string, double> low ; // 25% of data
std::map<std::string, double> upr ; // 75% of the data
std::map<std::string, double> swm ;
std::map<std::string, double> sws ;
std::map<std::string, double> avgD;
double overallDepth;
} ;
//------------------------------- SUBROUTINE --------------------------------
/*
Function input : left and right node
Function does : return true if the left is less than the right
Function returns: bool
*/
bool sortNodesBySupport(node * L, node * R){
return (getSupport(L) > getSupport(R)) ;
}
//------------------------------- SUBROUTINE --------------------------------
/*
Function input : a left and right node
Function does : provides the rule for the sort
Function returns: bool
*/
bool sortNodesByPos(node * L, node * R){
return (L->pos < R->pos);
}
//------------------------------- SUBROUTINE --------------------------------
//------------------------------- SUBROUTINE --------------------------------
/*
Function input : edge pointer
Function does : init
Function returns: void
*/
void initEdge(edge * e){
e->L = NULL;
e->R = NULL;
// mate too close
e->support['L'] = 0;
// mate too far
e->support['H'] = 0;
// split read
e->support['S'] = 0;
// split read different strand (split)
e->support['V'] = 0;
// insertion
e->support['I'] = 0;
// deletion
e->support['D'] = 0;
// same strand too far
e->support['M'] = 0;
// same strand too close
e->support['R'] = 0;
// everted read pairs
e->support['X'] = 0;
e->support['K'] = 0;
// same strand
e->support['A'] = 0;
}
//------------------------------- SUBROUTINE --------------------------------
/*
Function input : refID (int), left position (int), graph
Function does : determine if a node is in the graph
Function returns: bool
*/
inline bool isInGraph(int refID, int pos, graph & lc){
if(lc.nodes.find(refID) == lc.nodes.end()){
return false;
}
if(lc.nodes[refID].find(pos) != lc.nodes[refID].end()){
return true;
}
return false;
}
//------------------------------- SUBROUTINE --------------------------------
/*
Function input : two node pointer
Function does : finds if nodes are directly connected
Function returns: bool
*/
bool connectedNode(node * left, node * right){
for(std::vector<edge *>::iterator l = left->eds.begin();
l != left->eds.end(); l++){
if(((*l)->L->pos == right->pos
|| (*l)->R->pos == right->pos)
&& (*l)->R->seqid == right->seqid ){
return true;
}
}
return false;
}
//------------------------------- SUBROUTINE --------------------------------
/*
Function input : a vector of edge pointers
Function does : does a tree terversal and joins nodes
Function returns: NA
*/
bool findEdge(std::vector<edge *> & eds, edge ** e, int pos){
for(std::vector<edge *>::iterator it = eds.begin(); it != eds.end(); it++){
if((*it)->L->pos == pos || (*it)->R->pos == pos ){
(*e) = (*it);
return true;
}
}
return false;
}
//------------------------------- SUBROUTINE --------------------------------
/*
Function input : a vector of node pointers, and a postion
Function does : removes edges that contain a position
Function returns: NA
*/
void removeEdges(std::vector<node *> & tree, int pos){
for(std::vector<node *>::iterator rm = tree.begin();
rm != tree.end(); rm++){
std::vector<edge *> tmp;
for(std::vector<edge *>::iterator e = (*rm)->eds.begin();
e != (*rm)->eds.end(); e++){
if( (*e)->L->pos != pos && (*e)->R->pos != pos ){
tmp.push_back((*e));
}
else{
}
}
(*rm)->eds.clear();
(*rm)->eds.insert((*rm)->eds.end(), tmp.begin(), tmp.end());
}
}
#endif
<|endoftext|> |
<commit_before><commit_msg>new filter for unfinished tiles<commit_after><|endoftext|> |
<commit_before>#ifndef _SDD_DD_DEFINITION_HH_
#define _SDD_DD_DEFINITION_HH_
#include <initializer_list>
#include <type_traits> // is_integral
#include "sdd/dd/alpha.hh"
#include "sdd/dd/definition_fwd.hh"
#include "sdd/dd/node.hh"
#include "sdd/dd/terminal.hh"
#include "sdd/dd/top.hh"
#include "sdd/mem/ptr.hh"
#include "sdd/mem/ref_counted.hh"
#include "sdd/mem/variant.hh"
#include "sdd/order/order.hh"
#include "sdd/util/print_sizes_fwd.hh"
namespace sdd {
/*------------------------------------------------------------------------------------------------*/
/// @brief SDD at the deepest level.
template <typename C>
using flat_node = node<C, typename C::Values>;
/// @brief All but SDD at the deepest level.
template <typename C>
using hierarchical_node = node<C, SDD<C>>;
/*------------------------------------------------------------------------------------------------*/
/// @brief Hierarchical Set Decision Diagram.
template <typename C>
class SDD final
{
static_assert( std::is_integral<typename C::Variable>::value
, "A variable must be an integral type.");
private:
/// @brief A canonized SDD.
///
/// This is the real recursive definition of an SDD: it can be a |0| or |1| terminal, or it
/// can be a flat or an hierachical node.
typedef mem::variant<zero_terminal<C>, one_terminal<C>, flat_node<C>, hierarchical_node<C>>
data_type;
public:
/// @internal
static constexpr std::size_t flat_node_index
= data_type::template index_for_type<flat_node<C>>();
/// @internal
static constexpr std::size_t hierarchical_node_index
= data_type::template index_for_type<hierarchical_node<C>>();
/// @internal
/// @brief A unified and canonized SDD, meant to be stored in a unique table.
///
/// It is automatically erased when there is no more reference to it.
typedef mem::ref_counted<data_type> unique_type;
/// @internal
/// @brief The type of the smart pointer around a unified SDD.
///
/// It handles the reference counting as well as the deletion of the SDD when it is no longer
/// referenced.
typedef mem::ptr<unique_type> ptr_type;
/// @brief The type of variables.
typedef typename C::Variable variable_type;
/// @brief The type of a set of values.
typedef typename C::Values values_type;
private:
/// @brief The real smart pointer around a unified SDD.
ptr_type ptr_;
public:
/// @brief Copy constructor.
///
/// O(1).
SDD(const SDD&) noexcept = default;
/// @brief Copy operator.
///
/// O(1).
SDD&
operator=(const SDD&) noexcept = default;
/// @brief Construct a hierarchical SDD.
/// @param var The SDD's variable.
/// @param values The SDD's valuation, a set of values constructed from an initialization list.
/// @param succ The SDD's successor.
///
/// O(1), for the creation of the SDD itself, but the complexity of the construction of the
/// set of values depends on values_type.
/// This constructor is only available when the set of values define the type value_type.
template <typename T = decltype(C::Values::value_type)>
SDD( const variable_type& var, std::initializer_list<typename C::Values::value_type> values
, const SDD& succ)
: ptr_(create_node(var, values_type(values), SDD(succ)))
{}
/// @brief Construct a flat SDD.
/// @param var The SDD's variable.
/// @param val The SDD's valuation, a set of values.
/// @param succ The SDD's successor.
///
/// O(1).
SDD(const variable_type& var, values_type&& val, const SDD& succ)
: ptr_(create_node(var, std::move(val), succ))
{}
/// @brief Construct a flat SDD.
/// @param var The SDD's variable.
/// @param val The SDD's valuation, a set of values.
/// @param succ The SDD's successor.
///
/// O(1).
SDD(const variable_type& var, const values_type& val, const SDD& succ)
: ptr_(create_node(var, val, succ))
{}
/// @brief Construct a hierarchical SDD.
/// @param var The SDD's variable.
/// @param val The SDD's valuation, an SDD in this case.
/// @param succ The SDD's successor.
///
/// O(1).
SDD(const variable_type& var, const SDD& val, const SDD& succ)
: ptr_(create_node(var, val, succ))
{}
/// @brief Construct an SDD with an order.
template <typename Initializer>
SDD(const order<C>& o, const Initializer& init)
: ptr_(one_ptr())
{
if (o.empty())
{
return;
}
// flat
else if (o.nested().empty())
{
ptr_ = create_node(o.variable(), init(o.identifier()), SDD(o.next(), init));
}
// hierarchical
else
{
ptr_ = create_node(o.variable(), SDD(o.nested(), init), SDD(o.next(), init));
}
}
/// @brief Indicate if the SDD is |0|.
/// @return true if the SDD is |0|, false otherwise.
///
/// O(1).
bool
empty()
const noexcept
{
return ptr_ == zero_ptr();
}
/// @brief Swap two SDD.
///
/// O(1).
friend void
swap(SDD& lhs, SDD& rhs)
noexcept
{
using std::swap;
swap(lhs.ptr_, rhs.ptr_);
}
/// @internal
/// @brief Construct an SDD from a ptr.
///
/// O(1).
SDD(const ptr_type& ptr)
noexcept
: ptr_(ptr)
{}
/// @internal
/// @brief Construct an SDD, flat or hierarchical, with an alpha.
/// \tparam Valuation If an SDD, constructs a hierarchical SDD; if a set of values,
/// constructs a flat SDD.
///
/// O(n) where n is the number of arcs in the builder.
template <typename Valuation>
SDD(const variable_type& var, dd::alpha_builder<C, Valuation>&& builder)
: ptr_(create_node(var, std::move(builder)))
{}
/// @internal
/// @brief Get the content of the SDD (an mem::variant).
///
/// O(1).
const data_type&
operator*()
const noexcept
{
return ptr_->data();
}
/// @internal
/// @brief Get a pointer to the content of the SDD (an mem::variant).
///
/// O(1).
const data_type*
operator->()
const noexcept
{
return &ptr_->data();
}
/// @internal
/// @brief Get the real smart pointer of the unified data.
///
/// O(1).
ptr_type
ptr()
const noexcept
{
return ptr_;
}
/// @internal
/// @brief Return the globally cached |0| terminal.
///
/// O(1).
static
ptr_type
zero_ptr()
noexcept
{
return global<C>().zero;
}
/// @internal
/// @brief Return the globally cached |1| terminal.
///
/// O(1).
static
ptr_type
one_ptr()
noexcept
{
return global<C>().one;
}
/// @internal
std::size_t
index()
const noexcept
{
return ptr_->data().index();
}
private:
/// @internal
/// @brief Helper function to create a node, flat or hierarchical, with only one arc.
///
/// O(1).
template <typename Valuation>
static
ptr_type
create_node(const variable_type& var, Valuation&& val, const SDD& succ)
{
if (succ.empty() or val.empty())
{
return zero_ptr();
}
else
{
dd::alpha_builder<C, Valuation> builder;
builder.add(std::move(val), succ);
return ptr_type(unify_node<Valuation>(var, std::move(builder)));
}
}
/// @internal
/// @brief Helper function to create a node, flat or hierarchical, with only one arc.
///
/// O(1).
template <typename Valuation>
static
ptr_type
create_node(const variable_type& var, const Valuation& val, const SDD& succ)
{
if (succ.empty() or val.empty())
{
return zero_ptr();
}
else
{
dd::alpha_builder<C, Valuation> builder;
builder.add(val, succ);
return ptr_type(unify_node<Valuation>(var, std::move(builder)));
}
}
/// @internal
/// @brief Helper function to create a node, flat or hierarchical, from an alpha.
///
/// O(n) where n is the number of arcs in the builder.
template <typename Valuation>
static
ptr_type
create_node(const variable_type& var, dd::alpha_builder<C, Valuation>&& builder)
{
if (builder.empty())
{
return zero_ptr();
}
else
{
return ptr_type(unify_node<Valuation>(var, std::move(builder)));
}
}
/// @internal
/// @brief Helper function to unify a node, flat or hierarchical, from an alpha.
///
/// O(n) where n is the number of arcs in the builder.
template <typename Valuation>
static
unique_type&
unify_node(const variable_type& var, dd::alpha_builder<C, Valuation>&& builder)
{
// Will be erased by the unicity table, either it's an already existing node or a deletion
// is requested by ptr.
// Note that the alpha function is allocated right behind the node, thus extra care must be
// taken. This is also why we use Boost.Intrusive in order to be able to manage memory
// exactly the way we want.
auto& ut = global<C>().sdd_unique_table;
char* addr = ut.allocate(builder.size_to_allocate());
unique_type* u =
new (addr) unique_type(mem::construct<node<C, Valuation>>(), var, builder);
return ut(u);
}
friend void util::print_sizes<C>(std::ostream&);
};
/*------------------------------------------------------------------------------------------------*/
/// @brief Equality of two SDD.
/// @related SDD
///
/// O(1).
template <typename C>
inline
bool
operator==(const SDD<C>& lhs, const SDD<C>& rhs)
noexcept
{
return lhs.ptr() == rhs.ptr();
}
/// @brief Inequality of two SDD.
/// @related SDD
///
/// O(1).
template <typename C>
inline
bool
operator!=(const SDD<C>& lhs, const SDD<C>& rhs)
noexcept
{
return not (lhs.ptr() == rhs.ptr());
}
/// @brief Comparison of two SDD.
/// @related SDD
///
/// O(1). The order of SDD is arbitrary and can change at each run.
template <typename C>
inline
bool
operator<(const SDD<C>& lhs, const SDD<C>& rhs)
noexcept
{
return lhs.ptr() < rhs.ptr();
}
/// @brief Export the textual representation of an SDD to a stream.
/// @related SDD
///
/// Use only with small SDD, output can be huge.
template <typename C>
std::ostream&
operator<<(std::ostream& os, const SDD<C>& x)
{
return os << *x;
}
/*------------------------------------------------------------------------------------------------*/
/// @brief Return the |0| terminal.
/// @related SDD
///
/// O(1).
template <typename C>
inline
SDD<C>
zero()
noexcept
{
return {SDD<C>::zero_ptr()};
}
/// @brief Return the |1| terminal.
/// @related SDD
///
/// O(1).
template <typename C>
inline
SDD<C>
one()
noexcept
{
return {SDD<C>::one_ptr()};
}
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @related SDD
template <typename C>
std::size_t
check_compatibility(const SDD<C>& lhs, const SDD<C>& rhs)
{
const auto lhs_index = lhs.index();
const auto rhs_index = rhs.index();
if (lhs_index != rhs_index)
{
// different type of nodes
throw top<C>(lhs, rhs);
}
typename SDD<C>::variable_type lhs_variable;
typename SDD<C>::variable_type rhs_variable;
// we must convert to the right type before comparing variables
if (lhs_index == SDD<C>::flat_node_index)
{
lhs_variable = mem::variant_cast<flat_node<C>>(*lhs).variable();
rhs_variable = mem::variant_cast<flat_node<C>>(*rhs).variable();
}
else
{
lhs_variable = mem::variant_cast<hierarchical_node<C>>(*lhs).variable();
rhs_variable = mem::variant_cast<hierarchical_node<C>>(*rhs).variable();
}
if (lhs_variable != rhs_variable)
{
throw top<C>(lhs, rhs);
}
return lhs_index;
}
/*------------------------------------------------------------------------------------------------*/
} // namespace sdd
namespace std {
/*------------------------------------------------------------------------------------------------*/
/// @brief Hash specialization for sdd::dd::SDD.
template <typename C>
struct hash<sdd::SDD<C>>
{
std::size_t
operator()(const sdd::SDD<C>& x)
const noexcept
{
return std::hash<decltype(x.ptr())>()(x.ptr());
}
};
/*------------------------------------------------------------------------------------------------*/
} // namespace std
#endif // _SDD_DD_DEFINITION_HH_
<commit_msg>Constructors taking a variable, not an identifier, should not be exposed in the user documentation.<commit_after>#ifndef _SDD_DD_DEFINITION_HH_
#define _SDD_DD_DEFINITION_HH_
#include <initializer_list>
#include <type_traits> // is_integral
#include "sdd/dd/alpha.hh"
#include "sdd/dd/definition_fwd.hh"
#include "sdd/dd/node.hh"
#include "sdd/dd/terminal.hh"
#include "sdd/dd/top.hh"
#include "sdd/mem/ptr.hh"
#include "sdd/mem/ref_counted.hh"
#include "sdd/mem/variant.hh"
#include "sdd/order/order.hh"
#include "sdd/util/print_sizes_fwd.hh"
namespace sdd {
/*------------------------------------------------------------------------------------------------*/
/// @brief SDD at the deepest level.
template <typename C>
using flat_node = node<C, typename C::Values>;
/// @brief All but SDD at the deepest level.
template <typename C>
using hierarchical_node = node<C, SDD<C>>;
/*------------------------------------------------------------------------------------------------*/
/// @brief Hierarchical Set Decision Diagram.
template <typename C>
class SDD final
{
static_assert( std::is_integral<typename C::Variable>::value
, "A variable must be an integral type.");
private:
/// @brief A canonized SDD.
///
/// This is the real recursive definition of an SDD: it can be a |0| or |1| terminal, or it
/// can be a flat or an hierachical node.
typedef mem::variant<zero_terminal<C>, one_terminal<C>, flat_node<C>, hierarchical_node<C>>
data_type;
public:
/// @internal
static constexpr std::size_t flat_node_index
= data_type::template index_for_type<flat_node<C>>();
/// @internal
static constexpr std::size_t hierarchical_node_index
= data_type::template index_for_type<hierarchical_node<C>>();
/// @internal
/// @brief A unified and canonized SDD, meant to be stored in a unique table.
///
/// It is automatically erased when there is no more reference to it.
typedef mem::ref_counted<data_type> unique_type;
/// @internal
/// @brief The type of the smart pointer around a unified SDD.
///
/// It handles the reference counting as well as the deletion of the SDD when it is no longer
/// referenced.
typedef mem::ptr<unique_type> ptr_type;
/// @brief The type of variables.
typedef typename C::Variable variable_type;
/// @brief The type of a set of values.
typedef typename C::Values values_type;
private:
/// @brief The real smart pointer around a unified SDD.
ptr_type ptr_;
public:
/// @brief Copy constructor.
///
/// O(1).
SDD(const SDD&) noexcept = default;
/// @brief Copy operator.
///
/// O(1).
SDD&
operator=(const SDD&) noexcept = default;
/// @internal
/// @brief Construct a hierarchical SDD.
/// @param var The SDD's variable.
/// @param values The SDD's valuation, a set of values constructed from an initialization list.
/// @param succ The SDD's successor.
///
/// O(1), for the creation of the SDD itself, but the complexity of the construction of the
/// set of values depends on values_type.
/// This constructor is only available when the set of values define the type value_type.
template <typename T = decltype(C::Values::value_type)>
SDD( const variable_type& var, std::initializer_list<typename C::Values::value_type> values
, const SDD& succ)
: ptr_(create_node(var, values_type(values), SDD(succ)))
{}
/// @internal
/// @brief Construct a flat SDD.
/// @param var The SDD's variable.
/// @param val The SDD's valuation, a set of values.
/// @param succ The SDD's successor.
///
/// O(1).
SDD(const variable_type& var, values_type&& val, const SDD& succ)
: ptr_(create_node(var, std::move(val), succ))
{}
/// @internal
/// @brief Construct a flat SDD.
/// @param var The SDD's variable.
/// @param val The SDD's valuation, a set of values.
/// @param succ The SDD's successor.
///
/// O(1).
SDD(const variable_type& var, const values_type& val, const SDD& succ)
: ptr_(create_node(var, val, succ))
{}
/// @internal
/// @brief Construct a hierarchical SDD.
/// @param var The SDD's variable.
/// @param val The SDD's valuation, an SDD in this case.
/// @param succ The SDD's successor.
///
/// O(1).
SDD(const variable_type& var, const SDD& val, const SDD& succ)
: ptr_(create_node(var, val, succ))
{}
/// @brief Construct an SDD with an order.
template <typename Initializer>
SDD(const order<C>& o, const Initializer& init)
: ptr_(one_ptr())
{
if (o.empty())
{
return;
}
// flat
else if (o.nested().empty())
{
ptr_ = create_node(o.variable(), init(o.identifier()), SDD(o.next(), init));
}
// hierarchical
else
{
ptr_ = create_node(o.variable(), SDD(o.nested(), init), SDD(o.next(), init));
}
}
/// @brief Indicate if the SDD is |0|.
/// @return true if the SDD is |0|, false otherwise.
///
/// O(1).
bool
empty()
const noexcept
{
return ptr_ == zero_ptr();
}
/// @brief Swap two SDD.
///
/// O(1).
friend void
swap(SDD& lhs, SDD& rhs)
noexcept
{
using std::swap;
swap(lhs.ptr_, rhs.ptr_);
}
/// @internal
/// @brief Construct an SDD from a ptr.
///
/// O(1).
SDD(const ptr_type& ptr)
noexcept
: ptr_(ptr)
{}
/// @internal
/// @brief Construct an SDD, flat or hierarchical, with an alpha.
/// \tparam Valuation If an SDD, constructs a hierarchical SDD; if a set of values,
/// constructs a flat SDD.
///
/// O(n) where n is the number of arcs in the builder.
template <typename Valuation>
SDD(const variable_type& var, dd::alpha_builder<C, Valuation>&& builder)
: ptr_(create_node(var, std::move(builder)))
{}
/// @internal
/// @brief Get the content of the SDD (an mem::variant).
///
/// O(1).
const data_type&
operator*()
const noexcept
{
return ptr_->data();
}
/// @internal
/// @brief Get a pointer to the content of the SDD (an mem::variant).
///
/// O(1).
const data_type*
operator->()
const noexcept
{
return &ptr_->data();
}
/// @internal
/// @brief Get the real smart pointer of the unified data.
///
/// O(1).
ptr_type
ptr()
const noexcept
{
return ptr_;
}
/// @internal
/// @brief Return the globally cached |0| terminal.
///
/// O(1).
static
ptr_type
zero_ptr()
noexcept
{
return global<C>().zero;
}
/// @internal
/// @brief Return the globally cached |1| terminal.
///
/// O(1).
static
ptr_type
one_ptr()
noexcept
{
return global<C>().one;
}
/// @internal
std::size_t
index()
const noexcept
{
return ptr_->data().index();
}
private:
/// @internal
/// @brief Helper function to create a node, flat or hierarchical, with only one arc.
///
/// O(1).
template <typename Valuation>
static
ptr_type
create_node(const variable_type& var, Valuation&& val, const SDD& succ)
{
if (succ.empty() or val.empty())
{
return zero_ptr();
}
else
{
dd::alpha_builder<C, Valuation> builder;
builder.add(std::move(val), succ);
return ptr_type(unify_node<Valuation>(var, std::move(builder)));
}
}
/// @internal
/// @brief Helper function to create a node, flat or hierarchical, with only one arc.
///
/// O(1).
template <typename Valuation>
static
ptr_type
create_node(const variable_type& var, const Valuation& val, const SDD& succ)
{
if (succ.empty() or val.empty())
{
return zero_ptr();
}
else
{
dd::alpha_builder<C, Valuation> builder;
builder.add(val, succ);
return ptr_type(unify_node<Valuation>(var, std::move(builder)));
}
}
/// @internal
/// @brief Helper function to create a node, flat or hierarchical, from an alpha.
///
/// O(n) where n is the number of arcs in the builder.
template <typename Valuation>
static
ptr_type
create_node(const variable_type& var, dd::alpha_builder<C, Valuation>&& builder)
{
if (builder.empty())
{
return zero_ptr();
}
else
{
return ptr_type(unify_node<Valuation>(var, std::move(builder)));
}
}
/// @internal
/// @brief Helper function to unify a node, flat or hierarchical, from an alpha.
///
/// O(n) where n is the number of arcs in the builder.
template <typename Valuation>
static
unique_type&
unify_node(const variable_type& var, dd::alpha_builder<C, Valuation>&& builder)
{
// Will be erased by the unicity table, either it's an already existing node or a deletion
// is requested by ptr.
// Note that the alpha function is allocated right behind the node, thus extra care must be
// taken. This is also why we use Boost.Intrusive in order to be able to manage memory
// exactly the way we want.
auto& ut = global<C>().sdd_unique_table;
char* addr = ut.allocate(builder.size_to_allocate());
unique_type* u =
new (addr) unique_type(mem::construct<node<C, Valuation>>(), var, builder);
return ut(u);
}
friend void util::print_sizes<C>(std::ostream&);
};
/*------------------------------------------------------------------------------------------------*/
/// @brief Equality of two SDD.
/// @related SDD
///
/// O(1).
template <typename C>
inline
bool
operator==(const SDD<C>& lhs, const SDD<C>& rhs)
noexcept
{
return lhs.ptr() == rhs.ptr();
}
/// @brief Inequality of two SDD.
/// @related SDD
///
/// O(1).
template <typename C>
inline
bool
operator!=(const SDD<C>& lhs, const SDD<C>& rhs)
noexcept
{
return not (lhs.ptr() == rhs.ptr());
}
/// @brief Comparison of two SDD.
/// @related SDD
///
/// O(1). The order of SDD is arbitrary and can change at each run.
template <typename C>
inline
bool
operator<(const SDD<C>& lhs, const SDD<C>& rhs)
noexcept
{
return lhs.ptr() < rhs.ptr();
}
/// @brief Export the textual representation of an SDD to a stream.
/// @related SDD
///
/// Use only with small SDD, output can be huge.
template <typename C>
std::ostream&
operator<<(std::ostream& os, const SDD<C>& x)
{
return os << *x;
}
/*------------------------------------------------------------------------------------------------*/
/// @brief Return the |0| terminal.
/// @related SDD
///
/// O(1).
template <typename C>
inline
SDD<C>
zero()
noexcept
{
return {SDD<C>::zero_ptr()};
}
/// @brief Return the |1| terminal.
/// @related SDD
///
/// O(1).
template <typename C>
inline
SDD<C>
one()
noexcept
{
return {SDD<C>::one_ptr()};
}
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @related SDD
template <typename C>
std::size_t
check_compatibility(const SDD<C>& lhs, const SDD<C>& rhs)
{
const auto lhs_index = lhs.index();
const auto rhs_index = rhs.index();
if (lhs_index != rhs_index)
{
// different type of nodes
throw top<C>(lhs, rhs);
}
typename SDD<C>::variable_type lhs_variable;
typename SDD<C>::variable_type rhs_variable;
// we must convert to the right type before comparing variables
if (lhs_index == SDD<C>::flat_node_index)
{
lhs_variable = mem::variant_cast<flat_node<C>>(*lhs).variable();
rhs_variable = mem::variant_cast<flat_node<C>>(*rhs).variable();
}
else
{
lhs_variable = mem::variant_cast<hierarchical_node<C>>(*lhs).variable();
rhs_variable = mem::variant_cast<hierarchical_node<C>>(*rhs).variable();
}
if (lhs_variable != rhs_variable)
{
throw top<C>(lhs, rhs);
}
return lhs_index;
}
/*------------------------------------------------------------------------------------------------*/
} // namespace sdd
namespace std {
/*------------------------------------------------------------------------------------------------*/
/// @brief Hash specialization for sdd::dd::SDD.
template <typename C>
struct hash<sdd::SDD<C>>
{
std::size_t
operator()(const sdd::SDD<C>& x)
const noexcept
{
return std::hash<decltype(x.ptr())>()(x.ptr());
}
};
/*------------------------------------------------------------------------------------------------*/
} // namespace std
#endif // _SDD_DD_DEFINITION_HH_
<|endoftext|> |
<commit_before>// Copyright 2006 The RE2 Authors. All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Format a regular expression structure as a string.
// Tested by parse_test.cc
#include <string.h>
#include <string>
#include "util/util.h"
#include "util/logging.h"
#include "util/strutil.h"
#include "util/utf.h"
#include "re2/regexp.h"
#include "re2/walker-inl.h"
namespace re2 {
enum {
PrecAtom,
PrecUnary,
PrecConcat,
PrecAlternate,
PrecEmpty,
PrecParen,
PrecToplevel,
};
// Helper function. See description below.
static void AppendCCRange(std::string* t, Rune lo, Rune hi);
// Walker to generate string in s_.
// The arg pointers are actually integers giving the
// context precedence.
// The child_args are always NULL.
class ToStringWalker : public Regexp::Walker<int> {
public:
explicit ToStringWalker(std::string* t) : t_(t) {}
virtual int PreVisit(Regexp* re, int parent_arg, bool* stop);
virtual int PostVisit(Regexp* re, int parent_arg, int pre_arg,
int* child_args, int nchild_args);
virtual int ShortVisit(Regexp* re, int parent_arg) {
return 0;
}
private:
std::string* t_; // The string the walker appends to.
ToStringWalker(const ToStringWalker&) = delete;
ToStringWalker& operator=(const ToStringWalker&) = delete;
};
std::string Regexp::ToString() {
std::string t;
ToStringWalker w(&t);
w.WalkExponential(this, PrecToplevel, 100000);
if (w.stopped_early())
t += " [truncated]";
return t;
}
#define ToString DontCallToString // Avoid accidental recursion.
// Visits re before children are processed.
// Appends ( if needed and passes new precedence to children.
int ToStringWalker::PreVisit(Regexp* re, int parent_arg, bool* stop) {
int prec = parent_arg;
int nprec = PrecAtom;
switch (re->op()) {
case kRegexpNoMatch:
case kRegexpEmptyMatch:
case kRegexpLiteral:
case kRegexpAnyChar:
case kRegexpAnyByte:
case kRegexpBeginLine:
case kRegexpEndLine:
case kRegexpBeginText:
case kRegexpEndText:
case kRegexpWordBoundary:
case kRegexpNoWordBoundary:
case kRegexpCharClass:
case kRegexpHaveMatch:
nprec = PrecAtom;
break;
case kRegexpConcat:
case kRegexpLiteralString:
if (prec < PrecConcat)
t_->append("(?:");
nprec = PrecConcat;
break;
case kRegexpAlternate:
if (prec < PrecAlternate)
t_->append("(?:");
nprec = PrecAlternate;
break;
case kRegexpCapture:
t_->append("(");
if (re->cap() == 0)
LOG(DFATAL) << "kRegexpCapture cap() == 0";
if (re->name()) {
t_->append("?P<");
t_->append(*re->name());
t_->append(">");
}
nprec = PrecParen;
break;
case kRegexpStar:
case kRegexpPlus:
case kRegexpQuest:
case kRegexpRepeat:
if (prec < PrecUnary)
t_->append("(?:");
// The subprecedence here is PrecAtom instead of PrecUnary
// because PCRE treats two unary ops in a row as a parse error.
nprec = PrecAtom;
break;
}
return nprec;
}
static void AppendLiteral(std::string *t, Rune r, bool foldcase) {
if (r != 0 && r < 0x80 && strchr("(){}[]*+?|.^$\\", r)) {
t->append(1, '\\');
t->append(1, static_cast<char>(r));
} else if (foldcase && 'a' <= r && r <= 'z') {
r -= 'a' - 'A';
t->append(1, '[');
t->append(1, static_cast<char>(r));
t->append(1, static_cast<char>(r) + 'a' - 'A');
t->append(1, ']');
} else {
AppendCCRange(t, r, r);
}
}
// Visits re after children are processed.
// For childless regexps, all the work is done here.
// For regexps with children, append any unary suffixes or ).
int ToStringWalker::PostVisit(Regexp* re, int parent_arg, int pre_arg,
int* child_args, int nchild_args) {
int prec = parent_arg;
switch (re->op()) {
case kRegexpNoMatch:
// There's no simple symbol for "no match", but
// [^0-Runemax] excludes everything.
t_->append("[^\\x00-\\x{10ffff}]");
break;
case kRegexpEmptyMatch:
// Append (?:) to make empty string visible,
// unless this is already being parenthesized.
if (prec < PrecEmpty)
t_->append("(?:)");
break;
case kRegexpLiteral:
AppendLiteral(t_, re->rune(),
(re->parse_flags() & Regexp::FoldCase) != 0);
break;
case kRegexpLiteralString:
for (int i = 0; i < re->nrunes(); i++)
AppendLiteral(t_, re->runes()[i],
(re->parse_flags() & Regexp::FoldCase) != 0);
if (prec < PrecConcat)
t_->append(")");
break;
case kRegexpConcat:
if (prec < PrecConcat)
t_->append(")");
break;
case kRegexpAlternate:
// Clumsy but workable: the children all appended |
// at the end of their strings, so just remove the last one.
if ((*t_)[t_->size()-1] == '|')
t_->erase(t_->size()-1);
else
LOG(DFATAL) << "Bad final char: " << t_;
if (prec < PrecAlternate)
t_->append(")");
break;
case kRegexpStar:
t_->append("*");
if (re->parse_flags() & Regexp::NonGreedy)
t_->append("?");
if (prec < PrecUnary)
t_->append(")");
break;
case kRegexpPlus:
t_->append("+");
if (re->parse_flags() & Regexp::NonGreedy)
t_->append("?");
if (prec < PrecUnary)
t_->append(")");
break;
case kRegexpQuest:
t_->append("?");
if (re->parse_flags() & Regexp::NonGreedy)
t_->append("?");
if (prec < PrecUnary)
t_->append(")");
break;
case kRegexpRepeat:
if (re->max() == -1)
t_->append(StringPrintf("{%d,}", re->min()));
else if (re->min() == re->max())
t_->append(StringPrintf("{%d}", re->min()));
else
t_->append(StringPrintf("{%d,%d}", re->min(), re->max()));
if (re->parse_flags() & Regexp::NonGreedy)
t_->append("?");
if (prec < PrecUnary)
t_->append(")");
break;
case kRegexpAnyChar:
t_->append(".");
break;
case kRegexpAnyByte:
t_->append("\\C");
break;
case kRegexpBeginLine:
t_->append("^");
break;
case kRegexpEndLine:
t_->append("$");
break;
case kRegexpBeginText:
t_->append("(?-m:^)");
break;
case kRegexpEndText:
if (re->parse_flags() & Regexp::WasDollar)
t_->append("(?-m:$)");
else
t_->append("\\z");
break;
case kRegexpWordBoundary:
t_->append("\\b");
break;
case kRegexpNoWordBoundary:
t_->append("\\B");
break;
case kRegexpCharClass: {
if (re->cc()->size() == 0) {
t_->append("[^\\x00-\\x{10ffff}]");
break;
}
t_->append("[");
// Heuristic: show class as negated if it contains the
// non-character 0xFFFE and yet somehow isn't full.
CharClass* cc = re->cc();
if (cc->Contains(0xFFFE) && !cc->full()) {
cc = cc->Negate();
t_->append("^");
}
for (CharClass::iterator i = cc->begin(); i != cc->end(); ++i)
AppendCCRange(t_, i->lo, i->hi);
if (cc != re->cc())
cc->Delete();
t_->append("]");
break;
}
case kRegexpCapture:
t_->append(")");
break;
case kRegexpHaveMatch:
// There's no syntax accepted by the parser to generate
// this node (it is generated by RE2::Set) so make something
// up that is readable but won't compile.
t_->append("(?HaveMatch:%d)", re->match_id());
break;
}
// If the parent is an alternation, append the | for it.
if (prec == PrecAlternate)
t_->append("|");
return 0;
}
// Appends a rune for use in a character class to the string t.
static void AppendCCChar(std::string* t, Rune r) {
if (0x20 <= r && r <= 0x7E) {
if (strchr("[]^-\\", r))
t->append("\\");
t->append(1, static_cast<char>(r));
return;
}
switch (r) {
default:
break;
case '\r':
t->append("\\r");
return;
case '\t':
t->append("\\t");
return;
case '\n':
t->append("\\n");
return;
case '\f':
t->append("\\f");
return;
}
if (r < 0x100) {
*t += StringPrintf("\\x%02x", static_cast<int>(r));
return;
}
*t += StringPrintf("\\x{%x}", static_cast<int>(r));
}
static void AppendCCRange(std::string* t, Rune lo, Rune hi) {
if (lo > hi)
return;
AppendCCChar(t, lo);
if (lo < hi) {
t->append("-");
AppendCCChar(t, hi);
}
}
} // namespace re2
<commit_msg>Fix a bug in `Regexp::ToString()`.<commit_after>// Copyright 2006 The RE2 Authors. All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Format a regular expression structure as a string.
// Tested by parse_test.cc
#include <string.h>
#include <string>
#include "util/util.h"
#include "util/logging.h"
#include "util/strutil.h"
#include "util/utf.h"
#include "re2/regexp.h"
#include "re2/walker-inl.h"
namespace re2 {
enum {
PrecAtom,
PrecUnary,
PrecConcat,
PrecAlternate,
PrecEmpty,
PrecParen,
PrecToplevel,
};
// Helper function. See description below.
static void AppendCCRange(std::string* t, Rune lo, Rune hi);
// Walker to generate string in s_.
// The arg pointers are actually integers giving the
// context precedence.
// The child_args are always NULL.
class ToStringWalker : public Regexp::Walker<int> {
public:
explicit ToStringWalker(std::string* t) : t_(t) {}
virtual int PreVisit(Regexp* re, int parent_arg, bool* stop);
virtual int PostVisit(Regexp* re, int parent_arg, int pre_arg,
int* child_args, int nchild_args);
virtual int ShortVisit(Regexp* re, int parent_arg) {
return 0;
}
private:
std::string* t_; // The string the walker appends to.
ToStringWalker(const ToStringWalker&) = delete;
ToStringWalker& operator=(const ToStringWalker&) = delete;
};
std::string Regexp::ToString() {
std::string t;
ToStringWalker w(&t);
w.WalkExponential(this, PrecToplevel, 100000);
if (w.stopped_early())
t += " [truncated]";
return t;
}
#define ToString DontCallToString // Avoid accidental recursion.
// Visits re before children are processed.
// Appends ( if needed and passes new precedence to children.
int ToStringWalker::PreVisit(Regexp* re, int parent_arg, bool* stop) {
int prec = parent_arg;
int nprec = PrecAtom;
switch (re->op()) {
case kRegexpNoMatch:
case kRegexpEmptyMatch:
case kRegexpLiteral:
case kRegexpAnyChar:
case kRegexpAnyByte:
case kRegexpBeginLine:
case kRegexpEndLine:
case kRegexpBeginText:
case kRegexpEndText:
case kRegexpWordBoundary:
case kRegexpNoWordBoundary:
case kRegexpCharClass:
case kRegexpHaveMatch:
nprec = PrecAtom;
break;
case kRegexpConcat:
case kRegexpLiteralString:
if (prec < PrecConcat)
t_->append("(?:");
nprec = PrecConcat;
break;
case kRegexpAlternate:
if (prec < PrecAlternate)
t_->append("(?:");
nprec = PrecAlternate;
break;
case kRegexpCapture:
t_->append("(");
if (re->cap() == 0)
LOG(DFATAL) << "kRegexpCapture cap() == 0";
if (re->name()) {
t_->append("?P<");
t_->append(*re->name());
t_->append(">");
}
nprec = PrecParen;
break;
case kRegexpStar:
case kRegexpPlus:
case kRegexpQuest:
case kRegexpRepeat:
if (prec < PrecUnary)
t_->append("(?:");
// The subprecedence here is PrecAtom instead of PrecUnary
// because PCRE treats two unary ops in a row as a parse error.
nprec = PrecAtom;
break;
}
return nprec;
}
static void AppendLiteral(std::string *t, Rune r, bool foldcase) {
if (r != 0 && r < 0x80 && strchr("(){}[]*+?|.^$\\", r)) {
t->append(1, '\\');
t->append(1, static_cast<char>(r));
} else if (foldcase && 'a' <= r && r <= 'z') {
r -= 'a' - 'A';
t->append(1, '[');
t->append(1, static_cast<char>(r));
t->append(1, static_cast<char>(r) + 'a' - 'A');
t->append(1, ']');
} else {
AppendCCRange(t, r, r);
}
}
// Visits re after children are processed.
// For childless regexps, all the work is done here.
// For regexps with children, append any unary suffixes or ).
int ToStringWalker::PostVisit(Regexp* re, int parent_arg, int pre_arg,
int* child_args, int nchild_args) {
int prec = parent_arg;
switch (re->op()) {
case kRegexpNoMatch:
// There's no simple symbol for "no match", but
// [^0-Runemax] excludes everything.
t_->append("[^\\x00-\\x{10ffff}]");
break;
case kRegexpEmptyMatch:
// Append (?:) to make empty string visible,
// unless this is already being parenthesized.
if (prec < PrecEmpty)
t_->append("(?:)");
break;
case kRegexpLiteral:
AppendLiteral(t_, re->rune(),
(re->parse_flags() & Regexp::FoldCase) != 0);
break;
case kRegexpLiteralString:
for (int i = 0; i < re->nrunes(); i++)
AppendLiteral(t_, re->runes()[i],
(re->parse_flags() & Regexp::FoldCase) != 0);
if (prec < PrecConcat)
t_->append(")");
break;
case kRegexpConcat:
if (prec < PrecConcat)
t_->append(")");
break;
case kRegexpAlternate:
// Clumsy but workable: the children all appended |
// at the end of their strings, so just remove the last one.
if ((*t_)[t_->size()-1] == '|')
t_->erase(t_->size()-1);
else
LOG(DFATAL) << "Bad final char: " << t_;
if (prec < PrecAlternate)
t_->append(")");
break;
case kRegexpStar:
t_->append("*");
if (re->parse_flags() & Regexp::NonGreedy)
t_->append("?");
if (prec < PrecUnary)
t_->append(")");
break;
case kRegexpPlus:
t_->append("+");
if (re->parse_flags() & Regexp::NonGreedy)
t_->append("?");
if (prec < PrecUnary)
t_->append(")");
break;
case kRegexpQuest:
t_->append("?");
if (re->parse_flags() & Regexp::NonGreedy)
t_->append("?");
if (prec < PrecUnary)
t_->append(")");
break;
case kRegexpRepeat:
if (re->max() == -1)
t_->append(StringPrintf("{%d,}", re->min()));
else if (re->min() == re->max())
t_->append(StringPrintf("{%d}", re->min()));
else
t_->append(StringPrintf("{%d,%d}", re->min(), re->max()));
if (re->parse_flags() & Regexp::NonGreedy)
t_->append("?");
if (prec < PrecUnary)
t_->append(")");
break;
case kRegexpAnyChar:
t_->append(".");
break;
case kRegexpAnyByte:
t_->append("\\C");
break;
case kRegexpBeginLine:
t_->append("^");
break;
case kRegexpEndLine:
t_->append("$");
break;
case kRegexpBeginText:
t_->append("(?-m:^)");
break;
case kRegexpEndText:
if (re->parse_flags() & Regexp::WasDollar)
t_->append("(?-m:$)");
else
t_->append("\\z");
break;
case kRegexpWordBoundary:
t_->append("\\b");
break;
case kRegexpNoWordBoundary:
t_->append("\\B");
break;
case kRegexpCharClass: {
if (re->cc()->size() == 0) {
t_->append("[^\\x00-\\x{10ffff}]");
break;
}
t_->append("[");
// Heuristic: show class as negated if it contains the
// non-character 0xFFFE and yet somehow isn't full.
CharClass* cc = re->cc();
if (cc->Contains(0xFFFE) && !cc->full()) {
cc = cc->Negate();
t_->append("^");
}
for (CharClass::iterator i = cc->begin(); i != cc->end(); ++i)
AppendCCRange(t_, i->lo, i->hi);
if (cc != re->cc())
cc->Delete();
t_->append("]");
break;
}
case kRegexpCapture:
t_->append(")");
break;
case kRegexpHaveMatch:
// There's no syntax accepted by the parser to generate
// this node (it is generated by RE2::Set) so make something
// up that is readable but won't compile.
t_->append(StringPrintf("(?HaveMatch:%d)", re->match_id()));
break;
}
// If the parent is an alternation, append the | for it.
if (prec == PrecAlternate)
t_->append("|");
return 0;
}
// Appends a rune for use in a character class to the string t.
static void AppendCCChar(std::string* t, Rune r) {
if (0x20 <= r && r <= 0x7E) {
if (strchr("[]^-\\", r))
t->append("\\");
t->append(1, static_cast<char>(r));
return;
}
switch (r) {
default:
break;
case '\r':
t->append("\\r");
return;
case '\t':
t->append("\\t");
return;
case '\n':
t->append("\\n");
return;
case '\f':
t->append("\\f");
return;
}
if (r < 0x100) {
*t += StringPrintf("\\x%02x", static_cast<int>(r));
return;
}
*t += StringPrintf("\\x{%x}", static_cast<int>(r));
}
static void AppendCCRange(std::string* t, Rune lo, Rune hi) {
if (lo > hi)
return;
AppendCCChar(t, lo);
if (lo < hi) {
t->append("-");
AppendCCChar(t, hi);
}
}
} // namespace re2
<|endoftext|> |
<commit_before>/**
* @file localStorageManager.cc
* @author Krzysztof Trzepla
* @copyright (C) 2014 ACK CYFRONET AGH
* @copyright This software is released under the MIT license cited in 'LICENSE.txt'
*/
#include "localStorageManager.h"
#include "config.h"
#include "veilfs.h"
#include "logging.h"
#include "communication_protocol.pb.h"
#include "fuse_messages.pb.h"
#include <google/protobuf/descriptor.h>
using boost::filesystem::path;
using namespace veil::protocol::fuse_messages;
using namespace veil::protocol::communication_protocol;
namespace veil {
namespace client {
LocalStorageManager::LocalStorageManager()
{
}
LocalStorageManager::~LocalStorageManager()
{
}
#ifdef __APPLE__
std::vector<path> LocalStorageManager::getMountPoints()
{
std::vector<path> mountPoints;
int fs_num;
if((fs_num = getfsstat(NULL, 0, MNT_NOWAIT)) < 0) {
LOG(ERROR) << "Can not count mounted filesystems.";
return mountPoints;
}
int buf_size = sizeof(*buf) * fs_num;
struct statfs *buf = (struct statfs*) malloc(buf_size);
if(buf == NULL) {
LOG(ERROR) << "Can not allocate memory for statfs structures.";
return mountPoints;
}
int stat_num;
if((stat_num = getstatfs(buf, buf_size, MNT_NOWAIT)) < 0) {
LOG(ERROR) << "Can not get fsstat.";
return mountPoints;
}
for(int i = 0; i < stat_num; ++i) {
std::string type(buf[i].f_fstypename);
if(type.compare(0, 4, "fuse") != 0) {
mountPoints.push_back(path(buf[i].f_mntonname).normalize())
}
}
return mountPoints;
}
#else
std::vector<path> LocalStorageManager::getMountPoints()
{
std::vector<path> mountPoints;
FILE *file;
if((file = setmntent(MOUNTS_INFO_FILE_PATH, "r")) == NULL) {
LOG(ERROR) << "Can not parse /proc/mounts file.";
return mountPoints;
}
struct mntent *ent;
while ((ent = getmntent(file)) != NULL) {
std::string type(ent->mnt_type);
if(type.compare(0, 4, "fuse") != 0) {
mountPoints.push_back(path(ent->mnt_dir).normalize());
}
}
endmntent(file);
return mountPoints;
}
#endif
std::vector< std::pair<int, std::string> > LocalStorageManager::parseStorageInfo(path mountPoint)
{
std::vector< std::pair<int, std::string> > storageInfo;
path storageInfoPath = (mountPoint / STORAGE_INFO_FILENAME).normalize();
if(boost::filesystem::exists(storageInfoPath) && boost::filesystem::is_regular_file(storageInfoPath)) {
boost::filesystem::ifstream storageInfoFile(storageInfoPath);
std::string line;
while(std::getline(storageInfoFile, line)) {
std::vector<std::string> tokens;
boost::char_separator<char> sep(" ,{}");
boost::tokenizer< boost::char_separator<char> > tok(line, sep);
for(auto token: tok) tokens.push_back(token);
// each line in file should by of form {storage id, relative path to storage against mount point}
if(tokens.size() == 2) {
try {
int storageId = boost::lexical_cast<int>(tokens[0]);
path absoluteStoragePath = mountPoint;
boost::algorithm::trim_left_if(tokens[1], boost::algorithm::is_any_of("./"));
if(!tokens[1].empty()) {
absoluteStoragePath /= tokens[1];
}
storageInfo.push_back(make_pair(storageId, absoluteStoragePath.string()));
} catch(boost::bad_lexical_cast const&) {
LOG(ERROR) << "Wrong format of storage id in file: " << storageInfoPath;
}
}
}
}
return std::move(storageInfo);
}
std::vector< std::pair<int, std::string> > LocalStorageManager::getClientStorageInfo(const std::vector<path> &mountPoints)
{
std::vector< std::pair<int, std::string> > clientStorageInfo;
for(auto mountPoint: mountPoints) {
// Skip client mount point (just in case)
if(mountPoint == Config::getMountPoint()) continue;
std::vector< std::pair<int, std::string> > storageInfo = parseStorageInfo(mountPoint);
for(std::vector< std::pair<int, std::string> >::iterator it = storageInfo.begin(); it != storageInfo.end(); ++it) {
int storageId = it->first;
std::string absolutePath = it->second;
std::string relativePath = "";
std::string text = "";
if(!createStorageTestFile(storageId, relativePath, text)) {
LOG(WARNING) << "Cannot create storage test file for storage with id: " << storageId;
continue;
}
if(!hasClientStorageReadPermission(absolutePath, relativePath, text)) {
LOG(WARNING) << "Client does not have read permission for storage with id: " << storageId;
continue;
}
if(!hasClientStorageWritePermission(storageId, absolutePath, relativePath)) {
LOG(WARNING) << "Client does not have write permission for storage with id: " << storageId;
continue;
}
LOG(INFO) << "Storage with id: " << storageId << " is directly accessible to the client via: " << absolutePath;
clientStorageInfo.push_back(make_pair(storageId, absolutePath));
}
}
return std::move(clientStorageInfo);
}
bool LocalStorageManager::sendClientStorageInfo(std::vector< std::pair<int, std::string> > clientStorageInfo)
{
ClusterMsg cMsg;
ClientStorageInfo reqMsg;
ClientStorageInfo::StorageInfo *info;
Atom resMsg;
Answer ans;
MessageBuilder builder;
boost::shared_ptr<CommunicationHandler> conn;
conn = VeilFS::getConnectionPool()->selectConnection();
if(conn) {
// Build CreateStorageTestFileRequest message
for(std::vector< std::pair<int,std::string> >::iterator it = clientStorageInfo.begin(); it != clientStorageInfo.end(); ++it) {
info = reqMsg.add_storage_info();
info->set_storage_id(it->first);
info->set_absolute_path(it->second);
}
ClusterMsg cMsg = builder.packFuseMessage(ClientStorageInfo::descriptor()->name(), Atom::descriptor()->name(), COMMUNICATION_PROTOCOL, reqMsg.SerializeAsString());
// Send CreateStorageTestFileRequest message
ans = conn->communicate(cMsg, 2);
// Check answer
if(ans.answer_status() == VOK && resMsg.ParseFromString(ans.worker_answer())) {
return resMsg.value() == "ok";
} else if(ans.answer_status() == NO_USER_FOUND_ERROR) {
LOG(ERROR) << "Cannot find user in database.";
} else {
LOG(ERROR) << "Cannot send client storage info.";
}
} else {
LOG(ERROR) << "Cannot select connection for storage test file creation";
}
return false;
}
bool LocalStorageManager::createStorageTestFile(int storageId, std::string& relativePath, std::string& text)
{
ClusterMsg cMsg;
CreateStorageTestFileRequest reqMsg;
CreateStorageTestFileResponse resMsg;
Answer ans;
MessageBuilder builder;
boost::shared_ptr<CommunicationHandler> conn;
conn = VeilFS::getConnectionPool()->selectConnection();
if(conn) {
// Build CreateStorageTestFileRequest message
reqMsg.set_storage_id(storageId);
ClusterMsg cMsg = builder.packFuseMessage(CreateStorageTestFileRequest::descriptor()->name(), CreateStorageTestFileResponse::descriptor()->name(), FUSE_MESSAGES, reqMsg.SerializeAsString());
// Send CreateStorageTestFileRequest message
ans = conn->communicate(cMsg, 2);
// Check answer
if(ans.answer_status() == VOK && resMsg.ParseFromString(ans.worker_answer())) {
relativePath = resMsg.relative_path();
text = resMsg.text();
return resMsg.answer();
} else if(ans.answer_status() == NO_USER_FOUND_ERROR) {
LOG(ERROR) << "Cannot find user in database.";
} else {
LOG(ERROR) << "Cannot create test file for storage with id: " << storageId;
}
} else {
LOG(ERROR) << "Cannot select connection for storage test file creation";
}
return false;
}
bool LocalStorageManager::hasClientStorageReadPermission(std::string absolutePath, std::string relativePath, std::string expectedText)
{
int fd = open((absolutePath + "/" + relativePath).c_str(), O_RDONLY);
if(fd == -1) {
return false;
}
fsync(fd);
void* buf = malloc(expectedText.size());
if(read(fd, buf, expectedText.size()) != (int) expectedText.size()) {
free(buf);
close(fd);
return false;
}
std::string actualText((char *) buf);
free(buf);
close(fd);
return expectedText == actualText;
}
bool LocalStorageManager::hasClientStorageWritePermission(int storageId, std::string absolutePath, std::string relativePath)
{
int fd = open((absolutePath + "/" + relativePath).c_str(), O_WRONLY | O_FSYNC);
if(fd == -1) {
return false;
}
int length = 20;
std::string text(length, ' ');
srand(time(0));
for(int i = 0; i < length; ++i) {
text[i] = (char) (33 + rand() % 93);
}
if(write(fd, text.c_str(), length) != length) {
close(fd);
return false;
}
close(fd);
ClusterMsg cMsg;
StorageTestFileModifiedRequest reqMsg;
StorageTestFileModifiedResponse resMsg;
Answer ans;
MessageBuilder builder;
boost::shared_ptr<CommunicationHandler> conn;
conn = VeilFS::getConnectionPool()->selectConnection();
if(conn) {
// Build CreateStorageTestFileRequest message
reqMsg.set_storage_id(storageId);
reqMsg.set_relative_path(relativePath);
reqMsg.set_text(text);
ClusterMsg cMsg = builder.packFuseMessage(StorageTestFileModifiedRequest::descriptor()->name(), StorageTestFileModifiedResponse::descriptor()->name(), FUSE_MESSAGES, reqMsg.SerializeAsString());
// Send CreateStorageTestFileRequest message
ans = conn->communicate(cMsg, 2);
// Check answer
if(ans.answer_status() == VOK && resMsg.ParseFromString(ans.worker_answer())) {
return resMsg.answer();
} else if(ans.answer_status() == NO_USER_FOUND_ERROR) {
LOG(ERROR) << "Cannot find user in database.";
} else {
LOG(ERROR) << "Cannot check client write permission for storage with id: " << storageId;
}
} else {
LOG(ERROR) << "Cannot select connection for storage test file creation";
}
return false;
}
} // namespace client
} // namespace veil
<commit_msg>VFS-644 Add additional log for client storage info sending.<commit_after>/**
* @file localStorageManager.cc
* @author Krzysztof Trzepla
* @copyright (C) 2014 ACK CYFRONET AGH
* @copyright This software is released under the MIT license cited in 'LICENSE.txt'
*/
#include "localStorageManager.h"
#include "config.h"
#include "veilfs.h"
#include "logging.h"
#include "communication_protocol.pb.h"
#include "fuse_messages.pb.h"
#include <google/protobuf/descriptor.h>
using boost::filesystem::path;
using namespace veil::protocol::fuse_messages;
using namespace veil::protocol::communication_protocol;
namespace veil {
namespace client {
LocalStorageManager::LocalStorageManager()
{
}
LocalStorageManager::~LocalStorageManager()
{
}
#ifdef __APPLE__
std::vector<path> LocalStorageManager::getMountPoints()
{
std::vector<path> mountPoints;
int fs_num;
if((fs_num = getfsstat(NULL, 0, MNT_NOWAIT)) < 0) {
LOG(ERROR) << "Can not count mounted filesystems.";
return mountPoints;
}
int buf_size = sizeof(*buf) * fs_num;
struct statfs *buf = (struct statfs*) malloc(buf_size);
if(buf == NULL) {
LOG(ERROR) << "Can not allocate memory for statfs structures.";
return mountPoints;
}
int stat_num;
if((stat_num = getstatfs(buf, buf_size, MNT_NOWAIT)) < 0) {
LOG(ERROR) << "Can not get fsstat.";
return mountPoints;
}
for(int i = 0; i < stat_num; ++i) {
std::string type(buf[i].f_fstypename);
if(type.compare(0, 4, "fuse") != 0) {
mountPoints.push_back(path(buf[i].f_mntonname).normalize())
}
}
return mountPoints;
}
#else
std::vector<path> LocalStorageManager::getMountPoints()
{
std::vector<path> mountPoints;
FILE *file;
if((file = setmntent(MOUNTS_INFO_FILE_PATH, "r")) == NULL) {
LOG(ERROR) << "Can not parse /proc/mounts file.";
return mountPoints;
}
struct mntent *ent;
while ((ent = getmntent(file)) != NULL) {
std::string type(ent->mnt_type);
if(type.compare(0, 4, "fuse") != 0) {
mountPoints.push_back(path(ent->mnt_dir).normalize());
}
}
endmntent(file);
return mountPoints;
}
#endif
std::vector< std::pair<int, std::string> > LocalStorageManager::parseStorageInfo(path mountPoint)
{
std::vector< std::pair<int, std::string> > storageInfo;
path storageInfoPath = (mountPoint / STORAGE_INFO_FILENAME).normalize();
if(boost::filesystem::exists(storageInfoPath) && boost::filesystem::is_regular_file(storageInfoPath)) {
boost::filesystem::ifstream storageInfoFile(storageInfoPath);
std::string line;
while(std::getline(storageInfoFile, line)) {
std::vector<std::string> tokens;
boost::char_separator<char> sep(" ,{}");
boost::tokenizer< boost::char_separator<char> > tok(line, sep);
for(auto token: tok) tokens.push_back(token);
// each line in file should by of form {storage id, relative path to storage against mount point}
if(tokens.size() == 2) {
try {
int storageId = boost::lexical_cast<int>(tokens[0]);
path absoluteStoragePath = mountPoint;
boost::algorithm::trim_left_if(tokens[1], boost::algorithm::is_any_of("./"));
if(!tokens[1].empty()) {
absoluteStoragePath /= tokens[1];
}
storageInfo.push_back(make_pair(storageId, absoluteStoragePath.string()));
} catch(boost::bad_lexical_cast const&) {
LOG(ERROR) << "Wrong format of storage id in file: " << storageInfoPath;
}
}
}
}
return std::move(storageInfo);
}
std::vector< std::pair<int, std::string> > LocalStorageManager::getClientStorageInfo(const std::vector<path> &mountPoints)
{
std::vector< std::pair<int, std::string> > clientStorageInfo;
for(auto mountPoint: mountPoints) {
// Skip client mount point (just in case)
if(mountPoint == Config::getMountPoint()) continue;
std::vector< std::pair<int, std::string> > storageInfo = parseStorageInfo(mountPoint);
for(std::vector< std::pair<int, std::string> >::iterator it = storageInfo.begin(); it != storageInfo.end(); ++it) {
int storageId = it->first;
std::string absolutePath = it->second;
std::string relativePath = "";
std::string text = "";
if(!createStorageTestFile(storageId, relativePath, text)) {
LOG(WARNING) << "Cannot create storage test file for storage with id: " << storageId;
continue;
}
if(!hasClientStorageReadPermission(absolutePath, relativePath, text)) {
LOG(WARNING) << "Client does not have read permission for storage with id: " << storageId;
continue;
}
if(!hasClientStorageWritePermission(storageId, absolutePath, relativePath)) {
LOG(WARNING) << "Client does not have write permission for storage with id: " << storageId;
continue;
}
LOG(INFO) << "Storage with id: " << storageId << " is directly accessible to the client via: " << absolutePath;
clientStorageInfo.push_back(make_pair(storageId, absolutePath));
}
}
return std::move(clientStorageInfo);
}
bool LocalStorageManager::sendClientStorageInfo(std::vector< std::pair<int, std::string> > clientStorageInfo)
{
ClusterMsg cMsg;
ClientStorageInfo reqMsg;
ClientStorageInfo::StorageInfo *info;
Atom resMsg;
Answer ans;
MessageBuilder builder;
boost::shared_ptr<CommunicationHandler> conn;
conn = VeilFS::getConnectionPool()->selectConnection();
if(conn) {
// Build CreateStorageTestFileRequest message
for(std::vector< std::pair<int,std::string> >::iterator it = clientStorageInfo.begin(); it != clientStorageInfo.end(); ++it) {
info = reqMsg.add_storage_info();
info->set_storage_id(it->first);
info->set_absolute_path(it->second);
LOG(INFO) << "Sending client storage info: {" << it->first << ", " << it->second << "}";
}
ClusterMsg cMsg = builder.packFuseMessage(ClientStorageInfo::descriptor()->name(), Atom::descriptor()->name(), COMMUNICATION_PROTOCOL, reqMsg.SerializeAsString());
// Send CreateStorageTestFileRequest message
ans = conn->communicate(cMsg, 2);
// Check answer
if(ans.answer_status() == VOK && resMsg.ParseFromString(ans.worker_answer())) {
return resMsg.value() == "ok";
} else if(ans.answer_status() == NO_USER_FOUND_ERROR) {
LOG(ERROR) << "Cannot find user in database.";
} else {
LOG(ERROR) << "Cannot send client storage info.";
}
} else {
LOG(ERROR) << "Cannot select connection for storage test file creation";
}
return false;
}
bool LocalStorageManager::createStorageTestFile(int storageId, std::string& relativePath, std::string& text)
{
ClusterMsg cMsg;
CreateStorageTestFileRequest reqMsg;
CreateStorageTestFileResponse resMsg;
Answer ans;
MessageBuilder builder;
boost::shared_ptr<CommunicationHandler> conn;
conn = VeilFS::getConnectionPool()->selectConnection();
if(conn) {
// Build CreateStorageTestFileRequest message
reqMsg.set_storage_id(storageId);
ClusterMsg cMsg = builder.packFuseMessage(CreateStorageTestFileRequest::descriptor()->name(), CreateStorageTestFileResponse::descriptor()->name(), FUSE_MESSAGES, reqMsg.SerializeAsString());
// Send CreateStorageTestFileRequest message
ans = conn->communicate(cMsg, 2);
// Check answer
if(ans.answer_status() == VOK && resMsg.ParseFromString(ans.worker_answer())) {
relativePath = resMsg.relative_path();
text = resMsg.text();
return resMsg.answer();
} else if(ans.answer_status() == NO_USER_FOUND_ERROR) {
LOG(ERROR) << "Cannot find user in database.";
} else {
LOG(ERROR) << "Cannot create test file for storage with id: " << storageId;
}
} else {
LOG(ERROR) << "Cannot select connection for storage test file creation";
}
return false;
}
bool LocalStorageManager::hasClientStorageReadPermission(std::string absolutePath, std::string relativePath, std::string expectedText)
{
int fd = open((absolutePath + "/" + relativePath).c_str(), O_RDONLY);
if(fd == -1) {
return false;
}
fsync(fd);
void* buf = malloc(expectedText.size());
if(read(fd, buf, expectedText.size()) != (int) expectedText.size()) {
free(buf);
close(fd);
return false;
}
std::string actualText((char *) buf);
free(buf);
close(fd);
return expectedText == actualText;
}
bool LocalStorageManager::hasClientStorageWritePermission(int storageId, std::string absolutePath, std::string relativePath)
{
int fd = open((absolutePath + "/" + relativePath).c_str(), O_WRONLY | O_FSYNC);
if(fd == -1) {
return false;
}
int length = 20;
std::string text(length, ' ');
srand(time(0));
for(int i = 0; i < length; ++i) {
text[i] = (char) (33 + rand() % 93);
}
if(write(fd, text.c_str(), length) != length) {
close(fd);
return false;
}
close(fd);
ClusterMsg cMsg;
StorageTestFileModifiedRequest reqMsg;
StorageTestFileModifiedResponse resMsg;
Answer ans;
MessageBuilder builder;
boost::shared_ptr<CommunicationHandler> conn;
conn = VeilFS::getConnectionPool()->selectConnection();
if(conn) {
// Build CreateStorageTestFileRequest message
reqMsg.set_storage_id(storageId);
reqMsg.set_relative_path(relativePath);
reqMsg.set_text(text);
ClusterMsg cMsg = builder.packFuseMessage(StorageTestFileModifiedRequest::descriptor()->name(), StorageTestFileModifiedResponse::descriptor()->name(), FUSE_MESSAGES, reqMsg.SerializeAsString());
// Send CreateStorageTestFileRequest message
ans = conn->communicate(cMsg, 2);
// Check answer
if(ans.answer_status() == VOK && resMsg.ParseFromString(ans.worker_answer())) {
return resMsg.answer();
} else if(ans.answer_status() == NO_USER_FOUND_ERROR) {
LOG(ERROR) << "Cannot find user in database.";
} else {
LOG(ERROR) << "Cannot check client write permission for storage with id: " << storageId;
}
} else {
LOG(ERROR) << "Cannot select connection for storage test file creation";
}
return false;
}
} // namespace client
} // namespace veil
<|endoftext|> |
<commit_before>
/*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkGLWidget.h"
#if SK_SUPPORT_GPU
SkGLWidget::SkGLWidget(SkDebugger* debugger) : QGLWidget() {
this->setStyleSheet("QWidget {background-color: white; border: 1px solid #cccccc;}");
fDebugger = debugger;
fCurIntf = NULL;
fCurContext = NULL;
fGpuDevice = NULL;
fCanvas = NULL;
}
SkGLWidget::~SkGLWidget() {
SkSafeUnref(fCurIntf);
SkSafeUnref(fCurContext);
SkSafeUnref(fGpuDevice);
SkSafeUnref(fCanvas);
}
void SkGLWidget::setSampleCount(int sampleCount)
{
QGLFormat currentFormat = format();
currentFormat.setSampleBuffers(sampleCount > 0);
currentFormat.setSamples(sampleCount);
setFormat(currentFormat);
}
void SkGLWidget::initializeGL() {
fCurIntf = GrGLCreateNativeInterface();
if (!fCurIntf) {
return;
}
fCurContext = GrContext::Create(kOpenGL_GrBackend, (GrBackendContext) fCurIntf);
GrBackendRenderTargetDesc desc = this->getDesc(this->width(), this->height());
desc.fOrigin = kBottomLeft_GrSurfaceOrigin;
GrRenderTarget* curRenderTarget = fCurContext->wrapBackendRenderTarget(desc);
fGpuDevice = new SkGpuDevice(fCurContext, curRenderTarget);
fCanvas = new SkCanvas(fGpuDevice);
curRenderTarget->unref();
glClearColor(1, 1, 1, 0);
glClearStencil(0);
glClear(GL_STENCIL_BUFFER_BIT);
}
void SkGLWidget::resizeGL(int w, int h) {
if (fCurContext) {
GrBackendRenderTargetDesc desc = this->getDesc(w, h);
desc.fOrigin = kBottomLeft_GrSurfaceOrigin;
GrRenderTarget* curRenderTarget = fCurContext->wrapBackendRenderTarget(desc);
SkSafeUnref(fGpuDevice);
SkSafeUnref(fCanvas);
fGpuDevice = new SkGpuDevice(fCurContext, curRenderTarget);
fCanvas = new SkCanvas(fGpuDevice);
}
fDebugger->resize(w, h);
draw();
}
void SkGLWidget::paintGL() {
if (!this->isHidden() && fCanvas) {
fDebugger->draw(fCanvas);
// TODO(chudy): Implement an optional flush button in Gui.
fCanvas->flush();
emit drawComplete();
}
}
GrBackendRenderTargetDesc SkGLWidget::getDesc(int w, int h) {
GrBackendRenderTargetDesc desc;
desc.fWidth = SkScalarRoundToInt(this->width());
desc.fHeight = SkScalarRoundToInt(this->height());
desc.fConfig = kSkia8888_GrPixelConfig;
GR_GL_GetIntegerv(fCurIntf, GR_GL_SAMPLES, &desc.fSampleCnt);
GR_GL_GetIntegerv(fCurIntf, GR_GL_STENCIL_BITS, &desc.fStencilBits);
GrGLint buffer;
GR_GL_GetIntegerv(fCurIntf, GR_GL_FRAMEBUFFER_BINDING, &buffer);
desc.fRenderTargetHandle = buffer;
return desc;
}
#endif
<commit_msg>Avoid black flashes when resizing debugger window using MSAA<commit_after>
/*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkGLWidget.h"
#if SK_SUPPORT_GPU
SkGLWidget::SkGLWidget(SkDebugger* debugger) : QGLWidget() {
fDebugger = debugger;
fCurIntf = NULL;
fCurContext = NULL;
fGpuDevice = NULL;
fCanvas = NULL;
}
SkGLWidget::~SkGLWidget() {
SkSafeUnref(fCurIntf);
SkSafeUnref(fCurContext);
SkSafeUnref(fGpuDevice);
SkSafeUnref(fCanvas);
}
void SkGLWidget::setSampleCount(int sampleCount)
{
QGLFormat currentFormat = format();
currentFormat.setSampleBuffers(sampleCount > 0);
currentFormat.setSamples(sampleCount);
setFormat(currentFormat);
}
void SkGLWidget::initializeGL() {
fCurIntf = GrGLCreateNativeInterface();
if (!fCurIntf) {
return;
}
glStencilMask(0xffffffff);
glClearStencil(0);
glClear(GL_STENCIL_BUFFER_BIT);
fCurContext = GrContext::Create(kOpenGL_GrBackend, (GrBackendContext) fCurIntf);
GrBackendRenderTargetDesc desc = this->getDesc(this->width(), this->height());
desc.fOrigin = kBottomLeft_GrSurfaceOrigin;
GrRenderTarget* curRenderTarget = fCurContext->wrapBackendRenderTarget(desc);
fGpuDevice = new SkGpuDevice(fCurContext, curRenderTarget);
fCanvas = new SkCanvas(fGpuDevice);
curRenderTarget->unref();
}
void SkGLWidget::resizeGL(int w, int h) {
if (fCurContext) {
glDisable(GL_SCISSOR_TEST);
glStencilMask(0xffffffff);
glClearStencil(0);
glClear(GL_STENCIL_BUFFER_BIT);
fCurContext->resetContext();
GrBackendRenderTargetDesc desc = this->getDesc(w, h);
desc.fOrigin = kBottomLeft_GrSurfaceOrigin;
GrRenderTarget* curRenderTarget = fCurContext->wrapBackendRenderTarget(desc);
SkSafeUnref(fGpuDevice);
SkSafeUnref(fCanvas);
fGpuDevice = new SkGpuDevice(fCurContext, curRenderTarget);
fCanvas = new SkCanvas(fGpuDevice);
}
fDebugger->resize(w, h);
draw();
}
void SkGLWidget::paintGL() {
if (!this->isHidden() && fCanvas) {
fDebugger->draw(fCanvas);
// TODO(chudy): Implement an optional flush button in Gui.
fCanvas->flush();
emit drawComplete();
}
}
GrBackendRenderTargetDesc SkGLWidget::getDesc(int w, int h) {
GrBackendRenderTargetDesc desc;
desc.fWidth = SkScalarRoundToInt(this->width());
desc.fHeight = SkScalarRoundToInt(this->height());
desc.fConfig = kSkia8888_GrPixelConfig;
GR_GL_GetIntegerv(fCurIntf, GR_GL_SAMPLES, &desc.fSampleCnt);
GR_GL_GetIntegerv(fCurIntf, GR_GL_STENCIL_BITS, &desc.fStencilBits);
GrGLint buffer;
GR_GL_GetIntegerv(fCurIntf, GR_GL_FRAMEBUFFER_BINDING, &buffer);
desc.fRenderTargetHandle = buffer;
return desc;
}
#endif
<|endoftext|> |
<commit_before>#ifndef _cz_Request_hpp__
#define _cz_Request_hpp__
// Copyright (c) 2012, Andre Caron (andre.l.caron@gmail.com)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 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.
#include <w32.hpp>
#include <w32.io.hpp>
#include <w32.tp.hpp>
#include "Hub.hpp"
namespace cz {
class Engine;
// TODO: make this non-copyable.
// TODO: implement `reset()` method for reusing the request.
class Request
{
friend class Engine;
/* nested types. */
private:
// Attention: make sure this stays a POD.
struct Data :
public ::OVERLAPPED
{
Request * request; // owner.
};
/* class methods. */
public:
// Yields entry point for thread pool.
static w32::tp::Work::Callback work_callback ();
static w32::tp::Wait::Callback wait_callback ();
/* data. */
private:
Data myData;
Engine& myEngine;
// TOOD: break this down into necessary items?
w32::io::Notification myNotification;
Hub::Slave& mySlave; // slave that started the request.
void * myContext; // application defined context.
/* construction. */
public:
Request (Engine& engine, void * context=0);
virtual ~Request ();
/* methods. */
public:
Engine& engine ();
/*!
* @internal
*/
Data& data ();
/*!
* @internal
* @see close()
*/
void start (); // patch `ready()` test for async operations that don't
// deal with system streams.
/*!
* @brief Check if the operation has completed.
*/
bool ready () const;
/*!
* @internal
* @see start()
*/
void close (); // patch `ready()` test for async operations that don't
// deal with system streams.
/*!
* @internal
* @brief Prepare for issuing another request.
*/
void reset ();
/*!
* @internal
*/
const w32::io::Notification& notification () const;
void * context () const;
template<typename T>
T * context () const
{
return (static_cast<T>(myContext));
}
private:
// Post notification to completion port.
void report_completion (w32::dword size=0);
// Entry point for thread pool.
void execute_computation (w32::tp::Hints& hints);
// Entry point for thread pool.
void release_wait_client (w32::tp::Hints& hints);
};
}
#endif /* _cz_Request_hpp__ */
<commit_msg>Fixes cast of request context pointer.<commit_after>#ifndef _cz_Request_hpp__
#define _cz_Request_hpp__
// Copyright (c) 2012, Andre Caron (andre.l.caron@gmail.com)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 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.
#include <w32.hpp>
#include <w32.io.hpp>
#include <w32.tp.hpp>
#include "Hub.hpp"
namespace cz {
class Engine;
// TODO: make this non-copyable.
// TODO: implement `reset()` method for reusing the request.
class Request
{
friend class Engine;
/* nested types. */
private:
// Attention: make sure this stays a POD.
struct Data :
public ::OVERLAPPED
{
Request * request; // owner.
};
/* class methods. */
public:
// Yields entry point for thread pool.
static w32::tp::Work::Callback work_callback ();
static w32::tp::Wait::Callback wait_callback ();
/* data. */
private:
Data myData;
Engine& myEngine;
// TOOD: break this down into necessary items?
w32::io::Notification myNotification;
Hub::Slave& mySlave; // slave that started the request.
void * myContext; // application defined context.
/* construction. */
public:
Request (Engine& engine, void * context=0);
virtual ~Request ();
/* methods. */
public:
Engine& engine ();
/*!
* @internal
*/
Data& data ();
/*!
* @internal
* @see close()
*/
void start (); // patch `ready()` test for async operations that don't
// deal with system streams.
/*!
* @brief Check if the operation has completed.
*/
bool ready () const;
/*!
* @internal
* @see start()
*/
void close (); // patch `ready()` test for async operations that don't
// deal with system streams.
/*!
* @internal
* @brief Prepare for issuing another request.
*/
void reset ();
/*!
* @internal
*/
const w32::io::Notification& notification () const;
void * context () const;
template<typename T>
T * context () const
{
return (static_cast<T*>(myContext));
}
private:
// Post notification to completion port.
void report_completion (w32::dword size=0);
// Entry point for thread pool.
void execute_computation (w32::tp::Hints& hints);
// Entry point for thread pool.
void release_wait_client (w32::tp::Hints& hints);
};
}
#endif /* _cz_Request_hpp__ */
<|endoftext|> |
<commit_before>/*
* Phusion Passenger - https://www.phusionpassenger.com/
* Copyright (c) 2010-2017 Phusion Holding B.V.
*
* "Passenger", "Phusion Passenger" and "Union Station" are registered
* trademarks of Phusion Holding B.V.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <algorithm>
#include <cstdlib>
#include <climits>
/* ap_config.h checks whether the compiler has support for C99's designated
* initializers, and defines AP_HAVE_DESIGNATED_INITIALIZER if it does. However,
* g++ does not support designated initializers, even when ap_config.h thinks
* it does. Here we undefine the macro to force httpd_config.h to not use
* designated initializers. This should fix compilation problems on some systems.
*/
#include <ap_config.h>
#undef AP_HAVE_DESIGNATED_INITIALIZER
#include "Config.h"
#include "ConfigGeneral/SetterFuncs.h"
#include "DirConfig/AutoGeneratedCreateFunction.cpp"
#include "DirConfig/AutoGeneratedMergeFunction.cpp"
#include <JsonTools/Autocast.h>
#include <Utils.h>
#include <Constants.h>
// The APR headers must come after the Passenger headers.
// See Hooks.cpp to learn why.
#include <apr_strings.h>
// In Apache < 2.4, this macro was necessary for core_dir_config and other structs
#define CORE_PRIVATE
#include <http_core.h>
extern "C" module AP_MODULE_DECLARE_DATA passenger_module;
#ifndef ap_get_core_module_config
#define ap_get_core_module_config(s) ap_get_module_config(s, &core_module)
#endif
namespace Passenger {
namespace Apache2Module {
typedef const char * (*Take1Func)();
typedef const char * (*Take2Func)();
typedef const char * (*FlagFunc)();
ServerConfig serverConfig;
template<typename T> static apr_status_t
destroyConfigStruct(void *x) {
delete (T *) x;
return APR_SUCCESS;
}
template<typename Collection, typename T> static bool
contains(const Collection &coll, const T &item) {
typename Collection::const_iterator it;
for (it = coll.begin(); it != coll.end(); it++) {
if (*it == item) {
return true;
}
}
return false;
}
static DirConfig *
createDirConfigStruct(apr_pool_t *pool) {
DirConfig *config = new DirConfig();
apr_pool_cleanup_register(pool, config, destroyConfigStruct<DirConfig>, apr_pool_cleanup_null);
return config;
}
void *
createDirConfig(apr_pool_t *p, char *dirspec) {
DirConfig *config = createDirConfigStruct(p);
createDirConfig_autoGenerated(config);
/*************************************/
return config;
}
void *
mergeDirConfig(apr_pool_t *p, void *basev, void *addv) {
DirConfig *config = createDirConfigStruct(p);
DirConfig *base = (DirConfig *) basev;
DirConfig *add = (DirConfig *) addv;
mergeDirConfig_autoGenerated(config, base, add);
/*************************************/
return config;
}
static void
postprocessDirConfig(server_rec *s, core_dir_config *core_dconf,
DirConfig *psg_dconf, bool isTopLevel = false)
{
// Invoke the merge function on toplevel dir configs
// in order to set defaults.
if (isTopLevel) {
*psg_dconf = *((DirConfig *) mergeDirConfig(
s->process->pconf,
createDirConfig(s->process->pconf, NULL),
psg_dconf));
}
}
void
postprocessConfig(server_rec *s, apr_pool_t *pool) {
core_server_config *sconf;
core_dir_config *core_dconf;
DirConfig *psg_dconf;
int nelts;
ap_conf_vector_t **elts;
int i;
serverConfig.finalize(pool);
for (; s != NULL; s = s->next) {
sconf = (core_server_config *) ap_get_core_module_config(s->module_config);
core_dconf = (core_dir_config *) ap_get_core_module_config(s->lookup_defaults);
psg_dconf = (DirConfig *) ap_get_module_config(s->lookup_defaults, &passenger_module);
postprocessDirConfig(s, core_dconf, psg_dconf, true);
nelts = sconf->sec_dir->nelts;
elts = (ap_conf_vector_t **) sconf->sec_dir->elts;
for (i = 0; i < nelts; ++i) {
core_dconf = (core_dir_config *) ap_get_core_module_config(elts[i]);
psg_dconf = (DirConfig *) ap_get_module_config(elts[i], &passenger_module);
if (core_dconf != NULL && psg_dconf != NULL) {
postprocessDirConfig(s, core_dconf, psg_dconf);
}
}
nelts = sconf->sec_url->nelts;
elts = (ap_conf_vector_t **) sconf->sec_url->elts;
for (i = 0; i < nelts; ++i) {
core_dconf = (core_dir_config *) ap_get_core_module_config(elts[i]);
psg_dconf = (DirConfig *) ap_get_module_config(elts[i], &passenger_module);
if (core_dconf != NULL && psg_dconf != NULL) {
postprocessDirConfig(s, core_dconf, psg_dconf);
}
}
}
}
/*************************************************
* Passenger settings
*************************************************/
#include "ConfigGeneral/AutoGeneratedSetterFuncs.cpp"
static const char *
cmd_passenger_ctl(cmd_parms *cmd, void *dummy, const char *name, const char *value) {
try {
serverConfig.ctl[name] = autocastValueToJson(value);
return NULL;
} catch (const Json::Reader &) {
return "Error parsing value as JSON";
}
}
static const char *
cmd_passenger_spawn_method(cmd_parms *cmd, void *pcfg, const char *arg) {
DirConfig *config = (DirConfig *) pcfg;
if (strcmp(arg, "smart") == 0 || strcmp(arg, "smart-lv2") == 0) {
config->mSpawnMethod = "smart";
} else if (strcmp(arg, "conservative") == 0 || strcmp(arg, "direct") == 0) {
config->mSpawnMethod = "direct";
} else {
return "PassengerSpawnMethod may only be 'smart', 'direct'.";
}
return NULL;
}
static const char *
cmd_passenger_base_uri(cmd_parms *cmd, void *pcfg, const char *arg) {
DirConfig *config = (DirConfig *) pcfg;
if (strlen(arg) == 0) {
return "PassengerBaseURI may not be set to the empty string";
} else if (arg[0] != '/') {
return "PassengerBaseURI must start with a slash (/)";
} else if (strlen(arg) > 1 && arg[strlen(arg) - 1] == '/') {
return "PassengerBaseURI must not end with a slash (/)";
} else {
config->mBaseURIs.insert(arg);
return NULL;
}
}
extern "C" const command_rec passenger_commands[] = {
#include "ConfigGeneral/AutoGeneratedDefinitions.cpp"
{ NULL }
};
} // namespace Apache2Module
} // namespace Passenger
<commit_msg>Apache module: do not merge top-level DirConfig in the postprocessing function<commit_after>/*
* Phusion Passenger - https://www.phusionpassenger.com/
* Copyright (c) 2010-2017 Phusion Holding B.V.
*
* "Passenger", "Phusion Passenger" and "Union Station" are registered
* trademarks of Phusion Holding B.V.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <algorithm>
#include <cstdlib>
#include <climits>
/* ap_config.h checks whether the compiler has support for C99's designated
* initializers, and defines AP_HAVE_DESIGNATED_INITIALIZER if it does. However,
* g++ does not support designated initializers, even when ap_config.h thinks
* it does. Here we undefine the macro to force httpd_config.h to not use
* designated initializers. This should fix compilation problems on some systems.
*/
#include <ap_config.h>
#undef AP_HAVE_DESIGNATED_INITIALIZER
#include "Config.h"
#include "ConfigGeneral/SetterFuncs.h"
#include "DirConfig/AutoGeneratedCreateFunction.cpp"
#include "DirConfig/AutoGeneratedMergeFunction.cpp"
#include <JsonTools/Autocast.h>
#include <Utils.h>
#include <Constants.h>
// The APR headers must come after the Passenger headers.
// See Hooks.cpp to learn why.
#include <apr_strings.h>
// In Apache < 2.4, this macro was necessary for core_dir_config and other structs
#define CORE_PRIVATE
#include <http_core.h>
extern "C" module AP_MODULE_DECLARE_DATA passenger_module;
#ifndef ap_get_core_module_config
#define ap_get_core_module_config(s) ap_get_module_config(s, &core_module)
#endif
namespace Passenger {
namespace Apache2Module {
typedef const char * (*Take1Func)();
typedef const char * (*Take2Func)();
typedef const char * (*FlagFunc)();
ServerConfig serverConfig;
template<typename T> static apr_status_t
destroyConfigStruct(void *x) {
delete (T *) x;
return APR_SUCCESS;
}
template<typename Collection, typename T> static bool
contains(const Collection &coll, const T &item) {
typename Collection::const_iterator it;
for (it = coll.begin(); it != coll.end(); it++) {
if (*it == item) {
return true;
}
}
return false;
}
static DirConfig *
createDirConfigStruct(apr_pool_t *pool) {
DirConfig *config = new DirConfig();
apr_pool_cleanup_register(pool, config, destroyConfigStruct<DirConfig>, apr_pool_cleanup_null);
return config;
}
void *
createDirConfig(apr_pool_t *p, char *dirspec) {
DirConfig *config = createDirConfigStruct(p);
createDirConfig_autoGenerated(config);
/*************************************/
return config;
}
void *
mergeDirConfig(apr_pool_t *p, void *basev, void *addv) {
DirConfig *config = createDirConfigStruct(p);
DirConfig *base = (DirConfig *) basev;
DirConfig *add = (DirConfig *) addv;
mergeDirConfig_autoGenerated(config, base, add);
/*************************************/
return config;
}
void
postprocessConfig(server_rec *s, apr_pool_t *pool) {
serverConfig.finalize(pool);
}
/*************************************************
* Passenger settings
*************************************************/
#include "ConfigGeneral/AutoGeneratedSetterFuncs.cpp"
static const char *
cmd_passenger_ctl(cmd_parms *cmd, void *dummy, const char *name, const char *value) {
try {
serverConfig.ctl[name] = autocastValueToJson(value);
return NULL;
} catch (const Json::Reader &) {
return "Error parsing value as JSON";
}
}
static const char *
cmd_passenger_spawn_method(cmd_parms *cmd, void *pcfg, const char *arg) {
DirConfig *config = (DirConfig *) pcfg;
if (strcmp(arg, "smart") == 0 || strcmp(arg, "smart-lv2") == 0) {
config->mSpawnMethod = "smart";
} else if (strcmp(arg, "conservative") == 0 || strcmp(arg, "direct") == 0) {
config->mSpawnMethod = "direct";
} else {
return "PassengerSpawnMethod may only be 'smart', 'direct'.";
}
return NULL;
}
static const char *
cmd_passenger_base_uri(cmd_parms *cmd, void *pcfg, const char *arg) {
DirConfig *config = (DirConfig *) pcfg;
if (strlen(arg) == 0) {
return "PassengerBaseURI may not be set to the empty string";
} else if (arg[0] != '/') {
return "PassengerBaseURI must start with a slash (/)";
} else if (strlen(arg) > 1 && arg[strlen(arg) - 1] == '/') {
return "PassengerBaseURI must not end with a slash (/)";
} else {
config->mBaseURIs.insert(arg);
return NULL;
}
}
extern "C" const command_rec passenger_commands[] = {
#include "ConfigGeneral/AutoGeneratedDefinitions.cpp"
{ NULL }
};
} // namespace Apache2Module
} // namespace Passenger
<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
using namespace std;
int main()
{
long long a = 0;
long long b = 0;
long long r = 0;
cin >> a >> b;
long long ans = 0;
while (b != 0)
{
ans += a / b;
r = a % b;
a = b;
b = r;
}
cout << ans << endl;
}
// The main idea behind this problem
//
// first, we have a/b (a > b, a % b = r), thus we need at least
// a/b resistors in sequence, thus left r/b resistance to be constructed
// we need two elements in parallel, i.e.
// 1 / ( (1 / RA) + (1 / RB) ) = r / b
// 1 / RA + 1 / RB = b / r (where b > r)
// 1 / RA + 1 / RB = c + r2 / r
// so we need c in parallel to construct RA, so
// 1 / RB = r2 / r OR RB = r / r2
// so return back to our orignal problem, construct a r / r2 (where r > r2 )
// what we need is
// a / b = c1 .... r
// b / r = c2 .... r2
// r / r2 is our new problem, c1 + c2 is our current resistors we need
//
// so
// Loop:
// sum += a / b;
// a % b = r;
// a = b;
// b = r
// This is typecially GCD Algorithm
<commit_msg>delete tmp files<commit_after><|endoftext|> |
<commit_before>typedef Matrix<double, 5, 3> Matrix5x3;
typedef Matrix<double, 5, 5> Matrix5x5;
Matrix5x3 m = Matrix5x3::Random();
cout << "Here is the matrix m:" << endl << m << endl;
Eigen::FullPivLU<Matrix5x3> lu(m);
cout << "Here is, up to permutations, its LU decomposition matrix:"
<< endl << lu.matrixLU() << endl;
cout << "Here is the L part:" << endl;
Matrix5x5 l = Matrix5x5::Identity();
l.block<5,3>(0,0).part<StrictlyLower>() = lu.matrixLU();
cout << l << endl;
cout << "Here is the U part:" << endl;
Matrix5x3 u = lu.matrixLU().part<Upper>();
cout << u << endl;
cout << "Let us now reconstruct the original matrix m:" << endl;
cout << lu.permutationP().inverse() * l * u * lu.permutationQ().inverse() << endl;
<commit_msg>fix compilation of LU class example<commit_after>typedef Matrix<double, 5, 3> Matrix5x3;
typedef Matrix<double, 5, 5> Matrix5x5;
Matrix5x3 m = Matrix5x3::Random();
cout << "Here is the matrix m:" << endl << m << endl;
Eigen::FullPivLU<Matrix5x3> lu(m);
cout << "Here is, up to permutations, its LU decomposition matrix:"
<< endl << lu.matrixLU() << endl;
cout << "Here is the L part:" << endl;
Matrix5x5 l = Matrix5x5::Identity();
l.block<5,3>(0,0).triangularView<StrictlyLower>() = lu.matrixLU();
cout << l << endl;
cout << "Here is the U part:" << endl;
Matrix5x3 u = lu.matrixLU().triangularView<Upper>();
cout << u << endl;
cout << "Let us now reconstruct the original matrix m:" << endl;
cout << lu.permutationP().inverse() * l * u * lu.permutationQ().inverse() << endl;
<|endoftext|> |
<commit_before>#ifndef TEST_HELPER_H_
#define TEST_HELPER_H_
#include <internal/iterbase.hpp>
#include <stdexcept>
#include <type_traits>
#include <utility>
#include <vector>
namespace itertest {
// non-copyable. non-movable. non-default-constructible
class SolidInt {
private:
const int i;
public:
constexpr SolidInt(int n) : i{n} {}
constexpr int getint() const {
return this->i;
}
SolidInt() = delete;
SolidInt(const SolidInt&) = delete;
SolidInt& operator=(const SolidInt&) = delete;
SolidInt& operator=(SolidInt&&) = delete;
SolidInt(SolidInt&&) = delete;
};
namespace {
struct DoubleDereferenceError : std::exception {
const char* what() const noexcept override {
return "Iterator dereferenced twice without increment";
}
};
// this class's iterator will throw if it's dereference twice without
// an increment in between
class InputIterable {
public:
class Iterator {
private:
int i;
bool was_incremented = true;
public:
Iterator(int n) : i{n} {}
Iterator& operator++() {
++this->i;
this->was_incremented = true;
return *this;
}
int operator*() {
if (!this->was_incremented) {
throw DoubleDereferenceError{};
}
this->was_incremented = false;
return this->i;
}
bool operator!=(const Iterator& other) const {
return this->i != other.i;
}
};
Iterator begin() {
return {0};
}
Iterator end() {
return {5};
}
};
}
// BasicIterable provides a minimal forward iterator
// operator++(), operator!=(const BasicIterable&), operator*()
// move constructible only
// not copy constructible, move assignable, or copy assignable
template <typename T>
class BasicIterable {
private:
T* data;
std::size_t size;
bool was_moved_from_ = false;
bool was_copied_from_ = false;
public:
BasicIterable(std::initializer_list<T> il)
: data{new T[il.size()]}, size{il.size()} {
// would like to use enumerate, can't because it's for unit
// testing enumerate
std::size_t i = 0;
for (auto&& e : il) {
data[i] = e;
++i;
}
}
BasicIterable& operator=(BasicIterable&&) = delete;
BasicIterable& operator=(const BasicIterable&) = delete;
BasicIterable(const BasicIterable&) = delete;
#if 0
BasicIterable(const BasicIterable& other)
: data{new T[other.size()]},
size{other.size}
{
for (auto it = this->begin(), o_it = other.begin();
o_it != other.end();
++it, ++o_it) {
*it = *o_it;
}
}
#endif
BasicIterable(BasicIterable&& other) : data{other.data}, size{other.size} {
other.data = nullptr;
other.was_moved_from_ = true;
}
bool was_moved_from() const {
return this->was_moved_from_;
}
bool was_copied_from() const {
return this->was_copied_from_;
}
~BasicIterable() {
delete[] this->data;
}
class Iterator {
private:
T* p;
public:
#ifdef DEFINE_DEFAULT_ITERATOR_CTOR
Iterator() = default;
#endif
Iterator(T* b) : p{b} {}
bool operator!=(const Iterator& other) const {
return this->p != other.p;
}
Iterator& operator++() {
++this->p;
return *this;
}
T& operator*() {
return *this->p;
}
};
Iterator begin() {
return {this->data};
}
Iterator end() {
return {this->data + this->size};
}
#ifdef DECLARE_REVERSE_ITERATOR
Iterator rbegin();
Iterator rend();
#endif // ifdef DECLARE_REVERSE_ITERATOR
};
using iter::impl::void_t;
template <typename, typename = void>
struct IsIterator : std::false_type {};
template <typename T>
struct IsIterator<T,
void_t<decltype(T(std::declval<const T&>())), // copyctor
decltype(std::declval<T&>() = std::declval<const T&>()), // copy =
decltype(*std::declval<T&>()), // operator*
decltype(std::declval<T&>().operator->()), // operator->
decltype(++std::declval<T&>()), // prefix ++
decltype(std::declval<T&>()++), // postfix ++
decltype(
std::declval<const T&>() != std::declval<const T&>()), // !=
decltype(std::declval<const T&>() == std::declval<const T&>()) // ==
>> : std::true_type {};
template <typename T>
struct IsForwardIterator
: std::integral_constant<bool,
IsIterator<T>::value && std::is_default_constructible<T>::value> {};
template <typename T>
struct IsMoveConstructibleOnly
: std::integral_constant<bool,
!std::is_copy_constructible<T>::value
&& !std::is_copy_assignable<T>::value
&& !std::is_move_assignable<T>::value
&& std::is_move_constructible<T>::value> {};
}
template <typename T, typename Inc>
class DiffEndRange {
private:
T start_;
T stop_;
std::vector<T> all_results_;
public:
constexpr DiffEndRange(T start, T stop) : start_{start}, stop_{stop} {
while (start < stop_) {
all_results_.push_back(start);
Inc{}(start);
}
}
class Iterator;
class EndIterator;
class Iterator {
using SubIter = typename std::vector<T>::iterator;
private:
SubIter it_;
SubIter end_;
public:
#ifdef CHAR_RANGE_DEFAULT_CONSTRUCTIBLE
Iterator() = default;
#endif
Iterator(SubIter it, SubIter end_it) : it_{it}, end_{end_it} {}
T& operator*() const {
return *it_;
}
T* operator->() const {
return &*it_;
}
Iterator& operator++() {
++it_;
return *this;
}
bool operator!=(const Iterator& other) const {
return it_ != other.it_;
}
bool operator!=(const EndIterator&) const {
return it_ != end_;
}
friend bool operator!=(const EndIterator& lhs, const Iterator& rhs) {
return rhs != lhs;
}
};
class ReverseIterator {
using SubIter = typename std::vector<T>::reverse_iterator;
private:
SubIter it_;
SubIter end_;
public:
#ifdef CHAR_RANGE_DEFAULT_CONSTRUCTIBLE
ReverseIterator() = default;
#endif
ReverseIterator(SubIter it, SubIter end_it) : it_{it}, end_{end_it} {}
T& operator*() const {
return *it_;
}
T* operator->() const {
return &*it_;
}
Iterator& operator++() {
++it_;
return *this;
}
bool operator!=(const Iterator& other) const {
return it_ != other.it_;
}
bool operator!=(const EndIterator&) const {
return it_ != end_;
}
friend bool operator!=(const EndIterator& lhs, const Iterator& rhs) {
return rhs != lhs;
}
};
class EndIterator {};
class ReverseEndIterator {};
Iterator begin() {
return {std::begin(all_results_), std::end(all_results_)};
}
EndIterator end() {
return {};
}
ReverseIterator rbegin() {
return {std::rbegin(all_results_), std::rend(all_results_)};
}
ReverseEndIterator rend() {
return {};
}
};
struct CharInc {
void operator()(char& c) {
++c;
}
};
// A range from 'a' to stop, begin() and end() are different
class CharRange : public DiffEndRange<char, CharInc> {
public:
constexpr CharRange(char stop) : DiffEndRange<char, CharInc>('a', stop) {}
};
struct IncIntCharPair {
void operator()(std::pair<int, char>& p) {
++p.first;
++p.second;
}
};
class IntCharPairRange
: public DiffEndRange<std::pair<int, char>, IncIntCharPair> {
public:
IntCharPairRange(std::pair<int, char> stop)
: DiffEndRange<std::pair<int, char>, IncIntCharPair>({0, 'a'}, stop) {}
};
#if 0
class CharRange {
private:
char stop_{};
public:
constexpr CharRange(char stop) : stop_{stop} {}
class Iterator;
class EndIterator;
class Iterator {
private:
char stop_{};
mutable char value_{'a'};
public:
#ifdef CHAR_RANGE_DEFAULT_CONSTRUCTIBLE
Iterator() = default;
#endif
Iterator(char stop) : stop_{stop} {}
char& operator*() const { return value_; }
char* operator->() const { return &value_; }
Iterator& operator++() {
++value_;
return *this;
}
bool operator!=(const Iterator& other) const {
return value_ != other.value_;
}
bool operator!=(const EndIterator&) const {
return value_ < stop_;
}
friend bool operator!=(const EndIterator& lhs, const Iterator& rhs) {
return rhs != lhs;
}
};
class EndIterator { };
Iterator begin() {
return {stop_};
}
EndIterator end() {
return {};
}
};
#endif
#endif
<commit_msg>Switches BasicIterable to non-member begin and end<commit_after>#ifndef TEST_HELPER_H_
#define TEST_HELPER_H_
#include <internal/iterbase.hpp>
#include <stdexcept>
#include <type_traits>
#include <utility>
#include <vector>
namespace itertest {
// non-copyable. non-movable. non-default-constructible
class SolidInt {
private:
const int i;
public:
constexpr SolidInt(int n) : i{n} {}
constexpr int getint() const {
return this->i;
}
SolidInt() = delete;
SolidInt(const SolidInt&) = delete;
SolidInt& operator=(const SolidInt&) = delete;
SolidInt& operator=(SolidInt&&) = delete;
SolidInt(SolidInt&&) = delete;
};
namespace {
struct DoubleDereferenceError : std::exception {
const char* what() const noexcept override {
return "Iterator dereferenced twice without increment";
}
};
// this class's iterator will throw if it's dereference twice without
// an increment in between
class InputIterable {
public:
class Iterator {
private:
int i;
bool was_incremented = true;
public:
Iterator(int n) : i{n} {}
Iterator& operator++() {
++this->i;
this->was_incremented = true;
return *this;
}
int operator*() {
if (!this->was_incremented) {
throw DoubleDereferenceError{};
}
this->was_incremented = false;
return this->i;
}
bool operator!=(const Iterator& other) const {
return this->i != other.i;
}
};
Iterator begin() {
return {0};
}
Iterator end() {
return {5};
}
};
}
// BasicIterable provides a minimal forward iterator
// operator++(), operator!=(const BasicIterable&), operator*()
// move constructible only
// not copy constructible, move assignable, or copy assignable
template <typename T>
class BasicIterable {
private:
T* data;
std::size_t size;
bool was_moved_from_ = false;
bool was_copied_from_ = false;
public:
BasicIterable(std::initializer_list<T> il)
: data{new T[il.size()]}, size{il.size()} {
// would like to use enumerate, can't because it's for unit
// testing enumerate
std::size_t i = 0;
for (auto&& e : il) {
data[i] = e;
++i;
}
}
BasicIterable& operator=(BasicIterable&&) = delete;
BasicIterable& operator=(const BasicIterable&) = delete;
BasicIterable(const BasicIterable&) = delete;
#if 0
BasicIterable(const BasicIterable& other)
: data{new T[other.size()]},
size{other.size}
{
for (auto it = this->begin(), o_it = other.begin();
o_it != other.end();
++it, ++o_it) {
*it = *o_it;
}
}
#endif
BasicIterable(BasicIterable&& other) : data{other.data}, size{other.size} {
other.data = nullptr;
other.was_moved_from_ = true;
}
bool was_moved_from() const {
return this->was_moved_from_;
}
bool was_copied_from() const {
return this->was_copied_from_;
}
~BasicIterable() {
delete[] this->data;
}
class Iterator {
private:
T* p;
public:
#ifdef DEFINE_DEFAULT_ITERATOR_CTOR
Iterator() = default;
#endif
Iterator(T* b) : p{b} {}
bool operator!=(const Iterator& other) const {
return this->p != other.p;
}
Iterator& operator++() {
++this->p;
return *this;
}
T& operator*() {
return *this->p;
}
};
friend BasicIterable::Iterator begin(BasicIterable& b) {
return {b.data};
}
friend BasicIterable::Iterator end(BasicIterable& b) {
return {b.data + b.size};
}
#ifdef DECLARE_REVERSE_ITERATOR
Iterator rbegin();
Iterator rend();
#endif // ifdef DECLARE_REVERSE_ITERATOR
};
using iter::impl::void_t;
template <typename, typename = void>
struct IsIterator : std::false_type {};
template <typename T>
struct IsIterator<T,
void_t<decltype(T(std::declval<const T&>())), // copyctor
decltype(std::declval<T&>() = std::declval<const T&>()), // copy =
decltype(*std::declval<T&>()), // operator*
decltype(std::declval<T&>().operator->()), // operator->
decltype(++std::declval<T&>()), // prefix ++
decltype(std::declval<T&>()++), // postfix ++
decltype(
std::declval<const T&>() != std::declval<const T&>()), // !=
decltype(std::declval<const T&>() == std::declval<const T&>()) // ==
>> : std::true_type {};
template <typename T>
struct IsForwardIterator
: std::integral_constant<bool,
IsIterator<T>::value && std::is_default_constructible<T>::value> {};
template <typename T>
struct IsMoveConstructibleOnly
: std::integral_constant<bool,
!std::is_copy_constructible<T>::value
&& !std::is_copy_assignable<T>::value
&& !std::is_move_assignable<T>::value
&& std::is_move_constructible<T>::value> {};
}
template <typename T, typename Inc>
class DiffEndRange {
private:
T start_;
T stop_;
std::vector<T> all_results_;
public:
constexpr DiffEndRange(T start, T stop) : start_{start}, stop_{stop} {
while (start < stop_) {
all_results_.push_back(start);
Inc{}(start);
}
}
class Iterator;
class EndIterator;
class Iterator {
using SubIter = typename std::vector<T>::iterator;
private:
SubIter it_;
SubIter end_;
public:
#ifdef CHAR_RANGE_DEFAULT_CONSTRUCTIBLE
Iterator() = default;
#endif
Iterator(SubIter it, SubIter end_it) : it_{it}, end_{end_it} {}
T& operator*() const {
return *it_;
}
T* operator->() const {
return &*it_;
}
Iterator& operator++() {
++it_;
return *this;
}
bool operator!=(const Iterator& other) const {
return it_ != other.it_;
}
bool operator!=(const EndIterator&) const {
return it_ != end_;
}
friend bool operator!=(const EndIterator& lhs, const Iterator& rhs) {
return rhs != lhs;
}
};
class ReverseIterator {
using SubIter = typename std::vector<T>::reverse_iterator;
private:
SubIter it_;
SubIter end_;
public:
#ifdef CHAR_RANGE_DEFAULT_CONSTRUCTIBLE
ReverseIterator() = default;
#endif
ReverseIterator(SubIter it, SubIter end_it) : it_{it}, end_{end_it} {}
T& operator*() const {
return *it_;
}
T* operator->() const {
return &*it_;
}
Iterator& operator++() {
++it_;
return *this;
}
bool operator!=(const Iterator& other) const {
return it_ != other.it_;
}
bool operator!=(const EndIterator&) const {
return it_ != end_;
}
friend bool operator!=(const EndIterator& lhs, const Iterator& rhs) {
return rhs != lhs;
}
};
class EndIterator {};
class ReverseEndIterator {};
Iterator begin() {
return {std::begin(all_results_), std::end(all_results_)};
}
EndIterator end() {
return {};
}
ReverseIterator rbegin() {
return {std::rbegin(all_results_), std::rend(all_results_)};
}
ReverseEndIterator rend() {
return {};
}
};
struct CharInc {
void operator()(char& c) {
++c;
}
};
// A range from 'a' to stop, begin() and end() are different
class CharRange : public DiffEndRange<char, CharInc> {
public:
constexpr CharRange(char stop) : DiffEndRange<char, CharInc>('a', stop) {}
};
struct IncIntCharPair {
void operator()(std::pair<int, char>& p) {
++p.first;
++p.second;
}
};
class IntCharPairRange
: public DiffEndRange<std::pair<int, char>, IncIntCharPair> {
public:
IntCharPairRange(std::pair<int, char> stop)
: DiffEndRange<std::pair<int, char>, IncIntCharPair>({0, 'a'}, stop) {}
};
#endif
<|endoftext|> |
<commit_before>#include "webcam.hpp"
using namespace cv;
using namespace std;
int main (int argc, char** argv) {
CvCapture* capture = 0;
int width, height, fps;
capture = cvCaptureFromCAM(0);
if (!capture) {
printf("No camera detected!");
return -1;
}
ifstream configFile (".config");
if (configFile.is_open()) {
//probably want to support corrupted .config
string line;
getline(configFile, line);
istringstream(line)>>width;
getline(configFile, line);
istringstream(line)>>height;
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, width);
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, height);
configFile.close();
} else {
initResolutions();
for (int i=36; i<150; i++) {
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, resolutions[i].width);
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, resolutions[i].height);
}
width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH);
height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT);
ofstream configFileOut(".config");
configFileOut << width;
configFileOut << "\n";
configFileOut << height;
configFileOut << "\n";
configFileOut.close();
}
bool keepGoing = true;
// srand(890);//not interested in good randomness
for (int i = 0; i < 30; i++) {
// capture some frames so exposure correction takes place
cvQueryFrame(capture);
}
Mat background = cvQueryFrame(capture);
background = background.clone();
blur(background, background, Size(50,50));
imshow("background", background);
Mat image;
Mat channel[3];
while (keepGoing) {
image = cvQueryFrame(capture);
//imshow("webcam", image);
Mat gray;
cvtColor(image, gray, CV_RGB2GRAY);
Mat canny;
Canny(gray, canny, 50, 50, 3);
blur(canny, canny, Size(width/20,height/20));
bitwise_not(canny, canny);
threshold(canny, canny, 220, 1, THRESH_BINARY);
imshow("canny1", canny*255);
waitKey(1);
int kwidth, kheight;
if (width/2 > height) {
kwidth = height/4;
kheight = height/8;
} else {
kwidth = width/8;
kheight = width/16;
}
kwidth += (1-(kwidth%2));//round up to nearest odd
kheight += (1-(kheight%2));//round up to nearest odd
Size kernelSize(kwidth, kheight);
Mat kernel = getStructuringElement(MORPH_ELLIPSE, kernelSize);
morphologyEx(canny, canny, MORPH_OPEN, kernel);
imshow("canny2", canny*255);
waitKey(1);
Size kernelSmall((kwidth/2)+(1-((kwidth/2)%2)),(kheight/2)+(1-((kheight/2)%2)));
kernel = getStructuringElement(MORPH_ELLIPSE, kernelSmall);
morphologyEx(canny, canny, MORPH_CLOSE, kernelSmall);
imshow("canny3", canny*255);
waitKey(1);
erode(canny, canny, kernel);
imshow("canny4", canny*255);
waitKey(1);
Mat flow;
blur(image, flow, Size(50,50));
absdiff(flow, background, flow);
cvtColor(flow, flow, CV_RGB2GRAY);
blur(flow, flow, Size(50,50));
equalizeHist(flow, flow);
Mat mask;
threshold(flow, mask, 170, 1, THRESH_BINARY);
mask = mask.mul(canny);
dilate(mask, mask, kernel); // maybe repeat some more
imshow("FLOW", gray.mul(mask));
// Moments lol = moments(mask, 1);
// circle(image, Point(lol.m10/lol.m00,lol.m01/lol.m00),20,Scalar(128),30);
// imshow("leimage", image);
/*
CascadeClassifier mouth_cascade;
mouth_cascade.load("Mouth.xml");
vector<Rect> mouths;
Mat classifyThis;
bilateralFilter(gray, classifyThis, 15, 10, 1);
equalizeHist(classifyThis, classifyThis);
classifyThis = classifyThis.mul(mask);
mouth_cascade.detectMultiScale(classifyThis, mouths, 1.1, 2, CV_HAAR_SCALE_IMAGE);
for (size_t i=0; i<mouths.size(); i++) {
Point center( mouths[i].x + mouths[i].width*0.5, mouths[i].y + mouths[i].height*0.5 );
ellipse( image, center, Size( mouths[i].width*0.5, mouths[i].height*0.5), 0, 0, 360, Scalar( 255, 0, 255 ), 4, 8, 0 );
}
imshow("MOUTH", image);
*/
keepGoing = (waitKey(25)<0);
}
cvReleaseCapture(&capture);
return 0;
}
<commit_msg>hacking<commit_after>#include "webcam.hpp"
using namespace cv;
using namespace std;
int main (int argc, char** argv) {
CvCapture* capture = 0;
int width, height, fps;
capture = cvCaptureFromCAM(0);
if (!capture) {
printf("No camera detected!");
return -1;
}
ifstream configFile (".config");
if (configFile.is_open()) {
//probably want to support corrupted .config
string line;
getline(configFile, line);
istringstream(line)>>width;
getline(configFile, line);
istringstream(line)>>height;
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, width);
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, height);
configFile.close();
} else {
initResolutions();
for (int i=36; i<150; i++) {
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, resolutions[i].width);
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, resolutions[i].height);
}
width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH);
height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT);
ofstream configFileOut(".config");
configFileOut << width;
configFileOut << "\n";
configFileOut << height;
configFileOut << "\n";
configFileOut.close();
}
bool keepGoing = true;
// srand(890);//not interested in good randomness
for (int i = 0; i < 30; i++) {
// capture some frames so exposure correction takes place
cvQueryFrame(capture);
}
Mat background = cvQueryFrame(capture);
background = background.clone();
blur(background, background, Size(50,50));
imshow("background", background);
Mat image;
Mat channel[3];
while (keepGoing) {
image = cvQueryFrame(capture);
//imshow("webcam", image);
Mat gray;
cvtColor(image, gray, CV_RGB2GRAY);
Mat canny;
Canny(gray, canny, 50, 50, 3);
blur(canny, canny, Size(width/20,height/20));
bitwise_not(canny, canny);
threshold(canny, canny, 220, 1, THRESH_BINARY);
imshow("canny1", canny*255);
waitKey(1);
int kwidth, kheight;
if (width/2 > height) {
kwidth = height/4;
kheight = height/8;
} else {
kwidth = width/8;
kheight = width/16;
}
kwidth += (1-(kwidth%2));//round up to nearest odd
kheight += (1-(kheight%2));//round up to nearest odd
Size kernelSize(kwidth, kheight);
Mat kernel = getStructuringElement(MORPH_ELLIPSE, kernelSize);
morphologyEx(canny, canny, MORPH_OPEN, kernel);
imshow("canny2", canny*255);
waitKey(1);
Mat kernalSmall = getStructuringElement(MORPH_ELLIPSE, Size((kwidth/2)+(1-((kwidth/2)%2)),(kheight/2)+(1-((kheight/2)%2))));
morphologyEx(canny, canny, MORPH_CLOSE, kernelSmall);
imshow("canny3", canny*255);
waitKey(1);
erode(canny, canny, kernel);
imshow("canny4", canny*255);
waitKey(1);
Mat flow;
blur(image, flow, Size(50,50));
absdiff(flow, background, flow);
cvtColor(flow, flow, CV_RGB2GRAY);
blur(flow, flow, Size(50,50));
equalizeHist(flow, flow);
Mat mask;
threshold(flow, mask, 170, 1, THRESH_BINARY);
mask = mask.mul(canny);
dilate(mask, mask, kernel); // maybe repeat some more
imshow("FLOW", gray.mul(mask));
// Moments lol = moments(mask, 1);
// circle(image, Point(lol.m10/lol.m00,lol.m01/lol.m00),20,Scalar(128),30);
// imshow("leimage", image);
/*
CascadeClassifier mouth_cascade;
mouth_cascade.load("Mouth.xml");
vector<Rect> mouths;
Mat classifyThis;
bilateralFilter(gray, classifyThis, 15, 10, 1);
equalizeHist(classifyThis, classifyThis);
classifyThis = classifyThis.mul(mask);
mouth_cascade.detectMultiScale(classifyThis, mouths, 1.1, 2, CV_HAAR_SCALE_IMAGE);
for (size_t i=0; i<mouths.size(); i++) {
Point center( mouths[i].x + mouths[i].width*0.5, mouths[i].y + mouths[i].height*0.5 );
ellipse( image, center, Size( mouths[i].width*0.5, mouths[i].height*0.5), 0, 0, 360, Scalar( 255, 0, 255 ), 4, 8, 0 );
}
imshow("MOUTH", image);
*/
keepGoing = (waitKey(25)<0);
}
cvReleaseCapture(&capture);
return 0;
}
<|endoftext|> |
<commit_before>#include "gflags/gflags.h"
DEFINE_string(race_id, "", "");
DEFINE_double(safe_angle, 60.0, "");
DEFINE_int32(handicap, 0, "");
DEFINE_bool(check_if_safe_ahead, true, "");
DEFINE_int32(answer_time, 7000, "Time limit for answer in ms");
DEFINE_bool(disable_attack, false, "");
DEFINE_bool(bump_with_turbo, true, "kamikazebumps");
DEFINE_bool(defend_turbo_bump, false, "Defend against people that have bump_with_turbo");
DEFINE_string(switch_scheduler, "ShortestPathSwitchScheduler", "");
DEFINE_string(throttle_scheduler, "WojtekThrottleScheduler", "");
DEFINE_bool(print_models, false, "If true, all models will print summary at destruction");
DEFINE_bool(continuous_integration, true, "");
DEFINE_bool(read_switch_models, true, "If true, switch models (length + radius) are read from files");
DEFINE_bool(write_switch_models, false, "If true, switch models (length + radius) are written to files");
DEFINE_bool(log_overtaking, false, "log overtaking scores");
DEFINE_bool(always_switch, false, "");
DEFINE_bool(force_safe_angle, false, "");
DEFINE_bool(log_simulator_csv, false, "Log in simulator to data.csv");
DEFINE_int32(laps, 3, "Number of laps");
DEFINE_double(overtake_treshold, 0.9, "Ratio of velocity to overtake guy");
<commit_msg>Default answer time = 5000<commit_after>#include "gflags/gflags.h"
DEFINE_string(race_id, "", "");
DEFINE_double(safe_angle, 60.0, "");
DEFINE_int32(handicap, 0, "");
DEFINE_bool(check_if_safe_ahead, true, "");
DEFINE_int32(answer_time, 5000, "Time limit for answer in ms");
DEFINE_bool(disable_attack, false, "");
DEFINE_bool(bump_with_turbo, true, "kamikazebumps");
DEFINE_bool(defend_turbo_bump, false, "Defend against people that have bump_with_turbo");
DEFINE_string(switch_scheduler, "ShortestPathSwitchScheduler", "");
DEFINE_string(throttle_scheduler, "WojtekThrottleScheduler", "");
DEFINE_bool(print_models, false, "If true, all models will print summary at destruction");
DEFINE_bool(continuous_integration, true, "");
DEFINE_bool(read_switch_models, true, "If true, switch models (length + radius) are read from files");
DEFINE_bool(write_switch_models, false, "If true, switch models (length + radius) are written to files");
DEFINE_bool(log_overtaking, false, "log overtaking scores");
DEFINE_bool(always_switch, false, "");
DEFINE_bool(force_safe_angle, false, "");
DEFINE_bool(log_simulator_csv, false, "Log in simulator to data.csv");
// Simulator
DEFINE_int32(laps, 3, "Number of laps");
DEFINE_double(overtake_treshold, 0.9, "Ratio of velocity to overtake guy");
<|endoftext|> |
<commit_before>#include "FileUtil.h"
#include "Zeder.h"
namespace Zeder {
const std::string &Entry::getAttribute(const std::string &name) const {
const auto match(attributes_.find(name));
if (match == attributes_.end())
LOG_ERROR("Couldn't find attribute '" + name + "'! in entry " + std::to_string(id_));
else
return match->second;
}
void Entry::setAttribute(const std::string &name, const std::string &value, bool overwrite) {
if (attributes_.find(name) == attributes_.end() or overwrite)
attributes_[name] = value;
else
LOG_ERROR("Attribute '" + name + "' already exists in entry " + std::to_string(id_));
}
void Entry::removeAttribute(const std::string &name) {
const auto match(attributes_.find(name));
if (match == attributes_.end())
LOG_ERROR("Couldn't find attribute '" + name + "'! in entry " + std::to_string(id_));
else
attributes_.erase(match);
}
unsigned Entry::keepAttributes(const std::vector<std::string> &names_to_keep) {
std::vector<std::string> names_to_remove;
for (const auto &key_value : attributes_) {
if (std::find(names_to_keep.begin(), names_to_keep.end(), key_value.first) == names_to_keep.end())
names_to_remove.emplace_back(key_value.first);
}
for (const auto &name : names_to_remove)
attributes_.erase(attributes_.find(name));
return names_to_remove.size();
}
void Entry::prettyPrint(std::string * const print_buffer) const {
*print_buffer = "Entry " + std::to_string(id_) + ":\n";
for (const auto &attribute : attributes_)
print_buffer->append("\t{").append(attribute.first).append("} -> '").append(attribute.second).append("'\n");
}
void Entry::DiffResult::prettyPrint(std::string * const print_buffer) const {
*print_buffer = "Diff " + std::to_string(id_) + ":\n";
for (const auto &attribute : modified_attributes_) {
if (not attribute.second.first.empty()) {
print_buffer->append("\t{").append(attribute.first).append("} -> '").append(attribute.second.first)
.append("' => '").append(attribute.second.second).append("'\n");
} else
print_buffer->append("\t{").append(attribute.first).append("} -> '").append(attribute.second.second).append("'\n");
}
}
Entry::DiffResult Entry::Diff(const Entry &lhs, const Entry &rhs, const bool skip_timestamp_check) {
if (lhs.getId() != rhs.getId())
LOG_ERROR("Can only diff revisions of the same entry! LHS = " + std::to_string(lhs.getId()) + ", RHS = "
+ std::to_string(rhs.getId()));
DiffResult delta{ false, rhs.getId(), rhs.getLastModifiedTimestamp() };
if (not skip_timestamp_check) {
const auto time_difference(TimeUtil::DiffStructTm(rhs.getLastModifiedTimestamp(), lhs.getLastModifiedTimestamp()));
if (time_difference < 0) {
LOG_WARNING("The existing entry " + std::to_string(rhs.getId()) + " is newer than the diff by "
+ std::to_string(time_difference) + " seconds");
} else
delta.timestamp_is_newer_ = true;
} else {
delta.timestamp_is_newer_ = true;
delta.last_modified_timestamp_ = TimeUtil::GetCurrentTimeGMT();
}
for (const auto &key_value : rhs) {
const auto &attribute_name(key_value.first), &attribute_value(key_value.second);
if (lhs.hasAttribute(attribute_name)) {
const auto value(lhs.getAttribute(attribute_name));
if (value != attribute_value) {
// copy the old value before updating it (since it's a reference)
delta.modified_attributes_[attribute_name] = std::make_pair(value, attribute_value);
}
} else
delta.modified_attributes_[attribute_name] = std::make_pair("", attribute_value);
}
return delta;
}
void Entry::Merge(const DiffResult &delta, Entry * const merge_into) {
if (delta.id_ != merge_into->getId()) {
LOG_ERROR("ID mismatch between diff and entry. Diff = " + std::to_string(delta.id_) +
", Entry = " + std::to_string(merge_into->getId()));
}
if (not delta.timestamp_is_newer_) {
const auto time_difference(TimeUtil::DiffStructTm(delta.last_modified_timestamp_, merge_into->getLastModifiedTimestamp()));
LOG_WARNING("Diff of entry " + std::to_string(delta.id_) + " is not newer than the source revision. " +
"Timestamp difference: " + std::to_string(time_difference) + " seconds");
}
merge_into->setModifiedTimestamp(delta.last_modified_timestamp_);
for (const auto &key_value : delta.modified_attributes_)
merge_into->setAttribute(key_value.first, key_value.second.second, true);
}
void EntryCollection::addEntry(const Entry &new_entry, const bool sort_after_add) {
const iterator match(find(new_entry.getId()));
if (unlikely(match != end()))
LOG_ERROR("Duplicate ID " + std::to_string(new_entry.getId()) + "!");
else
entries_.emplace_back(new_entry);
if (sort_after_add)
sortEntries();
}
FileType GetFileTypeFromPath(const std::string &path, bool check_if_file_exists) {
if (check_if_file_exists and not FileUtil::Exists(path))
LOG_ERROR("file '" + path + "' not found");
if (StringUtil::EndsWith(path, ".csv", /* ignore_case = */true))
return FileType::CSV;
if (StringUtil::EndsWith(path, ".json", /* ignore_case = */true))
return FileType::JSON;
if (StringUtil::EndsWith(path, ".conf", /* ignore_case = */true) or StringUtil::EndsWith(path, ".ini", /* ignore_case = */true) )
return FileType::INI;
LOG_ERROR("can't guess the file type of \"" + path + "\"!");
}
std::unique_ptr<Importer> Importer::Factory(std::unique_ptr<Params> params) {
auto file_type(GetFileTypeFromPath(params->file_path_));
switch (file_type) {
case FileType::CSV:
return std::unique_ptr<Importer>(new CsvReader(std::move(params)));
case FileType::INI:
return std::unique_ptr<Importer>(new IniReader(std::move(params)));
default:
LOG_ERROR("Reader not implemented for file '" + params->file_path_ + "'");
};
}
void CsvReader::parse(EntryCollection * const collection) {
std::vector<std::string> columns, splits;
size_t line(0);
while (reader_.readLine(&splits)) {
++line;
if (splits.size() < 2)
LOG_ERROR("Incorrect number of splits on line " + std::to_string(line));
else if (line == 1) {
columns.swap(splits);
if (columns[0] != MANDATORY_FIELD_TO_STRING_MAP.at(Z) or columns[columns.size() - 1] != MANDATORY_FIELD_TO_STRING_MAP.at(MTIME))
LOG_ERROR("Mandatory fields were not found in the first and last columns!");
continue;
}
// the first and last columns are Z and Mtime respectively
unsigned id(0);
if (not StringUtil::ToUnsigned(splits[0], &id)) {
LOG_WARNING("Couldn't parse Zeder ID on line " + std::to_string(line));
continue;
}
Entry new_entry(id);
new_entry.setModifiedTimestamp(TimeUtil::StringToStructTm(splits[splits.size() - 1].c_str(), MODIFIED_TIMESTAMP_FORMAT_STRING));
for (size_t i(1); i < splits.size() - 1; ++i) {
const auto &attribute_name(columns[i]);
const auto &attribute_value (splits[i]);
new_entry.setAttribute(attribute_name, attribute_value);
}
if (input_params_->postprocessor_(&new_entry))
collection->addEntry(new_entry);
}
collection->sortEntries();
}
void IniReader::parse(EntryCollection * const collection) {
const auto params(dynamic_cast<IniReader::Params * const>(input_params_.get()));
if (not params)
LOG_ERROR("Invalid input parameters passed to IniReader!");
for (const auto §ion_name : params->valid_section_names_) {
const auto §ion(*config_.getSection(section_name));
Entry new_entry;
new_entry.setAttribute(params->section_name_attribute_, section_name);
for (const auto &entry : section) {
// skip empty lines
if (entry.name_.empty())
continue;
if (entry.name_ == params->zeder_id_key_) {
unsigned id(0);
if (not StringUtil::ToUnsigned(entry.value_, &id))
LOG_WARNING("Couldn't parse Zeder ID in section '" + section_name + "'");
else
new_entry.setId(id);
} else if (entry.name_ == params->zeder_last_modified_timestamp_key_)
new_entry.setModifiedTimestamp(TimeUtil::StringToStructTm(entry.value_, MODIFIED_TIMESTAMP_FORMAT_STRING));
else {
const auto attribute_name(params->key_to_attribute_map_.find(entry.name_));
if (attribute_name == params->key_to_attribute_map_.end()) {
LOG_DEBUG("Key '" + entry.name_ + "' has no corresponding Zeder attribute. Section: '" +
section_name + "', value: '" + entry.value_ + "'");
} else
new_entry.setAttribute(attribute_name->second, entry.value_);
}
}
struct tm last_modified(new_entry.getLastModifiedTimestamp());
if (new_entry.getId() == 0 or std::mktime(&last_modified) == -1) {
LOG_WARNING("Mandatory fields were not found in section '" + section_name + "'");
std::string debug_print_buffer;
new_entry.prettyPrint(&debug_print_buffer);
LOG_DEBUG(debug_print_buffer);
} else if (input_params_->postprocessor_(&new_entry))
collection->addEntry(new_entry);
}
collection->sortEntries();
}
std::unique_ptr<Exporter> Exporter::Factory(std::unique_ptr<Params> params) {
auto file_type(GetFileTypeFromPath(params->file_path_, /* check_if_file_exists = */ false));
switch (file_type) {
case FileType::INI:
return std::unique_ptr<Exporter>(new IniWriter(std::move(params)));
default:
LOG_ERROR("Reader not implemented for file '" + params->file_path_ + "'");
};
}
IniWriter::IniWriter(std::unique_ptr<Exporter::Params> params): Exporter(std::move(params)) {
if (FileUtil::Exists(input_params_->file_path_))
config_.reset(new IniFile(input_params_->file_path_));
else
config_.reset(new IniFile(input_params_->file_path_, /* ignore_failed_includes = */ true, /* create_empty = */ true));
}
void IniWriter::write(const EntryCollection &collection) {
const auto params(dynamic_cast<IniWriter::Params * const>(input_params_.get()));
char time_buffer[100]{};
// we assume that the entries are sorted at this point
for (const auto &entry : collection) {
config_->appendSection(entry.getAttribute(params->section_name_attribute_));
auto current_section(config_->getSection(entry.getAttribute(params->section_name_attribute_)));
current_section->insert(params->zeder_id_key_, std::to_string(entry.getId()), "", IniFile::Section::DupeInsertionBehaviour::OVERWRITE_EXISTING_VALUE);
std::strftime(time_buffer, sizeof(time_buffer), MODIFIED_TIMESTAMP_FORMAT_STRING, &entry.getLastModifiedTimestamp());
current_section->insert(params->zeder_last_modified_timestamp_key_, time_buffer, "", IniFile::Section::DupeInsertionBehaviour::OVERWRITE_EXISTING_VALUE);
for (const auto &attribute_name : params->attributes_to_export_) {
if (entry.hasAttribute(attribute_name)) {
const auto &attribute_value(entry.getAttribute(attribute_name));
if (not attribute_value.empty()) {
current_section->insert(params->attribute_to_key_map_.at(attribute_name), attribute_value,
"", IniFile::Section::DupeInsertionBehaviour::OVERWRITE_EXISTING_VALUE);
}
} else
LOG_DEBUG("Attribute '" + attribute_name + "' not found for exporting in entry " + std::to_string(entry.getId()));
}
params->extra_keys_appender_(&*current_section, entry);
}
config_->write(params->file_path_);
}
} // namespace Zeder
<commit_msg>Missing copyright notice<commit_after>/** \brief Interaction with the Zeder collaboration tool
* \author Madeesh Kannan
*
* \copyright 2018 Universitätsbibliothek Tübingen. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "FileUtil.h"
#include "Zeder.h"
namespace Zeder {
const std::string &Entry::getAttribute(const std::string &name) const {
const auto match(attributes_.find(name));
if (match == attributes_.end())
LOG_ERROR("Couldn't find attribute '" + name + "'! in entry " + std::to_string(id_));
else
return match->second;
}
void Entry::setAttribute(const std::string &name, const std::string &value, bool overwrite) {
if (attributes_.find(name) == attributes_.end() or overwrite)
attributes_[name] = value;
else
LOG_ERROR("Attribute '" + name + "' already exists in entry " + std::to_string(id_));
}
void Entry::removeAttribute(const std::string &name) {
const auto match(attributes_.find(name));
if (match == attributes_.end())
LOG_ERROR("Couldn't find attribute '" + name + "'! in entry " + std::to_string(id_));
else
attributes_.erase(match);
}
unsigned Entry::keepAttributes(const std::vector<std::string> &names_to_keep) {
std::vector<std::string> names_to_remove;
for (const auto &key_value : attributes_) {
if (std::find(names_to_keep.begin(), names_to_keep.end(), key_value.first) == names_to_keep.end())
names_to_remove.emplace_back(key_value.first);
}
for (const auto &name : names_to_remove)
attributes_.erase(attributes_.find(name));
return names_to_remove.size();
}
void Entry::prettyPrint(std::string * const print_buffer) const {
*print_buffer = "Entry " + std::to_string(id_) + ":\n";
for (const auto &attribute : attributes_)
print_buffer->append("\t{").append(attribute.first).append("} -> '").append(attribute.second).append("'\n");
}
void Entry::DiffResult::prettyPrint(std::string * const print_buffer) const {
*print_buffer = "Diff " + std::to_string(id_) + ":\n";
for (const auto &attribute : modified_attributes_) {
if (not attribute.second.first.empty()) {
print_buffer->append("\t{").append(attribute.first).append("} -> '").append(attribute.second.first)
.append("' => '").append(attribute.second.second).append("'\n");
} else
print_buffer->append("\t{").append(attribute.first).append("} -> '").append(attribute.second.second).append("'\n");
}
}
Entry::DiffResult Entry::Diff(const Entry &lhs, const Entry &rhs, const bool skip_timestamp_check) {
if (lhs.getId() != rhs.getId())
LOG_ERROR("Can only diff revisions of the same entry! LHS = " + std::to_string(lhs.getId()) + ", RHS = "
+ std::to_string(rhs.getId()));
DiffResult delta{ false, rhs.getId(), rhs.getLastModifiedTimestamp() };
if (not skip_timestamp_check) {
const auto time_difference(TimeUtil::DiffStructTm(rhs.getLastModifiedTimestamp(), lhs.getLastModifiedTimestamp()));
if (time_difference < 0) {
LOG_WARNING("The existing entry " + std::to_string(rhs.getId()) + " is newer than the diff by "
+ std::to_string(time_difference) + " seconds");
} else
delta.timestamp_is_newer_ = true;
} else {
delta.timestamp_is_newer_ = true;
delta.last_modified_timestamp_ = TimeUtil::GetCurrentTimeGMT();
}
for (const auto &key_value : rhs) {
const auto &attribute_name(key_value.first), &attribute_value(key_value.second);
if (lhs.hasAttribute(attribute_name)) {
const auto value(lhs.getAttribute(attribute_name));
if (value != attribute_value) {
// copy the old value before updating it (since it's a reference)
delta.modified_attributes_[attribute_name] = std::make_pair(value, attribute_value);
}
} else
delta.modified_attributes_[attribute_name] = std::make_pair("", attribute_value);
}
return delta;
}
void Entry::Merge(const DiffResult &delta, Entry * const merge_into) {
if (delta.id_ != merge_into->getId()) {
LOG_ERROR("ID mismatch between diff and entry. Diff = " + std::to_string(delta.id_) +
", Entry = " + std::to_string(merge_into->getId()));
}
if (not delta.timestamp_is_newer_) {
const auto time_difference(TimeUtil::DiffStructTm(delta.last_modified_timestamp_, merge_into->getLastModifiedTimestamp()));
LOG_WARNING("Diff of entry " + std::to_string(delta.id_) + " is not newer than the source revision. " +
"Timestamp difference: " + std::to_string(time_difference) + " seconds");
}
merge_into->setModifiedTimestamp(delta.last_modified_timestamp_);
for (const auto &key_value : delta.modified_attributes_)
merge_into->setAttribute(key_value.first, key_value.second.second, true);
}
void EntryCollection::addEntry(const Entry &new_entry, const bool sort_after_add) {
const iterator match(find(new_entry.getId()));
if (unlikely(match != end()))
LOG_ERROR("Duplicate ID " + std::to_string(new_entry.getId()) + "!");
else
entries_.emplace_back(new_entry);
if (sort_after_add)
sortEntries();
}
FileType GetFileTypeFromPath(const std::string &path, bool check_if_file_exists) {
if (check_if_file_exists and not FileUtil::Exists(path))
LOG_ERROR("file '" + path + "' not found");
if (StringUtil::EndsWith(path, ".csv", /* ignore_case = */true))
return FileType::CSV;
if (StringUtil::EndsWith(path, ".json", /* ignore_case = */true))
return FileType::JSON;
if (StringUtil::EndsWith(path, ".conf", /* ignore_case = */true) or StringUtil::EndsWith(path, ".ini", /* ignore_case = */true) )
return FileType::INI;
LOG_ERROR("can't guess the file type of \"" + path + "\"!");
}
std::unique_ptr<Importer> Importer::Factory(std::unique_ptr<Params> params) {
auto file_type(GetFileTypeFromPath(params->file_path_));
switch (file_type) {
case FileType::CSV:
return std::unique_ptr<Importer>(new CsvReader(std::move(params)));
case FileType::INI:
return std::unique_ptr<Importer>(new IniReader(std::move(params)));
default:
LOG_ERROR("Reader not implemented for file '" + params->file_path_ + "'");
};
}
void CsvReader::parse(EntryCollection * const collection) {
std::vector<std::string> columns, splits;
size_t line(0);
while (reader_.readLine(&splits)) {
++line;
if (splits.size() < 2)
LOG_ERROR("Incorrect number of splits on line " + std::to_string(line));
else if (line == 1) {
columns.swap(splits);
if (columns[0] != MANDATORY_FIELD_TO_STRING_MAP.at(Z) or columns[columns.size() - 1] != MANDATORY_FIELD_TO_STRING_MAP.at(MTIME))
LOG_ERROR("Mandatory fields were not found in the first and last columns!");
continue;
}
// the first and last columns are Z and Mtime respectively
unsigned id(0);
if (not StringUtil::ToUnsigned(splits[0], &id)) {
LOG_WARNING("Couldn't parse Zeder ID on line " + std::to_string(line));
continue;
}
Entry new_entry(id);
new_entry.setModifiedTimestamp(TimeUtil::StringToStructTm(splits[splits.size() - 1].c_str(), MODIFIED_TIMESTAMP_FORMAT_STRING));
for (size_t i(1); i < splits.size() - 1; ++i) {
const auto &attribute_name(columns[i]);
const auto &attribute_value (splits[i]);
new_entry.setAttribute(attribute_name, attribute_value);
}
if (input_params_->postprocessor_(&new_entry))
collection->addEntry(new_entry);
}
collection->sortEntries();
}
void IniReader::parse(EntryCollection * const collection) {
const auto params(dynamic_cast<IniReader::Params * const>(input_params_.get()));
if (not params)
LOG_ERROR("Invalid input parameters passed to IniReader!");
for (const auto §ion_name : params->valid_section_names_) {
const auto §ion(*config_.getSection(section_name));
Entry new_entry;
new_entry.setAttribute(params->section_name_attribute_, section_name);
for (const auto &entry : section) {
// skip empty lines
if (entry.name_.empty())
continue;
if (entry.name_ == params->zeder_id_key_) {
unsigned id(0);
if (not StringUtil::ToUnsigned(entry.value_, &id))
LOG_WARNING("Couldn't parse Zeder ID in section '" + section_name + "'");
else
new_entry.setId(id);
} else if (entry.name_ == params->zeder_last_modified_timestamp_key_)
new_entry.setModifiedTimestamp(TimeUtil::StringToStructTm(entry.value_, MODIFIED_TIMESTAMP_FORMAT_STRING));
else {
const auto attribute_name(params->key_to_attribute_map_.find(entry.name_));
if (attribute_name == params->key_to_attribute_map_.end()) {
LOG_DEBUG("Key '" + entry.name_ + "' has no corresponding Zeder attribute. Section: '" +
section_name + "', value: '" + entry.value_ + "'");
} else
new_entry.setAttribute(attribute_name->second, entry.value_);
}
}
struct tm last_modified(new_entry.getLastModifiedTimestamp());
if (new_entry.getId() == 0 or std::mktime(&last_modified) == -1) {
LOG_WARNING("Mandatory fields were not found in section '" + section_name + "'");
std::string debug_print_buffer;
new_entry.prettyPrint(&debug_print_buffer);
LOG_DEBUG(debug_print_buffer);
} else if (input_params_->postprocessor_(&new_entry))
collection->addEntry(new_entry);
}
collection->sortEntries();
}
std::unique_ptr<Exporter> Exporter::Factory(std::unique_ptr<Params> params) {
auto file_type(GetFileTypeFromPath(params->file_path_, /* check_if_file_exists = */ false));
switch (file_type) {
case FileType::INI:
return std::unique_ptr<Exporter>(new IniWriter(std::move(params)));
default:
LOG_ERROR("Reader not implemented for file '" + params->file_path_ + "'");
};
}
IniWriter::IniWriter(std::unique_ptr<Exporter::Params> params): Exporter(std::move(params)) {
if (FileUtil::Exists(input_params_->file_path_))
config_.reset(new IniFile(input_params_->file_path_));
else
config_.reset(new IniFile(input_params_->file_path_, /* ignore_failed_includes = */ true, /* create_empty = */ true));
}
void IniWriter::write(const EntryCollection &collection) {
const auto params(dynamic_cast<IniWriter::Params * const>(input_params_.get()));
char time_buffer[100]{};
// we assume that the entries are sorted at this point
for (const auto &entry : collection) {
config_->appendSection(entry.getAttribute(params->section_name_attribute_));
auto current_section(config_->getSection(entry.getAttribute(params->section_name_attribute_)));
current_section->insert(params->zeder_id_key_, std::to_string(entry.getId()), "", IniFile::Section::DupeInsertionBehaviour::OVERWRITE_EXISTING_VALUE);
std::strftime(time_buffer, sizeof(time_buffer), MODIFIED_TIMESTAMP_FORMAT_STRING, &entry.getLastModifiedTimestamp());
current_section->insert(params->zeder_last_modified_timestamp_key_, time_buffer, "", IniFile::Section::DupeInsertionBehaviour::OVERWRITE_EXISTING_VALUE);
for (const auto &attribute_name : params->attributes_to_export_) {
if (entry.hasAttribute(attribute_name)) {
const auto &attribute_value(entry.getAttribute(attribute_name));
if (not attribute_value.empty()) {
current_section->insert(params->attribute_to_key_map_.at(attribute_name), attribute_value,
"", IniFile::Section::DupeInsertionBehaviour::OVERWRITE_EXISTING_VALUE);
}
} else
LOG_DEBUG("Attribute '" + attribute_name + "' not found for exporting in entry " + std::to_string(entry.getId()));
}
params->extra_keys_appender_(&*current_section, entry);
}
config_->write(params->file_path_);
}
} // namespace Zeder
<|endoftext|> |
<commit_before>#include "webcam.hpp"
#include <chrono>
using namespace cv;
using namespace std;
Mat ellipticKernel(int width, int height = -1) {
if (height==-1) {
return getStructuringElement(MORPH_ELLIPSE,Size(width,width), Point(width/2, width/2));
} else {
return getStructuringElement(MORPH_ELLIPSE,Size(width,height), Point(width/2, height/2));
}
}
unsigned long long getMilliseconds() {
return chrono::system_clock::now().time_since_epoch()/chrono::milliseconds(1);
}
void morphFast(Mat inout, int smallsize = 100, int factor = 25, int eq = 1, int diler = 0) {
int width, height;
width = inout.size().width;
height = inout.size().height;
Mat downsample;
resize(inout, downsample, Size(smallsize,smallsize));
Mat kernel = ellipticKernel(factor);
if (diler) {
erode(downsample, downsample, kernel);
} else {
dilate(downsample, downsample, kernel);
}
if (eq) {
equalizeHist(downsample, downsample);
}
resize(downsample, inout, Size(width, height));
}
int main (int argc, char** argv) {
int tracker1, tracker2, tracker3;
namedWindow("s",1);
createTrackbar("1","s",&tracker1,100);
createTrackbar("2","s",&tracker2,100);
createTrackbar("3","s",&tracker3,100);
CvCapture* capture = 0;
int width, height, fps;
capture = cvCaptureFromCAM(0);
if (!capture) {
printf("No camera detected!");
return -1;
}
unsigned long long times[100];
int f = 0;
for (int i=0; i<100; i++)
times[i] = 0;
ifstream configFile (".config");
if (configFile.is_open()) {
//probably want to support corrupted .config
string line;
getline(configFile, line);
istringstream(line)>>width;
getline(configFile, line);
istringstream(line)>>height;
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, width);
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, height);
configFile.close();
} else {
initResolutions();
for (int i=36; i<150; i++) {
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, resolutions[i].width);
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, resolutions[i].height);
}
width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH);
height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT);
ofstream configFileOut(".config");
configFileOut << width;
configFileOut << "\n";
configFileOut << height;
configFileOut << "\n";
configFileOut.close();
}
bool keepGoing = true;
// srand(890);//not interested in good randomness
for (int i = 0; i < 30; i++) {
// capture some frames so exposure correction takes place
cvQueryFrame(capture);
}
Mat background = cvQueryFrame(capture);
background = background.clone();
blur(background, background, Size(50,50));
Mat image;
Mat channel[3];
unsigned long long timenow = getMilliseconds();
while (keepGoing) {
image = cvQueryFrame(capture);
times[0] += getMilliseconds() - timenow;
timenow = getMilliseconds();
// preprocess by rotating according to OVR roll
// imshow("webcam", image);
// let's make multiple masks where 0=not mouth, 1=uncertain
// then multiply them together and multiply that with image
// and run haar classifier on image
Mat gray, blurred_img;
cvtColor(image, gray, CV_RGB2GRAY);
blur(image, blurred_img, Size(50,50));
times[1] += getMilliseconds() - timenow;
timenow = getMilliseconds();
// this mask filters out areas with too many edges
// removed for now; it didn't generalize well
/*
Mat canny;
Canny(gray, canny, 50, 50, 3);
blur(canny, canny, Size(width/20,height/20));
bitwise_not(canny, canny);
threshold(canny, canny, 200, 1, THRESH_BINARY);
blur(canny*255, canny, Size(width/10, height/10));
threshold(canny, canny, 220, 1, THRESH_BINARY);
imshow("canny mask", gray.mul(canny));
*/
// this mask filters out areas which have not changed much
// background needs to be updated when person is not in frame
// use OVR SDK to do this later
Mat flow;
absdiff(blurred_img, background, flow);
cvtColor(flow, flow, CV_RGB2GRAY);
morphFast(flow);
threshold(flow, flow, 60, 1, THRESH_BINARY);
imshow("flow mask", gray.mul(flow));
times[2] += getMilliseconds() - timenow;
timenow = getMilliseconds();
// this mask gets anything kind of dark (DK2) and dilates
Mat kindofdark;
equalizeHist(gray, kindofdark);
threshold(kindofdark, kindofdark, 100, 1, THRESH_BINARY_INV);
morphFast(kindofdark, 100, 17, 0);
imshow("dark mask", gray.mul(kindofdark));
times[3] += getMilliseconds() - timenow;
timenow = getMilliseconds();
// this mask gets rid of anything far away from red stuff
// did not work well and was slow
/*
Mat notlips;
Mat channels[3];
split(image, channels);
channels[2].convertTo(notlips, CV_32FC1);
divide(notlips, gray, notlips, 1, CV_32FC1);
//equalistHist is horrible for a red background
//equalizeHist(notlips, notlips);
threshold(notlips, notlips, tracker3/30.0, 1, THRESH_BINARY);
notlips.convertTo(notlips, CV_8UC1);
imshow("lip mask", notlips*255);
Mat otherMorph = notlips.clone();
int tx = tracker1+1-(tracker1%2);
if (tx<3) tx=1;
if (tx>90) tx=91;
morphFast(notlips, 100, tx, 0, 0);
int ty = tracker2+1-(tracker2%2);
if (ty<3) ty=1;
if (ty>90) ty=91;
morphFast(notlips, 100, ty, 0, 1);
imshow("lips2", notlips.mul(gray));
morphFast(otherMorph, 100, tx, 0, 1);
morphFast(otherMorph, 100, tx, 0, 0);
imshow("lips3", otherMorph.mul(gray));
waitKey(1);
*/
Mat mask = flow.mul(kindofdark);
// open the mask
Mat smallMask0, smallMask1;
resize(mask, smallMask0, Size(width/5,height/5));
Mat smallKernel = ellipticKernel(69,79);
erode(smallMask0, smallMask1, smallKernel);
dilate(smallMask1, smallMask1, smallKernel);
bitwise_and(smallMask0, smallMask1, smallMask1);
resize(smallMask1, mask, Size(width, height));
imshow("morph mask", gray.mul(mask));
times[4] += getMilliseconds() - timenow;
timenow = getMilliseconds();
// update background with new morph mask
// average what we know is background with prior background
// dilate it first since we really want to be sure it's bg
/*
// actually dilation is slow and our current mask is already
// really nice :)
Mat dilatedMask;
dilate(smallMask1, dilatedMask, smallKernel);
resize(dilatedMask, dilatedMask, Size(width, height));
imshow("erosion", dilatedMask.mul(gray));
*/
Mat mask_;
subtract(1, mask ,mask_);
Mat mask3, mask3_;
channel[0] = mask;
channel[1] = mask;
channel[2] = mask;
merge(channel, 3, mask3);
channel[0] = mask_;
channel[1] = mask_;
channel[2] = mask_;
merge(channel, 3, mask3_);
background = background.mul(mask3) +
(background.mul(mask3_)/2 + blurred_img.mul(mask3_)/2);
times[5] += getMilliseconds() - timenow;
timenow = getMilliseconds();
// imshow("background", background);
/*
Moments lol = moments(gray, 1);
circle(image, Point(lol.m10/lol.m00,lol.m01/lol.m00),20,Scalar(128),30);
imshow("leimage", image);
*/
CascadeClassifier mouth_cascade;
mouth_cascade.load("Mouth.xml");
vector<Rect> mouths;
int scale = 3;
Mat classifyThis;
equalizeHist(gray, gray);//ew; watch out not to use this later
resize(gray.mul(mask), classifyThis, Size(width/scale,height/scale));
// bilateralFilter(gray, classifyThis, 15, 10, 1);
mouth_cascade.detectMultiScale(classifyThis, mouths, 1.1, 0, CV_HAAR_SCALE_IMAGE);
for (size_t i=0; i<mouths.size(); i++) {
Rect scaled(mouths[i].x*scale, mouths[i].y*scale, mouths[i].width*scale,mouths[i].height*scale);
rectangle(image, scaled, Scalar(255,0,0));
}
times[6] += getMilliseconds() - timenow;
timenow = getMilliseconds();
imshow("MOUTH", image);
for (int i=0; i<7; i++) {
printf("%llu , ", times[i]);
times[i] = 0;
}
printf("\n");
keepGoing = (waitKey(1)<0);
}
cvReleaseCapture(&capture);
return 0;
}
<commit_msg>hacking<commit_after>#include "webcam.hpp"
#include <chrono>
using namespace cv;
using namespace std;
Mat ellipticKernel(int width, int height = -1) {
if (height==-1) {
return getStructuringElement(MORPH_ELLIPSE,Size(width,width), Point(width/2, width/2));
} else {
return getStructuringElement(MORPH_ELLIPSE,Size(width,height), Point(width/2, height/2));
}
}
unsigned long long getMilliseconds() {
return chrono::system_clock::now().time_since_epoch()/chrono::milliseconds(1);
}
void morphFast(Mat inout, int smallsize = 100, int factor = 25, int eq = 1, int diler = 0) {
int width, height;
width = inout.size().width;
height = inout.size().height;
Mat downsample;
resize(inout, downsample, Size(smallsize,smallsize));
Mat kernel = ellipticKernel(factor);
if (diler) {
erode(downsample, downsample, kernel);
} else {
dilate(downsample, downsample, kernel);
}
if (eq) {
equalizeHist(downsample, downsample);
}
resize(downsample, inout, Size(width, height));
}
int main (int argc, char** argv) {
int tracker1, tracker2, tracker3;
namedWindow("s",1);
createTrackbar("1","s",&tracker1,100);
createTrackbar("2","s",&tracker2,100);
createTrackbar("3","s",&tracker3,100);
CvCapture* capture = 0;
int width, height, fps;
capture = cvCaptureFromCAM(0);
if (!capture) {
printf("No camera detected!");
return -1;
}
unsigned long long times[100];
int f = 0;
for (int i=0; i<100; i++)
times[i] = 0;
ifstream configFile (".config");
if (configFile.is_open()) {
//probably want to support corrupted .config
string line;
getline(configFile, line);
istringstream(line)>>width;
getline(configFile, line);
istringstream(line)>>height;
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, width);
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, height);
configFile.close();
} else {
initResolutions();
for (int i=36; i<150; i++) {
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, resolutions[i].width);
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, resolutions[i].height);
}
width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH);
height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT);
ofstream configFileOut(".config");
configFileOut << width;
configFileOut << "\n";
configFileOut << height;
configFileOut << "\n";
configFileOut.close();
}
bool keepGoing = true;
// srand(890);//not interested in good randomness
for (int i = 0; i < 30; i++) {
// capture some frames so exposure correction takes place
cvQueryFrame(capture);
}
Mat background = cvQueryFrame(capture);
background = background.clone();
blur(background, background, Size(50,50));
Mat image;
Mat channel[3];
unsigned long long timenow = getMilliseconds();
while (keepGoing) {
image = cvQueryFrame(capture);
times[0] += getMilliseconds() - timenow;
timenow = getMilliseconds();
// preprocess by rotating according to OVR roll
// imshow("webcam", image);
// let's make multiple masks where 0=not mouth, 1=uncertain
// then multiply them together and multiply that with image
// and run haar classifier on image
Mat gray, blurred_img;
cvtColor(image, gray, CV_RGB2GRAY);
blur(image, blurred_img, Size(50,50));
times[1] += getMilliseconds() - timenow;
timenow = getMilliseconds();
// this mask filters out areas with too many edges
// removed for now; it didn't generalize well
/*
Mat canny;
Canny(gray, canny, 50, 50, 3);
blur(canny, canny, Size(width/20,height/20));
bitwise_not(canny, canny);
threshold(canny, canny, 200, 1, THRESH_BINARY);
blur(canny*255, canny, Size(width/10, height/10));
threshold(canny, canny, 220, 1, THRESH_BINARY);
imshow("canny mask", gray.mul(canny));
*/
// this mask filters out areas which have not changed much
// background needs to be updated when person is not in frame
// use OVR SDK to do this later
Mat flow;
absdiff(blurred_img, background, flow);
cvtColor(flow, flow, CV_RGB2GRAY);
morphFast(flow);
threshold(flow, flow, 60, 1, THRESH_BINARY);
imshow("flow mask", gray.mul(flow));
times[2] += getMilliseconds() - timenow;
timenow = getMilliseconds();
// this mask gets anything kind of dark (DK2) and dilates
Mat kindofdark;
equalizeHist(gray, kindofdark);
threshold(kindofdark, kindofdark, 100, 1, THRESH_BINARY_INV);
morphFast(kindofdark, 100, 17, 0);
imshow("dark mask", gray.mul(kindofdark));
times[3] += getMilliseconds() - timenow;
timenow = getMilliseconds();
// this mask gets rid of anything far away from red stuff
// did not work well and was slow
/*
Mat notlips;
Mat channels[3];
split(image, channels);
channels[2].convertTo(notlips, CV_32FC1);
divide(notlips, gray, notlips, 1, CV_32FC1);
//equalistHist is horrible for a red background
//equalizeHist(notlips, notlips);
threshold(notlips, notlips, tracker3/30.0, 1, THRESH_BINARY);
notlips.convertTo(notlips, CV_8UC1);
imshow("lip mask", notlips*255);
Mat otherMorph = notlips.clone();
int tx = tracker1+1-(tracker1%2);
if (tx<3) tx=1;
if (tx>90) tx=91;
morphFast(notlips, 100, tx, 0, 0);
int ty = tracker2+1-(tracker2%2);
if (ty<3) ty=1;
if (ty>90) ty=91;
morphFast(notlips, 100, ty, 0, 1);
imshow("lips2", notlips.mul(gray));
morphFast(otherMorph, 100, tx, 0, 1);
morphFast(otherMorph, 100, tx, 0, 0);
imshow("lips3", otherMorph.mul(gray));
waitKey(1);
*/
Mat mask = flow.mul(kindofdark);
// open the mask
Mat smallMask0, smallMask1;
resize(mask, smallMask0, Size(width/5,height/5));
Mat smallKernel = ellipticKernel(69,79);
erode(smallMask0, smallMask1, smallKernel);
dilate(smallMask1, smallMask1, smallKernel);
bitwise_and(smallMask0, smallMask1, smallMask1);
resize(smallMask1, mask, Size(width, height));
imshow("morph mask", gray.mul(mask));
times[4] += getMilliseconds() - timenow;
timenow = getMilliseconds();
// update background with new morph mask
// average what we know is background with prior background
// dilate it first since we really want to be sure it's bg
/*
// actually dilation is slow and our current mask is already
// really nice :)
Mat dilatedMask;
dilate(smallMask1, dilatedMask, smallKernel);
resize(dilatedMask, dilatedMask, Size(width, height));
imshow("erosion", dilatedMask.mul(gray));
*/
Mat mask_;
subtract(1, mask ,mask_);
Mat mask3, mask3_;
channel[0] = mask;
channel[1] = mask;
channel[2] = mask;
merge(channel, 3, mask3);
channel[0] = mask_;
channel[1] = mask_;
channel[2] = mask_;
merge(channel, 3, mask3_);
background = background.mul(mask3) +
(background.mul(mask3_)/2 + blurred_img.mul(mask3_)/2);
times[5] += getMilliseconds() - timenow;
timenow = getMilliseconds();
// imshow("background", background);
/*
Moments lol = moments(gray, 1);
circle(image, Point(lol.m10/lol.m00,lol.m01/lol.m00),20,Scalar(128),30);
imshow("leimage", image);
*/
CascadeClassifier mouth_cascade;
mouth_cascade.load("Mouth.xml");
vector<Rect> mouths;
int scale = 3;
Mat classifyThis;
equalizeHist(gray, gray);//ew; watch out not to use this later
resize(gray.mul(mask), classifyThis, Size(width/scale,height/scale));
// bilateralFilter(gray, classifyThis, 15, 10, 1);
mouth_cascade.detectMultiScale(classifyThis, mouths, 1.1, 8, CV_HAAR_SCALE_IMAGE);
for (size_t i=0; i<mouths.size(); i++) {
Rect scaled(mouths[i].x*scale, mouths[i].y*scale, mouths[i].width*scale,mouths[i].height*scale);
rectangle(image, scaled, Scalar(255,0,0));
}
times[6] += getMilliseconds() - timenow;
timenow = getMilliseconds();
imshow("MOUTH", image);
for (int i=0; i<7; i++) {
printf("%llu , ", times[i]);
times[i] = 0;
}
printf("\n");
keepGoing = (waitKey(1)<0);
}
cvReleaseCapture(&capture);
return 0;
}
<|endoftext|> |
<commit_before>#include "webcam.hpp"
using namespace cv;
using namespace std;
int main (int argc, char** argv) {
int tracker1, tracker2, tracker3;
namedWindow("s",1);
createTrackbar("1","s",&tracker1,100);
createTrackbar("2","s",&tracker2,100);
createTrackbar("3","s",&tracker3,100);
CvCapture* capture = 0;
int width, height, fps;
capture = cvCaptureFromCAM(0);
if (!capture) {
printf("No camera detected!");
return -1;
}
ifstream configFile (".config");
if (configFile.is_open()) {
//probably want to support corrupted .config
string line;
getline(configFile, line);
istringstream(line)>>width;
getline(configFile, line);
istringstream(line)>>height;
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, width);
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, height);
configFile.close();
} else {
initResolutions();
for (int i=36; i<150; i++) {
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, resolutions[i].width);
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, resolutions[i].height);
}
width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH);
height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT);
ofstream configFileOut(".config");
configFileOut << width;
configFileOut << "\n";
configFileOut << height;
configFileOut << "\n";
configFileOut.close();
}
bool keepGoing = true;
// srand(890);//not interested in good randomness
for (int i = 0; i < 30; i++) {
// capture some frames so exposure correction takes place
cvQueryFrame(capture);
}
Mat background = cvQueryFrame(capture);
background = background.clone();
blur(background, background, Size(50,50));
imshow("background", background);
Mat image;
Mat channel[3];
while (keepGoing) {
image = cvQueryFrame(capture);
// preprocess by rotating according to OVR roll
imshow("webcam", image);
// let's make multiple masks where 0=not mouth, 1=uncertain
// then multiply them together and multiply that with image
// and run haar classifier on image
Mat gray;
cvtColor(image, gray, CV_RGB2GRAY);
// this mask filters out areas with too many edges
Mat canny;
Canny(gray, canny, 50, 50, 3);
blur(canny, canny, Size(width/20,height/20));
bitwise_not(canny, canny);
threshold(canny, canny, 200, 1, THRESH_BINARY);
blur(canny*255, canny, Size(width/10, height/10));
threshold(canny, canny, 220, 1, THRESH_BINARY);
// this mask filters out areas which have not changed much
// background needs to be updated when person is not in frame
// use OVR SDK to do this later
Mat flow;
blur(image, flow, Size(50,50));
absdiff(flow, background, flow);
cvtColor(flow, flow, CV_RGB2GRAY);
// blur(flow, flow, Size(tracker1+1,tracker1+1));
// equalizeHist(flow, flow);
int factor = (tracker1/5) + 1;
Mat flowKernel = getStructuringElement(MORPH_ELLIPSE,
Size(
width/factor+(1-(width/factor)%2),
height/factor+(1-(height/factor)%2)
)
);
imshow("FLOW1", flow);
waitKey(1);
dilate(flow, flow, flowKernel);
imshow("FLOW1.5", flow);
waitKey(1);
threshold(flow, flow, tracker2*3, 1, THRESH_BINARY);
imshow("FLOW2", gray.mul(flow));
// Moments lol = moments(mask, 1);
// circle(image, Point(lol.m10/lol.m00,lol.m01/lol.m00),20,Scalar(128),30);
// imshow("leimage", image);
/*
CascadeClassifier mouth_cascade;
mouth_cascade.load("Mouth.xml");
vector<Rect> mouths;
Mat classifyThis;
bilateralFilter(gray, classifyThis, 15, 10, 1);
equalizeHist(classifyThis, classifyThis);
classifyThis = classifyThis.mul(mask);
mouth_cascade.detectMultiScale(classifyThis, mouths, 1.1, 2, CV_HAAR_SCALE_IMAGE);
for (size_t i=0; i<mouths.size(); i++) {
Point center( mouths[i].x + mouths[i].width*0.5, mouths[i].y + mouths[i].height*0.5 );
ellipse( image, center, Size( mouths[i].width*0.5, mouths[i].height*0.5), 0, 0, 360, Scalar( 255, 0, 255 ), 4, 8, 0 );
}
imshow("MOUTH", image);
*/
keepGoing = (waitKey(25)<0);
}
cvReleaseCapture(&capture);
return 0;
}
<commit_msg>hacking<commit_after>#include "webcam.hpp"
using namespace cv;
using namespace std;
int main (int argc, char** argv) {
int tracker1, tracker2, tracker3;
namedWindow("s",1);
createTrackbar("1","s",&tracker1,100);
createTrackbar("2","s",&tracker2,100);
createTrackbar("3","s",&tracker3,100);
CvCapture* capture = 0;
int width, height, fps;
capture = cvCaptureFromCAM(0);
if (!capture) {
printf("No camera detected!");
return -1;
}
ifstream configFile (".config");
if (configFile.is_open()) {
//probably want to support corrupted .config
string line;
getline(configFile, line);
istringstream(line)>>width;
getline(configFile, line);
istringstream(line)>>height;
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, width);
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, height);
configFile.close();
} else {
initResolutions();
for (int i=36; i<150; i++) {
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, resolutions[i].width);
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, resolutions[i].height);
}
width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH);
height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT);
ofstream configFileOut(".config");
configFileOut << width;
configFileOut << "\n";
configFileOut << height;
configFileOut << "\n";
configFileOut.close();
}
bool keepGoing = true;
// srand(890);//not interested in good randomness
for (int i = 0; i < 30; i++) {
// capture some frames so exposure correction takes place
cvQueryFrame(capture);
}
Mat background = cvQueryFrame(capture);
background = background.clone();
blur(background, background, Size(50,50));
imshow("background", background);
Mat image;
Mat channel[3];
while (keepGoing) {
image = cvQueryFrame(capture);
// preprocess by rotating according to OVR roll
imshow("webcam", image);
// let's make multiple masks where 0=not mouth, 1=uncertain
// then multiply them together and multiply that with image
// and run haar classifier on image
Mat gray;
cvtColor(image, gray, CV_RGB2GRAY);
// this mask filters out areas with too many edges
Mat canny;
Canny(gray, canny, 50, 50, 3);
blur(canny, canny, Size(width/20,height/20));
bitwise_not(canny, canny);
threshold(canny, canny, 200, 1, THRESH_BINARY);
blur(canny*255, canny, Size(width/10, height/10));
threshold(canny, canny, 220, 1, THRESH_BINARY);
// this mask filters out areas which have not changed much
// background needs to be updated when person is not in frame
// use OVR SDK to do this later
Mat flow;
blur(image, flow, Size(50,50));
absdiff(flow, background, flow);
cvtColor(flow, flow, CV_RGB2GRAY);
// blur(flow, flow, Size(tracker1+1,tracker1+1));
// equalizeHist(flow, flow);
Mat downsample;
resize(flow, downsample, Size(250,250));
int kerSize = tracker1+3-(tracker1%2);
Mat flowKernel = getStructuringElement(MORPH_ELLIPSE,
Size(kerSize,kerSize)
);
imshow("FLOW1", flow);
imshow("RESIZE", downsample);
waitKey(1);
dilate(downsample, downsample, flowKernel);
resize(downsample, flow, Size(width, height));
imshow("FLOW1.5", flow);
waitKey(1);
threshold(flow, flow, tracker2*3, 1, THRESH_BINARY);
imshow("FLOW2", gray.mul(flow));
// Moments lol = moments(mask, 1);
// circle(image, Point(lol.m10/lol.m00,lol.m01/lol.m00),20,Scalar(128),30);
// imshow("leimage", image);
/*
CascadeClassifier mouth_cascade;
mouth_cascade.load("Mouth.xml");
vector<Rect> mouths;
Mat classifyThis;
bilateralFilter(gray, classifyThis, 15, 10, 1);
equalizeHist(classifyThis, classifyThis);
classifyThis = classifyThis.mul(mask);
mouth_cascade.detectMultiScale(classifyThis, mouths, 1.1, 2, CV_HAAR_SCALE_IMAGE);
for (size_t i=0; i<mouths.size(); i++) {
Point center( mouths[i].x + mouths[i].width*0.5, mouths[i].y + mouths[i].height*0.5 );
ellipse( image, center, Size( mouths[i].width*0.5, mouths[i].height*0.5), 0, 0, 360, Scalar( 255, 0, 255 ), 4, 8, 0 );
}
imshow("MOUTH", image);
*/
keepGoing = (waitKey(25)<0);
}
cvReleaseCapture(&capture);
return 0;
}
<|endoftext|> |
<commit_before>#include "diana_runner.hpp"
#include "sophos_runner.hpp"
#include "utility.hpp"
#include <sse/schemes/utils/utils.hpp>
#include <sse/crypto/utils.hpp>
#include <grpc++/create_channel.h>
#include <grpc++/impl/codegen/service_type.h>
#include <grpc++/server_builder.h>
#include <condition_variable>
#include <gtest/gtest.h>
#include <algorithm>
#include <fstream>
#include <functional>
#include <iostream>
#include <map>
#include <memory>
#include <mutex>
#include <thread>
namespace sse {
namespace test {
// The runners class should be as follows
// class SophosRunner
// {
// public:
// using ClientRunner = SophosClientRunner;
// using ServerRunner = SophosServerRunner;
// constexpr auto test_dir;
// constexpr auto server_db_path = SSE_DIANA_TEST_DIR "/server.db";
// constexpr auto client_db_path = SSE_DIANA_TEST_DIR "/client.db";
// constexpr auto server_address = "127.0.0.1:4343";
// }
template<typename Runner>
class RunnerTest : public ::testing::Test
{
public:
using ClientRunner = typename Runner::ClientRunner;
using ServerRunner = typename Runner::ServerRunner;
protected:
void create_client_server()
{
server_.reset(
new ServerRunner(Runner::server_address, Runner::server_db_path));
server_->set_async_search(false);
// Create the channel
std::shared_ptr<grpc::Channel> channel(grpc::CreateChannel(
Runner::server_address, grpc::InsecureChannelCredentials()));
// Create the client
client_.reset(new ClientRunner(channel, Runner::client_db_path));
}
void destroy_client_server()
{
client_.reset(nullptr);
server_->shutdown();
server_.reset(nullptr);
}
virtual void SetUp()
{
sse::test::cleanup_directory(Runner::test_dir);
create_client_server();
}
// You can define per-test tear-down logic as usual.
virtual void TearDown()
{
destroy_client_server();
}
std::unique_ptr<ClientRunner> client_;
std::unique_ptr<ServerRunner> server_;
};
// TYPED_TEST_CASE(RunnerTest);
using RunnerTypes = ::testing::Types<sse::sophos::test::SophosRunner,
sse::diana::test::DianaRunner>;
TYPED_TEST_CASE(RunnerTest, RunnerTypes);
TYPED_TEST(RunnerTest, insertion_search)
{
const std::map<std::string, std::list<uint64_t>> test_db
= {{"kw_1", {0, 1}}, {"kw_2", {0}}, {"kw_3", {0}}};
sse::test::insert_database(this->client_, test_db);
sse::test::test_search_correctness(this->client_, test_db);
}
TYPED_TEST(RunnerTest, start_stop)
{
const std::map<std::string, std::list<uint64_t>> test_db
= {{"kw_1", {0, 1}}, {"kw_2", {0}}, {"kw_3", {0}}};
sse::test::insert_database(this->client_, test_db);
this->destroy_client_server();
this->create_client_server();
sse::test::test_search_correctness(this->client_, test_db);
}
// REGISTER_TYPED_TEST_CASE_P(RunnerTest, insertion_search, start_stop);
} // namespace test
} // namespace sse<commit_msg>Add an asynchronous search test on the runners.<commit_after>#include "diana_runner.hpp"
#include "sophos_runner.hpp"
#include "utility.hpp"
#include <sse/schemes/utils/utils.hpp>
#include <sse/crypto/utils.hpp>
#include <grpc++/create_channel.h>
#include <grpc++/impl/codegen/service_type.h>
#include <grpc++/server_builder.h>
#include <condition_variable>
#include <gtest/gtest.h>
#include <algorithm>
#include <fstream>
#include <functional>
#include <iostream>
#include <map>
#include <memory>
#include <mutex>
#include <thread>
namespace sse {
namespace test {
// The runners class should be as follows
// class SophosRunner
// {
// public:
// using ClientRunner = SophosClientRunner;
// using ServerRunner = SophosServerRunner;
// constexpr auto test_dir;
// constexpr auto server_db_path = SSE_DIANA_TEST_DIR "/server.db";
// constexpr auto client_db_path = SSE_DIANA_TEST_DIR "/client.db";
// constexpr auto server_address = "127.0.0.1:4343";
// }
template<typename Runner>
class RunnerTest : public ::testing::Test
{
public:
using ClientRunner = typename Runner::ClientRunner;
using ServerRunner = typename Runner::ServerRunner;
protected:
void create_client_server()
{
server_.reset(
new ServerRunner(Runner::server_address, Runner::server_db_path));
server_->set_async_search(false);
// Create the channel
std::shared_ptr<grpc::Channel> channel(grpc::CreateChannel(
Runner::server_address, grpc::InsecureChannelCredentials()));
// Create the client
client_.reset(new ClientRunner(channel, Runner::client_db_path));
}
void destroy_client_server()
{
client_.reset(nullptr);
server_->shutdown();
server_.reset(nullptr);
}
virtual void SetUp()
{
sse::test::cleanup_directory(Runner::test_dir);
create_client_server();
}
// You can define per-test tear-down logic as usual.
virtual void TearDown()
{
destroy_client_server();
}
std::unique_ptr<ClientRunner> client_;
std::unique_ptr<ServerRunner> server_;
};
// TYPED_TEST_CASE(RunnerTest);
using RunnerTypes = ::testing::Types<sse::sophos::test::SophosRunner,
sse::diana::test::DianaRunner>;
TYPED_TEST_CASE(RunnerTest, RunnerTypes);
TYPED_TEST(RunnerTest, insertion_search)
{
const std::map<std::string, std::list<uint64_t>> test_db
= {{"kw_1", {0, 1}}, {"kw_2", {0}}, {"kw_3", {0}}};
sse::test::insert_database(this->client_, test_db);
sse::test::test_search_correctness(this->client_, test_db);
}
TYPED_TEST(RunnerTest, start_stop)
{
const std::map<std::string, std::list<uint64_t>> test_db
= {{"kw_1", {0, 1}}, {"kw_2", {0}}, {"kw_3", {0}}};
sse::test::insert_database(this->client_, test_db);
this->destroy_client_server();
this->create_client_server();
sse::test::test_search_correctness(this->client_, test_db);
}
TYPED_TEST(RunnerTest, search_async)
{
this->server_->set_async_search(true);
std::list<uint64_t> long_list;
for (size_t i = 0; i < 1000; i++) {
long_list.push_back(i);
}
const std::string keyword = "kw_1";
const std::map<std::string, std::list<uint64_t>> test_db
= {{keyword, long_list}};
sse::test::insert_database(this->client_, test_db);
sse::test::test_search_correctness(this->client_, test_db);
}
} // namespace test
} // namespace sse<|endoftext|> |
<commit_before>#include <cassert>
#include <iostream>
#include <list>
#include <pqxx/pqxx>
using namespace PGSTD;
using namespace pqxx;
namespace
{
void compare_results(string name, result lhs, result rhs)
{
if (lhs != rhs)
throw logic_error("Executing " + name + " as prepared statement "
"yields different results from direct execution");
if (lhs.empty())
throw logic_error("Results being compared are empty. Not much point!");
}
template<typename STR1, typename STR2>
void cmp_exec(transaction_base &T, string desc, STR1 name, STR2 def)
{
compare_results(desc, T.exec_prepared(name), T.exec(def));
}
string stringize(const string &arg) { return "'" + arg + "'"; }
string stringize(const char arg[]) {return arg?stringize(string(arg)):"null";}
string stringize(char arg[]) {return arg?stringize(string(arg)):"null";}
template<typename T> string stringize(T i) { return stringize(to_string(i)); }
// Substitute variables in raw query. This is not likely to be very robust,
// but it should do for just this test. The main shortcomings are escaping,
// and not knowing when to quote the variables.
// Note we need to do the replacement backwards (meaning forward_only
// iterators won't do!) to avoid substituting "$12" as "$1" first.
template<typename ITER> string subst(string q, ITER patbegin, ITER patend)
{
int i = distance(patbegin, patend);
for (ITER arg = --patend; i > 0; --arg, --i)
{
const string marker = "$" + to_string(i), var = stringize(*arg);
const string::size_type msz = marker.size();
while (q.find(marker) != string::npos) q.replace(q.find(marker),msz,var);
}
return q;
}
template<typename CNTNR> string subst(string q, const CNTNR &patterns)
{
return subst(q, patterns.begin(), patterns.end());
}
template<typename STR1, typename STR2, typename ITER>
void cmp_exec(transaction_base &T,
string desc,
STR1 name,
STR2 def,
ITER argsbegin,
ITER argsend)
{
compare_results(desc,
T.exec_prepared(name, argsbegin, argsend),
T.exec(subst(def, argsbegin, argsend)));
}
template<typename STR1, typename STR2, typename CNTNR>
void cmp_exec(transaction_base &T,
string desc,
STR1 name,
STR2 def,
CNTNR args)
{
compare_results(desc, T.exec_prepared(name,args), T.exec(subst(def,args)));
}
} // namespace
// Test program for libpqxx. Define and use prepared statements.
//
// Usage: test085
int main()
{
try
{
const string QN_readpgtables = "readpgtables",
Q_readpgtables = "SELECT * FROM pg_tables",
QN_seetable = "seetable",
Q_seetable = Q_readpgtables + " WHERE tablename=$1",
QN_seetables = "seetables",
Q_seetables = Q_seetable + " OR tablename=$2";
lazyconnection C;
cout << "Preparing a simple statement..." << endl;
C.prepare(QN_readpgtables, Q_readpgtables);
nontransaction T(C, "test85");
// See if a basic prepared statement runs consistently with a regular query
cout << "Basic correctness check on prepared statement..." << endl;
cmp_exec(T,QN_readpgtables,QN_readpgtables,Q_readpgtables);
// Pro forma check: same thing but with name passed as C-style string
cmp_exec(T,QN_readpgtables+"_char",QN_readpgtables.c_str(),Q_readpgtables);
cout << "Dropping prepared statement..." << endl;
C.unprepare(QN_readpgtables);
// Just to try and confuse things, "unprepare" twice
cout << "Testing error detection and handling..." << endl;
try { C.unprepare(QN_readpgtables); }
catch (const exception &e) { cout << "(Expected) " << e.what() << endl; }
// Verify that attempt to execute unprepared statement fails
bool failsOK = true;
try { T.exec_prepared(QN_readpgtables); failsOK = false; }
catch (const exception &e) { cout << "(Expected) " << e.what() << endl; }
if (!failsOK) throw logic_error("Execute unprepared statement didn't fail");
// Re-prepare the same statement and test again
C.prepare(QN_readpgtables, Q_readpgtables);
cmp_exec(T,QN_readpgtables+"_2", QN_readpgtables, Q_readpgtables);
// Double preparation of identical statement should be ignored...
C.prepare(QN_readpgtables, Q_readpgtables);
cmp_exec(T,QN_readpgtables+"_double", QN_readpgtables, Q_readpgtables);
// ...But a modified definition shouldn't
try
{
failsOK = true;
C.prepare(QN_readpgtables, Q_readpgtables + " ORDER BY tablename");
failsOK = false;
}
catch (const exception &e)
{
cout << "(Expected) " << e.what() << endl;
}
if (!failsOK)
throw logic_error("Bad redefinition of statement went unnoticed");
cout << "Testing parameterized prepared-statement functions..." << endl;
// Try definitions of same statement with empty parameter lists
const list<string> dummy;
C.unprepare(QN_readpgtables);
C.prepare(QN_readpgtables, Q_readpgtables, dummy.begin(), dummy.end());
cmp_exec(T,QN_readpgtables+"_seq", QN_readpgtables, Q_readpgtables);
C.unprepare(QN_readpgtables);
C.prepare(QN_readpgtables, Q_readpgtables, list<string>());
cmp_exec(T,QN_readpgtables+"_cntnr", QN_readpgtables, Q_readpgtables);
// Try executing with empty argument lists
cmp_exec(T,
QN_readpgtables+" with empty argument sequence",
QN_readpgtables,
Q_readpgtables,
dummy.begin(),
dummy.end());
cmp_exec(T,
QN_readpgtables+" with empty argument container",
QN_readpgtables,
Q_readpgtables,
dummy);
cmp_exec(T,
QN_readpgtables+" with empty argument container and char name",
QN_readpgtables.c_str(),
Q_readpgtables,
dummy);
cout << "Testing prepared statement with parameter..." << endl;
list<string> parms, args;
parms.push_back("varchar");
C.prepare(QN_seetable, Q_seetable, parms);
args.push_back("pg_type");
cmp_exec(T,
QN_seetable+"_seq",
QN_seetable,
Q_seetable,
args.begin(),
args.end());
cmp_exec(T, QN_seetable+"_cntnr", QN_seetable, Q_seetable, args);
cout << "Testing prepared statement with 2 parameters..." << endl;
parms.push_back("varchar");
C.prepare(QN_seetables, Q_seetables, parms.begin(), parms.end());
args.push_back("pg_index");
cmp_exec(T,
QN_seetables+"_seq",
QN_seetables,
Q_seetables,
args.begin(),
args.end());
cmp_exec(T, QN_seetables+"_cntnr", QN_seetables, Q_seetables, args);
cout << "Testing prepared statement with a null parameter..." << endl;
vector<const char *> ptrs;
ptrs.push_back(0);
ptrs.push_back("pg_index");
cmp_exec(T, QN_seetables+"_cntnr", QN_seetables, Q_seetables, ptrs);
cout << "Done." << endl;
}
catch (const exception &e)
{
// All exceptions thrown by libpqxx are derived from std::exception
cerr << "Exception: " << e.what() << endl;
return 2;
}
catch (...)
{
// This is really unexpected (see above)
cerr << "Unhandled exception" << endl;
return 100;
}
return 0;
}
<commit_msg>Escape strings before using them in SQL<commit_after>#include <cassert>
#include <iostream>
#include <list>
#include <pqxx/pqxx>
using namespace PGSTD;
using namespace pqxx;
namespace
{
void compare_results(string name, result lhs, result rhs)
{
if (lhs != rhs)
throw logic_error("Executing " + name + " as prepared statement "
"yields different results from direct execution");
if (lhs.empty())
throw logic_error("Results being compared are empty. Not much point!");
}
template<typename STR1, typename STR2>
void cmp_exec(transaction_base &T, string desc, STR1 name, STR2 def)
{
compare_results(desc, T.exec_prepared(name), T.exec(def));
}
string stringize(const string &arg) { return "'" + sqlesc(arg) + "'"; }
string stringize(const char arg[]) {return arg?stringize(string(arg)):"null";}
string stringize(char arg[]) {return arg?stringize(string(arg)):"null";}
template<typename T> string stringize(T i) { return stringize(to_string(i)); }
// Substitute variables in raw query. This is not likely to be very robust,
// but it should do for just this test. The main shortcomings are escaping,
// and not knowing when to quote the variables.
// Note we do the replacement backwards (meaning forward_only iterators won't
// do!) to avoid substituting e.g. "$12" as "$1" first.
template<typename ITER> string subst(string q, ITER patbegin, ITER patend)
{
int i = distance(patbegin, patend);
for (ITER arg = --patend; i > 0; --arg, --i)
{
const string marker = "$" + to_string(i),
var = stringize(*arg);
const string::size_type msz = marker.size();
while (q.find(marker) != string::npos) q.replace(q.find(marker),msz,var);
}
return q;
}
template<typename CNTNR> string subst(string q, const CNTNR &patterns)
{
return subst(q, patterns.begin(), patterns.end());
}
template<typename STR1, typename STR2, typename ITER>
void cmp_exec(transaction_base &T,
string desc,
STR1 name,
STR2 def,
ITER argsbegin,
ITER argsend)
{
compare_results(desc,
T.exec_prepared(name, argsbegin, argsend),
T.exec(subst(def, argsbegin, argsend)));
}
template<typename STR1, typename STR2, typename CNTNR>
void cmp_exec(transaction_base &T,
string desc,
STR1 name,
STR2 def,
CNTNR args)
{
compare_results(desc, T.exec_prepared(name,args), T.exec(subst(def,args)));
}
} // namespace
// Test program for libpqxx. Define and use prepared statements.
//
// Usage: test085
int main()
{
try
{
const string QN_readpgtables = "readpgtables",
Q_readpgtables = "SELECT * FROM pg_tables",
QN_seetable = "seetable",
Q_seetable = Q_readpgtables + " WHERE tablename=$1",
QN_seetables = "seetables",
Q_seetables = Q_seetable + " OR tablename=$2";
lazyconnection C;
cout << "Preparing a simple statement..." << endl;
C.prepare(QN_readpgtables, Q_readpgtables);
nontransaction T(C, "test85");
// See if a basic prepared statement runs consistently with a regular query
cout << "Basic correctness check on prepared statement..." << endl;
cmp_exec(T,QN_readpgtables,QN_readpgtables,Q_readpgtables);
// Pro forma check: same thing but with name passed as C-style string
cmp_exec(T,QN_readpgtables+"_char",QN_readpgtables.c_str(),Q_readpgtables);
cout << "Dropping prepared statement..." << endl;
C.unprepare(QN_readpgtables);
// Just to try and confuse things, "unprepare" twice
cout << "Testing error detection and handling..." << endl;
try { C.unprepare(QN_readpgtables); }
catch (const exception &e) { cout << "(Expected) " << e.what() << endl; }
// Verify that attempt to execute unprepared statement fails
bool failsOK = true;
try { T.exec_prepared(QN_readpgtables); failsOK = false; }
catch (const exception &e) { cout << "(Expected) " << e.what() << endl; }
if (!failsOK) throw logic_error("Execute unprepared statement didn't fail");
// Re-prepare the same statement and test again
C.prepare(QN_readpgtables, Q_readpgtables);
cmp_exec(T,QN_readpgtables+"_2", QN_readpgtables, Q_readpgtables);
// Double preparation of identical statement should be ignored...
C.prepare(QN_readpgtables, Q_readpgtables);
cmp_exec(T,QN_readpgtables+"_double", QN_readpgtables, Q_readpgtables);
// ...But a modified definition shouldn't
try
{
failsOK = true;
C.prepare(QN_readpgtables, Q_readpgtables + " ORDER BY tablename");
failsOK = false;
}
catch (const exception &e)
{
cout << "(Expected) " << e.what() << endl;
}
if (!failsOK)
throw logic_error("Bad redefinition of statement went unnoticed");
cout << "Testing parameterized prepared-statement functions..." << endl;
// Try definitions of same statement with empty parameter lists
const list<string> dummy;
C.unprepare(QN_readpgtables);
C.prepare(QN_readpgtables, Q_readpgtables, dummy.begin(), dummy.end());
cmp_exec(T,QN_readpgtables+"_seq", QN_readpgtables, Q_readpgtables);
C.unprepare(QN_readpgtables);
C.prepare(QN_readpgtables, Q_readpgtables, list<string>());
cmp_exec(T,QN_readpgtables+"_cntnr", QN_readpgtables, Q_readpgtables);
// Try executing with empty argument lists
cmp_exec(T,
QN_readpgtables+" with empty argument sequence",
QN_readpgtables,
Q_readpgtables,
dummy.begin(),
dummy.end());
cmp_exec(T,
QN_readpgtables+" with empty argument container",
QN_readpgtables,
Q_readpgtables,
dummy);
cmp_exec(T,
QN_readpgtables+" with empty argument container and char name",
QN_readpgtables.c_str(),
Q_readpgtables,
dummy);
cout << "Testing prepared statement with parameter..." << endl;
list<string> parms, args;
parms.push_back("varchar");
C.prepare(QN_seetable, Q_seetable, parms);
args.push_back("pg_type");
cmp_exec(T,
QN_seetable+"_seq",
QN_seetable,
Q_seetable,
args.begin(),
args.end());
cmp_exec(T, QN_seetable+"_cntnr", QN_seetable, Q_seetable, args);
cout << "Testing prepared statement with 2 parameters..." << endl;
parms.push_back("varchar");
C.prepare(QN_seetables, Q_seetables, parms.begin(), parms.end());
args.push_back("pg_index");
cmp_exec(T,
QN_seetables+"_seq",
QN_seetables,
Q_seetables,
args.begin(),
args.end());
cmp_exec(T, QN_seetables+"_cntnr", QN_seetables, Q_seetables, args);
cout << "Testing prepared statement with a null parameter..." << endl;
vector<const char *> ptrs;
ptrs.push_back(0);
ptrs.push_back("pg_index");
cmp_exec(T, QN_seetables+"_cntnr", QN_seetables, Q_seetables, ptrs);
cout << "Done." << endl;
}
catch (const exception &e)
{
// All exceptions thrown by libpqxx are derived from std::exception
cerr << "Exception: " << e.what() << endl;
return 2;
}
catch (...)
{
// This is really unexpected (see above)
cerr << "Unhandled exception" << endl;
return 100;
}
return 0;
}
<|endoftext|> |
<commit_before>#include <cassert>
#include <iostream>
#include <list>
#include <pqxx/pqxx>
using namespace PGSTD;
using namespace pqxx;
// Test program for libpqxx. Test binary parameters to prepared statements.
//
// Usage: test092
int main()
{
try
{
const char databuf[] = "Test\0data";
const string data(databuf, sizeof(databuf));
assert(data.size() > strlen(databuf));
const string Table = "pqxxbin", Field = "binfield", Stat = "nully";
lazyconnection C;
work T(C, "test92");
T.exec("CREATE TEMP TABLE " + Table + " (" + Field + " BYTEA)");
if (!C.supports(connection_base::cap_prepared_statements))
{
cout << "Backend version does not support prepared statements. Skipping."
<< endl;
return 0;
}
C.prepare(Stat, "INSERT INTO " + Table + " VALUES ($1)")
("BYTEA", pqxx::prepare::treat_binary);
T.prepared(Stat)(data).exec();
const result L( T.exec("SELECT length("+Field+") FROM " + Table) );
if (L[0][0].as<size_t>() != data.size())
throw logic_error("Inserted " + to_string(data.size()) + " bytes, "
"but " + L[0][0].as<string>() + " arrived");
const result R( T.exec("SELECT " + Field + " FROM " + Table) );
const binarystring roundtrip(R[0][0]);
if (string(roundtrip.str()) != data)
throw logic_error("Sent " + to_string(data.size()) + " bytes "
"of binary data, got " + to_string(roundtrip.size()) + " back: "
"'" + roundtrip.str() + "'");
if (roundtrip.size() != data.size())
throw logic_error("Binary string reports wrong size: " +
to_string(roundtrip.size()) + " "
"(expected " + to_string(data.size()) + ")");
}
catch (const sql_error &e)
{
cerr << "SQL error: " << e.what() << endl
<< "Query was: " << e.query() << endl;
return 1;
}
catch (const exception &e)
{
cerr << "Exception: " << e.what() << endl;
return 2;
}
catch (...)
{
cerr << "Unhandled exception" << endl;
return 100;
}
return 0;
}
<commit_msg>Test "one parameter per line" style of invoking prepared statements<commit_after>#include <cassert>
#include <iostream>
#include <list>
#include <pqxx/pqxx>
using namespace PGSTD;
using namespace pqxx;
// Test program for libpqxx. Test binary parameters to prepared statements.
//
// Usage: test092
int main()
{
try
{
const char databuf[] = "Test\0data";
const string data(databuf, sizeof(databuf));
assert(data.size() > strlen(databuf));
const string Table = "pqxxbin", Field = "binfield", Stat = "nully";
lazyconnection C;
work T(C, "test92");
T.exec("CREATE TEMP TABLE " + Table + " (" + Field + " BYTEA)");
if (!C.supports(connection_base::cap_prepared_statements))
{
cout << "Backend version does not support prepared statements. Skipping."
<< endl;
return 0;
}
C.prepare(Stat, "INSERT INTO " + Table + " VALUES ($1)")
("BYTEA", pqxx::prepare::treat_binary);
T.prepared(Stat)(data).exec();
const result L( T.exec("SELECT length("+Field+") FROM " + Table) );
if (L[0][0].as<size_t>() != data.size())
throw logic_error("Inserted " + to_string(data.size()) + " bytes, "
"but " + L[0][0].as<string>() + " arrived");
const result R( T.exec("SELECT " + Field + " FROM " + Table) );
const binarystring roundtrip(R[0][0]);
if (string(roundtrip.str()) != data)
throw logic_error("Sent " + to_string(data.size()) + " bytes "
"of binary data, got " + to_string(roundtrip.size()) + " back: "
"'" + roundtrip.str() + "'");
if (roundtrip.size() != data.size())
throw logic_error("Binary string reports wrong size: " +
to_string(roundtrip.size()) + " "
"(expected " + to_string(data.size()) + ")");
// People seem to like the multi-line invocation style, where you get your
// invocation object first, then add parameters in separate C++ statements.
// As John Mudd found, that used to break the code. Let's test it.
T.exec("CREATE TEMP TABLE tuple (one INTEGER, two VARCHAR)");
pqxx::prepare::declaration d(
C.prepare("maketuple", "INSERT INTO tuple VALUES ($1, $2)") );
d("INTEGER", pqxx::prepare::treat_direct);
d("VARCHAR", pqxx::prepare::treat_string);
pqxx::prepare::invocation i( T.prepared("maketuple") );
const string f = "frobnalicious";
i(6);
i(f);
i.exec();
const result t( T.exec("SELECT * FROM tuple") );
if (t.size() != 1)
throw logic_error("Expected 1 tuple, got " + to_string(t.size()));
if (t[0][0].as<string>() != "6")
throw logic_error("Expected value 6, got " + t[0][0].as<string>());
if (t[0][1].c_str() != f)
throw logic_error("Expected string '" + f + "', "
"got '" + t[0][1].c_str() + "'");
}
catch (const sql_error &e)
{
cerr << "SQL error: " << e.what() << endl
<< "Query was: " << e.query() << endl;
return 1;
}
catch (const exception &e)
{
cerr << "Exception: " << e.what() << endl;
return 2;
}
catch (...)
{
cerr << "Unhandled exception" << endl;
return 100;
}
return 0;
}
<|endoftext|> |
<commit_before>#include <string>
// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp>
#endif
// Include matrix_transform.hpp .
#ifndef __GLM_GTC_MATRIX_TRANSFORM_HPP_INCLUDED
#define __GLM_GTC_MATRIX_TRANSFORM_HPP_INCLUDED
#include <glm/gtc/matrix_transform.hpp>
#endif
#include "model.hpp"
#include "globals.hpp"
#include "texture.hpp"
#include "bmploader.hpp"
#include "objloader.hpp"
#include "vboindexer.hpp"
#include "controls.hpp"
namespace model
{
Species::Species(SpeciesStruct species_struct)
{
// constructor.
this->model_file_format = species_struct.model_file_format;
this->model_filename = species_struct.model_filename;
this->texture_file_format = species_struct.texture_file_format;
this->texture_filename = species_struct.texture_filename;
this->color_channel = species_struct.color_channel;
this->vertex_shader = species_struct.vertex_shader;
this->fragment_shader = species_struct.fragment_shader;
this->lightPos = species_struct.lightPos;
this->char_model_file_format = this->model_file_format.c_str();
this->char_model_filename = this->model_filename.c_str();
this->char_texture_file_format = this->texture_file_format.c_str();
this->char_texture_filename = this->texture_filename.c_str();
this->char_color_channel = this->color_channel.c_str();
this->char_vertex_shader = this->vertex_shader.c_str();
this->char_fragment_shader = this->fragment_shader.c_str();
// Load the shaders.
this->programID = LoadShaders(this->char_vertex_shader, this->char_fragment_shader);
// Get a handle for our "MVP" uniform
this->MatrixID = glGetUniformLocation(this->programID, "MVP");
this->ViewMatrixID = glGetUniformLocation(this->programID, "V");
this->ModelMatrixID = glGetUniformLocation(this->programID, "M");
// Get a handle for our buffers
this->vertexPosition_modelspaceID = glGetAttribLocation(this->programID, "vertexPosition_modelspace");
this->vertexUVID = glGetAttribLocation(this->programID, "vertexUV");
this->vertexNormal_modelspaceID = glGetAttribLocation(this->programID, "vertexNormal_modelspace");
// Load the texture
if ((strcmp(this->char_texture_file_format, "bmp") == 0) || (strcmp(this->char_texture_file_format, "BMP") == 0))
{
this->texture = texture::loadBMP_custom(this->char_texture_filename);
}
else if ((strcmp(this->char_texture_file_format, "dds") == 0) || (strcmp(this->char_texture_file_format, "DDS") == 0))
{
this->texture = texture::loadDDS(this->char_texture_filename);
}
else
{
std::cerr << "no texture was loaded!\n";
std::cerr << "texture file format: " << this->texture_file_format << "\n";
}
// Get a handle for our "myTextureSampler" uniform
this->textureID = glGetUniformLocation(programID, "myTextureSampler");
bool model_loading_result;
if ((strcmp(this->char_model_file_format, "obj") == 0) || (strcmp(this->char_model_file_format, "OBJ") == 0))
{
model_loading_result = model::load_OBJ(this->char_model_filename, this->vertices, this->UVs, this->normals);
}
else if ((strcmp(this->char_model_file_format, "bmp") == 0) || (strcmp(this->char_model_file_format, "BMP") == 0))
{
model_loading_result = model::load_BMP_world(this->char_model_filename, this->vertices, this->UVs, this->normals, this->color_channel);
}
else
{
std::cerr << "no model was loaded!\n";
std::cerr << "model file format: " << this->model_file_format << "\n";
}
model::indexVBO(this->vertices, this->UVs, this->normals, this->indices, this->indexed_vertices, this->indexed_UVs, this->indexed_normals);
// Load it into a VBO
glGenBuffers(1, &this->vertexbuffer);
glBindBuffer(GL_ARRAY_BUFFER, this->vertexbuffer);
glBufferData(GL_ARRAY_BUFFER, this->indexed_vertices.size() * sizeof(glm::vec3), &this->indexed_vertices[0], GL_STATIC_DRAW);
glGenBuffers(1, &this->uvbuffer);
glBindBuffer(GL_ARRAY_BUFFER, this->uvbuffer);
glBufferData(GL_ARRAY_BUFFER, this->indexed_UVs.size() * sizeof(glm::vec2), &this->indexed_UVs[0], GL_STATIC_DRAW);
glGenBuffers(1, &this->normalbuffer);
glBindBuffer(GL_ARRAY_BUFFER, this->normalbuffer);
glBufferData(GL_ARRAY_BUFFER, this->indexed_normals.size() * sizeof(glm::vec3), &this->indexed_normals[0], GL_STATIC_DRAW);
glGenBuffers(1, &this->elementbuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this->elementbuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, this->indices.size() * sizeof(GLuint), &this->indices[0] , GL_STATIC_DRAW);
// Get a handle for our "LightPosition" uniform
glUseProgram(this->programID);
this->lightID = glGetUniformLocation(this->programID, "LightPosition_worldspace");
}
void Species::render()
{
// Compute the MVP matrix from keyboard and mouse input
controls::computeMatricesFromInputs();
this->ProjectionMatrix = controls::getProjectionMatrix();
this->ViewMatrix = controls::getViewMatrix();
// [re]bind `programID` shader.
glUseProgram(this->programID);
glUniform3f(this->lightID, this->lightPos.x, this->lightPos.y, this->lightPos.z);
glUniformMatrix4fv(this->ViewMatrixID, 1, GL_FALSE, &this->ViewMatrix[0][0]); // This one doesn't change between objects, so this can be done once for all objects that use "programID"
// Bind our texture in Texture Unit 0
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, this->texture);
// Set our "myTextureSampler" sampler to user Texture Unit 0
glUniform1i(this->textureID, 0);
// 1st attribute buffer : vertices
glEnableVertexAttribArray(this->vertexPosition_modelspaceID);
// 2nd attribute buffer : UVs
glEnableVertexAttribArray(this->vertexUVID);
// 3rd attribute buffer : normals
glEnableVertexAttribArray(this->vertexNormal_modelspaceID);
}
Object::Object(ObjectStruct object_struct)
{
// constructor.
this->model_matrix = object_struct.model_matrix;
this->translate_vector = object_struct.translate_vector;
this->species_ptr = static_cast<model::Species*>(object_struct.species_ptr);
bool model_loading_result = false;
}
void Object::render()
{
this->model_matrix = glm::translate(this->model_matrix, this->translate_vector);
this->MVP_matrix = this->species_ptr->ProjectionMatrix * this->species_ptr->ViewMatrix * this->model_matrix;
// Send our transformation to the currently bound shader,
// in the "MVP" uniform
glUniformMatrix4fv(this->species_ptr->MatrixID, 1, GL_FALSE, &this->MVP_matrix[0][0]);
glUniformMatrix4fv(this->species_ptr->ModelMatrixID, 1, GL_FALSE, &this->model_matrix[0][0]);
// 1st attribute buffer : vertices
glBindBuffer(GL_ARRAY_BUFFER, this->species_ptr->vertexbuffer);
glVertexAttribPointer(
this->species_ptr->vertexPosition_modelspaceID, // The attribute we want to configure
3, // size
GL_FLOAT, // type
GL_FALSE, // normalized?
0, // stride
(void*) 0 // array buffer offset
);
// 2nd attribute buffer : UVs
glBindBuffer(GL_ARRAY_BUFFER, this->species_ptr->uvbuffer);
glVertexAttribPointer(
this->species_ptr->vertexUVID, // The attribute we want to configure
2, // size : U+V => 2
GL_FLOAT, // type
GL_FALSE, // normalized?
0, // stride
(void*) 0 // array buffer offset
);
// 3rd attribute buffer : normals
glBindBuffer(GL_ARRAY_BUFFER, this->species_ptr->normalbuffer);
glVertexAttribPointer(
this->species_ptr->vertexNormal_modelspaceID, // The attribute we want to configure
3, // size
GL_FLOAT, // type
GL_FALSE, // normalized?
0, // stride
(void*) 0 // array buffer offset
);
// Index buffer
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this->species_ptr->elementbuffer);
// Draw the triangles!
glDrawElements(
GL_TRIANGLES, // mode
this->species_ptr->indices.size(), // count
GL_UNSIGNED_INT, // type
(void*) 0 // element array buffer offset
);
}
}
<commit_msg>Muokattu kommentteja.<commit_after>#include <string>
// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp>
#endif
// Include matrix_transform.hpp .
#ifndef __GLM_GTC_MATRIX_TRANSFORM_HPP_INCLUDED
#define __GLM_GTC_MATRIX_TRANSFORM_HPP_INCLUDED
#include <glm/gtc/matrix_transform.hpp>
#endif
#include "model.hpp"
#include "globals.hpp"
#include "texture.hpp"
#include "bmploader.hpp"
#include "objloader.hpp"
#include "vboindexer.hpp"
#include "controls.hpp"
namespace model
{
Species::Species(SpeciesStruct species_struct)
{
// constructor.
this->model_file_format = species_struct.model_file_format;
this->model_filename = species_struct.model_filename;
this->texture_file_format = species_struct.texture_file_format;
this->texture_filename = species_struct.texture_filename;
this->color_channel = species_struct.color_channel;
this->vertex_shader = species_struct.vertex_shader;
this->fragment_shader = species_struct.fragment_shader;
this->lightPos = species_struct.lightPos;
this->char_model_file_format = this->model_file_format.c_str();
this->char_model_filename = this->model_filename.c_str();
this->char_texture_file_format = this->texture_file_format.c_str();
this->char_texture_filename = this->texture_filename.c_str();
this->char_color_channel = this->color_channel.c_str();
this->char_vertex_shader = this->vertex_shader.c_str();
this->char_fragment_shader = this->fragment_shader.c_str();
// Create and compile our GLSL program from the shaders
this->programID = LoadShaders(this->char_vertex_shader, this->char_fragment_shader);
// Get a handle for our "MVP" uniform
this->MatrixID = glGetUniformLocation(this->programID, "MVP");
this->ViewMatrixID = glGetUniformLocation(this->programID, "V");
this->ModelMatrixID = glGetUniformLocation(this->programID, "M");
// Get a handle for our buffers
this->vertexPosition_modelspaceID = glGetAttribLocation(this->programID, "vertexPosition_modelspace");
this->vertexUVID = glGetAttribLocation(this->programID, "vertexUV");
this->vertexNormal_modelspaceID = glGetAttribLocation(this->programID, "vertexNormal_modelspace");
// Load the texture
if ((strcmp(this->char_texture_file_format, "bmp") == 0) || (strcmp(this->char_texture_file_format, "BMP") == 0))
{
this->texture = texture::loadBMP_custom(this->char_texture_filename);
}
else if ((strcmp(this->char_texture_file_format, "dds") == 0) || (strcmp(this->char_texture_file_format, "DDS") == 0))
{
this->texture = texture::loadDDS(this->char_texture_filename);
}
else
{
std::cerr << "no texture was loaded!\n";
std::cerr << "texture file format: " << this->texture_file_format << "\n";
}
// Get a handle for our "myTextureSampler" uniform
this->textureID = glGetUniformLocation(programID, "myTextureSampler");
bool model_loading_result;
if ((strcmp(this->char_model_file_format, "obj") == 0) || (strcmp(this->char_model_file_format, "OBJ") == 0))
{
model_loading_result = model::load_OBJ(this->char_model_filename, this->vertices, this->UVs, this->normals);
}
else if ((strcmp(this->char_model_file_format, "bmp") == 0) || (strcmp(this->char_model_file_format, "BMP") == 0))
{
model_loading_result = model::load_BMP_world(this->char_model_filename, this->vertices, this->UVs, this->normals, this->color_channel);
}
else
{
std::cerr << "no model was loaded!\n";
std::cerr << "model file format: " << this->model_file_format << "\n";
}
model::indexVBO(this->vertices, this->UVs, this->normals, this->indices, this->indexed_vertices, this->indexed_UVs, this->indexed_normals);
// Load it into a VBO
glGenBuffers(1, &this->vertexbuffer);
glBindBuffer(GL_ARRAY_BUFFER, this->vertexbuffer);
glBufferData(GL_ARRAY_BUFFER, this->indexed_vertices.size() * sizeof(glm::vec3), &this->indexed_vertices[0], GL_STATIC_DRAW);
glGenBuffers(1, &this->uvbuffer);
glBindBuffer(GL_ARRAY_BUFFER, this->uvbuffer);
glBufferData(GL_ARRAY_BUFFER, this->indexed_UVs.size() * sizeof(glm::vec2), &this->indexed_UVs[0], GL_STATIC_DRAW);
glGenBuffers(1, &this->normalbuffer);
glBindBuffer(GL_ARRAY_BUFFER, this->normalbuffer);
glBufferData(GL_ARRAY_BUFFER, this->indexed_normals.size() * sizeof(glm::vec3), &this->indexed_normals[0], GL_STATIC_DRAW);
glGenBuffers(1, &this->elementbuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this->elementbuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, this->indices.size() * sizeof(GLuint), &this->indices[0] , GL_STATIC_DRAW);
// Get a handle for our "LightPosition" uniform
glUseProgram(this->programID);
this->lightID = glGetUniformLocation(this->programID, "LightPosition_worldspace");
}
void Species::render()
{
// Compute the MVP matrix from keyboard and mouse input
controls::computeMatricesFromInputs();
this->ProjectionMatrix = controls::getProjectionMatrix();
this->ViewMatrix = controls::getViewMatrix();
// [re]bind `programID` shader.
glUseProgram(this->programID);
glUniform3f(this->lightID, this->lightPos.x, this->lightPos.y, this->lightPos.z);
glUniformMatrix4fv(this->ViewMatrixID, 1, GL_FALSE, &this->ViewMatrix[0][0]); // This one doesn't change between objects, so this can be done once for all objects that use "programID"
// Bind our texture in Texture Unit 0
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, this->texture);
// Set our "myTextureSampler" sampler to user Texture Unit 0
glUniform1i(this->textureID, 0);
// 1st attribute buffer : vertices
glEnableVertexAttribArray(this->vertexPosition_modelspaceID);
// 2nd attribute buffer : UVs
glEnableVertexAttribArray(this->vertexUVID);
// 3rd attribute buffer : normals
glEnableVertexAttribArray(this->vertexNormal_modelspaceID);
}
Object::Object(ObjectStruct object_struct)
{
// constructor.
this->model_matrix = object_struct.model_matrix;
this->translate_vector = object_struct.translate_vector;
this->species_ptr = static_cast<model::Species*>(object_struct.species_ptr);
bool model_loading_result = false;
}
void Object::render()
{
this->model_matrix = glm::translate(this->model_matrix, this->translate_vector);
this->MVP_matrix = this->species_ptr->ProjectionMatrix * this->species_ptr->ViewMatrix * this->model_matrix;
// Send our transformation to the currently bound shader,
// in the "MVP" uniform
glUniformMatrix4fv(this->species_ptr->MatrixID, 1, GL_FALSE, &this->MVP_matrix[0][0]);
glUniformMatrix4fv(this->species_ptr->ModelMatrixID, 1, GL_FALSE, &this->model_matrix[0][0]);
// 1st attribute buffer : vertices
glBindBuffer(GL_ARRAY_BUFFER, this->species_ptr->vertexbuffer);
glVertexAttribPointer(
this->species_ptr->vertexPosition_modelspaceID, // The attribute we want to configure
3, // size
GL_FLOAT, // type
GL_FALSE, // normalized?
0, // stride
(void*) 0 // array buffer offset
);
// 2nd attribute buffer : UVs
glBindBuffer(GL_ARRAY_BUFFER, this->species_ptr->uvbuffer);
glVertexAttribPointer(
this->species_ptr->vertexUVID, // The attribute we want to configure
2, // size : U+V => 2
GL_FLOAT, // type
GL_FALSE, // normalized?
0, // stride
(void*) 0 // array buffer offset
);
// 3rd attribute buffer : normals
glBindBuffer(GL_ARRAY_BUFFER, this->species_ptr->normalbuffer);
glVertexAttribPointer(
this->species_ptr->vertexNormal_modelspaceID, // The attribute we want to configure
3, // size
GL_FLOAT, // type
GL_FALSE, // normalized?
0, // stride
(void*) 0 // array buffer offset
);
// Index buffer
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this->species_ptr->elementbuffer);
// Draw the triangles!
glDrawElements(
GL_TRIANGLES, // mode
this->species_ptr->indices.size(), // count
GL_UNSIGNED_INT, // type
(void*) 0 // element array buffer offset
);
}
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <fstream>
#include "../src/MPSegment.hpp"
#include "../src/HMMSegment.hpp"
#include "../src/MixSegment.hpp"
using namespace CppJieba;
void cut(const ISegment * seg, const char * const filePath)
{
ifstream ifile(filePath);
vector<string> res;
string line;
while(getline(ifile, line))
{
if(!line.empty())
{
res.clear();
seg->cut(line, res);
cout<<join(res.begin(), res.end(),"/")<<endl;
}
}
}
const char * const TEST_FILE = "../test/testdata/testlines.utf8";
const char * const JIEBA_DICT_FILE = "../dict/jieba.dict.utf8";
const char * const HMM_DICT_FILE = "../dict/hmm_model.utf8";
int main(int argc, char ** argv)
{
//demo
{
HMMSegment seg(HMM_DICT_FILE);
if(!seg)
{
cout<<"seg init failed."<<endl;
return EXIT_FAILURE;
}
cut(&seg, TEST_FILE);
}
{
MixSegment seg(JIEBA_DICT_FILE, HMM_DICT_FILE);
if(!seg)
{
cout<<"seg init failed."<<endl;
return EXIT_FAILURE;
}
cut(&seg, TEST_FILE);
}
{
MPSegment seg(JIEBA_DICT_FILE);
if(!seg)
{
cout<<"seg init failed."<<endl;
return false;
}
cut(&seg, TEST_FILE);
}
return EXIT_SUCCESS;
}
<commit_msg>modify test demo<commit_after>#include <iostream>
#include <fstream>
#include "../src/MPSegment.hpp"
#include "../src/HMMSegment.hpp"
#include "../src/MixSegment.hpp"
using namespace CppJieba;
void cut(const ISegment * seg, const char * const filePath)
{
ifstream ifile(filePath);
vector<string> res;
string line;
while(getline(ifile, line))
{
if(!line.empty())
{
res.clear();
seg->cut(line, res);
cout<<join(res.begin(), res.end(),"/")<<endl;
}
}
}
const char * const TEST_FILE = "../test/testdata/testlines.utf8";
const char * const JIEBA_DICT_FILE = "../dict/jieba.dict.utf8";
const char * const HMM_DICT_FILE = "../dict/hmm_model.utf8";
int main(int argc, char ** argv)
{
//demo
{
MPSegment seg(JIEBA_DICT_FILE);
if(!seg)
{
cout<<"seg init failed."<<endl;
return false;
}
cut(&seg, TEST_FILE);
}
{
HMMSegment seg(HMM_DICT_FILE);
if(!seg)
{
cout<<"seg init failed."<<endl;
return EXIT_FAILURE;
}
cut(&seg, TEST_FILE);
}
{
MixSegment seg(JIEBA_DICT_FILE, HMM_DICT_FILE);
if(!seg)
{
cout<<"seg init failed."<<endl;
return EXIT_FAILURE;
}
cut(&seg, TEST_FILE);
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>// @(#)root/test:$Name: $:$Id: tcollex.cxx,v 1.2 2000/07/11 18:05:26 rdm Exp $
// Author: Fons Rademakers 19/08/96
#include <stdlib.h>
#include <iostream.h>
#include "TROOT.h"
#include "TString.h"
#include "TObjString.h"
#include "TSortedList.h"
#include "TObjArray.h"
#include "TOrdCollection.h"
#include "THashTable.h"
#include "TBtree.h"
#include "TStopwatch.h"
// To focus on basic collection protocol, this sample program uses
// simple classes inheriting from TObject. One class, TObjString, is a
// collectable string class (a TString wrapped in a TObject) provided
// by the ROOT system. The other class we define below, is an integer
// wrapped in a TObject, just like TObjString.
// TObjNum is a simple container for an integer.
class TObjNum : public TObject {
private:
int num;
public:
TObjNum(int i = 0) : num(i) { }
~TObjNum() { Printf("~TObjNum = %d", num); }
void SetNum(int i) { num = i; }
int GetNum() { return num; }
void Print(Option_t *) const { Printf("TObjNum = %d", num); }
ULong_t Hash() const { return num; }
Bool_t IsEqual(const TObject *obj) const { return num == ((TObjNum*)obj)->num; }
Bool_t IsSortable() const { return kTRUE; }
Int_t Compare(const TObject *obj) const { if (num > ((TObjNum*)obj)->num)
return 1;
else if (num < ((TObjNum*)obj)->num)
return -1;
else
return 0; }
};
void Test_TObjArray()
{
Printf(
"////////////////////////////////////////////////////////////////\n"
"// Test of TObjArray //\n"
"////////////////////////////////////////////////////////////////"
);
// Array of capacity 10, Add() will automatically expand the array if necessary.
TObjArray a(10);
Printf("Filling TObjArray");
a.Add(new TObjNum(1)); // add at next free slot, pos 0
a[1] = new TObjNum(2); // use operator[], put at pos 1
TObjNum *n3 = new TObjNum(3);
a.AddAt(n3,2); // add at position 2
a.Add(new TObjNum(4)); // add at next free slot, pos 3
a.AddLast(new TObjNum(10)); // add at pos 4
TObjNum n6(6); // stack based TObjNum
a.AddAt(&n6,5); // add at pos 5
a[6] = new TObjNum(5); // add at respective positions
a[7] = new TObjNum(8);
a[8] = new TObjNum(7);
// a[10] = &n6; // gives out-of-bound error
Printf("Print array");
a.Print(); // invoke Print() of all objects
Printf("Sort array");
a.Sort();
for (int i = 0; i < a.Capacity(); i++) // typical way of iterating over array
if (a[i])
a[i]->Print(); // can also use operator[] to access elements
else
Printf("%d empty slot", i);
Printf("Use binary search to get position of number 6");
Printf("6 is at position %d", a.BinarySearch(&n6));
Printf("Find number before 6");
a.Before(&n6)->Print();
Printf("Find number after 3");
a.After(n3)->Print();
Printf("Remove 3 and print list again");
a.Remove(n3);
delete n3;
a.Print();
Printf("Iterate forward over list and remove 4 and 7");
// TIter encapsulates the actual class iterator. The type of iterator
// used depends on the type of the collection.
TIter next(&a);
TObjNum *obj;
while ((obj = (TObjNum*)next())) // iterator skips empty slots
if (obj->GetNum() == 4) {
a.Remove(obj);
delete obj;
}
// Reset the iterator and loop again
next.Reset();
while ((obj = (TObjNum*)next()))
if (obj->GetNum() == 7) {
a.Remove(obj);
delete obj;
}
Printf("Iterate backward over list and remove 2");
TIter next1(&a, kIterBackward);
while ((obj = (TObjNum*)next1()))
if (obj->GetNum() == 2) {
a.Remove(obj);
delete obj;
}
Printf("Delete remainder of list: 1,5,8,10 (6 not deleted since not on heap)");
// Delete heap objects and clear list. Attention: do this only when you
// own all objects stored in the collection. When you stored aliases to
// the actual objects (i.e. you did not create the objects) use Clear()
// instead.
a.Delete();
Printf("Delete stack based objects (6)");
}
void Test_TOrdCollection()
{
Printf(
"////////////////////////////////////////////////////////////////\n"
"// Test of TOrdCollection //\n"
"////////////////////////////////////////////////////////////////"
);
// Create collection with default size, Add() will automatically expand
// the collection if necessary.
TOrdCollection c;
Printf("Filling TOrdCollection");
c.Add(new TObjString("anton")); // add at next free slot, pos 0
c.AddFirst(new TObjString("bobo")); // put at pos 0, bump anton to pos 1
TObjString *s3 = new TObjString("damon");
c.AddAt(s3,1); // add at position 1, bump anton to pos 2
c.Add(new TObjString("cassius")); // add at next free slot, pos 3
c.AddLast(new TObjString("enigma")); // add at pos 4
TObjString s6("fons"); // stack based TObjString
c.AddBefore(s3,&s6); // add at pos 1
c.AddAfter(s3, new TObjString("gaia"));
Printf("Print collection");
c.Print(); // invoke Print() of all objects
Printf("Sort collection");
c.Sort();
c.Print();
Printf("Use binary search to get position of string damon");
Printf("damon is at position %d", c.BinarySearch(s3));
Printf("Find str before fons");
c.Before(&s6)->Print();
Printf("Find string after damon");
c.After(s3)->Print();
Printf("Remove damon and print list again");
c.Remove(s3);
delete s3;
c.Print();
Printf("Iterate forward over list and remove cassius");
TObjString *objs;
TIter next(&c);
while ((objs = (TObjString*)next())) // iterator skips empty slots
if (objs->String() == "cassius") {
c.Remove(objs);
delete objs;
}
Printf("Iterate backward over list and remove gaia");
TIter next1(&c, kIterBackward);
while ((objs = (TObjString*)next1()))
if (objs->String() == "gaia") {
c.Remove(objs);
delete objs;
}
Printf("Delete remainder of list: anton,bobo,enigma (fons not deleted since not on heap)");
c.Delete(); // delete heap objects and clear list
Printf("Delete stack based objects (fons)");
}
void Test_TList()
{
Printf(
"////////////////////////////////////////////////////////////////\n"
"// Test of TList //\n"
"////////////////////////////////////////////////////////////////"
);
// Create a doubly linked list.
TList l;
Printf("Filling TList");
TObjNum *n3 = new TObjNum(3);
l.Add(n3);
l.AddBefore(n3, new TObjNum(5));
l.AddAfter(n3, new TObjNum(2));
l.Add(new TObjNum(1));
l.AddBefore(n3, new TObjNum(4));
TObjNum n6(6); // stack based TObjNum
l.AddFirst(&n6);
Printf("Print list");
l.Print();
Printf("Remove 3 and print list again");
l.Remove(n3);
delete n3;
l.Print();
Printf("Iterate forward over list and remove 4");
TObjNum *obj;
TIter next(&l);
while ((obj = (TObjNum*)next()))
if (obj->GetNum() == 4) l.Remove(obj);
Printf("Iterate backward over list and remove 2");
TIter next1(&l, kIterBackward);
while ((obj = (TObjNum*)next1()))
if (obj->GetNum() == 2) {
l.Remove(obj);
delete obj;
}
Printf("Delete remainder of list: 1, 5 (6 not deleted since not on heap)");
l.Delete();
Printf("Delete stack based objects (6)");
}
void Test_TSortedList()
{
Printf(
"////////////////////////////////////////////////////////////////\n"
"// Test of TSortedList //\n"
"////////////////////////////////////////////////////////////////"
);
// Create a sorted doubly linked list.
TSortedList sl;
Printf("Filling TSortedList");
TObjNum *n3 = new TObjNum(3);
sl.Add(n3);
sl.AddBefore(n3,new TObjNum(5));
sl.AddAfter(n3, new TObjNum(2));
sl.Add(new TObjNum(1));
sl.AddBefore(n3, new TObjNum(4));
TObjNum n6(6); // stack based TObjNum
sl.AddFirst(&n6);
Printf("Print list");
sl.Print();
Printf("Delete all heap based objects (6 not deleted since not on heap)");
sl.Delete();
Printf("Delete stack based objects (6)");
}
void Test_THashTable()
{
Printf(
"////////////////////////////////////////////////////////////////\n"
"// Test of THashTable //\n"
"////////////////////////////////////////////////////////////////"
);
int i;
// Create a hash table with an initial size of 20 (actually the next prime
// above 20). No automatic rehashing.
THashTable ht(20);
Printf("Filling THashTable");
Printf("Number of slots before filling: %d", ht.Capacity());
for (i = 0; i < 1000; i++)
ht.Add(new TObject);
Printf("Average collisions: %f", ht.AverageCollisions());
// rehash the hash table to reduce the collission rate
ht.Rehash(ht.GetSize());
Printf("Number of slots after rehash: %d", ht.Capacity());
Printf("Average collisions after rehash: %f", ht.AverageCollisions());
ht.Delete();
// Create a hash table and trigger automatic rehashing when average
// collision rate becomes larger than 5.
THashTable ht2(20,5);
Printf("Filling THashTable with automatic rehash when AverageCollisions>5");
Printf("Number of slots before filling: %d", ht2.Capacity());
for (i = 0; i < 1000; i++)
ht2.Add(new TObject);
Printf("Number of slots after filling: %d", ht2.Capacity());
Printf("Average collisions: %f", ht2.AverageCollisions());
Printf("\nDelete all heap based objects");
ht2.Delete();
}
void Test_TBtree()
{
Printf(
"////////////////////////////////////////////////////////////////\n"
"// Test of TBtree //\n"
"////////////////////////////////////////////////////////////////"
);
TStopwatch timer; // create a timer
TBtree l; // btree of order 3
Printf("Filling TBtree");
TObjNum *n3 = new TObjNum(3);
l.Add(n3);
l.AddBefore(n3,new TObjNum(5));
l.AddAfter(n3, new TObjNum(2));
l.Add(new TObjNum(1));
l.AddBefore(n3, new TObjNum(4));
TObjNum n6(6); // stack based TObjNum
l.AddFirst(&n6);
timer.Start();
for (int i = 0; i < 50; i++)
l.Add(new TObjNum(i));
timer.Print();
Printf("Print TBtree");
l.Print();
Printf("Remove 3 and print TBtree again");
l.Remove(n3);
l.Print();
Printf("Iterate forward over TBtree and remove 4 from tree");
TIter next(&l);
TObjNum *obj;
while ((obj = (TObjNum*)next()))
if (obj->GetNum() == 4) l.Remove(obj);
Printf("Iterate backward over TBtree and remove 2 from tree");
TIter next1(&l, kIterBackward);
while ((obj = (TObjNum*)next1()))
if (obj->GetNum() == 2) l.Remove(obj);
Printf("\nDelete all heap based objects");
l.Delete();
Printf("Delete stack based objects (6)");
}
int main()
{
// Initialize the ROOT framework
TROOT tcollex("Collection", "Test collection classes");
Test_TObjArray();
Test_TOrdCollection();
Test_TList();
Test_TSortedList();
Test_THashTable();
Test_TBtree();
return 0;
}
<commit_msg>minimal formatting change.<commit_after>// @(#)root/test:$Name: $:$Id: tcollex.cxx,v 1.3 2000/12/14 13:52:27 brun Exp $
// Author: Fons Rademakers 19/08/96
#include <stdlib.h>
#include <iostream.h>
#include "TROOT.h"
#include "TString.h"
#include "TObjString.h"
#include "TSortedList.h"
#include "TObjArray.h"
#include "TOrdCollection.h"
#include "THashTable.h"
#include "TBtree.h"
#include "TStopwatch.h"
// To focus on basic collection protocol, this sample program uses
// simple classes inheriting from TObject. One class, TObjString, is a
// collectable string class (a TString wrapped in a TObject) provided
// by the ROOT system. The other class we define below, is an integer
// wrapped in a TObject, just like TObjString.
// TObjNum is a simple container for an integer.
class TObjNum : public TObject {
private:
int num;
public:
TObjNum(int i = 0) : num(i) { }
~TObjNum() { Printf("~TObjNum = %d", num); }
void SetNum(int i) { num = i; }
int GetNum() { return num; }
void Print(Option_t *) const { Printf("TObjNum = %d", num); }
ULong_t Hash() const { return num; }
Bool_t IsEqual(const TObject *obj) const { return num == ((TObjNum*)obj)->num; }
Bool_t IsSortable() const { return kTRUE; }
Int_t Compare(const TObject *obj) const { if (num > ((TObjNum*)obj)->num)
return 1;
else if (num < ((TObjNum*)obj)->num)
return -1;
else
return 0; }
};
void Test_TObjArray()
{
Printf(
"////////////////////////////////////////////////////////////////\n"
"// Test of TObjArray //\n"
"////////////////////////////////////////////////////////////////"
);
// Array of capacity 10, Add() will automatically expand the array if necessary.
TObjArray a(10);
Printf("Filling TObjArray");
a.Add(new TObjNum(1)); // add at next free slot, pos 0
a[1] = new TObjNum(2); // use operator[], put at pos 1
TObjNum *n3 = new TObjNum(3);
a.AddAt(n3,2); // add at position 2
a.Add(new TObjNum(4)); // add at next free slot, pos 3
a.AddLast(new TObjNum(10)); // add at pos 4
TObjNum n6(6); // stack based TObjNum
a.AddAt(&n6,5); // add at pos 5
a[6] = new TObjNum(5); // add at respective positions
a[7] = new TObjNum(8);
a[8] = new TObjNum(7);
// a[10] = &n6; // gives out-of-bound error
Printf("Print array");
a.Print(); // invoke Print() of all objects
Printf("Sort array");
a.Sort();
for (int i = 0; i < a.Capacity(); i++) // typical way of iterating over array
if (a[i])
a[i]->Print(); // can also use operator[] to access elements
else
Printf("%d empty slot", i);
Printf("Use binary search to get position of number 6");
Printf("6 is at position %d", a.BinarySearch(&n6));
Printf("Find number before 6");
a.Before(&n6)->Print();
Printf("Find number after 3");
a.After(n3)->Print();
Printf("Remove 3 and print list again");
a.Remove(n3);
delete n3;
a.Print();
Printf("Iterate forward over list and remove 4 and 7");
// TIter encapsulates the actual class iterator. The type of iterator
// used depends on the type of the collection.
TIter next(&a);
TObjNum *obj;
while ((obj = (TObjNum*)next())) // iterator skips empty slots
if (obj->GetNum() == 4) {
a.Remove(obj);
delete obj;
}
// Reset the iterator and loop again
next.Reset();
while ((obj = (TObjNum*)next()))
if (obj->GetNum() == 7) {
a.Remove(obj);
delete obj;
}
Printf("Iterate backward over list and remove 2");
TIter next1(&a, kIterBackward);
while ((obj = (TObjNum*)next1()))
if (obj->GetNum() == 2) {
a.Remove(obj);
delete obj;
}
Printf("Delete remainder of list: 1,5,8,10 (6 not deleted since not on heap)");
// Delete heap objects and clear list. Attention: do this only when you
// own all objects stored in the collection. When you stored aliases to
// the actual objects (i.e. you did not create the objects) use Clear()
// instead.
a.Delete();
Printf("Delete stack based objects (6)");
}
void Test_TOrdCollection()
{
Printf(
"////////////////////////////////////////////////////////////////\n"
"// Test of TOrdCollection //\n"
"////////////////////////////////////////////////////////////////"
);
// Create collection with default size, Add() will automatically expand
// the collection if necessary.
TOrdCollection c;
Printf("Filling TOrdCollection");
c.Add(new TObjString("anton")); // add at next free slot, pos 0
c.AddFirst(new TObjString("bobo")); // put at pos 0, bump anton to pos 1
TObjString *s3 = new TObjString("damon");
c.AddAt(s3,1); // add at position 1, bump anton to pos 2
c.Add(new TObjString("cassius")); // add at next free slot, pos 3
c.AddLast(new TObjString("enigma")); // add at pos 4
TObjString s6("fons"); // stack based TObjString
c.AddBefore(s3,&s6); // add at pos 1
c.AddAfter(s3, new TObjString("gaia"));
Printf("Print collection");
c.Print(); // invoke Print() of all objects
Printf("Sort collection");
c.Sort();
c.Print();
Printf("Use binary search to get position of string damon");
Printf("damon is at position %d", c.BinarySearch(s3));
Printf("Find str before fons");
c.Before(&s6)->Print();
Printf("Find string after damon");
c.After(s3)->Print();
Printf("Remove damon and print list again");
c.Remove(s3);
delete s3;
c.Print();
Printf("Iterate forward over list and remove cassius");
TObjString *objs;
TIter next(&c);
while ((objs = (TObjString*)next())) // iterator skips empty slots
if (objs->String() == "cassius") {
c.Remove(objs);
delete objs;
}
Printf("Iterate backward over list and remove gaia");
TIter next1(&c, kIterBackward);
while ((objs = (TObjString*)next1()))
if (objs->String() == "gaia") {
c.Remove(objs);
delete objs;
}
Printf("Delete remainder of list: anton,bobo,enigma (fons not deleted since not on heap)");
c.Delete(); // delete heap objects and clear list
Printf("Delete stack based objects (fons)");
}
void Test_TList()
{
Printf(
"////////////////////////////////////////////////////////////////\n"
"// Test of TList //\n"
"////////////////////////////////////////////////////////////////"
);
// Create a doubly linked list.
TList l;
Printf("Filling TList");
TObjNum *n3 = new TObjNum(3);
l.Add(n3);
l.AddBefore(n3, new TObjNum(5));
l.AddAfter(n3, new TObjNum(2));
l.Add(new TObjNum(1));
l.AddBefore(n3, new TObjNum(4));
TObjNum n6(6); // stack based TObjNum
l.AddFirst(&n6);
Printf("Print list");
l.Print();
Printf("Remove 3 and print list again");
l.Remove(n3);
delete n3;
l.Print();
Printf("Iterate forward over list and remove 4");
TObjNum *obj;
TIter next(&l);
while ((obj = (TObjNum*)next()))
if (obj->GetNum() == 4) l.Remove(obj);
Printf("Iterate backward over list and remove 2");
TIter next1(&l, kIterBackward);
while ((obj = (TObjNum*)next1()))
if (obj->GetNum() == 2) {
l.Remove(obj);
delete obj;
}
Printf("Delete remainder of list: 1, 5 (6 not deleted since not on heap)");
l.Delete();
Printf("Delete stack based objects (6)");
}
void Test_TSortedList()
{
Printf(
"////////////////////////////////////////////////////////////////\n"
"// Test of TSortedList //\n"
"////////////////////////////////////////////////////////////////"
);
// Create a sorted doubly linked list.
TSortedList sl;
Printf("Filling TSortedList");
TObjNum *n3 = new TObjNum(3);
sl.Add(n3);
sl.AddBefore(n3,new TObjNum(5));
sl.AddAfter(n3, new TObjNum(2));
sl.Add(new TObjNum(1));
sl.AddBefore(n3, new TObjNum(4));
TObjNum n6(6); // stack based TObjNum
sl.AddFirst(&n6);
Printf("Print list");
sl.Print();
Printf("Delete all heap based objects (6 not deleted since not on heap)");
sl.Delete();
Printf("Delete stack based objects (6)");
}
void Test_THashTable()
{
Printf(
"////////////////////////////////////////////////////////////////\n"
"// Test of THashTable //\n"
"////////////////////////////////////////////////////////////////"
);
int i;
// Create a hash table with an initial size of 20 (actually the next prime
// above 20). No automatic rehashing.
THashTable ht(20);
Printf("Filling THashTable");
Printf("Number of slots before filling: %d", ht.Capacity());
for (i = 0; i < 1000; i++)
ht.Add(new TObject);
Printf("Average collisions: %f", ht.AverageCollisions());
// rehash the hash table to reduce the collission rate
ht.Rehash(ht.GetSize());
Printf("Number of slots after rehash: %d", ht.Capacity());
Printf("Average collisions after rehash: %f", ht.AverageCollisions());
ht.Delete();
// Create a hash table and trigger automatic rehashing when average
// collision rate becomes larger than 5.
THashTable ht2(20,5);
Printf("Filling THashTable with automatic rehash when AverageCollisions>5");
Printf("Number of slots before filling: %d", ht2.Capacity());
for (i = 0; i < 1000; i++)
ht2.Add(new TObject);
Printf("Number of slots after filling: %d", ht2.Capacity());
Printf("Average collisions: %f", ht2.AverageCollisions());
Printf("\nDelete all heap based objects");
ht2.Delete();
}
void Test_TBtree()
{
Printf(
"////////////////////////////////////////////////////////////////\n"
"// Test of TBtree //\n"
"////////////////////////////////////////////////////////////////"
);
TStopwatch timer; // create a timer
TBtree l; // btree of order 3
Printf("Filling TBtree");
TObjNum *n3 = new TObjNum(3);
l.Add(n3);
l.AddBefore(n3,new TObjNum(5));
l.AddAfter(n3, new TObjNum(2));
l.Add(new TObjNum(1));
l.AddBefore(n3, new TObjNum(4));
TObjNum n6(6); // stack based TObjNum
l.AddFirst(&n6);
timer.Start();
for (int i = 0; i < 50; i++)
l.Add(new TObjNum(i));
timer.Print();
Printf("Print TBtree");
l.Print();
Printf("Remove 3 and print TBtree again");
l.Remove(n3);
l.Print();
Printf("Iterate forward over TBtree and remove 4 from tree");
TIter next(&l);
TObjNum *obj;
while ((obj = (TObjNum*)next()))
if (obj->GetNum() == 4) l.Remove(obj);
Printf("Iterate backward over TBtree and remove 2 from tree");
TIter next1(&l, kIterBackward);
while ((obj = (TObjNum*)next1()))
if (obj->GetNum() == 2) l.Remove(obj);
Printf("\nDelete all heap based objects");
l.Delete();
Printf("Delete stack based objects (6)");
}
int main()
{
// Initialize the ROOT framework
TROOT tcollex("Collection", "Test collection classes");
Test_TObjArray();
Test_TOrdCollection();
Test_TList();
Test_TSortedList();
Test_THashTable();
Test_TBtree();
return 0;
}
<|endoftext|> |
<commit_before>#include <cassert>
#include <iostream>
#include <list>
#include <pqxx/pqxx>
#include <pqxx/compiler-internal.hxx>
using namespace PGSTD;
using namespace pqxx;
namespace
{
#ifndef PQXX_HAVE_DISTANCE
template<typename ITERATOR> size_t distance(ITERATOR begin, ITERATOR end)
{
size_t d = 0;
while (begin != end)
{
++begin;
++d;
}
}
#endif // PQXX_HAVE_DISTANCE
void compare_results(string name, result lhs, result rhs)
{
if (lhs != rhs)
throw logic_error("Executing " + name + " as prepared statement "
"yields different results from direct execution");
if (lhs.empty())
throw logic_error("Results being compared are empty. Not much point!");
}
string stringize(transaction_base &t, const string &arg)
{
return "'" + t.esc(arg) + "'";
}
string stringize(transaction_base &t, const char arg[])
{
return arg ? stringize(t,string(arg)) : "null";
}
string stringize(transaction_base &t, char arg[])
{
return arg ? stringize(t, string(arg)) : "null";
}
template<typename T> string stringize(transaction_base &t, T i)
{
return stringize(t, to_string(i));
}
// Substitute variables in raw query. This is not likely to be very robust,
// but it should do for just this test. The main shortcomings are escaping,
// and not knowing when to quote the variables.
// Note we do the replacement backwards (meaning forward_only iterators won't
// do!) to avoid substituting e.g. "$12" as "$1" first.
template<typename ITER> string subst(transaction_base &t,
string q,
ITER patbegin,
ITER patend)
{
int i = distance(patbegin, patend);
for (ITER arg = patend; i > 0; --i)
{
--arg;
const string marker = "$" + to_string(i),
var = stringize(t, *arg);
const string::size_type msz = marker.size();
while (q.find(marker) != string::npos) q.replace(q.find(marker),msz,var);
}
return q;
}
template<typename CNTNR> string subst(transaction_base &t,
string q,
const CNTNR &patterns)
{
return subst(t, q, patterns.begin(), patterns.end());
}
} // namespace
// Test program for libpqxx. Define and use prepared statements.
//
// Usage: test085
int main()
{
try
{
/* A bit of nastiness in prepared statements: on 7.3.x backends we can't
* compare pg_tables.tablename to a string. We work around this by using
* the LIKE operator.
*
* Later backend versions do not suffer from this problem.
*/
const string QN_readpgtables = "ReadPGTables",
Q_readpgtables = "SELECT * FROM pg_tables",
QN_seetable = "SeeTable",
Q_seetable = Q_readpgtables + " WHERE tablename LIKE $1",
QN_seetables = "SeeTables",
Q_seetables = Q_seetable + " OR tablename LIKE $2";
lazyconnection C;
cout << "Preparing a simple statement..." << endl;
C.prepare(QN_readpgtables, Q_readpgtables);
nontransaction T(C, "test85");
try
{
// See if a basic prepared statement works just like a regular query
cout << "Basic correctness check on prepared statement..." << endl;
compare_results(QN_readpgtables,
T.prepared(QN_readpgtables).exec(),
T.exec(Q_readpgtables));
}
catch (const exception &)
{
if (!C.supports(connection_base::cap_prepared_statements))
{
cout << "Backend version does not support prepared statements. "
"Skipping."
<< endl;
return 0;
}
throw;
}
// Try prepare_now() on an already prepared statement
C.prepare_now(QN_readpgtables);
// Pro forma check: same thing but with name passed as C-style string
compare_results(QN_readpgtables+"_char",
T.prepared(QN_readpgtables.c_str()).exec(),
T.exec(Q_readpgtables));
cout << "Dropping prepared statement..." << endl;
C.unprepare(QN_readpgtables);
bool failed = true;
try
{
disable_noticer d(C);
C.prepare_now(QN_readpgtables);
failed = false;
}
catch (const exception &e)
{
cout << "(Expected) " << e.what() << endl;
}
if (!failed)
throw runtime_error("prepare_now() succeeded on dropped statement");
// Just to try and confuse things, "unprepare" twice
cout << "Testing error detection and handling..." << endl;
try { C.unprepare(QN_readpgtables); }
catch (const exception &e) { cout << "(Expected) " << e.what() << endl; }
// Verify that attempt to execute unprepared statement fails
bool failsOK = true;
try { T.prepared(QN_readpgtables).exec(); failsOK = false; }
catch (const exception &e) { cout << "(Expected) " << e.what() << endl; }
if (!failsOK) throw logic_error("Execute unprepared statement didn't fail");
// Re-prepare the same statement and test again
C.prepare(QN_readpgtables, Q_readpgtables);
C.prepare_now(QN_readpgtables);
compare_results(QN_readpgtables+"_2",
T.prepared(QN_readpgtables).exec(),
T.exec(Q_readpgtables));
// Double preparation of identical statement should be ignored...
C.prepare(QN_readpgtables, Q_readpgtables);
compare_results(QN_readpgtables+"_double",
T.prepared(QN_readpgtables).exec(),
T.exec(Q_readpgtables));
// ...But a modified definition shouldn't
try
{
failsOK = true;
C.prepare(QN_readpgtables, Q_readpgtables + " ORDER BY tablename");
failsOK = false;
}
catch (const exception &e)
{
cout << "(Expected) " << e.what() << endl;
}
if (!failsOK)
throw logic_error("Bad redefinition of statement went unnoticed");
cout << "Testing prepared statement with parameter..." << endl;
C.prepare(QN_seetable, Q_seetable)("varchar", pqxx::prepare::treat_string);
vector<string> args;
args.push_back("pg_type");
compare_results(QN_seetable+"_seq",
T.prepared(QN_seetable)(args[0]).exec(),
T.exec(subst(T,Q_seetable,args)));
cout << "Testing prepared statement with 2 parameters..." << endl;
C.prepare(QN_seetables, Q_seetables)
("varchar",pqxx::prepare::treat_string)
("varchar",pqxx::prepare::treat_string);
args.push_back("pg_index");
compare_results(QN_seetables+"_seq",
T.prepared(QN_seetables)(args[0])(args[1]).exec(),
T.exec(subst(T,Q_seetables,args)));
cout << "Testing prepared statement with a null parameter..." << endl;
vector<const char *> ptrs;
ptrs.push_back(0);
ptrs.push_back("pg_index");
compare_results(QN_seetables+"_null1",
T.prepared(QN_seetables)(ptrs[0])(ptrs[1]).exec(),
T.exec(subst(T,Q_seetables,ptrs)));
compare_results(QN_seetables+"_null2",
T.prepared(QN_seetables)(ptrs[0])(ptrs[1]).exec(),
T.prepared(QN_seetables)()(ptrs[1]).exec());
compare_results(QN_seetables+"_null3",
T.prepared(QN_seetables)(ptrs[0])(ptrs[1]).exec(),
T.prepared(QN_seetables)("somestring",false)(ptrs[1]).exec());
compare_results(QN_seetables+"_null4",
T.prepared(QN_seetables)(ptrs[0])(ptrs[1]).exec(),
T.prepared(QN_seetables)(42,false)(ptrs[1]).exec());
compare_results(QN_seetables+"_null5",
T.prepared(QN_seetables)(ptrs[0])(ptrs[1]).exec(),
T.prepared(QN_seetables)(0,false)(ptrs[1]).exec());
cout << "Testing wrong numbers of parameters..." << endl;
try
{
failsOK = true;
T.prepared(QN_seetables)()()("hi mom!").exec();
failsOK = false;
}
catch (const exception &e)
{
cout << "(Expected) " << e.what() << endl;
}
if (!failsOK)
throw logic_error("No error for too many parameters");
try
{
failsOK = true;
T.prepared(QN_seetables)("who, me?").exec();
failsOK = false;
}
catch (const exception &e)
{
cout << "(Expected) " << e.what() << endl;
}
if (!failsOK)
throw logic_error("No error for too few parameters");
cout << "Done." << endl;
}
catch (const feature_not_supported &e)
{
cout << "Backend version does not support prepared statements. Skipping."
<< endl;
return 0;
}
catch (const sql_error &e)
{
cerr << "SQL error: " << e.what() << endl
<< "Query was: " << e.query() << endl;
return 1;
}
catch (const exception &e)
{
// All exceptions thrown by libpqxx are derived from std::exception
cerr << "Exception: " << e.what() << endl;
return 2;
}
catch (...)
{
// This is really unexpected (see above)
cerr << "Unhandled exception" << endl;
return 100;
}
return 0;
}
<commit_msg>Oops, missing return.<commit_after>#include <cassert>
#include <iostream>
#include <list>
#include <pqxx/pqxx>
#include <pqxx/compiler-internal.hxx>
using namespace PGSTD;
using namespace pqxx;
namespace
{
#ifndef PQXX_HAVE_DISTANCE
template<typename ITERATOR> size_t distance(ITERATOR begin, ITERATOR end)
{
size_t d = 0;
while (begin != end)
{
++begin;
++d;
}
return d;
}
#endif // PQXX_HAVE_DISTANCE
void compare_results(string name, result lhs, result rhs)
{
if (lhs != rhs)
throw logic_error("Executing " + name + " as prepared statement "
"yields different results from direct execution");
if (lhs.empty())
throw logic_error("Results being compared are empty. Not much point!");
}
string stringize(transaction_base &t, const string &arg)
{
return "'" + t.esc(arg) + "'";
}
string stringize(transaction_base &t, const char arg[])
{
return arg ? stringize(t,string(arg)) : "null";
}
string stringize(transaction_base &t, char arg[])
{
return arg ? stringize(t, string(arg)) : "null";
}
template<typename T> string stringize(transaction_base &t, T i)
{
return stringize(t, to_string(i));
}
// Substitute variables in raw query. This is not likely to be very robust,
// but it should do for just this test. The main shortcomings are escaping,
// and not knowing when to quote the variables.
// Note we do the replacement backwards (meaning forward_only iterators won't
// do!) to avoid substituting e.g. "$12" as "$1" first.
template<typename ITER> string subst(transaction_base &t,
string q,
ITER patbegin,
ITER patend)
{
int i = distance(patbegin, patend);
for (ITER arg = patend; i > 0; --i)
{
--arg;
const string marker = "$" + to_string(i),
var = stringize(t, *arg);
const string::size_type msz = marker.size();
while (q.find(marker) != string::npos) q.replace(q.find(marker),msz,var);
}
return q;
}
template<typename CNTNR> string subst(transaction_base &t,
string q,
const CNTNR &patterns)
{
return subst(t, q, patterns.begin(), patterns.end());
}
} // namespace
// Test program for libpqxx. Define and use prepared statements.
//
// Usage: test085
int main()
{
try
{
/* A bit of nastiness in prepared statements: on 7.3.x backends we can't
* compare pg_tables.tablename to a string. We work around this by using
* the LIKE operator.
*
* Later backend versions do not suffer from this problem.
*/
const string QN_readpgtables = "ReadPGTables",
Q_readpgtables = "SELECT * FROM pg_tables",
QN_seetable = "SeeTable",
Q_seetable = Q_readpgtables + " WHERE tablename LIKE $1",
QN_seetables = "SeeTables",
Q_seetables = Q_seetable + " OR tablename LIKE $2";
lazyconnection C;
cout << "Preparing a simple statement..." << endl;
C.prepare(QN_readpgtables, Q_readpgtables);
nontransaction T(C, "test85");
try
{
// See if a basic prepared statement works just like a regular query
cout << "Basic correctness check on prepared statement..." << endl;
compare_results(QN_readpgtables,
T.prepared(QN_readpgtables).exec(),
T.exec(Q_readpgtables));
}
catch (const exception &)
{
if (!C.supports(connection_base::cap_prepared_statements))
{
cout << "Backend version does not support prepared statements. "
"Skipping."
<< endl;
return 0;
}
throw;
}
// Try prepare_now() on an already prepared statement
C.prepare_now(QN_readpgtables);
// Pro forma check: same thing but with name passed as C-style string
compare_results(QN_readpgtables+"_char",
T.prepared(QN_readpgtables.c_str()).exec(),
T.exec(Q_readpgtables));
cout << "Dropping prepared statement..." << endl;
C.unprepare(QN_readpgtables);
bool failed = true;
try
{
disable_noticer d(C);
C.prepare_now(QN_readpgtables);
failed = false;
}
catch (const exception &e)
{
cout << "(Expected) " << e.what() << endl;
}
if (!failed)
throw runtime_error("prepare_now() succeeded on dropped statement");
// Just to try and confuse things, "unprepare" twice
cout << "Testing error detection and handling..." << endl;
try { C.unprepare(QN_readpgtables); }
catch (const exception &e) { cout << "(Expected) " << e.what() << endl; }
// Verify that attempt to execute unprepared statement fails
bool failsOK = true;
try { T.prepared(QN_readpgtables).exec(); failsOK = false; }
catch (const exception &e) { cout << "(Expected) " << e.what() << endl; }
if (!failsOK) throw logic_error("Execute unprepared statement didn't fail");
// Re-prepare the same statement and test again
C.prepare(QN_readpgtables, Q_readpgtables);
C.prepare_now(QN_readpgtables);
compare_results(QN_readpgtables+"_2",
T.prepared(QN_readpgtables).exec(),
T.exec(Q_readpgtables));
// Double preparation of identical statement should be ignored...
C.prepare(QN_readpgtables, Q_readpgtables);
compare_results(QN_readpgtables+"_double",
T.prepared(QN_readpgtables).exec(),
T.exec(Q_readpgtables));
// ...But a modified definition shouldn't
try
{
failsOK = true;
C.prepare(QN_readpgtables, Q_readpgtables + " ORDER BY tablename");
failsOK = false;
}
catch (const exception &e)
{
cout << "(Expected) " << e.what() << endl;
}
if (!failsOK)
throw logic_error("Bad redefinition of statement went unnoticed");
cout << "Testing prepared statement with parameter..." << endl;
C.prepare(QN_seetable, Q_seetable)("varchar", pqxx::prepare::treat_string);
vector<string> args;
args.push_back("pg_type");
compare_results(QN_seetable+"_seq",
T.prepared(QN_seetable)(args[0]).exec(),
T.exec(subst(T,Q_seetable,args)));
cout << "Testing prepared statement with 2 parameters..." << endl;
C.prepare(QN_seetables, Q_seetables)
("varchar",pqxx::prepare::treat_string)
("varchar",pqxx::prepare::treat_string);
args.push_back("pg_index");
compare_results(QN_seetables+"_seq",
T.prepared(QN_seetables)(args[0])(args[1]).exec(),
T.exec(subst(T,Q_seetables,args)));
cout << "Testing prepared statement with a null parameter..." << endl;
vector<const char *> ptrs;
ptrs.push_back(0);
ptrs.push_back("pg_index");
compare_results(QN_seetables+"_null1",
T.prepared(QN_seetables)(ptrs[0])(ptrs[1]).exec(),
T.exec(subst(T,Q_seetables,ptrs)));
compare_results(QN_seetables+"_null2",
T.prepared(QN_seetables)(ptrs[0])(ptrs[1]).exec(),
T.prepared(QN_seetables)()(ptrs[1]).exec());
compare_results(QN_seetables+"_null3",
T.prepared(QN_seetables)(ptrs[0])(ptrs[1]).exec(),
T.prepared(QN_seetables)("somestring",false)(ptrs[1]).exec());
compare_results(QN_seetables+"_null4",
T.prepared(QN_seetables)(ptrs[0])(ptrs[1]).exec(),
T.prepared(QN_seetables)(42,false)(ptrs[1]).exec());
compare_results(QN_seetables+"_null5",
T.prepared(QN_seetables)(ptrs[0])(ptrs[1]).exec(),
T.prepared(QN_seetables)(0,false)(ptrs[1]).exec());
cout << "Testing wrong numbers of parameters..." << endl;
try
{
failsOK = true;
T.prepared(QN_seetables)()()("hi mom!").exec();
failsOK = false;
}
catch (const exception &e)
{
cout << "(Expected) " << e.what() << endl;
}
if (!failsOK)
throw logic_error("No error for too many parameters");
try
{
failsOK = true;
T.prepared(QN_seetables)("who, me?").exec();
failsOK = false;
}
catch (const exception &e)
{
cout << "(Expected) " << e.what() << endl;
}
if (!failsOK)
throw logic_error("No error for too few parameters");
cout << "Done." << endl;
}
catch (const feature_not_supported &e)
{
cout << "Backend version does not support prepared statements. Skipping."
<< endl;
return 0;
}
catch (const sql_error &e)
{
cerr << "SQL error: " << e.what() << endl
<< "Query was: " << e.query() << endl;
return 1;
}
catch (const exception &e)
{
// All exceptions thrown by libpqxx are derived from std::exception
cerr << "Exception: " << e.what() << endl;
return 2;
}
catch (...)
{
// This is really unexpected (see above)
cerr << "Unhandled exception" << endl;
return 100;
}
return 0;
}
<|endoftext|> |
<commit_before>/**
* @cond ___LICENSE___
*
* Copyright (c) 2016 Koen Visscher, Paul Visscher and individual contributors.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @endcond
*/
#include "helper.h"
TEST( Mat, ConstructVec )
{
::Mat m( std::vector< std::vector< double > > { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } } );
EXPECT_EQ( 3, m.GetData().size() );
EXPECT_EQ( 3, m.GetData()[0].size() );
EXPECT_DOUBLE_EQ( 1, m.GetData()[0][0] );
EXPECT_DOUBLE_EQ( 2, m.GetData()[0][1] );
EXPECT_DOUBLE_EQ( 3, m.GetData()[0][2] );
EXPECT_EQ( 3, m.GetData()[1].size() );
EXPECT_DOUBLE_EQ( 4, m.GetData()[1][0] );
EXPECT_DOUBLE_EQ( 5, m.GetData()[1][1] );
EXPECT_DOUBLE_EQ( 6, m.GetData()[1][2] );
EXPECT_EQ( 3, m.GetData()[2].size() );
EXPECT_DOUBLE_EQ( 7, m.GetData()[2][0] );
EXPECT_DOUBLE_EQ( 8, m.GetData()[2][1] );
EXPECT_DOUBLE_EQ( 9, m.GetData()[2][2] );
EXPECT_EQ( 0, m.GetStrings().size() );
EXPECT_EQ( m.GetData().size(), m.GetSize() );
std::pair< size_t, size_t > dim = { 3, 3 };
EXPECT_EQ( dim, m.GetDimension() );
}
TEST( Mat, ConstructInit )
{
::Mat m( { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } } );
EXPECT_EQ( 3, m.GetData().size() );
EXPECT_EQ( 3, m.GetData()[0].size() );
EXPECT_DOUBLE_EQ( 1, m.GetData()[0][0] );
EXPECT_DOUBLE_EQ( 2, m.GetData()[0][1] );
EXPECT_DOUBLE_EQ( 3, m.GetData()[0][2] );
EXPECT_EQ( 3, m.GetData()[1].size() );
EXPECT_DOUBLE_EQ( 4, m.GetData()[1][0] );
EXPECT_DOUBLE_EQ( 5, m.GetData()[1][1] );
EXPECT_DOUBLE_EQ( 6, m.GetData()[1][2] );
EXPECT_EQ( 3, m.GetData()[2].size() );
EXPECT_DOUBLE_EQ( 7, m.GetData()[2][0] );
EXPECT_DOUBLE_EQ( 8, m.GetData()[2][1] );
EXPECT_DOUBLE_EQ( 9, m.GetData()[2][2] );
EXPECT_EQ( 0, m.GetStrings().size() );
EXPECT_EQ( m.GetData().size(), m.GetSize() );
std::pair< size_t, size_t > dim = { 3, 3 };
EXPECT_EQ( dim, m.GetDimension() );
}
TEST( Mat, ConstructArma )
{
::Mat m( mat{ { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } } );
EXPECT_EQ( 3, m.GetData().size() );
EXPECT_EQ( 3, m.GetData()[0].size() );
EXPECT_DOUBLE_EQ( 1, m.GetData()[0][0] );
EXPECT_DOUBLE_EQ( 2, m.GetData()[0][1] );
EXPECT_DOUBLE_EQ( 3, m.GetData()[0][2] );
EXPECT_EQ( 3, m.GetData()[1].size() );
EXPECT_DOUBLE_EQ( 4, m.GetData()[1][0] );
EXPECT_DOUBLE_EQ( 5, m.GetData()[1][1] );
EXPECT_DOUBLE_EQ( 6, m.GetData()[1][2] );
EXPECT_EQ( 3, m.GetData()[2].size() );
EXPECT_DOUBLE_EQ( 7, m.GetData()[2][0] );
EXPECT_DOUBLE_EQ( 8, m.GetData()[2][1] );
EXPECT_DOUBLE_EQ( 9, m.GetData()[2][2] );
EXPECT_EQ( 0, m.GetStrings().size() );
EXPECT_EQ( m.GetData().size(), m.GetSize() );
std::pair< size_t, size_t > dim = { 3, 3 };
EXPECT_EQ( dim, m.GetDimension() );
}
TEST( Mat, ConstructArma2 )
{
::Mat m( mat{ { 1, 2, 3 }, { 4, 5, 6 } } );
EXPECT_EQ( 2, m.GetData().size() );
EXPECT_EQ( 3, m.GetData()[0].size() );
EXPECT_DOUBLE_EQ( 1, m.GetData()[0][0] );
EXPECT_DOUBLE_EQ( 2, m.GetData()[0][1] );
EXPECT_DOUBLE_EQ( 3, m.GetData()[0][2] );
EXPECT_EQ( 3, m.GetData()[1].size() );
EXPECT_DOUBLE_EQ( 4, m.GetData()[1][0] );
EXPECT_DOUBLE_EQ( 5, m.GetData()[1][1] );
}
TEST( Mat, ConstructStr )
{
::Mat m( { { "1", "2", "3" }, { "4", "5", "6" }, { "7", "8", "9" } } );
EXPECT_EQ( 3, m.GetStrings().size() );
EXPECT_EQ( 3, m.GetStrings()[0].size() );
EXPECT_EQ( "1", m.GetStrings()[0][0] );
EXPECT_EQ( "2", m.GetStrings()[0][1] );
EXPECT_EQ( "3", m.GetStrings()[0][2] );
EXPECT_EQ( 3, m.GetStrings()[1].size() );
EXPECT_EQ( "4", m.GetStrings()[1][0] );
EXPECT_EQ( "5", m.GetStrings()[1][1] );
EXPECT_EQ( "6", m.GetStrings()[1][2] );
EXPECT_EQ( 3, m.GetStrings()[2].size() );
EXPECT_EQ( "7", m.GetStrings()[2][0] );
EXPECT_EQ( "8", m.GetStrings()[2][1] );
EXPECT_EQ( "9", m.GetStrings()[2][2] );
EXPECT_EQ( 0, m.GetData().size() );
EXPECT_EQ( m.GetStrings().size(), m.GetSize() );
std::pair< size_t, size_t > dim = { 3, 3 };
EXPECT_EQ( dim, m.GetDimension() );
}
TEST( Mat, ConstructMap )
{
::Mat m( { { 1, 2, 3 }, { 1, 2, 3 }, { 1, 2, 3 } },
{ { 1, "1" }, { 2, "2" }, { 3, "3" } } );
EXPECT_EQ( 3, m.GetStrings().size() );
EXPECT_EQ( 3, m.GetStrings()[0].size() );
EXPECT_EQ( "1", m.GetStrings()[0][0] );
EXPECT_EQ( "2", m.GetStrings()[0][1] );
EXPECT_EQ( "3", m.GetStrings()[0][2] );
EXPECT_EQ( 3, m.GetStrings()[1].size() );
EXPECT_EQ( "1", m.GetStrings()[1][0] );
EXPECT_EQ( "2", m.GetStrings()[1][1] );
EXPECT_EQ( "3", m.GetStrings()[1][2] );
EXPECT_EQ( 3, m.GetStrings()[2].size() );
EXPECT_EQ( "1", m.GetStrings()[2][0] );
EXPECT_EQ( "2", m.GetStrings()[2][1] );
EXPECT_EQ( "3", m.GetStrings()[2][2] );
EXPECT_EQ( 0, m.GetData().size() );
EXPECT_EQ( m.GetStrings().size(), m.GetSize() );
std::pair< size_t, size_t > dim = { 3, 3 };
EXPECT_EQ( dim, m.GetDimension() );
}
template< typename tT >
void PreventOptimisation( tT func )
{
func();
}
TEST( Mat, ConstructVecCheckDim )
{
EXPECT_DEATH( PreventOptimisation( []()
{
::Mat m( std::vector< std::vector< double > > { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8 } } );
EXPECT_EQ( std::vector< std::vector< std::string > > {{""}}, m.GetStrings() );
} ), "== size" );
}
TEST( Mat, ConstructInitCheckDim )
{
EXPECT_DEATH( PreventOptimisation( []()
{
::Mat m( { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8 } } );
EXPECT_EQ( std::vector< std::vector< std::string > > { {""} }, m.GetStrings() );
} ), "== size" );
}
TEST( Mat, ConstructStrCheckDim )
{
EXPECT_DEATH( PreventOptimisation( []()
{
::Mat m( { { "1", "2", "3" }, { "4", "5", "6" }, { "7", "8" } } );
EXPECT_EQ( std::vector< std::vector< std::string > > { {""} }, m.GetStrings() );
} ), "== size" );
}
TEST( Mat, ConstructMapCheckDim )
{
EXPECT_DEATH( PreventOptimisation( []()
{
::Mat m( { {1, 2, 3}, {1, 2, 3}, {1, 2} },
{ {1, "1"}, {2, "2"}, {3, "3"} } );
EXPECT_EQ( std::vector< std::vector< std::string > > { {""} }, m.GetStrings() );
} ), "== size" );
}<commit_msg>Volatile declaration<commit_after>/**
* @cond ___LICENSE___
*
* Copyright (c) 2016 Koen Visscher, Paul Visscher and individual contributors.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @endcond
*/
#include "helper.h"
TEST( Mat, ConstructVec )
{
::Mat m( std::vector< std::vector< double > > { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } } );
EXPECT_EQ( 3, m.GetData().size() );
EXPECT_EQ( 3, m.GetData()[0].size() );
EXPECT_DOUBLE_EQ( 1, m.GetData()[0][0] );
EXPECT_DOUBLE_EQ( 2, m.GetData()[0][1] );
EXPECT_DOUBLE_EQ( 3, m.GetData()[0][2] );
EXPECT_EQ( 3, m.GetData()[1].size() );
EXPECT_DOUBLE_EQ( 4, m.GetData()[1][0] );
EXPECT_DOUBLE_EQ( 5, m.GetData()[1][1] );
EXPECT_DOUBLE_EQ( 6, m.GetData()[1][2] );
EXPECT_EQ( 3, m.GetData()[2].size() );
EXPECT_DOUBLE_EQ( 7, m.GetData()[2][0] );
EXPECT_DOUBLE_EQ( 8, m.GetData()[2][1] );
EXPECT_DOUBLE_EQ( 9, m.GetData()[2][2] );
EXPECT_EQ( 0, m.GetStrings().size() );
EXPECT_EQ( m.GetData().size(), m.GetSize() );
std::pair< size_t, size_t > dim = { 3, 3 };
EXPECT_EQ( dim, m.GetDimension() );
}
TEST( Mat, ConstructInit )
{
::Mat m( { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } } );
EXPECT_EQ( 3, m.GetData().size() );
EXPECT_EQ( 3, m.GetData()[0].size() );
EXPECT_DOUBLE_EQ( 1, m.GetData()[0][0] );
EXPECT_DOUBLE_EQ( 2, m.GetData()[0][1] );
EXPECT_DOUBLE_EQ( 3, m.GetData()[0][2] );
EXPECT_EQ( 3, m.GetData()[1].size() );
EXPECT_DOUBLE_EQ( 4, m.GetData()[1][0] );
EXPECT_DOUBLE_EQ( 5, m.GetData()[1][1] );
EXPECT_DOUBLE_EQ( 6, m.GetData()[1][2] );
EXPECT_EQ( 3, m.GetData()[2].size() );
EXPECT_DOUBLE_EQ( 7, m.GetData()[2][0] );
EXPECT_DOUBLE_EQ( 8, m.GetData()[2][1] );
EXPECT_DOUBLE_EQ( 9, m.GetData()[2][2] );
EXPECT_EQ( 0, m.GetStrings().size() );
EXPECT_EQ( m.GetData().size(), m.GetSize() );
std::pair< size_t, size_t > dim = { 3, 3 };
EXPECT_EQ( dim, m.GetDimension() );
}
TEST( Mat, ConstructArma )
{
::Mat m( mat{ { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } } );
EXPECT_EQ( 3, m.GetData().size() );
EXPECT_EQ( 3, m.GetData()[0].size() );
EXPECT_DOUBLE_EQ( 1, m.GetData()[0][0] );
EXPECT_DOUBLE_EQ( 2, m.GetData()[0][1] );
EXPECT_DOUBLE_EQ( 3, m.GetData()[0][2] );
EXPECT_EQ( 3, m.GetData()[1].size() );
EXPECT_DOUBLE_EQ( 4, m.GetData()[1][0] );
EXPECT_DOUBLE_EQ( 5, m.GetData()[1][1] );
EXPECT_DOUBLE_EQ( 6, m.GetData()[1][2] );
EXPECT_EQ( 3, m.GetData()[2].size() );
EXPECT_DOUBLE_EQ( 7, m.GetData()[2][0] );
EXPECT_DOUBLE_EQ( 8, m.GetData()[2][1] );
EXPECT_DOUBLE_EQ( 9, m.GetData()[2][2] );
EXPECT_EQ( 0, m.GetStrings().size() );
EXPECT_EQ( m.GetData().size(), m.GetSize() );
std::pair< size_t, size_t > dim = { 3, 3 };
EXPECT_EQ( dim, m.GetDimension() );
}
TEST( Mat, ConstructArma2 )
{
::Mat m( mat{ { 1, 2, 3 }, { 4, 5, 6 } } );
EXPECT_EQ( 2, m.GetData().size() );
EXPECT_EQ( 3, m.GetData()[0].size() );
EXPECT_DOUBLE_EQ( 1, m.GetData()[0][0] );
EXPECT_DOUBLE_EQ( 2, m.GetData()[0][1] );
EXPECT_DOUBLE_EQ( 3, m.GetData()[0][2] );
EXPECT_EQ( 3, m.GetData()[1].size() );
EXPECT_DOUBLE_EQ( 4, m.GetData()[1][0] );
EXPECT_DOUBLE_EQ( 5, m.GetData()[1][1] );
}
TEST( Mat, ConstructStr )
{
::Mat m( { { "1", "2", "3" }, { "4", "5", "6" }, { "7", "8", "9" } } );
EXPECT_EQ( 3, m.GetStrings().size() );
EXPECT_EQ( 3, m.GetStrings()[0].size() );
EXPECT_EQ( "1", m.GetStrings()[0][0] );
EXPECT_EQ( "2", m.GetStrings()[0][1] );
EXPECT_EQ( "3", m.GetStrings()[0][2] );
EXPECT_EQ( 3, m.GetStrings()[1].size() );
EXPECT_EQ( "4", m.GetStrings()[1][0] );
EXPECT_EQ( "5", m.GetStrings()[1][1] );
EXPECT_EQ( "6", m.GetStrings()[1][2] );
EXPECT_EQ( 3, m.GetStrings()[2].size() );
EXPECT_EQ( "7", m.GetStrings()[2][0] );
EXPECT_EQ( "8", m.GetStrings()[2][1] );
EXPECT_EQ( "9", m.GetStrings()[2][2] );
EXPECT_EQ( 0, m.GetData().size() );
EXPECT_EQ( m.GetStrings().size(), m.GetSize() );
std::pair< size_t, size_t > dim = { 3, 3 };
EXPECT_EQ( dim, m.GetDimension() );
}
TEST( Mat, ConstructMap )
{
::Mat m( { { 1, 2, 3 }, { 1, 2, 3 }, { 1, 2, 3 } },
{ { 1, "1" }, { 2, "2" }, { 3, "3" } } );
EXPECT_EQ( 3, m.GetStrings().size() );
EXPECT_EQ( 3, m.GetStrings()[0].size() );
EXPECT_EQ( "1", m.GetStrings()[0][0] );
EXPECT_EQ( "2", m.GetStrings()[0][1] );
EXPECT_EQ( "3", m.GetStrings()[0][2] );
EXPECT_EQ( 3, m.GetStrings()[1].size() );
EXPECT_EQ( "1", m.GetStrings()[1][0] );
EXPECT_EQ( "2", m.GetStrings()[1][1] );
EXPECT_EQ( "3", m.GetStrings()[1][2] );
EXPECT_EQ( 3, m.GetStrings()[2].size() );
EXPECT_EQ( "1", m.GetStrings()[2][0] );
EXPECT_EQ( "2", m.GetStrings()[2][1] );
EXPECT_EQ( "3", m.GetStrings()[2][2] );
EXPECT_EQ( 0, m.GetData().size() );
EXPECT_EQ( m.GetStrings().size(), m.GetSize() );
std::pair< size_t, size_t > dim = { 3, 3 };
EXPECT_EQ( dim, m.GetDimension() );
}
template< typename tT >
void PreventOptimisation( tT func )
{
func();
}
TEST( Mat, ConstructVecCheckDim )
{
EXPECT_DEATH( PreventOptimisation( []()
{
volatile ::Mat m( std::vector< std::vector< double > > { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8 } } );
} ), "== size" );
}
TEST( Mat, ConstructInitCheckDim )
{
EXPECT_DEATH( PreventOptimisation( []()
{
volatile ::Mat m( { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8 } } );
} ), "== size" );
}
TEST( Mat, ConstructStrCheckDim )
{
EXPECT_DEATH( PreventOptimisation( []()
{
volatile ::Mat m( { { "1", "2", "3" }, { "4", "5", "6" }, { "7", "8" } } );
} ), "== size" );
}
TEST( Mat, ConstructMapCheckDim )
{
EXPECT_DEATH( PreventOptimisation( []()
{
volatile ::Mat m( { {1, 2, 3}, {1, 2, 3}, {1, 2} },
{ {1, "1"}, {2, "2"}, {3, "3"} } );
} ), "== size" );
}<|endoftext|> |
<commit_before>#ifndef __MODEL_HPP_INCLUDED
#define __MODEL_HPP_INCLUDED
// Include GLEW
#ifndef __GL_GLEW_H_INCLUDED
#define __GL_GLEW_H_INCLUDED
#include <GL/glew.h>
#endif
// Include GLFW
#ifndef __GLFW3_H_INCLUDED
#define __GLFW3_H_INCLUDED
#include <glfw3.h>
#endif
// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp>
#endif
#include <iostream>
#include <queue> // std::queue
#include <string.h>
#include "globals.hpp"
#include "shader.hpp"
#include "heightmap_loader.hpp"
#include "objloader.hpp"
namespace model
{
class World
{
public:
// constructor.
World();
// destructor.
~World();
// this method renders the entire world, one shader at a time.
void render();
// this method sets a shader pointer.
void set_shader_pointer(GLuint shaderID, void* shader_pointer);
// this method gets a shader pointer.
void* get_shader_pointer(GLuint shaderID);
// this method sets a texture pointer.
void set_texture_pointer(GLuint textureID, void* texture_pointer);
// this method gets a texture pointer.
void* get_texture_pointer(GLuint textureID);
// this method gets a shader ID and removes it from the `free_shaderID_queue` if it was popped from the queue.
GLuint get_shaderID();
// this method gets a texture ID and removes it from the `free_textureID_queue` if it was popped from the queue.
GLuint get_textureID();
private:
std::vector<void*> shader_pointer_vector;
std::queue<GLuint> free_shaderID_queue;
std::vector<void*> texture_pointer_vector;
std::queue<GLuint> free_textureID_queue;
};
class Shader
{
public:
// constructor.
Shader(ShaderStruct shader_struct);
// destructor.
~Shader();
// this method renders all species using this shader.
void render();
// this method sets a species pointer.
void set_pointer(GLuint speciesID, void* species_pointer);
// this method gets a species pointer.
void* get_pointer(GLuint speciesID);
// this method gets a species ID and removes it from the `free_speciesID_queue` if it was popped from the queue.
GLuint get_speciesID();
// this method sets pointer to this shader to NULL, sets `world_pointer` according to the input, and requests a new `shaderID` from the new world.
void switch_to_new_world(model::World *new_world_pointer);
model::World *world_pointer; // pointer to the world.
GLuint shaderID; // shader ID, returned by `model::World->get_shaderID()`.
std::string vertex_shader; // filename of vertex shader.
std::string fragment_shader; // filename of fragment shader.
GLuint programID; // shaders' programID, returned by `LoadShaders`.
private:
std::vector<void*> species_pointer_vector;
std::queue<GLuint> free_speciesID_queue;
const char *char_vertex_shader;
const char *char_fragment_shader;
};
class Texture
{
public:
// constructor.
Texture(TextureStruct texture_struct);
// destructor.
~Texture();
// this method sets a species pointer.
void set_pointer(GLuint speciesID, void* species_pointer);
// this method gets a species pointer.
void* get_pointer(GLuint speciesID);
// this method gets a species ID and removes it from the `free_speciesID_queue` if it was popped from the queue.
GLuint get_speciesID();
// this method sets pointer to this shader to NULL, sets `world_pointer` according to the input, and requests a new `shaderID` from the new world.
void switch_to_new_world(model::World *new_world_pointer);
model::World *world_pointer; // pointer to the world.
GLuint textureID; // texture ID, returned by `glGetUniformLocation(programID, "myTextureSampler");`.
private:
std::vector<void*> species_pointer_vector;
std::queue<GLuint> free_speciesID_queue;
std::string texture_file_format; // type of the model file, eg. `"bmp"`.
std::string texture_filename; // filename of the model file.
const char *char_texture_file_format;
const char *char_texture_filename;
};
class Graph
{
public:
// constructor.
Graph();
// destructor.
~Graph();
// this method sets a node pointer.
void set_pointer(GLuint nodeID, void* node_pointer);
// this method gets a node pointer.
void* get_pointer(GLuint nodeID);
// this method gets a node ID and removes it from the `free_nodeID_queue` if it was popped from the queue.
GLuint get_nodeID();
private:
std::vector<void*> node_pointer_vector;
std::queue<GLuint> free_nodeID_queue;
};
// `Node` is not a subclass of `Graph` because if the graph splits, node may be transferred to an another graph.
// Transferring a node to a new graph naturally requires appropriate reindexing of `nodeID`s.
// The graph in which a node belongs is accessible through `void* graph_pointer` (must be cast to `model::Graph*`).
class Node
{
public:
// constructor.
Node(NodeStruct node_struct);
// destructor.
~Node();
// this method creates a bidirectional link.
// creating of bidirectional links is not possible before all nodes are created.
void create_bidirectional_link(GLuint nodeID);
// this method deletes a bidirectional link.
// deleting of links is not possible before all nodes are created.
void delete_bidirectional_link(GLuint nodeID);
// this method transfers this node to a new graph.
// links will not be changed.
// all nodes that are to be transferred must be transferred separately.
// before transfering any node to a new graph,
// all links to nodes that do not belong to the new graph of this node must be deleted with separate `delete_bidirectional_link` calls.
void transfer_to_new_graph(model::Graph *new_graph_pointer);
GLuint nodeID;
model::Graph *graph_pointer;
// nodes do not keep pointers to neighbor nodes, because all pointer values are not known yet before all nodes are created.
std::vector<GLuint> neighbor_nodeIDs;
private:
// this method creates an unidirectional link.
// in the constructor only unidirectional links can be created.
void create_unidirectional_link(GLuint nodeID);
// this method deletes an unidirectional link.
void delete_unidirectional_link(GLuint nodeID);
glm::vec3 coordinate_vector;
};
class Species
{
public:
// constructor.
Species(SpeciesStruct species_struct);
// destructor.
~Species();
// this method renders all objects of this species.
void render();
// this method sets a object pointer.
void set_pointer(GLuint objectID, void* object_pointer);
// this method gets a object pointer.
void* get_pointer(GLuint objectID);
// this method gets a object ID and removes it from the `free_objectID_queue` if it was popped from the queue.
GLuint get_objectID();
// this method sets pointer to this species to NULL, sets `shader_pointer` according to the input, and requests a new `speciesID` from the new shader.
void switch_to_new_shader(model::Shader *new_shader_pointer);
std::string color_channel; // color channel in use: `"red"`, `"green"`, `"blue"`, `"mean"` or `"all"`.
std::vector<ObjectStruct> object_vector; // vector of individual objects of this species.
glm::vec3 lightPos; // light position.
void *vertex_UV_pointer; // pointer to the vertex & UV species (not yet in use!).
// The rest fields are created in the constructor.
GLuint MatrixID;
GLuint ViewMatrixID;
GLuint ModelMatrixID;
GLuint vertexPosition_modelspaceID;
GLuint vertexUVID;
GLuint vertexNormal_modelspaceID;
std::vector<glm::vec3> vertices; // vertices of the object.
std::vector<glm::vec2> UVs; // UVs of the object.
std::vector<glm::vec3> normals; // normals of the object.
std::vector<GLuint> indices; // the deleted vertices will be reused (though it is not required, if there's enough memory).
std::vector<glm::vec3> indexed_vertices;
std::vector<glm::vec2> indexed_UVs;
std::vector<glm::vec3> indexed_normals;
GLuint vertexbuffer;
GLuint uvbuffer;
GLuint normalbuffer;
GLuint elementbuffer;
glm::mat4 ProjectionMatrix;
glm::mat4 ViewMatrix;
private:
model::Shader *shader_pointer; // pointer to the shader.
model::Texture *texture_pointer; // pointer to the texture.
std::string model_file_format; // type of the model file, eg. `"bmp"`.
std::string model_filename; // filename of the model file.
std::string texture_file_format; // type of the model file, eg. `"bmp"`.
std::string texture_filename; // filename of the model file.
GLuint speciesID_from_shader; // species ID, returned by `model::Shader->get_speciesID()`.
GLuint speciesID_from_texture; // species ID, returned by `model::Texture->get_speciesID()`.
GLuint lightID; // light ID, returned by `glGetUniformLocation(programID, "LightPosition_worldspace");`.
GLuint texture; // Texture, returned by `load_DDS_texture` or `load_BMP_texture`.
GLuint textureID; // texture ID, returned by `glGetUniformLocation(programID, "myTextureSampler");`.
const char *char_model_file_format;
const char *char_model_filename;
const char *char_texture_file_format;
const char *char_texture_filename;
const char *char_color_channel;
std::vector<void*> object_pointer_vector;
std::queue<GLuint> free_objectID_queue;
};
class Object
{
public:
// constructor.
Object(ObjectStruct object_struct);
// destructor.
~Object();
// this method renders this object.
void render();
// this method sets pointer to this object to NULL, sets `species_pointer` according to the input, and requests a new `objectID` from the new species.
void switch_to_new_species(model::Species *new_species_pointer);
model::Species *species_pointer; // pointer to the species.
GLuint objectID; // object ID, returned by `model::Species->get_objectID()`.
bool has_entered;
glm::vec3 coordinate_vector; // rotate vector.
GLfloat rotate_angle; // rotate angle.
glm::vec3 rotate_vector; // rotate vector.
glm::vec3 translate_vector; // translate vector.
// The rest fields are created in the constructor.
glm::mat4 model_matrix; // model matrix.
std::vector<glm::vec3> vertices; // vertices of the object.
std::vector<glm::vec2> UVs; // UVs of the object.
std::vector<glm::vec3> normals; // normals of the object. not used at the moment.
glm::mat4 MVP_matrix; // model view projection matrix.
};
}
#endif
<commit_msg>`class Texture`: `GLuint textureID` on `private`-muuttuja.<commit_after>#ifndef __MODEL_HPP_INCLUDED
#define __MODEL_HPP_INCLUDED
// Include GLEW
#ifndef __GL_GLEW_H_INCLUDED
#define __GL_GLEW_H_INCLUDED
#include <GL/glew.h>
#endif
// Include GLFW
#ifndef __GLFW3_H_INCLUDED
#define __GLFW3_H_INCLUDED
#include <glfw3.h>
#endif
// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp>
#endif
#include <iostream>
#include <queue> // std::queue
#include <string.h>
#include "globals.hpp"
#include "shader.hpp"
#include "heightmap_loader.hpp"
#include "objloader.hpp"
namespace model
{
class World
{
public:
// constructor.
World();
// destructor.
~World();
// this method renders the entire world, one shader at a time.
void render();
// this method sets a shader pointer.
void set_shader_pointer(GLuint shaderID, void* shader_pointer);
// this method gets a shader pointer.
void* get_shader_pointer(GLuint shaderID);
// this method sets a texture pointer.
void set_texture_pointer(GLuint textureID, void* texture_pointer);
// this method gets a texture pointer.
void* get_texture_pointer(GLuint textureID);
// this method gets a shader ID and removes it from the `free_shaderID_queue` if it was popped from the queue.
GLuint get_shaderID();
// this method gets a texture ID and removes it from the `free_textureID_queue` if it was popped from the queue.
GLuint get_textureID();
private:
std::vector<void*> shader_pointer_vector;
std::queue<GLuint> free_shaderID_queue;
std::vector<void*> texture_pointer_vector;
std::queue<GLuint> free_textureID_queue;
};
class Shader
{
public:
// constructor.
Shader(ShaderStruct shader_struct);
// destructor.
~Shader();
// this method renders all species using this shader.
void render();
// this method sets a species pointer.
void set_pointer(GLuint speciesID, void* species_pointer);
// this method gets a species pointer.
void* get_pointer(GLuint speciesID);
// this method gets a species ID and removes it from the `free_speciesID_queue` if it was popped from the queue.
GLuint get_speciesID();
// this method sets pointer to this shader to NULL, sets `world_pointer` according to the input, and requests a new `shaderID` from the new world.
void switch_to_new_world(model::World *new_world_pointer);
model::World *world_pointer; // pointer to the world.
GLuint shaderID; // shader ID, returned by `model::World->get_shaderID()`.
std::string vertex_shader; // filename of vertex shader.
std::string fragment_shader; // filename of fragment shader.
GLuint programID; // shaders' programID, returned by `LoadShaders`.
private:
std::vector<void*> species_pointer_vector;
std::queue<GLuint> free_speciesID_queue;
const char *char_vertex_shader;
const char *char_fragment_shader;
};
class Texture
{
public:
// constructor.
Texture(TextureStruct texture_struct);
// destructor.
~Texture();
// this method sets a species pointer.
void set_pointer(GLuint speciesID, void* species_pointer);
// this method gets a species pointer.
void* get_pointer(GLuint speciesID);
// this method gets a species ID and removes it from the `free_speciesID_queue` if it was popped from the queue.
GLuint get_speciesID();
// this method sets pointer to this shader to NULL, sets `world_pointer` according to the input, and requests a new `shaderID` from the new world.
void switch_to_new_world(model::World *new_world_pointer);
model::World *world_pointer; // pointer to the world.
private:
std::vector<void*> species_pointer_vector;
std::queue<GLuint> free_speciesID_queue;
std::string texture_file_format; // type of the model file, eg. `"bmp"`.
std::string texture_filename; // filename of the model file.
GLuint textureID; // texture ID, returned by `glGetUniformLocation(programID, "myTextureSampler");`.
const char *char_texture_file_format;
const char *char_texture_filename;
};
class Graph
{
public:
// constructor.
Graph();
// destructor.
~Graph();
// this method sets a node pointer.
void set_pointer(GLuint nodeID, void* node_pointer);
// this method gets a node pointer.
void* get_pointer(GLuint nodeID);
// this method gets a node ID and removes it from the `free_nodeID_queue` if it was popped from the queue.
GLuint get_nodeID();
private:
std::vector<void*> node_pointer_vector;
std::queue<GLuint> free_nodeID_queue;
};
// `Node` is not a subclass of `Graph` because if the graph splits, node may be transferred to an another graph.
// Transferring a node to a new graph naturally requires appropriate reindexing of `nodeID`s.
// The graph in which a node belongs is accessible through `void* graph_pointer` (must be cast to `model::Graph*`).
class Node
{
public:
// constructor.
Node(NodeStruct node_struct);
// destructor.
~Node();
// this method creates a bidirectional link.
// creating of bidirectional links is not possible before all nodes are created.
void create_bidirectional_link(GLuint nodeID);
// this method deletes a bidirectional link.
// deleting of links is not possible before all nodes are created.
void delete_bidirectional_link(GLuint nodeID);
// this method transfers this node to a new graph.
// links will not be changed.
// all nodes that are to be transferred must be transferred separately.
// before transfering any node to a new graph,
// all links to nodes that do not belong to the new graph of this node must be deleted with separate `delete_bidirectional_link` calls.
void transfer_to_new_graph(model::Graph *new_graph_pointer);
GLuint nodeID;
model::Graph *graph_pointer;
// nodes do not keep pointers to neighbor nodes, because all pointer values are not known yet before all nodes are created.
std::vector<GLuint> neighbor_nodeIDs;
private:
// this method creates an unidirectional link.
// in the constructor only unidirectional links can be created.
void create_unidirectional_link(GLuint nodeID);
// this method deletes an unidirectional link.
void delete_unidirectional_link(GLuint nodeID);
glm::vec3 coordinate_vector;
};
class Species
{
public:
// constructor.
Species(SpeciesStruct species_struct);
// destructor.
~Species();
// this method renders all objects of this species.
void render();
// this method sets a object pointer.
void set_pointer(GLuint objectID, void* object_pointer);
// this method gets a object pointer.
void* get_pointer(GLuint objectID);
// this method gets a object ID and removes it from the `free_objectID_queue` if it was popped from the queue.
GLuint get_objectID();
// this method sets pointer to this species to NULL, sets `shader_pointer` according to the input, and requests a new `speciesID` from the new shader.
void switch_to_new_shader(model::Shader *new_shader_pointer);
std::string color_channel; // color channel in use: `"red"`, `"green"`, `"blue"`, `"mean"` or `"all"`.
std::vector<ObjectStruct> object_vector; // vector of individual objects of this species.
glm::vec3 lightPos; // light position.
void *vertex_UV_pointer; // pointer to the vertex & UV species (not yet in use!).
// The rest fields are created in the constructor.
GLuint MatrixID;
GLuint ViewMatrixID;
GLuint ModelMatrixID;
GLuint vertexPosition_modelspaceID;
GLuint vertexUVID;
GLuint vertexNormal_modelspaceID;
std::vector<glm::vec3> vertices; // vertices of the object.
std::vector<glm::vec2> UVs; // UVs of the object.
std::vector<glm::vec3> normals; // normals of the object.
std::vector<GLuint> indices; // the deleted vertices will be reused (though it is not required, if there's enough memory).
std::vector<glm::vec3> indexed_vertices;
std::vector<glm::vec2> indexed_UVs;
std::vector<glm::vec3> indexed_normals;
GLuint vertexbuffer;
GLuint uvbuffer;
GLuint normalbuffer;
GLuint elementbuffer;
glm::mat4 ProjectionMatrix;
glm::mat4 ViewMatrix;
private:
model::Shader *shader_pointer; // pointer to the shader.
model::Texture *texture_pointer; // pointer to the texture.
std::string model_file_format; // type of the model file, eg. `"bmp"`.
std::string model_filename; // filename of the model file.
std::string texture_file_format; // type of the model file, eg. `"bmp"`.
std::string texture_filename; // filename of the model file.
GLuint speciesID_from_shader; // species ID, returned by `model::Shader->get_speciesID()`.
GLuint speciesID_from_texture; // species ID, returned by `model::Texture->get_speciesID()`.
GLuint lightID; // light ID, returned by `glGetUniformLocation(programID, "LightPosition_worldspace");`.
GLuint texture; // Texture, returned by `load_DDS_texture` or `load_BMP_texture`.
GLuint textureID; // texture ID, returned by `glGetUniformLocation(programID, "myTextureSampler");`.
const char *char_model_file_format;
const char *char_model_filename;
const char *char_texture_file_format;
const char *char_texture_filename;
const char *char_color_channel;
std::vector<void*> object_pointer_vector;
std::queue<GLuint> free_objectID_queue;
};
class Object
{
public:
// constructor.
Object(ObjectStruct object_struct);
// destructor.
~Object();
// this method renders this object.
void render();
// this method sets pointer to this object to NULL, sets `species_pointer` according to the input, and requests a new `objectID` from the new species.
void switch_to_new_species(model::Species *new_species_pointer);
model::Species *species_pointer; // pointer to the species.
GLuint objectID; // object ID, returned by `model::Species->get_objectID()`.
bool has_entered;
glm::vec3 coordinate_vector; // rotate vector.
GLfloat rotate_angle; // rotate angle.
glm::vec3 rotate_vector; // rotate vector.
glm::vec3 translate_vector; // translate vector.
// The rest fields are created in the constructor.
glm::mat4 model_matrix; // model matrix.
std::vector<glm::vec3> vertices; // vertices of the object.
std::vector<glm::vec2> UVs; // UVs of the object.
std::vector<glm::vec3> normals; // normals of the object. not used at the moment.
glm::mat4 MVP_matrix; // model view projection matrix.
};
}
#endif
<|endoftext|> |
<commit_before>//======================================================================
//-----------------------------------------------------------------------
/**
* @file iutest_filepath.hpp
* @brief iris unit test ファイルパスクラス ファイル
*
* @author t.shirayanagi
* @par copyright
* Copyright (C) 2012-2018, Takazumi Shirayanagi\n
* This software is released under the new BSD License,
* see LICENSE
*/
//-----------------------------------------------------------------------
//======================================================================
#ifndef INCG_IRIS_IUTEST_FILEPATH_HPP_D69E7545_BF8A_4EDC_9493_9105C69F9378_
#define INCG_IRIS_IUTEST_FILEPATH_HPP_D69E7545_BF8A_4EDC_9493_9105C69F9378_
#if !defined(IUTEST_USE_GTEST)
//======================================================================
// include
#include "iutest_port.hpp"
namespace iutest
{
namespace detail
{
//======================================================================
// class
/**
* @brief ファイルパスクラス
*/
class iuFilePath
{
#if !IUTEST_USE_CXX_FILESYSTEM
class comapt_filepath_string : public ::std::string
{
public:
comapt_filepath_string(const char* path) : ::std::string(path) {}
comapt_filepath_string(const ::std::string& path) : ::std::string(path) {}
const ::std::string& generic_string() const { return *this; }
};
#endif
public:
iuFilePath() : m_path("") {}
iuFilePath(const iuFilePath& rhs) : m_path(rhs.m_path) {}
explicit iuFilePath(const char* path) : m_path(path)
{
Normalize();
}
explicit iuFilePath(const ::std::string& path) : m_path(path)
{
Normalize();
}
#if IUTEST_USE_CXX_FILESYSTEM
explicit iuFilePath(const ::std::filesystem::path& path) : m_path(path)
{
}
#endif
public:
::std::string ToString() const { return m_path.generic_string(); }
const char* c_str() const { return m_path.generic_string().c_str(); }
bool IsEmpty() const { return m_path.empty(); }
size_t length() const { return m_path.generic_string().length(); }
public:
iuFilePath & operator = (const iuFilePath& rhs) { m_path = rhs.m_path; return *this; }
iuFilePath& operator == (const iuFilePath& rhs)
{
m_path = rhs.m_path;
return *this;
}
bool operator == (const iuFilePath& rhs) const
{
return IsStringCaseEqual(c_str(), rhs.c_str());
}
bool operator == (const char* rhs) const
{
return IsStringCaseEqual(c_str(), rhs);
}
//operator const char* () const { return c_str(); }
public:
/**
* @brief フォルダパスかどうか
*/
bool IsDirectory() const;
/**
* @brief ルートディレクトリパスかどうか
*/
bool IsRootDirectory() const;
/**
* @brief 絶対パスかどうか
*/
bool IsAbsolutePath() const;
/**
* @brief 末尾のセパレーターを削除
*/
iuFilePath RemoveTrailingPathSeparator() const;
/**
* @brief 拡張子の取得
*/
::std::string GetExtension() const;
/**
* @brief 拡張子の削除
*/
iuFilePath RemoveExtension(const char* extension=NULL) const;
/**
* @brief ディレクトリ名の削除
*/
iuFilePath RemoveDirectoryName() const;
/**
* @brief ファイル名の削除
*/
iuFilePath RemoveFileName() const;
/**
* @brief フォルダの作成
*/
bool CreateFolder() const;
/**
* @brief フォルダを再帰的に作成
*/
bool CreateDirectoriesRecursively() const;
/**
* @brief ファイルまたはフォルダが存在するかどうか
*/
bool FileOrDirectoryExists() const;
/**
* @brief フォルダが存在するかどうか
*/
bool DirectoryExists() const;
/**
* @brief 一番後ろのパスセパレータのアドレスを取得
*/
const char* FindLastPathSeparator() const;
public:
/**
* @brief カレントディレクトリの取得
*/
static iuFilePath GetCurrentDir();
/**
* @brief カレントディレクトリの相対パス取得
*/
static iuFilePath GetRelativeCurrentDir();
/**
* @brief 実行ファイルのパスを取得
*/
static iuFilePath GetExecFilePath();
/**
* @brief パスの結合
*/
static iuFilePath ConcatPaths(const iuFilePath& directory, const iuFilePath& relative_path);
private:
/**
* @brief 正規化
*/
void Normalize();
private:
#if IUTEST_USE_CXX_FILESYSTEM
::std::filesystem::path m_path;
#else
comapt_filepath_string m_path;
#endif
};
inline iu_ostream& operator << (iu_ostream& os, const iuFilePath& path)
{
return os << path.c_str();
}
} // end of namespace detail
namespace internal
{
// google test との互換性のため
typedef detail::iuFilePath FilePath;
}
} // end of namespace iutest
#if !IUTEST_HAS_LIB
# include "../impl/iutest_filepath.ipp"
#endif
#endif
#endif // INCG_IRIS_IUTEST_FILEPATH_HPP_D69E7545_BF8A_4EDC_9493_9105C69F9378_
<commit_msg>fix cpplint<commit_after>//======================================================================
//-----------------------------------------------------------------------
/**
* @file iutest_filepath.hpp
* @brief iris unit test ファイルパスクラス ファイル
*
* @author t.shirayanagi
* @par copyright
* Copyright (C) 2012-2018, Takazumi Shirayanagi\n
* This software is released under the new BSD License,
* see LICENSE
*/
//-----------------------------------------------------------------------
//======================================================================
#ifndef INCG_IRIS_IUTEST_FILEPATH_HPP_D69E7545_BF8A_4EDC_9493_9105C69F9378_
#define INCG_IRIS_IUTEST_FILEPATH_HPP_D69E7545_BF8A_4EDC_9493_9105C69F9378_
#if !defined(IUTEST_USE_GTEST)
//======================================================================
// include
#include "iutest_port.hpp"
namespace iutest
{
namespace detail
{
//======================================================================
// class
/**
* @brief ファイルパスクラス
*/
class iuFilePath
{
#if !IUTEST_USE_CXX_FILESYSTEM
class comapt_filepath_string : public ::std::string
{
public:
explicit comapt_filepath_string(const char* path) : ::std::string(path) {}
explicit comapt_filepath_string(const ::std::string& path) : ::std::string(path) {}
const ::std::string& generic_string() const { return *this; }
};
#endif
public:
iuFilePath() : m_path("") {}
iuFilePath(const iuFilePath& rhs) : m_path(rhs.m_path) {}
explicit iuFilePath(const char* path) : m_path(path)
{
Normalize();
}
explicit iuFilePath(const ::std::string& path) : m_path(path)
{
Normalize();
}
#if IUTEST_USE_CXX_FILESYSTEM
explicit iuFilePath(const ::std::filesystem::path& path) : m_path(path)
{
}
#endif
public:
::std::string ToString() const { return m_path.generic_string(); }
const char* c_str() const { return m_path.generic_string().c_str(); }
bool IsEmpty() const { return m_path.empty(); }
size_t length() const { return m_path.generic_string().length(); }
public:
iuFilePath & operator = (const iuFilePath& rhs) { m_path = rhs.m_path; return *this; }
iuFilePath& operator == (const iuFilePath& rhs)
{
m_path = rhs.m_path;
return *this;
}
bool operator == (const iuFilePath& rhs) const
{
return IsStringCaseEqual(c_str(), rhs.c_str());
}
bool operator == (const char* rhs) const
{
return IsStringCaseEqual(c_str(), rhs);
}
//operator const char* () const { return c_str(); }
public:
/**
* @brief フォルダパスかどうか
*/
bool IsDirectory() const;
/**
* @brief ルートディレクトリパスかどうか
*/
bool IsRootDirectory() const;
/**
* @brief 絶対パスかどうか
*/
bool IsAbsolutePath() const;
/**
* @brief 末尾のセパレーターを削除
*/
iuFilePath RemoveTrailingPathSeparator() const;
/**
* @brief 拡張子の取得
*/
::std::string GetExtension() const;
/**
* @brief 拡張子の削除
*/
iuFilePath RemoveExtension(const char* extension=NULL) const;
/**
* @brief ディレクトリ名の削除
*/
iuFilePath RemoveDirectoryName() const;
/**
* @brief ファイル名の削除
*/
iuFilePath RemoveFileName() const;
/**
* @brief フォルダの作成
*/
bool CreateFolder() const;
/**
* @brief フォルダを再帰的に作成
*/
bool CreateDirectoriesRecursively() const;
/**
* @brief ファイルまたはフォルダが存在するかどうか
*/
bool FileOrDirectoryExists() const;
/**
* @brief フォルダが存在するかどうか
*/
bool DirectoryExists() const;
/**
* @brief 一番後ろのパスセパレータのアドレスを取得
*/
const char* FindLastPathSeparator() const;
public:
/**
* @brief カレントディレクトリの取得
*/
static iuFilePath GetCurrentDir();
/**
* @brief カレントディレクトリの相対パス取得
*/
static iuFilePath GetRelativeCurrentDir();
/**
* @brief 実行ファイルのパスを取得
*/
static iuFilePath GetExecFilePath();
/**
* @brief パスの結合
*/
static iuFilePath ConcatPaths(const iuFilePath& directory, const iuFilePath& relative_path);
private:
/**
* @brief 正規化
*/
void Normalize();
private:
#if IUTEST_USE_CXX_FILESYSTEM
::std::filesystem::path m_path;
#else
comapt_filepath_string m_path;
#endif
};
inline iu_ostream& operator << (iu_ostream& os, const iuFilePath& path)
{
return os << path.c_str();
}
} // end of namespace detail
namespace internal
{
// google test との互換性のため
typedef detail::iuFilePath FilePath;
}
} // end of namespace iutest
#if !IUTEST_HAS_LIB
# include "../impl/iutest_filepath.ipp"
#endif
#endif
#endif // INCG_IRIS_IUTEST_FILEPATH_HPP_D69E7545_BF8A_4EDC_9493_9105C69F9378_
<|endoftext|> |
<commit_before>#include "cell.h"
#include "liste.h"
#include "tabListe.h"
using namespace std;
int main(int argc, char** argv)
{
Liste L1;
Cell a1(1);
Cell b1(2);
L1.ajoutFin(a1);
L1.ajoutFin(b1);
L1.afficheL();
Liste L2;
Cell a2(3);
Cell b2(4);
L2.ajoutFin(a2);
L2.ajoutFin(b2);
L2.afficheL();
TabListe T(2);
T[0]=L1;
T[1]=L2;
T.afficheT();
return 0;
}
<commit_msg>enleve un doublons<commit_after><|endoftext|> |
<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#ifndef MTAC_GLOBAL_OPTIMIZATIONS_H
#define MTAC_GLOBAL_OPTIMIZATIONS_H
#include <memory>
#include "mtac/ControlFlowGraph.hpp"
#include "mtac/Program.hpp"
#include "mtac/DataFlowProblem.hpp"
namespace eddic {
namespace mtac {
std::shared_ptr<ControlFlowGraph> build_control_flow_graph(std::shared_ptr<Function> function);
template<bool Forward, typename DomainValues>
std::shared_ptr<DataFlowResults<mtac::Domain<DomainValues>>> data_flow(std::shared_ptr<ControlFlowGraph> graph, DataFlowProblem<Forward, DomainValues>& problem){
if(Forward){
return forward_data_flow(graph, problem);
} else {
return backward_data_flow(graph, problem);
}
}
//TODO Find a way to improve it in order to pass value by reference
template<typename Values>
inline void assign(Values& old, Values value, bool& changes){
if(old.top()){
changes = !value.top();
} else if(old.values().size() != value.values().size()){
changes = true;
}
old = value;
}
template<bool Forward, typename DomainValues>
std::shared_ptr<DataFlowResults<mtac::Domain<DomainValues>>> forward_data_flow(std::shared_ptr<ControlFlowGraph> cfg, DataFlowProblem<Forward, DomainValues>& problem){
typedef mtac::Domain<DomainValues> Domain;
auto graph = cfg->get_graph();
auto results = std::make_shared<DataFlowResults<Domain>>();
auto& OUT = results->OUT;
auto& IN = results->IN;
auto& OUT_S = results->OUT_S;
auto& IN_S = results->IN_S;
OUT[cfg->entry()] = problem.Boundary();
ControlFlowGraph::BasicBlockIterator it, end;
for(boost::tie(it,end) = boost::vertices(graph); it != end; ++it){
//Init all but ENTRY
if(graph[*it].block->index != -1){
OUT[graph[*it].block] = problem.Init();
}
}
bool changes = true;
while(changes){
changes = false;
for(boost::tie(it,end) = boost::vertices(graph); it != end; ++it){
auto vertex = *it;
auto B = graph[vertex].block;
//Do not consider ENTRY
if(B->index == -1){
continue;
}
ControlFlowGraph::InEdgeIterator iit, iend;
for(boost::tie(iit, iend) = boost::in_edges(vertex, graph); iit != iend; ++iit){
auto edge = *iit;
auto predecessor = boost::source(edge, graph);
auto P = graph[predecessor].block;
assign(IN[B], problem.meet(IN[B], OUT[P]), changes);
auto& statements = B->statements;
assign(IN_S[statements.front()], IN[B], changes);
for(unsigned i = 0; i < statements.size(); ++i){
auto& statement = statements[i];
assign(OUT_S[statement], problem.transfer(statement, IN_S[statement]), changes);
//The entry value of the next statement are the exit values of the current statement
if(i != statements.size() - 1){
assign(IN_S[statements[i+1]], OUT_S[statement], changes);
}
}
assign(OUT[B], OUT_S[statements.back()], changes);
}
}
}
return results;
}
template<bool Forward, typename DomainValues>
std::shared_ptr<DataFlowResults<mtac::Domain<DomainValues>>> backward_data_flow(std::shared_ptr<ControlFlowGraph>/* graph*/, DataFlowProblem<Forward, DomainValues>&/* problem*/){
typedef mtac::Domain<DomainValues> Domain;
auto results = std::make_shared<DataFlowResults<Domain>>();
//TODO
return results;
}
} //end of mtac
} //end of eddic
#endif
<commit_msg>Handle empty basic blocks<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#ifndef MTAC_GLOBAL_OPTIMIZATIONS_H
#define MTAC_GLOBAL_OPTIMIZATIONS_H
#include <memory>
#include "mtac/ControlFlowGraph.hpp"
#include "mtac/Program.hpp"
#include "mtac/DataFlowProblem.hpp"
namespace eddic {
namespace mtac {
std::shared_ptr<ControlFlowGraph> build_control_flow_graph(std::shared_ptr<Function> function);
template<bool Forward, typename DomainValues>
std::shared_ptr<DataFlowResults<mtac::Domain<DomainValues>>> data_flow(std::shared_ptr<ControlFlowGraph> graph, DataFlowProblem<Forward, DomainValues>& problem){
if(Forward){
return forward_data_flow(graph, problem);
} else {
return backward_data_flow(graph, problem);
}
}
//TODO Find a way to improve it in order to pass value by reference
template<typename Values>
inline void assign(Values& old, Values value, bool& changes){
if(old.top()){
changes = !value.top();
} else if(old.values().size() != value.values().size()){
changes = true;
}
old = value;
}
template<bool Forward, typename DomainValues>
std::shared_ptr<DataFlowResults<mtac::Domain<DomainValues>>> forward_data_flow(std::shared_ptr<ControlFlowGraph> cfg, DataFlowProblem<Forward, DomainValues>& problem){
typedef mtac::Domain<DomainValues> Domain;
auto graph = cfg->get_graph();
auto results = std::make_shared<DataFlowResults<Domain>>();
auto& OUT = results->OUT;
auto& IN = results->IN;
auto& OUT_S = results->OUT_S;
auto& IN_S = results->IN_S;
OUT[cfg->entry()] = problem.Boundary();
ControlFlowGraph::BasicBlockIterator it, end;
for(boost::tie(it,end) = boost::vertices(graph); it != end; ++it){
//Init all but ENTRY
if(graph[*it].block->index != -1){
OUT[graph[*it].block] = problem.Init();
}
}
bool changes = true;
while(changes){
changes = false;
for(boost::tie(it,end) = boost::vertices(graph); it != end; ++it){
auto vertex = *it;
auto B = graph[vertex].block;
//Do not consider ENTRY
if(B->index == -1){
continue;
}
ControlFlowGraph::InEdgeIterator iit, iend;
for(boost::tie(iit, iend) = boost::in_edges(vertex, graph); iit != iend; ++iit){
auto edge = *iit;
auto predecessor = boost::source(edge, graph);
auto P = graph[predecessor].block;
assign(IN[B], problem.meet(IN[B], OUT[P]), changes);
auto& statements = B->statements;
if(statements.size() > 0){
assign(IN_S[statements.front()], IN[B], changes);
for(unsigned i = 0; i < statements.size(); ++i){
auto& statement = statements[i];
assign(OUT_S[statement], problem.transfer(statement, IN_S[statement]), changes);
//The entry value of the next statement are the exit values of the current statement
if(i != statements.size() - 1){
assign(IN_S[statements[i+1]], OUT_S[statement], changes);
}
}
assign(OUT[B], OUT_S[statements.back()], changes);
} else {
//If the basic block is empty, the OUT values are the IN values
assign(OUT[B], IN[B], changes);
}
}
}
}
return results;
}
template<bool Forward, typename DomainValues>
std::shared_ptr<DataFlowResults<mtac::Domain<DomainValues>>> backward_data_flow(std::shared_ptr<ControlFlowGraph>/* graph*/, DataFlowProblem<Forward, DomainValues>&/* problem*/){
typedef mtac::Domain<DomainValues> Domain;
auto results = std::make_shared<DataFlowResults<Domain>>();
//TODO
return results;
}
} //end of mtac
} //end of eddic
#endif
<|endoftext|> |
<commit_before>#ifndef V_SMC_HELPER_PARALLEL_TBB_HPP
#define V_SMC_HELPER_PARALLEL_TBB_HPP
#include <cstddef>
#include <Eigen/Dense>
#include <tbb/tbb.h>
#include <vSMC/internal/config.hpp>
#include <vSMC/helper/sequential.hpp>
#include <vSMC/helper/state_base.hpp>
namespace vSMC {
/// \brief Sampler::init_type class for helping implementing SMC using TBB
///
/// \note The template parameter has to be type StateBase or its derived class.
/// \sa vSMC::InitializeSeq
template <typename T>
class InitializeTBB : public InitializeSeq<T>
{
public :
typedef typename InitializeSeq<T>::initialize_state_type
initialize_state_type;
typedef typename InitializeSeq<T>::initialize_param_type
initialize_param_type;
typedef typename InitializeSeq<T>::pre_processor_type
pre_processor_type;
typedef typename InitializeSeq<T>::post_processor_type
post_processor_type;
explicit InitializeTBB (
initialize_state_type init_state = NULL,
initialize_param_type init_param = NULL,
pre_processor_type pre = NULL,
post_processor_type post = NULL) :
InitializeSeq<T>(init_state, init_param, pre, post) {}
InitializeTBB (const InitializeTBB<T> &init) {}
InitializeTBB<T> & operator= (const InitializeTBB<T> &init) {return *this;}
/// \brief Operator called by Sampler for initialize the particle set
///
/// \param particle The Particle set passed by Sampler
/// \param param Additional parameters
///
/// \return Accept count
std::size_t operator() (Particle<T> &particle, void *param)
{
this->initialize_param(particle, param);
this->pre_processor(particle);
log_weight_.resize(particle.size());
accept_.resize(particle.size());
tbb::parallel_for(tbb::blocked_range<std::size_t>(0, particle.size()),
Worker_(this, &particle, particle.value().state(),
log_weight_.data(), accept_.data()));
particle.set_log_weight(log_weight_.data());
std::size_t accept = 0;
for (std::size_t i = 0; i != particle.size(); ++i)
accept += accept_[i];
this->post_processor(particle);
return accept;
}
private :
Eigen::VectorXd log_weight_;
Eigen::VectorXi accept_;
class Worker_
{
public :
Worker_ (InitializeTBB<T> *init,
Particle<T> *particle, typename T::value_type *state,
double *log_weight, int *accept) :
init_(init), particle_(particle), state_(state),
log_weight_(log_weight), accept_(accept) {}
void operator () (const tbb::blocked_range<std::size_t> &range) const
{
for (std::size_t i = range.begin(); i != range.end(); ++i) {
accept_[i] = init_->initialize_state(i, state_ + T::dim() * i,
log_weight_[i], *particle_, particle_->prng(i));
}
}
private :
InitializeTBB<T> *const init_;
Particle<T> *const particle_;
typename T::value_type *const state_;
double *const log_weight_;
int *const accept_;
}; // class Woker_
}; // class InitializeTBB
/// \brief Sampler::move_type class for helping implementing SMC using TBB
///
/// \note The template parameter has to be type StateBase or its derived class.
/// \sa vSMC::MoveSeq
template <typename T>
class MoveTBB : public MoveSeq<T>
{
public :
typedef typename MoveSeq<T>::move_state_type move_state_type;
typedef typename MoveSeq<T>::weight_action_type weight_action_type;
typedef typename MoveSeq<T>::pre_processor_type pre_processor_type;
typedef typename MoveSeq<T>::post_processor_type post_processor_type;
explicit MoveTBB (
move_state_type move = NULL,
weight_action_type weight = NULL,
pre_processor_type pre = NULL,
post_processor_type post = NULL) :
MoveSeq<T>(move, weight, pre, post) {}
MoveTBB (const MoveTBB<T> &move) {}
MoveTBB<T> & operator= (const MoveTBB<T> &move) {return *this;}
/// \brief Operator called by Sampler for move the particle set
///
/// \param iter The iteration number
/// \param particle The Particle set passed by Sampler
///
/// \return Accept count
std::size_t operator () (std::size_t iter, Particle<T> &particle)
{
this->pre_processor(iter, particle);
weight_.resize(particle.size());
accept_.resize(particle.size());
tbb::parallel_for(tbb::blocked_range<std::size_t>(0, particle.size()),
Worker_(this, iter, &particle, particle.value().state(),
weight_.data(), accept_.data()));
MoveSeq<T>::set_weight(this->weight_action(), particle,
weight_.data());
std::size_t accept = 0;
for (std::size_t i = 0; i != particle.size(); ++i)
accept += accept_[i];
this->post_processor(iter, particle);
return accept;
}
private :
Eigen::VectorXd weight_;
Eigen::VectorXi accept_;
class Worker_
{
public :
Worker_ (MoveTBB<T> *move, std::size_t iter,
Particle<T> *particle, typename T::value_type *state,
double *weight, int *accept) :
move_(move), iter_(iter), particle_(particle), state_(state),
weight_(weight), accept_(accept) {}
void operator () (const tbb::blocked_range<std::size_t> &range) const
{
for (std::size_t i = range.begin(); i != range.end(); ++i) {
accept_[i] = move_->move_state(i, iter_, state_ + T::dim() * i,
weight_[i], *particle_, particle_->prng(i));
}
}
private :
MoveTBB<T> *const move_;
const std::size_t iter_;
Particle<T> *const particle_;
typename T::value_type *const state_;
double *const weight_;
int *const accept_;
}; // class Woker_
}; // class MoveTBB
/// \brief Monitor::integral_type class for helping implementing SMC using TBB
///
/// \note The template parameter has to be type StateBase or its derived class.
/// \sa vSMC::MonitorSeq
template <typename T, unsigned Dim = 1>
class MonitorTBB : public MonitorSeq<T, Dim>
{
public :
typedef typename MonitorSeq<T>::monitor_state_type monitor_state_type;
explicit MonitorTBB (monitor_state_type monitor = NULL) :
MonitorSeq<T, Dim>(monitor) {}
/// \brief Operator called by Monitor to record Monte Carlo integration
///
/// \param iter The iteration number
/// \param particle The Particle set passed by Sampler
/// \param [out] res The integrands. Sum(res * weight) is the Monte Carlo
/// integration result.
void operator () (std::size_t iter, Particle<T> &particle, double *res)
{
tbb::parallel_for(tbb::blocked_range<std::size_t>(0, particle.size()),
Worker_(this, iter, &particle, particle.value().state(), res));
}
private :
class Worker_
{
public :
Worker_ (MonitorTBB<T, Dim> *monitor, std::size_t iter,
Particle<T> *particle, typename T::value_type *state,
double *res) :
monitor_(monitor), iter_(iter), particle_(particle), state_(state),
res_(res) {}
void operator () (const tbb::blocked_range<std::size_t> &range) const
{
for (std::size_t i = range.begin(); i != range.end(); ++i) {
monitor_->monitor_state(i, iter_, state_ + T::dim() * i,
*particle_, res_ + i * Dim);
}
}
private :
MonitorTBB<T, Dim> *const monitor_;
const std::size_t iter_;
Particle<T> *const particle_;
typename T::value_type *const state_;
double *const res_;
}; // class Worker_
}; // class MonitorTBB
/// \brief Path::integral_type class for helping implementing SMC using TBB
///
/// \note The template parameter has to be type StateBase or its derived class.
/// \sa vSMC::PathSeq
template <typename T>
class PathTBB : public PathSeq<T>
{
public :
typedef typename PathSeq<T>::path_state_type path_state_type;
typedef typename PathSeq<T>::width_state_type width_state_type;
explicit PathTBB (
path_state_type path = NULL, width_state_type width = NULL) :
PathSeq<T>(path, width) {}
/// \brief Operator called by Path to record path sampling integrands and
/// widths
///
/// \param iter The iteration number
/// \param particle The particle set passed by Sampler
/// \param [out] res The integrands. Sum(res * weight) is the path
///
/// \return The width
/// sampling integrand.
double operator () (std::size_t iter, Particle<T> &particle, double *res)
{
tbb::parallel_for(tbb::blocked_range<std::size_t>(0, particle.size()),
Worker_(this, iter, &particle, particle.value().state(), res));
return this->width_state(iter, particle);
}
private :
class Worker_
{
public :
Worker_ (PathTBB<T> *path, std::size_t iter,
Particle<T> *particle, typename T::value_type *state,
double *res) :
path_(path), iter_(iter), particle_(particle), state_(state),
res_(res) {}
void operator () (const tbb::blocked_range<std::size_t> &range) const
{
for (std::size_t i = range.begin(); i != range.end(); ++i) {
res_[i] = path_->path_state(i, iter_, state_ + T::dim() * i,
*particle_);
}
}
private :
PathTBB<T> *const path_;
const std::size_t iter_;
Particle<T> *const particle_;
typename T::value_type *const state_;
double *const res_;
}; // class Worker_
}; // PathTBB
} // namespace vSMC
#endif // V_SMC_HELPER_PARALLEL_TBB_HPP
<commit_msg>fix parallel_tbb for the new StateBase interface<commit_after>#ifndef V_SMC_HELPER_PARALLEL_TBB_HPP
#define V_SMC_HELPER_PARALLEL_TBB_HPP
#include <cstddef>
#include <Eigen/Dense>
#include <tbb/tbb.h>
#include <vSMC/internal/config.hpp>
#include <vSMC/helper/sequential.hpp>
#include <vSMC/helper/state_base.hpp>
namespace vSMC {
/// \brief Sampler::init_type class for helping implementing SMC using TBB
///
/// \note The template parameter has to be type StateBase or its derived class.
/// \sa vSMC::InitializeSeq
template <typename T>
class InitializeTBB : public InitializeSeq<T>
{
public :
typedef typename InitializeSeq<T>::initialize_state_type
initialize_state_type;
typedef typename InitializeSeq<T>::initialize_param_type
initialize_param_type;
typedef typename InitializeSeq<T>::pre_processor_type
pre_processor_type;
typedef typename InitializeSeq<T>::post_processor_type
post_processor_type;
explicit InitializeTBB (
initialize_state_type init_state = NULL,
initialize_param_type init_param = NULL,
pre_processor_type pre = NULL,
post_processor_type post = NULL) :
InitializeSeq<T>(init_state, init_param, pre, post) {}
InitializeTBB (const InitializeTBB<T> &init) {}
InitializeTBB<T> & operator= (const InitializeTBB<T> &init) {return *this;}
/// \brief Operator called by Sampler for initialize the particle set
///
/// \param particle The Particle set passed by Sampler
/// \param param Additional parameters
///
/// \return Accept count
std::size_t operator() (Particle<T> &particle, void *param)
{
this->initialize_param(particle, param);
this->pre_processor(particle);
log_weight_.resize(particle.size());
accept_.resize(particle.size());
tbb::parallel_for(tbb::blocked_range<std::size_t>(0, particle.size()),
Worker_(this, &particle, particle.value().state().data(),
log_weight_.data(), accept_.data()));
particle.set_log_weight(log_weight_.data());
std::size_t accept = 0;
for (std::size_t i = 0; i != particle.size(); ++i)
accept += accept_[i];
this->post_processor(particle);
return accept;
}
private :
Eigen::VectorXd log_weight_;
Eigen::VectorXi accept_;
class Worker_
{
public :
Worker_ (InitializeTBB<T> *init,
Particle<T> *particle, typename T::value_type *state,
double *log_weight, int *accept) :
init_(init), particle_(particle), state_(state),
log_weight_(log_weight), accept_(accept) {}
void operator () (const tbb::blocked_range<std::size_t> &range) const
{
for (std::size_t i = range.begin(); i != range.end(); ++i) {
accept_[i] = init_->initialize_state(i, state_ + T::dim() * i,
log_weight_[i], *particle_, particle_->prng(i));
}
}
private :
InitializeTBB<T> *const init_;
Particle<T> *const particle_;
typename T::value_type *const state_;
double *const log_weight_;
int *const accept_;
}; // class Woker_
}; // class InitializeTBB
/// \brief Sampler::move_type class for helping implementing SMC using TBB
///
/// \note The template parameter has to be type StateBase or its derived class.
/// \sa vSMC::MoveSeq
template <typename T>
class MoveTBB : public MoveSeq<T>
{
public :
typedef typename MoveSeq<T>::move_state_type move_state_type;
typedef typename MoveSeq<T>::weight_action_type weight_action_type;
typedef typename MoveSeq<T>::pre_processor_type pre_processor_type;
typedef typename MoveSeq<T>::post_processor_type post_processor_type;
explicit MoveTBB (
move_state_type move = NULL,
weight_action_type weight = NULL,
pre_processor_type pre = NULL,
post_processor_type post = NULL) :
MoveSeq<T>(move, weight, pre, post) {}
MoveTBB (const MoveTBB<T> &move) {}
MoveTBB<T> & operator= (const MoveTBB<T> &move) {return *this;}
/// \brief Operator called by Sampler for move the particle set
///
/// \param iter The iteration number
/// \param particle The Particle set passed by Sampler
///
/// \return Accept count
std::size_t operator () (std::size_t iter, Particle<T> &particle)
{
this->pre_processor(iter, particle);
weight_.resize(particle.size());
accept_.resize(particle.size());
tbb::parallel_for(tbb::blocked_range<std::size_t>(0, particle.size()),
Worker_(this, iter, &particle, particle.value().state().data(),
weight_.data(), accept_.data()));
MoveSeq<T>::set_weight(this->weight_action(), particle,
weight_.data());
std::size_t accept = 0;
for (std::size_t i = 0; i != particle.size(); ++i)
accept += accept_[i];
this->post_processor(iter, particle);
return accept;
}
private :
Eigen::VectorXd weight_;
Eigen::VectorXi accept_;
class Worker_
{
public :
Worker_ (MoveTBB<T> *move, std::size_t iter,
Particle<T> *particle, typename T::value_type *state,
double *weight, int *accept) :
move_(move), iter_(iter), particle_(particle), state_(state),
weight_(weight), accept_(accept) {}
void operator () (const tbb::blocked_range<std::size_t> &range) const
{
for (std::size_t i = range.begin(); i != range.end(); ++i) {
accept_[i] = move_->move_state(i, iter_, state_ + T::dim() * i,
weight_[i], *particle_, particle_->prng(i));
}
}
private :
MoveTBB<T> *const move_;
const std::size_t iter_;
Particle<T> *const particle_;
typename T::value_type *const state_;
double *const weight_;
int *const accept_;
}; // class Woker_
}; // class MoveTBB
/// \brief Monitor::integral_type class for helping implementing SMC using TBB
///
/// \note The template parameter has to be type StateBase or its derived class.
/// \sa vSMC::MonitorSeq
template <typename T, unsigned Dim = 1>
class MonitorTBB : public MonitorSeq<T, Dim>
{
public :
typedef typename MonitorSeq<T>::monitor_state_type monitor_state_type;
explicit MonitorTBB (monitor_state_type monitor = NULL) :
MonitorSeq<T, Dim>(monitor) {}
/// \brief Operator called by Monitor to record Monte Carlo integration
///
/// \param iter The iteration number
/// \param particle The Particle set passed by Sampler
/// \param [out] res The integrands. Sum(res * weight) is the Monte Carlo
/// integration result.
void operator () (std::size_t iter, Particle<T> &particle, double *res)
{
tbb::parallel_for(tbb::blocked_range<std::size_t>(0, particle.size()),
Worker_(this, iter, &particle, particle.value().state().data(),
res));
}
private :
class Worker_
{
public :
Worker_ (MonitorTBB<T, Dim> *monitor, std::size_t iter,
Particle<T> *particle, typename T::value_type *state,
double *res) :
monitor_(monitor), iter_(iter), particle_(particle), state_(state),
res_(res) {}
void operator () (const tbb::blocked_range<std::size_t> &range) const
{
for (std::size_t i = range.begin(); i != range.end(); ++i) {
monitor_->monitor_state(i, iter_, state_ + T::dim() * i,
*particle_, res_ + i * Dim);
}
}
private :
MonitorTBB<T, Dim> *const monitor_;
const std::size_t iter_;
Particle<T> *const particle_;
typename T::value_type *const state_;
double *const res_;
}; // class Worker_
}; // class MonitorTBB
/// \brief Path::integral_type class for helping implementing SMC using TBB
///
/// \note The template parameter has to be type StateBase or its derived class.
/// \sa vSMC::PathSeq
template <typename T>
class PathTBB : public PathSeq<T>
{
public :
typedef typename PathSeq<T>::path_state_type path_state_type;
typedef typename PathSeq<T>::width_state_type width_state_type;
explicit PathTBB (
path_state_type path = NULL, width_state_type width = NULL) :
PathSeq<T>(path, width) {}
/// \brief Operator called by Path to record path sampling integrands and
/// widths
///
/// \param iter The iteration number
/// \param particle The particle set passed by Sampler
/// \param [out] res The integrands. Sum(res * weight) is the path
///
/// \return The width
/// sampling integrand.
double operator () (std::size_t iter, Particle<T> &particle, double *res)
{
tbb::parallel_for(tbb::blocked_range<std::size_t>(0, particle.size()),
Worker_(this, iter, &particle, particle.value().state().data(),
res));
return this->width_state(iter, particle);
}
private :
class Worker_
{
public :
Worker_ (PathTBB<T> *path, std::size_t iter,
Particle<T> *particle, typename T::value_type *state,
double *res) :
path_(path), iter_(iter), particle_(particle), state_(state),
res_(res) {}
void operator () (const tbb::blocked_range<std::size_t> &range) const
{
for (std::size_t i = range.begin(); i != range.end(); ++i) {
res_[i] = path_->path_state(i, iter_, state_ + T::dim() * i,
*particle_);
}
}
private :
PathTBB<T> *const path_;
const std::size_t iter_;
Particle<T> *const particle_;
typename T::value_type *const state_;
double *const res_;
}; // class Worker_
}; // PathTBB
} // namespace vSMC
#endif // V_SMC_HELPER_PARALLEL_TBB_HPP
<|endoftext|> |
<commit_before>#ifndef VSMC_HELPER_PARALLEL_OMP_HPP
#define VSMC_HELPER_PARALLEL_OMP_HPP
#include <vsmc/internal/common.hpp>
#include <vsmc/helper/base.hpp>
/// \defgroup OpenMP OpenMP
/// \ingroup Helper
/// \brief Parallelized samplers with OpenMP
namespace vsmc {
/// \brief Particle::value_type subtype
/// \ingroup OpenMP
///
/// \tparam Dim The dimension of the state parameter vector
/// \tparam T The type of the value of the state parameter vector
template <unsigned Dim, typename T, typename Timer>
class StateOMP : public StateBase<Dim, T, Timer>
{
public :
typedef StateBase<Dim, T, Timer> state_base_type;
using typename state_base_type::size_type;
using typename state_base_type::state_type;
using typename state_base_type::timer_type;
explicit StateOMP (size_type N) : StateBase<Dim, T, Timer>(N), size_(N) {}
template <typename SizeType>
void copy (const SizeType *copy_from)
{
#pragma omp parallel for
for (size_type to = 0; to < size_; ++to)
this->copy_particle(copy_from[to], to);
}
private :
size_type size_;
}; // class StateOMP
/// \brief Sampler<T>::init_type subtype
/// \ingroup OpenMP
///
/// \tparam T A subtype of StateBase
template <typename T, typename Derived>
class InitializeOMP : public InitializeBase<T, Derived>
{
public :
typedef typename Particle<T>::size_type size_type;
typedef T value_type;
unsigned operator() (Particle<T> &particle, void *param)
{
VSMC_STATIC_ASSERT_STATE_TYPE(StateOMP, T, InitializeOMP);
this->initialize_param(particle, param);
this->pre_processor(particle);
unsigned accept = 0;
particle.value().timer().start();
#pragma omp parallel for reduction(+ : accept)
for (size_type i = 0; i < particle.value().size(); ++i)
accept += this->initialize_state(SingleParticle<T>(i, &particle));
particle.value().timer().stop();
this->post_processor(particle);
return accept;
}
protected :
InitializeOMP () {}
InitializeOMP (const InitializeOMP<T, Derived> &) {}
const InitializeOMP<T, Derived> &operator=
(const InitializeOMP<T, Derived> &) {return *this;}
~InitializeOMP () {}
}; // class InitializeOMP
/// \brief Sampler<T>::move_type subtype
/// \ingroup OpenMP
///
/// \tparam T A subtype of StateBase
template <typename T, typename Derived>
class MoveOMP : public MoveBase<T, Derived>
{
public :
typedef typename Particle<T>::size_type size_type;
typedef T value_type;
unsigned operator() (unsigned iter, Particle<T> &particle)
{
VSMC_STATIC_ASSERT_STATE_TYPE(StateOMP, T, MoveOMP);
this->pre_processor(iter, particle);
unsigned accept = 0;
particle.value().timer().start();
#pragma omp parallel for reduction(+ : accept)
for (size_type i = 0; i < particle.value().size(); ++i)
accept += this->move_state(iter, SingleParticle<T>(i, &particle));
particle.value().timer().stop();
this->post_processor(iter, particle);
return accept;
}
protected :
MoveOMP () {}
MoveOMP (const MoveOMP<T, Derived> &) {}
const MoveOMP<T, Derived> &operator=
(const MoveOMP<T, Derived> &) {return *this;}
~MoveOMP () {}
}; // class MoveOMP
/// \brief Monitor<T>::eval_type subtype
/// \ingroup OpenMP
///
/// \tparam T A subtype of StateBase
template <typename T, typename Derived>
class MonitorEvalOMP : public MonitorEvalBase<T, Derived>
{
public :
typedef typename Particle<T>::size_type size_type;
typedef T value_type;
void operator() (unsigned iter, unsigned dim, const Particle<T> &particle,
double *res)
{
VSMC_STATIC_ASSERT_STATE_TYPE(StateOMP, T, MonitorEvalOMP);
this->pre_processor(iter, particle);
particle.value().timer().start();
#pragma omp parallel for
for (size_type i = 0; i < particle.value().size(); ++i) {
this->monitor_state(iter, dim,
ConstSingleParticle<T>(i, &particle), res + i * dim);
}
particle.value().timer().stop();
this->post_processor(iter, particle);
}
protected :
MonitorEvalOMP () {}
MonitorEvalOMP (const MonitorEvalOMP<T, Derived> &) {}
const MonitorEvalOMP<T, Derived> &operator=
(const MonitorEvalOMP<T, Derived> &) {return *this;}
~MonitorEvalOMP () {}
}; // class MonitorEvalOMP
/// \brief Path<T>::eval_type subtype
/// \ingroup OpenMP
///
/// \tparam T A subtype of StateBase
template <typename T, typename Derived>
class PathEvalOMP : public PathEvalBase<T, Derived>
{
public :
typedef typename Particle<T>::size_type size_type;
typedef T value_type;
double operator() (unsigned iter, const Particle<T> &particle, double *res)
{
VSMC_STATIC_ASSERT_STATE_TYPE(StateOMP, T, PathEvalOMP);
this->pre_processor(iter, particle);
particle.value().timer().start();
double *r = res;
#pragma omp parallel for
for (size_type i = 0; i < particle.value().size(); ++i) {
r[i] = this->path_state(iter,
ConstSingleParticle<T>(i, &particle));
}
particle.value().timer().stop();
this->post_processor(iter, particle);
return this->path_width(iter, particle);
}
protected :
PathEvalOMP () {}
PathEvalOMP (const PathEvalOMP<T, Derived> &) {}
const PathEvalOMP<T, Derived> &operator=
(const PathEvalOMP<T, Derived> &) {return *this;}
~PathEvalOMP () {}
}; // class PathEvalOMP
} // namespace vsmc
#endif // VSMC_HELPER_PARALLEL_OMP_HPP
<commit_msg>localize some OpenMP data<commit_after>#ifndef VSMC_HELPER_PARALLEL_OMP_HPP
#define VSMC_HELPER_PARALLEL_OMP_HPP
#include <vsmc/internal/common.hpp>
#include <vsmc/helper/base.hpp>
/// \defgroup OpenMP OpenMP
/// \ingroup Helper
/// \brief Parallelized samplers with OpenMP
namespace vsmc {
/// \brief Particle::value_type subtype
/// \ingroup OpenMP
///
/// \tparam Dim The dimension of the state parameter vector
/// \tparam T The type of the value of the state parameter vector
template <unsigned Dim, typename T, typename Timer>
class StateOMP : public StateBase<Dim, T, Timer>
{
public :
typedef StateBase<Dim, T, Timer> state_base_type;
using typename state_base_type::size_type;
using typename state_base_type::state_type;
using typename state_base_type::timer_type;
explicit StateOMP (size_type N) : StateBase<Dim, T, Timer>(N), size_(N) {}
template <typename SizeType>
void copy (const SizeType *copy_from)
{
const size_type N = size_;
#pragma omp parallel for
for (size_type to = 0; to < N; ++to) {
SizeType from = copy_from[to];
this->copy_particle(from, to);
}
}
private :
size_type size_;
}; // class StateOMP
/// \brief Sampler<T>::init_type subtype
/// \ingroup OpenMP
///
/// \tparam T A subtype of StateBase
template <typename T, typename Derived>
class InitializeOMP : public InitializeBase<T, Derived>
{
public :
typedef typename Particle<T>::size_type size_type;
typedef T value_type;
unsigned operator() (Particle<T> &particle, void *param)
{
VSMC_STATIC_ASSERT_STATE_TYPE(StateOMP, T, InitializeOMP);
this->initialize_param(particle, param);
this->pre_processor(particle);
unsigned accept = 0;
const size_type N = particle.value().size();
Particle<T> *const p = &particle;
particle.value().timer().start();
#pragma omp parallel for reduction(+ : accept)
for (size_type i = 0; i < N; ++i)
accept += this->initialize_state(SingleParticle<T>(i, p));
particle.value().timer().stop();
this->post_processor(particle);
return accept;
}
protected :
InitializeOMP () {}
InitializeOMP (const InitializeOMP<T, Derived> &) {}
const InitializeOMP<T, Derived> &operator=
(const InitializeOMP<T, Derived> &) {return *this;}
~InitializeOMP () {}
}; // class InitializeOMP
/// \brief Sampler<T>::move_type subtype
/// \ingroup OpenMP
///
/// \tparam T A subtype of StateBase
template <typename T, typename Derived>
class MoveOMP : public MoveBase<T, Derived>
{
public :
typedef typename Particle<T>::size_type size_type;
typedef T value_type;
unsigned operator() (unsigned iter, Particle<T> &particle)
{
VSMC_STATIC_ASSERT_STATE_TYPE(StateOMP, T, MoveOMP);
this->pre_processor(iter, particle);
unsigned accept = 0;
const size_type N = particle.value().size();
Particle<T> *const p = &particle;
particle.value().timer().start();
#pragma omp parallel for reduction(+ : accept)
for (size_type i = 0; i < N; ++i)
accept += this->move_state(iter, SingleParticle<T>(i, p));
particle.value().timer().stop();
this->post_processor(iter, particle);
return accept;
}
protected :
MoveOMP () {}
MoveOMP (const MoveOMP<T, Derived> &) {}
const MoveOMP<T, Derived> &operator=
(const MoveOMP<T, Derived> &) {return *this;}
~MoveOMP () {}
}; // class MoveOMP
/// \brief Monitor<T>::eval_type subtype
/// \ingroup OpenMP
///
/// \tparam T A subtype of StateBase
template <typename T, typename Derived>
class MonitorEvalOMP : public MonitorEvalBase<T, Derived>
{
public :
typedef typename Particle<T>::size_type size_type;
typedef T value_type;
void operator() (unsigned iter, unsigned dim, const Particle<T> &particle,
double *res)
{
VSMC_STATIC_ASSERT_STATE_TYPE(StateOMP, T, MonitorEvalOMP);
this->pre_processor(iter, particle);
const size_type N = particle.value().size();
const Particle<T> *const p = &particle;
double *const r = res;
particle.value().timer().start();
#pragma omp parallel for
for (size_type i = 0; i < N; ++i) {
double *rr = r + i * dim;
this->monitor_state(iter, dim, ConstSingleParticle<T>(i, p), rr);
}
particle.value().timer().stop();
this->post_processor(iter, particle);
}
protected :
MonitorEvalOMP () {}
MonitorEvalOMP (const MonitorEvalOMP<T, Derived> &) {}
const MonitorEvalOMP<T, Derived> &operator=
(const MonitorEvalOMP<T, Derived> &) {return *this;}
~MonitorEvalOMP () {}
}; // class MonitorEvalOMP
/// \brief Path<T>::eval_type subtype
/// \ingroup OpenMP
///
/// \tparam T A subtype of StateBase
template <typename T, typename Derived>
class PathEvalOMP : public PathEvalBase<T, Derived>
{
public :
typedef typename Particle<T>::size_type size_type;
typedef T value_type;
double operator() (unsigned iter, const Particle<T> &particle, double *res)
{
VSMC_STATIC_ASSERT_STATE_TYPE(StateOMP, T, PathEvalOMP);
this->pre_processor(iter, particle);
const size_type N = particle.value().size();
const Particle<T> *const p = &particle;
particle.value().timer().start();
double *const r = res;
#pragma omp parallel for
for (size_type i = 0; i < N; ++i)
r[i] = this->path_state(iter, ConstSingleParticle<T>(i, p));
particle.value().timer().stop();
this->post_processor(iter, particle);
return this->path_width(iter, particle);
}
protected :
PathEvalOMP () {}
PathEvalOMP (const PathEvalOMP<T, Derived> &) {}
const PathEvalOMP<T, Derived> &operator=
(const PathEvalOMP<T, Derived> &) {return *this;}
~PathEvalOMP () {}
}; // class PathEvalOMP
} // namespace vsmc
#endif // VSMC_HELPER_PARALLEL_OMP_HPP
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2015 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include "query-result-set.hh"
#include "query-result-reader.hh"
#include "partition_slice_builder.hh"
#include "mutation.hh"
namespace query {
// Result set builder is passed as a visitor to query_result::consume()
// function. You can call the build() method to obtain a result set that
// contains cells from the visited results.
class result_set_builder {
schema_ptr _schema;
const partition_slice& _slice;
std::vector<result_set_row> _rows;
std::unordered_map<sstring, data_value> _pkey_cells;
uint32_t _row_count;
public:
// Keep slice live as long as the builder is used.
result_set_builder(schema_ptr schema, const partition_slice& slice);
result_set build() const;
void accept_new_partition(const partition_key& key, uint32_t row_count);
void accept_new_partition(uint32_t row_count);
void accept_new_row(const clustering_key& key, const result_row_view& static_row, const result_row_view& row);
void accept_new_row(const result_row_view &static_row, const result_row_view &row);
void accept_partition_end(const result_row_view& static_row);
private:
std::unordered_map<sstring, data_value> deserialize(const partition_key& key);
std::unordered_map<sstring, data_value> deserialize(const clustering_key& key);
std::unordered_map<sstring, data_value> deserialize(const result_row_view& row, bool is_static);
};
std::ostream& operator<<(std::ostream& out, const result_set_row& row) {
for (auto&& cell : row._cells) {
auto&& type = cell.second.type();
auto&& value = cell.second;
out << cell.first << "=\"" << type->to_string(type->decompose(value)) << "\" ";
}
return out;
}
std::ostream& operator<<(std::ostream& out, const result_set& rs) {
for (auto&& row : rs._rows) {
out << row << std::endl;
}
return out;
}
result_set_builder::result_set_builder(schema_ptr schema, const partition_slice& slice)
: _schema{schema}, _slice(slice)
{ }
result_set result_set_builder::build() const {
return { _schema, _rows };
}
void result_set_builder::accept_new_partition(const partition_key& key, uint32_t row_count)
{
_pkey_cells = deserialize(key);
accept_new_partition(row_count);
}
void result_set_builder::accept_new_partition(uint32_t row_count)
{
_row_count = row_count;
}
void result_set_builder::accept_new_row(const clustering_key& key, const result_row_view& static_row, const result_row_view& row)
{
auto ckey_cells = deserialize(key);
auto static_cells = deserialize(static_row, true);
auto regular_cells = deserialize(row, false);
std::unordered_map<sstring, data_value> cells;
cells.insert(_pkey_cells.begin(), _pkey_cells.end());
cells.insert(ckey_cells.begin(), ckey_cells.end());
cells.insert(static_cells.begin(), static_cells.end());
cells.insert(regular_cells.begin(), regular_cells.end());
_rows.emplace_back(_schema, std::move(cells));
}
void result_set_builder::accept_new_row(const query::result_row_view &static_row, const query::result_row_view &row)
{
auto static_cells = deserialize(static_row, true);
auto regular_cells = deserialize(row, false);
std::unordered_map<sstring, data_value> cells;
cells.insert(_pkey_cells.begin(), _pkey_cells.end());
cells.insert(static_cells.begin(), static_cells.end());
cells.insert(regular_cells.begin(), regular_cells.end());
_rows.emplace_back(_schema, std::move(cells));
}
void result_set_builder::accept_partition_end(const result_row_view& static_row)
{
if (_row_count == 0) {
auto static_cells = deserialize(static_row, true);
std::unordered_map<sstring, data_value> cells;
cells.insert(_pkey_cells.begin(), _pkey_cells.end());
cells.insert(static_cells.begin(), static_cells.end());
_rows.emplace_back(_schema, std::move(cells));
}
_pkey_cells.clear();
}
std::unordered_map<sstring, data_value>
result_set_builder::deserialize(const partition_key& key)
{
std::unordered_map<sstring, data_value> cells;
auto i = key.begin(*_schema);
for (auto&& col : _schema->partition_key_columns()) {
cells.emplace(col.name_as_text(), col.type->deserialize_value(*i));
++i;
}
return cells;
}
std::unordered_map<sstring, data_value>
result_set_builder::deserialize(const clustering_key& key)
{
std::unordered_map<sstring, data_value> cells;
auto i = key.begin(*_schema);
for (auto&& col : _schema->clustering_key_columns()) {
cells.emplace(col.name_as_text(), col.type->deserialize_value(*i));
++i;
}
return cells;
}
std::unordered_map<sstring, data_value>
result_set_builder::deserialize(const result_row_view& row, bool is_static)
{
std::unordered_map<sstring, data_value> cells;
auto i = row.iterator();
auto column_ids = is_static ? _slice.static_columns : _slice.regular_columns;
auto columns = column_ids | boost::adaptors::transformed([this, is_static] (column_id id) -> const column_definition& {
if (is_static) {
return _schema->static_column_at(id);
} else {
return _schema->regular_column_at(id);
}
});
for (auto &&col : columns) {
if (col.is_atomic()) {
auto cell = i.next_atomic_cell();
if (cell) {
auto view = cell.value();
cells.emplace(col.name_as_text(), col.type->deserialize_value(view.value()));
}
} else {
auto cell = i.next_collection_cell();
if (cell) {
auto ctype = static_pointer_cast<const collection_type_impl>(col.type);
if (_slice.options.contains<partition_slice::option::collections_as_maps>()) {
ctype = map_type_impl::get_instance(ctype->name_comparator(), ctype->value_comparator(), true);
}
cells.emplace(col.name_as_text(), ctype->deserialize_value(*cell, _slice.cql_format()));
}
}
}
return cells;
}
result_set
result_set::from_raw_result(schema_ptr s, const partition_slice& slice, const result& r) {
auto make = [&slice, s = std::move(s)] (bytes_view v) mutable {
result_set_builder builder{std::move(s), slice};
result_view view(v);
view.consume(slice, builder);
return builder.build();
};
if (r.buf().is_linearized()) {
return make(r.buf().view());
} else {
// FIXME: make result_view::consume() work on fragments to avoid linearization.
bytes_ostream w(r.buf());
return make(w.linearize());
}
}
result_set::result_set(const mutation& m) : result_set([&m] {
auto slice = partition_slice_builder(*m.schema()).build();
auto qr = mutation(m).query(slice, result_request::only_result);
return result_set::from_raw_result(m.schema(), slice, qr);
}())
{ }
}
<commit_msg>query: fix non full clustering key deserialization<commit_after>/*
* Copyright (C) 2015 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include "query-result-set.hh"
#include "query-result-reader.hh"
#include "partition_slice_builder.hh"
#include "mutation.hh"
namespace query {
// Result set builder is passed as a visitor to query_result::consume()
// function. You can call the build() method to obtain a result set that
// contains cells from the visited results.
class result_set_builder {
schema_ptr _schema;
const partition_slice& _slice;
std::vector<result_set_row> _rows;
std::unordered_map<sstring, data_value> _pkey_cells;
uint32_t _row_count;
public:
// Keep slice live as long as the builder is used.
result_set_builder(schema_ptr schema, const partition_slice& slice);
result_set build() const;
void accept_new_partition(const partition_key& key, uint32_t row_count);
void accept_new_partition(uint32_t row_count);
void accept_new_row(const clustering_key& key, const result_row_view& static_row, const result_row_view& row);
void accept_new_row(const result_row_view &static_row, const result_row_view &row);
void accept_partition_end(const result_row_view& static_row);
private:
std::unordered_map<sstring, data_value> deserialize(const partition_key& key);
std::unordered_map<sstring, data_value> deserialize(const clustering_key& key);
std::unordered_map<sstring, data_value> deserialize(const result_row_view& row, bool is_static);
};
std::ostream& operator<<(std::ostream& out, const result_set_row& row) {
for (auto&& cell : row._cells) {
auto&& type = cell.second.type();
auto&& value = cell.second;
out << cell.first << "=\"" << type->to_string(type->decompose(value)) << "\" ";
}
return out;
}
std::ostream& operator<<(std::ostream& out, const result_set& rs) {
for (auto&& row : rs._rows) {
out << row << std::endl;
}
return out;
}
result_set_builder::result_set_builder(schema_ptr schema, const partition_slice& slice)
: _schema{schema}, _slice(slice)
{ }
result_set result_set_builder::build() const {
return { _schema, _rows };
}
void result_set_builder::accept_new_partition(const partition_key& key, uint32_t row_count)
{
_pkey_cells = deserialize(key);
accept_new_partition(row_count);
}
void result_set_builder::accept_new_partition(uint32_t row_count)
{
_row_count = row_count;
}
void result_set_builder::accept_new_row(const clustering_key& key, const result_row_view& static_row, const result_row_view& row)
{
auto ckey_cells = deserialize(key);
auto static_cells = deserialize(static_row, true);
auto regular_cells = deserialize(row, false);
std::unordered_map<sstring, data_value> cells;
cells.insert(_pkey_cells.begin(), _pkey_cells.end());
cells.insert(ckey_cells.begin(), ckey_cells.end());
cells.insert(static_cells.begin(), static_cells.end());
cells.insert(regular_cells.begin(), regular_cells.end());
_rows.emplace_back(_schema, std::move(cells));
}
void result_set_builder::accept_new_row(const query::result_row_view &static_row, const query::result_row_view &row)
{
auto static_cells = deserialize(static_row, true);
auto regular_cells = deserialize(row, false);
std::unordered_map<sstring, data_value> cells;
cells.insert(_pkey_cells.begin(), _pkey_cells.end());
cells.insert(static_cells.begin(), static_cells.end());
cells.insert(regular_cells.begin(), regular_cells.end());
_rows.emplace_back(_schema, std::move(cells));
}
void result_set_builder::accept_partition_end(const result_row_view& static_row)
{
if (_row_count == 0) {
auto static_cells = deserialize(static_row, true);
std::unordered_map<sstring, data_value> cells;
cells.insert(_pkey_cells.begin(), _pkey_cells.end());
cells.insert(static_cells.begin(), static_cells.end());
_rows.emplace_back(_schema, std::move(cells));
}
_pkey_cells.clear();
}
std::unordered_map<sstring, data_value>
result_set_builder::deserialize(const partition_key& key)
{
std::unordered_map<sstring, data_value> cells;
auto i = key.begin(*_schema);
for (auto&& col : _schema->partition_key_columns()) {
cells.emplace(col.name_as_text(), col.type->deserialize_value(*i));
++i;
}
return cells;
}
std::unordered_map<sstring, data_value>
result_set_builder::deserialize(const clustering_key& key)
{
std::unordered_map<sstring, data_value> cells;
auto i = key.begin(*_schema);
for (auto&& col : _schema->clustering_key_columns()) {
if (i == key.end(*_schema)) {
break;
}
cells.emplace(col.name_as_text(), col.type->deserialize_value(*i));
++i;
}
return cells;
}
std::unordered_map<sstring, data_value>
result_set_builder::deserialize(const result_row_view& row, bool is_static)
{
std::unordered_map<sstring, data_value> cells;
auto i = row.iterator();
auto column_ids = is_static ? _slice.static_columns : _slice.regular_columns;
auto columns = column_ids | boost::adaptors::transformed([this, is_static] (column_id id) -> const column_definition& {
if (is_static) {
return _schema->static_column_at(id);
} else {
return _schema->regular_column_at(id);
}
});
for (auto &&col : columns) {
if (col.is_atomic()) {
auto cell = i.next_atomic_cell();
if (cell) {
auto view = cell.value();
cells.emplace(col.name_as_text(), col.type->deserialize_value(view.value()));
}
} else {
auto cell = i.next_collection_cell();
if (cell) {
auto ctype = static_pointer_cast<const collection_type_impl>(col.type);
if (_slice.options.contains<partition_slice::option::collections_as_maps>()) {
ctype = map_type_impl::get_instance(ctype->name_comparator(), ctype->value_comparator(), true);
}
cells.emplace(col.name_as_text(), ctype->deserialize_value(*cell, _slice.cql_format()));
}
}
}
return cells;
}
result_set
result_set::from_raw_result(schema_ptr s, const partition_slice& slice, const result& r) {
auto make = [&slice, s = std::move(s)] (bytes_view v) mutable {
result_set_builder builder{std::move(s), slice};
result_view view(v);
view.consume(slice, builder);
return builder.build();
};
if (r.buf().is_linearized()) {
return make(r.buf().view());
} else {
// FIXME: make result_view::consume() work on fragments to avoid linearization.
bytes_ostream w(r.buf());
return make(w.linearize());
}
}
result_set::result_set(const mutation& m) : result_set([&m] {
auto slice = partition_slice_builder(*m.schema()).build();
auto qr = mutation(m).query(slice, result_request::only_result);
return result_set::from_raw_result(m.schema(), slice, qr);
}())
{ }
}
<|endoftext|> |
<commit_before>/*
* @file fsfloaterposestand.cpp
* @brief It's a pose stand!
*
* ----------------------------------------------------------------------------
* "THE BEER-WARE LICENSE" (Revision 42):
* Cinder Roxley wrote this file. As long as you retain this notice you can do
* whatever you want with this stuff. If we meet some day, and you think this
* stuff is worth it, you can buy me a beer in return <cinder@cinderblocks.biz>
* ----------------------------------------------------------------------------
*/
#include "llviewerprecompiledheaders.h"
#include "fsfloaterposestand.h"
#include "fspose.h"
#include "llsdserialize.h"
#include "lltrans.h"
FSFloaterPoseStand::FSFloaterPoseStand(const LLSD& key)
: LLFloater(key),
mComboPose(NULL)
{
}
FSFloaterPoseStand::~FSFloaterPoseStand()
{
}
BOOL FSFloaterPoseStand::postBuild()
{
mComboPose = getChild<LLComboBox>("pose_combo");
mComboPose->setCommitCallback(boost::bind(&FSFloaterPoseStand::onCommitCombo, this));
loadPoses();
onCommitCombo();
return TRUE;
}
// virtual
void FSFloaterPoseStand::onOpen(const LLSD& key)
{
onCommitCombo();
}
// virtual
void FSFloaterPoseStand::onClose(bool app_quitting)
{
FSPose::getInstance()->stopPose();
}
void FSFloaterPoseStand::loadPoses()
{
const std::string pose_filename = gDirUtilp->getExpandedFilename(LL_PATH_APP_SETTINGS, "posestand.xml");
llifstream pose_file(pose_filename);
LLSD poses;
if (pose_file.is_open())
{
if(LLSDSerialize::fromXML(poses, pose_file) >= 1)
{
for(LLSD::map_iterator p_itr = poses.beginMap(); p_itr != poses.endMap(); ++p_itr)
{
mComboPose->add(LLTrans::getString(p_itr->second["name"]), LLUUID(p_itr->first));
}
}
pose_file.close();
}
}
void FSFloaterPoseStand::onCommitCombo()
{
std::string selected_pose = mComboPose->getValue();
FSPose::getInstance()->setPose(selected_pose);
}
<commit_msg>Sort pose names in pose stand floater by name<commit_after>/*
* @file fsfloaterposestand.cpp
* @brief It's a pose stand!
*
* ----------------------------------------------------------------------------
* "THE BEER-WARE LICENSE" (Revision 42):
* Cinder Roxley wrote this file. As long as you retain this notice you can do
* whatever you want with this stuff. If we meet some day, and you think this
* stuff is worth it, you can buy me a beer in return <cinder@cinderblocks.biz>
* ----------------------------------------------------------------------------
*/
#include "llviewerprecompiledheaders.h"
#include "fsfloaterposestand.h"
#include "fspose.h"
#include "llsdserialize.h"
#include "lltrans.h"
FSFloaterPoseStand::FSFloaterPoseStand(const LLSD& key)
: LLFloater(key),
mComboPose(NULL)
{
}
FSFloaterPoseStand::~FSFloaterPoseStand()
{
}
BOOL FSFloaterPoseStand::postBuild()
{
mComboPose = getChild<LLComboBox>("pose_combo");
mComboPose->setCommitCallback(boost::bind(&FSFloaterPoseStand::onCommitCombo, this));
loadPoses();
onCommitCombo();
return TRUE;
}
// virtual
void FSFloaterPoseStand::onOpen(const LLSD& key)
{
onCommitCombo();
}
// virtual
void FSFloaterPoseStand::onClose(bool app_quitting)
{
FSPose::getInstance()->stopPose();
}
void FSFloaterPoseStand::loadPoses()
{
const std::string pose_filename = gDirUtilp->getExpandedFilename(LL_PATH_APP_SETTINGS, "posestand.xml");
llifstream pose_file(pose_filename);
LLSD poses;
if (pose_file.is_open())
{
if(LLSDSerialize::fromXML(poses, pose_file) >= 1)
{
for(LLSD::map_iterator p_itr = poses.beginMap(); p_itr != poses.endMap(); ++p_itr)
{
mComboPose->add(LLTrans::getString(p_itr->second["name"]), LLUUID(p_itr->first));
}
}
pose_file.close();
}
mComboPose->sortByName();
}
void FSFloaterPoseStand::onCommitCombo()
{
std::string selected_pose = mComboPose->getValue();
FSPose::getInstance()->setPose(selected_pose);
}
<|endoftext|> |
<commit_before>#include <QApplication>
#include <QTreeView>
#include <QAbstractItemModel>
#include <QList>
#include <assert.h>
#include "ntreg.h"
class RegistryItem
{
struct hive *hive;
RegistryItem* parent;
QString name;
bool enumerated;
QList<RegistryItem*> subkeys;
public:
RegistryItem( struct hive *h, RegistryItem* p, const char *n );
QString* getPath();
RegistryItem* getParent();
RegistryItem* getChild( int n );
int getSubkeyCount();
const QString& getName() const;
protected:
void enumerateChildren();
};
RegistryItem::RegistryItem( struct hive *h, RegistryItem* p, const char *n ) :
hive( h ),
parent( p ),
name( n ),
enumerated( false )
{
}
QString* RegistryItem::getPath()
{
QString* path;
if (parent)
{
path = parent->getPath();
path->append( name );
path->append( "\\" );
}
else
path = new QString( name );
return path;
}
RegistryItem* RegistryItem::getParent()
{
return parent;
}
void RegistryItem::enumerateChildren()
{
if (enumerated)
return;
struct ex_data key;
char *path = getPath()->toUtf8().data();
int i = 0;
while (1)
{
int r = nk_get_subkey( hive, path, 0, i, &key );
if (r < 0)
break;
fprintf(stderr, "enumerateChildren: %s\n", key.name);
RegistryItem* item = new RegistryItem( hive, this, key.name );
subkeys.append( item );
i++;
}
enumerated = true;
}
RegistryItem* RegistryItem::getChild( int n )
{
enumerateChildren();
return subkeys.at( n );
}
int RegistryItem::getSubkeyCount()
{
enumerateChildren();
return subkeys.count();
}
const QString& RegistryItem::getName() const
{
return name;
}
class RegistryItemModel : public QAbstractListModel
{
struct hive *hive;
RegistryItem *root;
public:
RegistryItemModel(RegistryItem* root, struct hive *h);
virtual QModelIndex index(int,int,const QModelIndex&) const;
virtual int rowCount(const QModelIndex& index) const;
virtual QVariant data(const QModelIndex&, int) const;
public:
int enum_func( struct nk_key *key );
};
RegistryItemModel::RegistryItemModel(RegistryItem* r, struct hive *h) :
hive( h ),
root( r )
{
fprintf(stderr, "RegistryItemModel::RegistryItemModel\n");
}
QModelIndex RegistryItemModel::index(int row, int column, const QModelIndex& parent) const
{
fprintf(stderr, "RegistryItemModel::index "
"%d, %d\n", row, column);
RegistryItem* parentItem;
if (!parent.isValid())
parentItem = root;
else
parentItem = static_cast<RegistryItem*>( parent.internalPointer() );
RegistryItem *child = parentItem->getChild( row );
if (!child)
return QModelIndex();
return createIndex( row, column, child );
}
int RegistryItemModel::rowCount(const QModelIndex& parent) const
{
if (parent.column()>0)
return 0;
fprintf(stderr, "RegistryItemModel::rowCount "
"%d, %d\n", parent.row(), parent.column());
RegistryItem* parentItem;
if (!parent.isValid())
parentItem = root;
else
parentItem = static_cast<RegistryItem*>( parent.internalPointer() );
return parentItem->getSubkeyCount();
}
QVariant RegistryItemModel::data(const QModelIndex& index, int role) const
{
if (!index.isValid())
return QVariant();
if (role != Qt::DisplayRole)
return QVariant();
fprintf(stderr, "RegistryItemModel::data "
"%d, %d\n", index.row(), index.column());
RegistryItem* item = static_cast<RegistryItem*>( index.internalPointer() );
return item->getName();
}
int main( int argc, char **argv )
{
QApplication app(argc, argv);
if (argc < 2)
{
fprintf(stderr, "Need the name of registry hive\n");
return 1;
}
const char *filename = argv[1];
struct hive *hive;
hive = open_hive(filename, HMODE_RO);
if (!hive)
{
fprintf(stderr, "Failed to open hive\n");
return 1;
}
//nk_ls( hive, "\\", 0, 0);
RegistryItem* rootItem = new RegistryItem( hive, NULL, "" );
RegistryItemModel model(rootItem, hive);
QTreeView keylist;
keylist.resize(320, 200);
keylist.setHeader( 0 );
keylist.setModel( &model );
keylist.show();
return app.exec();
}
<commit_msg>Fix the registry model<commit_after>#include <QApplication>
#include <QTreeView>
#include <QAbstractItemModel>
#include <QList>
#include <qstring.h>
#include <assert.h>
#include "ntreg.h"
class RegistryItem
{
struct hive *hive;
RegistryItem* parent;
QString name;
bool enumerated;
QList<RegistryItem*> subkeys;
public:
RegistryItem( struct hive *h, RegistryItem* p, const QString& n );
~RegistryItem();
QString getPath() const;
RegistryItem* getParent();
RegistryItem* getChild( int n );
int getSubkeyCount();
const QString& getName() const;
int getNumber() const;
protected:
void enumerateChildren();
};
RegistryItem::RegistryItem( struct hive *h, RegistryItem* p, const QString& n ) :
hive( h ),
parent( p ),
name( n ),
enumerated( false )
{
}
RegistryItem::~RegistryItem()
{
}
QString RegistryItem::getPath() const
{
QString path;
if (parent)
{
path = parent->getPath();
path.append( name );
path.append( "\\" );
}
else
{
path = name;
}
return path;
}
RegistryItem* RegistryItem::getParent()
{
return parent;
}
void RegistryItem::enumerateChildren()
{
if (enumerated)
return;
struct ex_data key;
memset( &key, 0, sizeof key );
QString path = getPath();
char *utf8_path = strdup(path.toUtf8().data());
int i = 0;
while (1)
{
int r = nk_get_subkey( hive, utf8_path, 0, i, &key );
if (r < 0)
break;
QString kn( key.name );
RegistryItem* item = new RegistryItem( hive, this, kn );
//free( key.name );
subkeys.append( item );
i++;
}
free( utf8_path );
enumerated = true;
}
RegistryItem* RegistryItem::getChild( int n )
{
enumerateChildren();
return subkeys.at( n );
}
int RegistryItem::getSubkeyCount()
{
enumerateChildren();
return subkeys.count();
}
const QString& RegistryItem::getName() const
{
return name;
}
int RegistryItem::getNumber() const
{
if (!parent)
return 0;
return parent->subkeys.lastIndexOf( const_cast<RegistryItem*>(this) );
}
class RegistryItemModel : public QAbstractItemModel
{
struct hive *hive;
RegistryItem *root;
public:
RegistryItemModel(RegistryItem* root, struct hive *h);
virtual Qt::ItemFlags flags(const QModelIndex &index) const;
virtual QModelIndex index(int,int,const QModelIndex&) const;
virtual int rowCount(const QModelIndex& index) const;
virtual int columnCount(const QModelIndex& index) const;
virtual QVariant data(const QModelIndex&, int) const;
virtual QModelIndex parent(const QModelIndex & index) const;
virtual QVariant headerData(int section, Qt::Orientation orientation, int role) const;
};
RegistryItemModel::RegistryItemModel(RegistryItem* r, struct hive *h) :
hive( h ),
root( r )
{
}
Qt::ItemFlags RegistryItemModel::flags(const QModelIndex &index) const
{
if (!index.isValid())
return 0;
return Qt::ItemIsEnabled | Qt::ItemIsSelectable;
}
QVariant RegistryItemModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (orientation == Qt::Horizontal && role == Qt::DisplayRole)
return "registry";
return QVariant();
}
QModelIndex RegistryItemModel::index(int row, int column, const QModelIndex& parent) const
{
if (!hasIndex(row, column, parent))
return QModelIndex();
RegistryItem *parentItem, *item;
if (!parent.isValid())
parentItem = root;
else
parentItem = static_cast<RegistryItem*>( parent.internalPointer() );
item = parentItem->getChild( row );
if (!item) return QModelIndex();
assert( row == item->getNumber());
return createIndex( row, column, item );
}
QModelIndex RegistryItemModel::parent(const QModelIndex &index) const
{
if (!index.isValid())
return QModelIndex();
RegistryItem* item = static_cast<RegistryItem*>( index.internalPointer() );
RegistryItem* parent = item->getParent();
if (parent == root)
return QModelIndex();
return createIndex( parent->getNumber(), 0, parent );
}
int RegistryItemModel::columnCount(const QModelIndex& parent) const
{
if (!parent.isValid())
return 1;
RegistryItem* parentItem = static_cast<RegistryItem*>( parent.internalPointer() );
if (parentItem->getSubkeyCount())
return 1;
else
return 0;
}
int RegistryItemModel::rowCount(const QModelIndex& parent) const
{
if (parent.column()>0)
return 0;
RegistryItem* parentItem;
if (!parent.isValid())
parentItem = root;
else
parentItem = static_cast<RegistryItem*>( parent.internalPointer() );
return parentItem->getSubkeyCount();
}
QVariant RegistryItemModel::data(const QModelIndex& index, int role) const
{
if (!index.isValid())
return QVariant();
if (role != Qt::DisplayRole)
return QVariant();
RegistryItem* item = static_cast<RegistryItem*>( index.internalPointer() );
return item->getName();
}
int main( int argc, char **argv )
{
QApplication app(argc, argv);
if (argc < 2)
{
fprintf(stderr, "Need the name of registry hive\n");
return 1;
}
struct hive *hive = 0;
const char *filename = argv[1];
hive = open_hive(filename, HMODE_RO);
if (!hive)
{
fprintf(stderr, "Failed to open hive\n");
return 1;
}
QString kn( "\\" );
RegistryItem *rootItem = new RegistryItem( hive, NULL, kn );
RegistryItemModel model(rootItem, hive);
QTreeView keylist;
keylist.setModel( &model );
keylist.setWindowTitle(QObject::tr("Registry editor"));
keylist.show();
return app.exec();
}
<|endoftext|> |
<commit_before>/*
This file is part of KOrganizer.
Copyright (c) 2003 Cornelius Schumacher <schumacher@kde.org>
Copyright (c) 2005 Rafal Rzepecki <divide@users.sourceforge.net>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include "urihandler.h"
#include <knodeinterface.h>
#include <kmailinterface.h>
#include <korganizerinterface.h>
#include <coreinterface.h>
#include <libkdepim/kdepimprotocols.h>
#include <kiconloader.h>
#include <krun.h>
#include <kapplication.h>
#include <kshell.h>
#include <kdebug.h>
#include <ktoolinvocation.h>
#include <QObject>
bool UriHandler::process( const QString &uri )
{
kDebug(5850) <<"UriHandler::process():" << uri;
if ( uri.startsWith( KDEPIMPROTOCOL_EMAIL ) ) {
// make sure kmail is running or the part is shown
KToolInvocation::startServiceByDesktopPath("kmail");
// parse string, show
int colon = uri.indexOf( ':' );
// extract 'number' from 'kmail:<number>/<id>'
QString serialNumberStr = uri.mid( colon + 1 );
serialNumberStr = serialNumberStr.left( serialNumberStr.indexOf( '/' ) );
org::kde::kmail::kmail kmail("org.kde.kmail", "/KMail", QDBusConnection::sessionBus());
kmail.showMail( serialNumberStr.toUInt(), QString() );
return true;
} else if ( uri.startsWith( "mailto:" ) ) {
KToolInvocation::invokeMailer( uri.mid(7), QString() );
return true;
} else if ( uri.startsWith( KDEPIMPROTOCOL_CONTACT ) ) {
if (QDBusConnection::sessionBus().interface()->isServiceRegistered("org.kde.kaddressbook") ) {
kapp->updateRemoteUserTimestamp("org.kde.kaddressbook");
org::kde::KAddressbook::Core kaddressbook("org.kde.kaddressbook", "/KAddressBook", QDBusConnection::sessionBus());
kaddressbook.showContactEditor(uri.mid( ::qstrlen( KDEPIMPROTOCOL_CONTACT ) ) );
return true;
} else {
/*
KaddressBook is not already running. Pass it the UID of the contact via the command line while starting it - its neater.
We start it without its main interface
*/
QString iconPath = KIconLoader::global()->iconPath( "go", KIconLoader::Small );
QString tmpStr = "kaddressbook --editor-only --uid ";
tmpStr += KShell::quoteArg( uri.mid( ::qstrlen( KDEPIMPROTOCOL_CONTACT ) )
);
KRun::runCommand( tmpStr, "KAddressBook", iconPath, 0 );
return true;
}
} else if ( uri.startsWith( KDEPIMPROTOCOL_INCIDENCE ) ) {
// make sure korganizer is running or the part is shown
KToolInvocation::startServiceByDesktopPath("korganizer");
// we must work around KUrl breakage (it doesn't know about URNs)
QString uid = KUrl::fromPercentEncoding( uri.toLatin1() ).mid( 11 );
OrgKdeKorganizerKorganizerInterface korganizerIface("org.kde.korganizer", "/Korganizer", QDBusConnection::sessionBus() );
return korganizerIface.showIncidence( uid );
} else if ( uri.startsWith( KDEPIMPROTOCOL_NEWSARTICLE ) ) {
KToolInvocation::startServiceByDesktopPath( "knode" );
org::kde::knode knode("org.kde.knode", "/KNode", QDBusConnection::sessionBus());
knode.openURL(uri);
} else { // no special URI, let KDE handle it
new KRun(KUrl( uri ),0);
}
return false;
}
<commit_msg>fix the kaddressbook icon. and some minor coding style fixes<commit_after>/*
This file is part of KOrganizer.
Copyright (c) 2003 Cornelius Schumacher <schumacher@kde.org>
Copyright (c) 2005 Rafal Rzepecki <divide@users.sourceforge.net>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include "urihandler.h"
#include <knodeinterface.h>
#include <kmailinterface.h>
#include <korganizerinterface.h>
#include <coreinterface.h>
#include <libkdepim/kdepimprotocols.h>
#include <kiconloader.h>
#include <krun.h>
#include <kapplication.h>
#include <kshell.h>
#include <kdebug.h>
#include <ktoolinvocation.h>
#include <QObject>
bool UriHandler::process( const QString &uri )
{
kDebug(5850) <<"UriHandler::process():" << uri;
if ( uri.startsWith( KDEPIMPROTOCOL_EMAIL ) ) {
// make sure kmail is running or the part is shown
KToolInvocation::startServiceByDesktopPath( "kmail" );
// parse string, show
int colon = uri.indexOf( ':' );
// extract 'number' from 'kmail:<number>/<id>'
QString serialNumberStr = uri.mid( colon + 1 );
serialNumberStr = serialNumberStr.left( serialNumberStr.indexOf( '/' ) );
org::kde::kmail::kmail kmail(
"org.kde.kmail", "/KMail", QDBusConnection::sessionBus() );
kmail.showMail( serialNumberStr.toUInt(), QString() );
return true;
} else if ( uri.startsWith( "mailto:" ) ) {
KToolInvocation::invokeMailer( uri.mid(7), QString() );
return true;
} else if ( uri.startsWith( KDEPIMPROTOCOL_CONTACT ) ) {
if ( QDBusConnection::sessionBus().interface()->isServiceRegistered(
"org.kde.kaddressbook" ) ) {
kapp->updateRemoteUserTimestamp( "org.kde.kaddressbook" );
org::kde::KAddressbook::Core kaddressbook(
"org.kde.kaddressbook", "/KAddressBook", QDBusConnection::sessionBus() );
kaddressbook.showContactEditor( uri.mid( ::qstrlen( KDEPIMPROTOCOL_CONTACT ) ) );
return true;
} else {
/*
KaddressBook is not already running. Pass it the UID of the contact via
the command line while starting it - its neater.
We start it without its main interface
*/
QString iconPath = KIconLoader::global()->iconPath( "view-pim-contacts", KIconLoader::Small );
QString tmpStr = "kaddressbook --editor-only --uid ";
tmpStr += KShell::quoteArg( uri.mid( ::qstrlen( KDEPIMPROTOCOL_CONTACT ) ) );
KRun::runCommand( tmpStr, "KAddressBook", iconPath, 0 );
return true;
}
} else if ( uri.startsWith( KDEPIMPROTOCOL_INCIDENCE ) ) {
// make sure korganizer is running or the part is shown
KToolInvocation::startServiceByDesktopPath( "korganizer" );
// we must work around KUrl breakage (it doesn't know about URNs)
QString uid = KUrl::fromPercentEncoding( uri.toLatin1() ).mid( 11 );
OrgKdeKorganizerKorganizerInterface korganizerIface(
"org.kde.korganizer", "/Korganizer", QDBusConnection::sessionBus() );
return korganizerIface.showIncidence( uid );
} else if ( uri.startsWith( KDEPIMPROTOCOL_NEWSARTICLE ) ) {
KToolInvocation::startServiceByDesktopPath( "knode" );
org::kde::knode knode(
"org.kde.knode", "/KNode", QDBusConnection::sessionBus() );
knode.openURL( uri );
} else { // no special URI, let KDE handle it
new KRun( KUrl( uri ), 0 );
}
return false;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2014 Andrew Duggan
* Copyright (C) 2014 Synaptics Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <getopt.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <dirent.h>
#include <unistd.h>
#include <time.h>
#include <string>
#include <sstream>
#include "hiddevice.h"
#include "rmi4update.h"
#define VERSION_MAJOR 1
#define VERSION_MINOR 2
#define VERSION_SUBMINOR 10
#define RMI4UPDATE_GETOPTS "hfdt:pclv"
void printHelp(const char *prog_name)
{
fprintf(stdout, "Usage: %s [OPTIONS] FIRMWAREFILE\n", prog_name);
fprintf(stdout, "\t-h, --help\tPrint this message\n");
fprintf(stdout, "\t-f, --force\tForce updating firmware even it the image provided is older\n\t\t\tthen the current firmware on the device.\n");
fprintf(stdout, "\t-d, --device\thidraw device file associated with the device being updated.\n");
fprintf(stdout, "\t-p, --fw-props\tPrint the firmware properties.\n");
fprintf(stdout, "\t-c, --config-id\tPrint the config id.\n");
fprintf(stdout, "\t-l, --lockdown\tPerform lockdown.\n");
fprintf(stdout, "\t-v, --version\tPrint version number.\n");
fprintf(stdout, "\t-t, --device-type\t\t\tFilter by device type [touchpad or touchscreen].\n");
}
void printVersion()
{
fprintf(stdout, "rmi4update version %d.%d.%d\n",
VERSION_MAJOR, VERSION_MINOR, VERSION_SUBMINOR);
}
int GetFirmwareProps(const char * deviceFile, std::string &props, bool configid)
{
HIDDevice rmidevice;
int rc = UPDATE_SUCCESS;
std::stringstream ss;
rc = rmidevice.Open(deviceFile);
if (rc)
return rc;
rmidevice.ScanPDT(0x1);
rmidevice.QueryBasicProperties();
if (configid) {
ss << std::hex << rmidevice.GetConfigID();
} else {
ss << rmidevice.GetFirmwareVersionMajor() << "."
<< rmidevice.GetFirmwareVersionMinor() << "."
<< std::hex << rmidevice.GetFirmwareID();
if (rmidevice.InBootloader())
ss << " bootloader";
}
props = ss.str();
return rc;
}
int main(int argc, char **argv)
{
int rc;
FirmwareImage image;
int opt;
int index;
char *deviceName = NULL;
const char *firmwareName = NULL;
bool force = false;
static struct option long_options[] = {
{"help", 0, NULL, 'h'},
{"force", 0, NULL, 'f'},
{"device", 1, NULL, 'd'},
{"fw-props", 0, NULL, 'p'},
{"config-id", 0, NULL, 'c'},
{"lockdown", 0, NULL, 'l'},
{"version", 0, NULL, 'v'},
{"device-type", 1, NULL, 't'},
{0, 0, 0, 0},
};
bool printFirmwareProps = false;
bool printConfigid = false;
bool performLockdown = false;
HIDDevice device;
enum RMIDeviceType deviceType = RMI_DEVICE_TYPE_ANY;
while ((opt = getopt_long(argc, argv, RMI4UPDATE_GETOPTS, long_options, &index)) != -1) {
switch (opt) {
case 'h':
printHelp(argv[0]);
return 0;
case 'f':
force = true;
break;
case 'd':
deviceName = optarg;
break;
case 'p':
printFirmwareProps = true;
break;
case 'c':
printFirmwareProps = true;
printConfigid = true;
break;
case 'l':
performLockdown = true;
break;
case 't':
if (!strcasecmp((const char *)optarg, "touchpad"))
deviceType = RMI_DEVICE_TYPE_TOUCHPAD;
else if (!strcasecmp((const char *)optarg, "touchscreen"))
deviceType = RMI_DEVICE_TYPE_TOUCHSCREEN;
break;
case 'v':
printVersion();
return 0;
default:
break;
}
}
if (printFirmwareProps) {
std::string props;
if (!deviceName) {
fprintf(stderr, "Specifiy which device to query\n");
return 1;
}
rc = GetFirmwareProps(deviceName, props, printConfigid);
if (rc) {
fprintf(stderr, "Failed to read properties from device: %s\n", update_err_to_string(rc));
return 1;
}
fprintf(stdout, "%s\n", props.c_str());
return 0;
}
if (optind < argc) {
firmwareName = argv[optind];
} else {
printHelp(argv[0]);
return -1;
}
rc = image.Initialize(firmwareName);
if (rc != UPDATE_SUCCESS) {
fprintf(stderr, "Failed to initialize the firmware image: %s\n", update_err_to_string(rc));
return 1;
}
if (deviceName) {
rc = device.Open(deviceName);
if (rc) {
fprintf(stderr, "%s: failed to initialize rmi device (%d): %s\n", argv[0], errno,
strerror(errno));
return 1;
}
} else {
if (!device.FindDevice(deviceType))
return 1;
}
RMI4Update update(device, image);
rc = update.UpdateFirmware(force, performLockdown);
if (rc != UPDATE_SUCCESS)
{
device.Reset();
return 1;
}
return 0;
}
<commit_msg>Fix spacing in help text<commit_after>/*
* Copyright (C) 2014 Andrew Duggan
* Copyright (C) 2014 Synaptics Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <getopt.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <dirent.h>
#include <unistd.h>
#include <time.h>
#include <string>
#include <sstream>
#include "hiddevice.h"
#include "rmi4update.h"
#define VERSION_MAJOR 1
#define VERSION_MINOR 2
#define VERSION_SUBMINOR 10
#define RMI4UPDATE_GETOPTS "hfdt:pclv"
void printHelp(const char *prog_name)
{
fprintf(stdout, "Usage: %s [OPTIONS] FIRMWAREFILE\n", prog_name);
fprintf(stdout, "\t-h, --help\t\tPrint this message\n");
fprintf(stdout, "\t-f, --force\t\tForce updating firmware even it the image provided is older\n\t\t\t\tthen the current firmware on the device.\n");
fprintf(stdout, "\t-d, --device\t\thidraw device file associated with the device being updated.\n");
fprintf(stdout, "\t-p, --fw-props\t\tPrint the firmware properties.\n");
fprintf(stdout, "\t-c, --config-id\t\tPrint the config id.\n");
fprintf(stdout, "\t-l, --lockdown\t\tPerform lockdown.\n");
fprintf(stdout, "\t-v, --version\t\tPrint version number.\n");
fprintf(stdout, "\t-t, --device-type\tFilter by device type [touchpad or touchscreen].\n");
}
void printVersion()
{
fprintf(stdout, "rmi4update version %d.%d.%d\n",
VERSION_MAJOR, VERSION_MINOR, VERSION_SUBMINOR);
}
int GetFirmwareProps(const char * deviceFile, std::string &props, bool configid)
{
HIDDevice rmidevice;
int rc = UPDATE_SUCCESS;
std::stringstream ss;
rc = rmidevice.Open(deviceFile);
if (rc)
return rc;
rmidevice.ScanPDT(0x1);
rmidevice.QueryBasicProperties();
if (configid) {
ss << std::hex << rmidevice.GetConfigID();
} else {
ss << rmidevice.GetFirmwareVersionMajor() << "."
<< rmidevice.GetFirmwareVersionMinor() << "."
<< std::hex << rmidevice.GetFirmwareID();
if (rmidevice.InBootloader())
ss << " bootloader";
}
props = ss.str();
return rc;
}
int main(int argc, char **argv)
{
int rc;
FirmwareImage image;
int opt;
int index;
char *deviceName = NULL;
const char *firmwareName = NULL;
bool force = false;
static struct option long_options[] = {
{"help", 0, NULL, 'h'},
{"force", 0, NULL, 'f'},
{"device", 1, NULL, 'd'},
{"fw-props", 0, NULL, 'p'},
{"config-id", 0, NULL, 'c'},
{"lockdown", 0, NULL, 'l'},
{"version", 0, NULL, 'v'},
{"device-type", 1, NULL, 't'},
{0, 0, 0, 0},
};
bool printFirmwareProps = false;
bool printConfigid = false;
bool performLockdown = false;
HIDDevice device;
enum RMIDeviceType deviceType = RMI_DEVICE_TYPE_ANY;
while ((opt = getopt_long(argc, argv, RMI4UPDATE_GETOPTS, long_options, &index)) != -1) {
switch (opt) {
case 'h':
printHelp(argv[0]);
return 0;
case 'f':
force = true;
break;
case 'd':
deviceName = optarg;
break;
case 'p':
printFirmwareProps = true;
break;
case 'c':
printFirmwareProps = true;
printConfigid = true;
break;
case 'l':
performLockdown = true;
break;
case 't':
if (!strcasecmp((const char *)optarg, "touchpad"))
deviceType = RMI_DEVICE_TYPE_TOUCHPAD;
else if (!strcasecmp((const char *)optarg, "touchscreen"))
deviceType = RMI_DEVICE_TYPE_TOUCHSCREEN;
break;
case 'v':
printVersion();
return 0;
default:
break;
}
}
if (printFirmwareProps) {
std::string props;
if (!deviceName) {
fprintf(stderr, "Specifiy which device to query\n");
return 1;
}
rc = GetFirmwareProps(deviceName, props, printConfigid);
if (rc) {
fprintf(stderr, "Failed to read properties from device: %s\n", update_err_to_string(rc));
return 1;
}
fprintf(stdout, "%s\n", props.c_str());
return 0;
}
if (optind < argc) {
firmwareName = argv[optind];
} else {
printHelp(argv[0]);
return -1;
}
rc = image.Initialize(firmwareName);
if (rc != UPDATE_SUCCESS) {
fprintf(stderr, "Failed to initialize the firmware image: %s\n", update_err_to_string(rc));
return 1;
}
if (deviceName) {
rc = device.Open(deviceName);
if (rc) {
fprintf(stderr, "%s: failed to initialize rmi device (%d): %s\n", argv[0], errno,
strerror(errno));
return 1;
}
} else {
if (!device.FindDevice(deviceType))
return 1;
}
RMI4Update update(device, image);
rc = update.UpdateFirmware(force, performLockdown);
if (rc != UPDATE_SUCCESS)
{
device.Reset();
return 1;
}
return 0;
}
<|endoftext|> |
<commit_before>// Core SPC emulation: CPU, timers, SMP registers, memory
// snes_spc 0.9.0. http://www.slack.net/~ant/
#include "SNES_SPC.h"
#include <string.h>
/* Copyright (C) 2004-2007 Shay Green. This module 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 2.1 of the License, or (at your option) any later version. This
module is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
details. You should have received a copy of the GNU Lesser General Public
License along with this module; if not, write to the Free Software Foundation,
Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */
#include "blargg_source.h"
#define RAM (m.ram.ram)
#define REGS (m.smp_regs [0])
#define REGS_IN (m.smp_regs [1])
// (n ? n : 256)
#define IF_0_THEN_256( n ) ((uint8_t) ((n) - 1) + 1)
#ifdef BLARGG_ENABLE_OPTIMIZER
#include BLARGG_ENABLE_OPTIMIZER
#endif
//// Timers
#define TIMER_DIV( t, n ) ((n) >> t->prescaler)
#define TIMER_MUL( t, n ) ((n) << t->prescaler)
SNES_SPC::Timer* SNES_SPC::run_timer_( Timer* t, rel_time_t time )
{
int elapsed = TIMER_DIV( t, time - t->next_time ) + 1;
t->next_time += TIMER_MUL( t, elapsed );
if ( t->enabled )
{
int remain = IF_0_THEN_256( t->period - t->divider );
int divider = t->divider + elapsed;
int over = elapsed - remain;
if ( over >= 0 )
{
int n = over / t->period;
t->counter = (t->counter + 1 + n) & 0x0F;
divider = over - n * t->period;
}
t->divider = (uint8_t) divider;
}
return t;
}
inline SNES_SPC::Timer* SNES_SPC::run_timer( Timer* t, rel_time_t time )
{
if ( time >= t->next_time )
t = run_timer_( t, time );
return t;
}
//// ROM
void SNES_SPC::enable_rom( int enable )
{
if ( m.rom_enabled != enable )
{
m.rom_enabled = enable;
if ( enable )
memcpy( m.hi_ram, &RAM [rom_addr], sizeof m.hi_ram );
memcpy( &RAM [rom_addr], (enable ? m.rom : m.hi_ram), rom_size );
// TODO: ROM can still get overwritten when DSP writes to echo buffer
}
}
//// DSP
#define RUN_DSP( time, offset ) \
{\
int count = (time) - m.dsp_time;\
assert( count > 0 );\
m.dsp_time = (time);\
dsp->run( count );\
}
int SNES_SPC::dsp_read( rel_time_t time )
{
RUN_DSP( time, reg_times [REGS [r_dspaddr] & 0x7F] );
int result = dsp->read( REGS [r_dspaddr] & 0x7F );
#ifdef SPC_DSP_READ_HOOK
SPC_DSP_READ_HOOK( spc_time + time, (REGS [r_dspaddr] & 0x7F), result );
#endif
return result;
}
inline void SNES_SPC::dsp_write( int data, rel_time_t time )
{
RUN_DSP( time, reg_times [REGS [r_dspaddr]] )
#ifdef SPC_DSP_WRITE_HOOK
SPC_DSP_WRITE_HOOK( m.spc_time + time, REGS [r_dspaddr], (uint8_t) data );
#endif
if ( REGS [r_dspaddr] <= 0x7F )
dsp->write( REGS [r_dspaddr], data );
else
dprintf( "SPC wrote to DSP register > $7F\n" );
}
//// Memory access extras
#define MEM_ACCESS( time, addr )
// divided into multiple functions to keep rarely-used functionality separate
// so often-used functionality can be optimized better by compiler
// If write isn't preceded by read, data has this added to it
int const no_read_before_write = 0x2000;
void SNES_SPC::cpu_write_smp_reg_( int data, rel_time_t time, int addr )
{
switch ( addr )
{
case r_t0target:
case r_t1target:
case r_t2target: {
Timer* t = &m.timers [addr - r_t0target];
int period = IF_0_THEN_256( data );
if ( t->period != period )
{
t = run_timer( t, time );
t->period = period;
}
break;
}
case r_t0out:
case r_t1out:
case r_t2out:
dprintf( "SPC wrote to counter %d\n", (int) addr - r_t0out );
if ( data < no_read_before_write / 2 )
run_timer( &m.timers [addr - r_t0out], time - 1 )->counter = 0;
break;
// Registers that act like RAM
case 0x8:
case 0x9:
REGS_IN [addr] = (uint8_t) data;
break;
case r_test:
if ( (uint8_t) data != 0x0A )
dprintf( "SPC wrote to test register\n" );
break;
case r_control:
// port clears
if ( data & 0x10 )
{
REGS_IN [r_cpuio0] = 0;
REGS_IN [r_cpuio1] = 0;
}
if ( data & 0x20 )
{
REGS_IN [r_cpuio2] = 0;
REGS_IN [r_cpuio3] = 0;
}
// timers
{
for ( int i = 0; i < timer_count; i++ )
{
Timer* t = &m.timers [i];
int enabled = data >> i & 1;
if ( t->enabled != enabled )
{
t = run_timer( t, time );
t->enabled = enabled;
if ( enabled )
{
t->divider = 0;
t->counter = 0;
}
}
}
}
enable_rom( data & 0x80 );
break;
}
}
void SNES_SPC::cpu_write_smp_reg( int data, rel_time_t time, int addr )
{
if ( addr == r_dspdata ) // 99%
dsp_write( data, time );
else
cpu_write_smp_reg_( data, time, addr );
}
void SNES_SPC::cpu_write_high( int data, int i, rel_time_t time )
{
if ( i < rom_size )
{
m.hi_ram [i] = (uint8_t) data;
if ( m.rom_enabled )
RAM [i + rom_addr] = m.rom [i]; // restore overwritten ROM
}
else
{
assert( RAM [i + rom_addr] == (uint8_t) data );
RAM [i + rom_addr] = cpu_pad_fill; // restore overwritten padding
cpu_write( data, i + rom_addr - 0x10000, time );
}
}
int const bits_in_int = CHAR_BIT * sizeof (int);
void SNES_SPC::cpu_write( int data, int addr, rel_time_t time )
{
MEM_ACCESS( time, addr )
// RAM
RAM [addr] = (uint8_t) data;
int reg = addr - 0xF0;
if ( reg >= 0 ) // 64%
{
// $F0-$FF
if ( reg < reg_count ) // 87%
{
REGS [reg] = (uint8_t) data;
// Ports
#ifdef SPC_PORT_WRITE_HOOK
if ( (unsigned) (reg - r_cpuio0) < port_count )
SPC_PORT_WRITE_HOOK( m.spc_time + time, (reg - r_cpuio0),
(uint8_t) data, ®S [r_cpuio0] );
#endif
// Registers other than $F2 and $F4-$F7
//if ( reg != 2 && reg != 4 && reg != 5 && reg != 6 && reg != 7 )
// TODO: this is a bit on the fragile side
if ( ((~0x2F00 << (bits_in_int - 16)) << reg) < 0 ) // 36%
cpu_write_smp_reg( data, time, reg );
}
// High mem/address wrap-around
else
{
reg -= rom_addr - 0xF0;
if ( reg >= 0 ) // 1% in IPL ROM area or address wrapped around
cpu_write_high( data, reg, time );
}
}
}
//// CPU read
inline int SNES_SPC::cpu_read_smp_reg( int reg, rel_time_t time )
{
int result = REGS_IN [reg];
reg -= r_dspaddr;
// DSP addr and data
if ( (unsigned) reg <= 1 ) // 4% 0xF2 and 0xF3
{
result = REGS [r_dspaddr];
if ( (unsigned) reg == 1 )
result = dsp_read( time ); // 0xF3
}
return result;
}
int SNES_SPC::cpu_read( int addr, rel_time_t time )
{
MEM_ACCESS( time, addr )
// RAM
int result = RAM [addr];
int reg = addr - 0xF0;
if ( reg >= 0 ) // 40%
{
reg -= 0x10;
if ( (unsigned) reg >= 0xFF00 ) // 21%
{
reg += 0x10 - r_t0out;
// Timers
if ( (unsigned) reg < timer_count ) // 90%
{
Timer* t = &m.timers [reg];
if ( time >= t->next_time )
t = run_timer_( t, time );
result = t->counter;
t->counter = 0;
}
// Other registers
else if ( reg < 0 ) // 10%
{
result = cpu_read_smp_reg( reg + r_t0out, time );
}
else // 1%
{
assert( reg + (r_t0out + 0xF0 - 0x10000) < 0x100 );
result = cpu_read( reg + (r_t0out + 0xF0 - 0x10000), time );
}
}
}
return result;
}
//// Run
// Prefix and suffix for CPU emulator function
#define SPC_CPU_RUN_FUNC \
BOOST::uint8_t* SNES_SPC::run_until_( time_t end_time )\
{\
rel_time_t rel_time = m.spc_time - end_time;\
assert( rel_time <= 0 );\
m.spc_time = end_time;\
m.dsp_time += rel_time;\
m.timers [0].next_time += rel_time;\
m.timers [1].next_time += rel_time;\
m.timers [2].next_time += rel_time;
#define SPC_CPU_RUN_FUNC_END \
m.spc_time += rel_time;\
m.dsp_time -= rel_time;\
m.timers [0].next_time -= rel_time;\
m.timers [1].next_time -= rel_time;\
m.timers [2].next_time -= rel_time;\
assert( m.spc_time <= end_time );\
return ®S [r_cpuio0];\
}
int const cpu_lag_max = 12 - 1; // DIV YA,X takes 12 clocks
void SNES_SPC::end_frame( time_t end_time )
{
// Catch CPU up to as close to end as possible. If final instruction
// would exceed end, does NOT execute it and leaves m.spc_time < end.
if ( end_time > m.spc_time )
run_until_( end_time );
m.spc_time -= end_time;
m.extra_clocks += end_time;
// Greatest number of clocks early that emulation can stop early due to
// not being able to execute current instruction without going over
// allowed time.
assert( -cpu_lag_max <= m.spc_time && m.spc_time <= 0 );
// Catch timers up to CPU
for ( int i = 0; i < timer_count; i++ )
run_timer( &m.timers [i], 0 );
// Catch DSP up to CPU
if ( m.dsp_time < 0 )
{
RUN_DSP( 0, max_reg_time );
}
// Save any extra samples beyond what should be generated
if ( m.buf_begin )
save_extra();
}
// Inclusion here allows static memory access functions and better optimization
#include "SPC_CPU.h"
<commit_msg>enough shaving; time to start separating<commit_after>// Core SPC emulation: CPU, timers, SMP registers, memory
// snes_spc 0.9.0. http://www.slack.net/~ant/
#include "SNES_SPC.h"
#include <string.h>
/* Copyright (C) 2004-2007 Shay Green. This module 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 2.1 of the License, or (at your option) any later version. This
module is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
details. You should have received a copy of the GNU Lesser General Public
License along with this module; if not, write to the Free Software Foundation,
Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */
#include "blargg_source.h"
#define RAM (m.ram.ram)
#define REGS (m.smp_regs [0])
#define REGS_IN (m.smp_regs [1])
// (n ? n : 256)
#define IF_0_THEN_256( n ) ((uint8_t) ((n) - 1) + 1)
#ifdef BLARGG_ENABLE_OPTIMIZER
#include BLARGG_ENABLE_OPTIMIZER
#endif
//// Timers
#define TIMER_DIV( t, n ) ((n) >> t->prescaler)
#define TIMER_MUL( t, n ) ((n) << t->prescaler)
SNES_SPC::Timer* SNES_SPC::run_timer_( Timer* t, rel_time_t time )
{
int elapsed = TIMER_DIV( t, time - t->next_time ) + 1;
t->next_time += TIMER_MUL( t, elapsed );
if ( t->enabled )
{
int remain = IF_0_THEN_256( t->period - t->divider );
int divider = t->divider + elapsed;
int over = elapsed - remain;
if ( over >= 0 )
{
int n = over / t->period;
t->counter = (t->counter + 1 + n) & 0x0F;
divider = over - n * t->period;
}
t->divider = (uint8_t) divider;
}
return t;
}
inline SNES_SPC::Timer* SNES_SPC::run_timer( Timer* t, rel_time_t time )
{
if ( time >= t->next_time )
t = run_timer_( t, time );
return t;
}
//// ROM
void SNES_SPC::enable_rom( int enable )
{
if ( m.rom_enabled != enable )
{
m.rom_enabled = enable;
if ( enable )
memcpy( m.hi_ram, &RAM [rom_addr], sizeof m.hi_ram );
memcpy( &RAM [rom_addr], (enable ? m.rom : m.hi_ram), rom_size );
// TODO: ROM can still get overwritten when DSP writes to echo buffer
}
}
//// DSP
#define RUN_DSP( time, offset ) \
{\
int count = (time) - m.dsp_time;\
assert( count > 0 );\
m.dsp_time = (time);\
dsp->run( count );\
}
int SNES_SPC::dsp_read( rel_time_t time )
{
RUN_DSP( time, reg_times [REGS [r_dspaddr] & 0x7F] );
int result = dsp->read( REGS [r_dspaddr] & 0x7F );
return result;
}
inline void SNES_SPC::dsp_write( int data, rel_time_t time )
{
RUN_DSP( time, reg_times [REGS [r_dspaddr]] )
if ( REGS [r_dspaddr] <= 0x7F )
dsp->write( REGS [r_dspaddr], data );
else
dprintf( "SPC wrote to DSP register > $7F\n" );
}
//// Memory access extras
#define MEM_ACCESS( time, addr )
// divided into multiple functions to keep rarely-used functionality separate
// so often-used functionality can be optimized better by compiler
// If write isn't preceded by read, data has this added to it
int const no_read_before_write = 0x2000;
void SNES_SPC::cpu_write_smp_reg_( int data, rel_time_t time, int addr )
{
switch ( addr )
{
case r_t0target:
case r_t1target:
case r_t2target: {
Timer* t = &m.timers [addr - r_t0target];
int period = IF_0_THEN_256( data );
if ( t->period != period )
{
t = run_timer( t, time );
t->period = period;
}
break;
}
case r_t0out:
case r_t1out:
case r_t2out:
dprintf( "SPC wrote to counter %d\n", (int) addr - r_t0out );
if ( data < no_read_before_write / 2 )
run_timer( &m.timers [addr - r_t0out], time - 1 )->counter = 0;
break;
// Registers that act like RAM
case 0x8:
case 0x9:
REGS_IN [addr] = (uint8_t) data;
break;
case r_test:
if ( (uint8_t) data != 0x0A )
dprintf( "SPC wrote to test register\n" );
break;
case r_control:
// port clears
if ( data & 0x10 )
{
REGS_IN [r_cpuio0] = 0;
REGS_IN [r_cpuio1] = 0;
}
if ( data & 0x20 )
{
REGS_IN [r_cpuio2] = 0;
REGS_IN [r_cpuio3] = 0;
}
// timers
{
for ( int i = 0; i < timer_count; i++ )
{
Timer* t = &m.timers [i];
int enabled = data >> i & 1;
if ( t->enabled != enabled )
{
t = run_timer( t, time );
t->enabled = enabled;
if ( enabled )
{
t->divider = 0;
t->counter = 0;
}
}
}
}
enable_rom( data & 0x80 );
break;
}
}
void SNES_SPC::cpu_write_smp_reg( int data, rel_time_t time, int addr )
{
if ( addr == r_dspdata ) // 99%
dsp_write( data, time );
else
cpu_write_smp_reg_( data, time, addr );
}
void SNES_SPC::cpu_write_high( int data, int i, rel_time_t time )
{
if ( i < rom_size )
{
m.hi_ram [i] = (uint8_t) data;
if ( m.rom_enabled )
RAM [i + rom_addr] = m.rom [i]; // restore overwritten ROM
}
else
{
assert( RAM [i + rom_addr] == (uint8_t) data );
RAM [i + rom_addr] = cpu_pad_fill; // restore overwritten padding
cpu_write( data, i + rom_addr - 0x10000, time );
}
}
int const bits_in_int = CHAR_BIT * sizeof (int);
void SNES_SPC::cpu_write( int data, int addr, rel_time_t time )
{
MEM_ACCESS( time, addr )
// RAM
RAM [addr] = (uint8_t) data;
int reg = addr - 0xF0;
if ( reg >= 0 ) // 64%
{
// $F0-$FF
if ( reg < reg_count ) // 87%
{
REGS [reg] = (uint8_t) data;
// Ports
#ifdef SPC_PORT_WRITE_HOOK
if ( (unsigned) (reg - r_cpuio0) < port_count )
SPC_PORT_WRITE_HOOK( m.spc_time + time, (reg - r_cpuio0),
(uint8_t) data, ®S [r_cpuio0] );
#endif
// Registers other than $F2 and $F4-$F7
//if ( reg != 2 && reg != 4 && reg != 5 && reg != 6 && reg != 7 )
// TODO: this is a bit on the fragile side
if ( ((~0x2F00 << (bits_in_int - 16)) << reg) < 0 ) // 36%
cpu_write_smp_reg( data, time, reg );
}
// High mem/address wrap-around
else
{
reg -= rom_addr - 0xF0;
if ( reg >= 0 ) // 1% in IPL ROM area or address wrapped around
cpu_write_high( data, reg, time );
}
}
}
//// CPU read
inline int SNES_SPC::cpu_read_smp_reg( int reg, rel_time_t time )
{
int result = REGS_IN [reg];
reg -= r_dspaddr;
// DSP addr and data
if ( (unsigned) reg <= 1 ) // 4% 0xF2 and 0xF3
{
result = REGS [r_dspaddr];
if ( (unsigned) reg == 1 )
result = dsp_read( time ); // 0xF3
}
return result;
}
int SNES_SPC::cpu_read( int addr, rel_time_t time )
{
MEM_ACCESS( time, addr )
// RAM
int result = RAM [addr];
int reg = addr - 0xF0;
if ( reg >= 0 ) // 40%
{
reg -= 0x10;
if ( (unsigned) reg >= 0xFF00 ) // 21%
{
reg += 0x10 - r_t0out;
// Timers
if ( (unsigned) reg < timer_count ) // 90%
{
Timer* t = &m.timers [reg];
if ( time >= t->next_time )
t = run_timer_( t, time );
result = t->counter;
t->counter = 0;
}
// Other registers
else if ( reg < 0 ) // 10%
{
result = cpu_read_smp_reg( reg + r_t0out, time );
}
else // 1%
{
assert( reg + (r_t0out + 0xF0 - 0x10000) < 0x100 );
result = cpu_read( reg + (r_t0out + 0xF0 - 0x10000), time );
}
}
}
return result;
}
//// Run
// Prefix and suffix for CPU emulator function
#define SPC_CPU_RUN_FUNC \
BOOST::uint8_t* SNES_SPC::run_until_( time_t end_time )\
{\
rel_time_t rel_time = m.spc_time - end_time;\
assert( rel_time <= 0 );\
m.spc_time = end_time;\
m.dsp_time += rel_time;\
m.timers [0].next_time += rel_time;\
m.timers [1].next_time += rel_time;\
m.timers [2].next_time += rel_time;
#define SPC_CPU_RUN_FUNC_END \
m.spc_time += rel_time;\
m.dsp_time -= rel_time;\
m.timers [0].next_time -= rel_time;\
m.timers [1].next_time -= rel_time;\
m.timers [2].next_time -= rel_time;\
assert( m.spc_time <= end_time );\
return ®S [r_cpuio0];\
}
int const cpu_lag_max = 12 - 1; // DIV YA,X takes 12 clocks
void SNES_SPC::end_frame( time_t end_time )
{
// Catch CPU up to as close to end as possible. If final instruction
// would exceed end, does NOT execute it and leaves m.spc_time < end.
if ( end_time > m.spc_time )
run_until_( end_time );
m.spc_time -= end_time;
m.extra_clocks += end_time;
// Greatest number of clocks early that emulation can stop early due to
// not being able to execute current instruction without going over
// allowed time.
assert( -cpu_lag_max <= m.spc_time && m.spc_time <= 0 );
// Catch timers up to CPU
for ( int i = 0; i < timer_count; i++ )
run_timer( &m.timers [i], 0 );
// Catch DSP up to CPU
if ( m.dsp_time < 0 )
{
RUN_DSP( 0, max_reg_time );
}
// Save any extra samples beyond what should be generated
if ( m.buf_begin )
save_extra();
}
// Inclusion here allows static memory access functions and better optimization
#include "SPC_CPU.h"
<|endoftext|> |
<commit_before>#include<iostream>
using namespace std;
int main(){
int size,i,leftTop,rightTop,temp;
cout<<"Enter size of array\n";
cin>>size;
leftTop = 0;
rightTop = size-1;
cout<<"Enter elements of Array\n";
int A[size];
for(i=0;i<size;i++)
cin>>A[i];
while(leftTop < rightTop){
while(A[leftTop]%2 == 0 && leftTop < rightTop)
leftTop++;
while(A[rightTop]%2 == 1 && leftTop < rightTop)
rightTop--;
if(leftTop < rightTop){
temp = A[leftTop];
A[leftTop] = A[rightTop];
A[rightTop] = temp;
}
}
for(i=0;i<size;i++)
cout<<A[i]<<" ";
cout<<"\n";
return 0;
}
<commit_msg>Amazon Question<commit_after>// Given a Linked List of integers, write a function to modify the linked list such that all even numbers appear before all the odd numbers in the modified linked list. Also, keep the order of even and odd numbers same.
#include<iostream>
using namespace std;
struct Node{
int data;
struct Node *next;
}*newptr,*head,*end,*np;
struct Node *createNewNode(int x){
newptr = new Node;
newptr->data = x;
newptr->next = NULL;
return newptr;
}
void display(struct Node *head){
while(head != NULL){
cout<<head->data<<"->";
head = head->next;
}
cout<<"\n";
}
void insertEnd(int x){
np = createNewNode(x);
if(head == NULL)
head = end = np;
else{
end->next = np;
end = np;
}
}
void segregateEvenOdd(struct Node **head){
struct Node *end = *head;
struct Node *prev = NULL;
struct Node *curr = *head;
while(end->next != NULL)
end = end->next;
struct Node *newEnd = end;
while((curr->data)%2 != 0 && curr != end){
newEnd->next = curr;
curr = curr->next;
newEnd->next->next = NULL;
newEnd = newEnd->next;
}
if(curr->data%2 == 0){
*head = curr;
while(curr != end){
if(curr->data%2 == 0){
prev = curr;
curr = curr->next;
}
else{
prev->next = curr->next;
curr->next = NULL;
newEnd->next = curr;
newEnd = curr;
curr = prev->next;
}
}
}
else
prev = curr;
if(newEnd != end && (end->data)%2 != 0){
prev->next = end->next;
end->next = NULL;
newEnd->next = end;
}
return;
}
int main(){
head = end = NULL;
int num,x;
cout<<"Enter the number of elements to be inserted\n";
cin>>num;
cout<<"Enter the elements of linked list\n";
while(num--){
cin>>x;
insertEnd(x);
}
cout<<"The entered linked list is\n";
display(head);
segregateEvenOdd(&head);
cout<<"The modified linked list is\n";
display(head);
return 0;
}
<|endoftext|> |
<commit_before>// $Id: file.cpp,v 1.6 1999/12/28 11:14:05 cisc Exp $
#include <stdio.h>
#include "fmgen_types.h"
#include "fmgen_headers.h"
#include "fmgen_file.h"
// ---------------------------------------------------------------------------
// \z/
// ---------------------------------------------------------------------------
FileIO::FileIO()
{
flags = 0;
}
FileIO::FileIO(const char* filename, uint flg)
{
flags = 0;
Open(filename, flg);
}
FileIO::~FileIO()
{
Close();
}
// ---------------------------------------------------------------------------
// t@CJ
// ---------------------------------------------------------------------------
bool FileIO::Open(const char* filename, uint flg)
{
char mode[5] = "rwb";
Close();
strncpy(path, filename, MAX_PATH);
if(flg & readonly)
strcpy(mode, "rb");
else {
if(flg & create)
strcpy(mode, "rwb+");
else
strcpy(mode, "rwb");
}
pfile = fopen(filename, mode);
flags = (flg & readonly) | (pfile == NULL ? 0 : open);
if (pfile == NULL)
error = file_not_found;
SetLogicalOrigin(0);
return !(pfile == NULL);
}
// ---------------------------------------------------------------------------
// t@CȂꍇ͍쐬
// ---------------------------------------------------------------------------
bool FileIO::CreateNew(const char* filename)
{
uint flg = create;
return Open(filename, flg);
}
// ---------------------------------------------------------------------------
// t@C蒼
// ---------------------------------------------------------------------------
bool FileIO::Reopen(uint flg)
{
if (!(flags & open)) return false;
if ((flags & readonly) && (flg & create)) return false;
if (flags & readonly) flg |= readonly;
return Open(path, flg);
}
// ---------------------------------------------------------------------------
// t@C
// ---------------------------------------------------------------------------
void FileIO::Close()
{
if (GetFlags() & open)
{
fclose(pfile);
flags = 0;
}
}
// ---------------------------------------------------------------------------
// t@Ck̓ǂݏo
// ---------------------------------------------------------------------------
int32 FileIO::Read(void* dest, int32 size)
{
if (!(GetFlags() & open))
return -1;
DWORD readsize;
if (!(readsize = fread(dest, 1, size, pfile)))
return -1;
return size;
}
// ---------------------------------------------------------------------------
// t@Cւ̏o
// ---------------------------------------------------------------------------
int32 FileIO::Write(const void* dest, int32 size)
{
if (!(GetFlags() & open) || (GetFlags() & readonly))
return -1;
DWORD writtensize;
if (!(writtensize = fwrite(dest, 1, size, pfile)))
return -1;
return writtensize;
}
// ---------------------------------------------------------------------------
// t@CV[N
// ---------------------------------------------------------------------------
bool FileIO::Seek(int32 pos, SeekMethod method)
{
if (!(GetFlags() & open))
return false;
int origin;
switch (method)
{
case begin:
origin = SEEK_SET;
break;
case current:
origin = SEEK_CUR;
break;
case end:
origin = SEEK_END;
break;
default:
return false;
}
return fseek(pfile, pos, origin);
}
// ---------------------------------------------------------------------------
// t@C̈ʒu
// ---------------------------------------------------------------------------
int32 FileIO::Tellp()
{
if (!(GetFlags() & open))
return 0;
return ftell(pfile);
}
// ---------------------------------------------------------------------------
// ݂̈ʒut@C̏I[Ƃ
// ---------------------------------------------------------------------------
bool FileIO::SetEndOfFile()
{
if (!(GetFlags() & open))
return false;
return Seek(0, end);
}
<commit_msg>replace libretro-common 30<commit_after>// $Id: file.cpp,v 1.6 1999/12/28 11:14:05 cisc Exp $
#ifdef __cplusplus
extern "C" {
#endif
#include <stdio.h>
#ifdef __cplusplus
}
#endif
#include "fmgen_types.h"
#include "fmgen_headers.h"
#include "fmgen_file.h"
// ---------------------------------------------------------------------------
// \z/
// ---------------------------------------------------------------------------
FileIO::FileIO()
{
flags = 0;
}
FileIO::FileIO(const char* filename, uint flg)
{
flags = 0;
Open(filename, flg);
}
FileIO::~FileIO()
{
Close();
}
// ---------------------------------------------------------------------------
// t@CJ
// ---------------------------------------------------------------------------
bool FileIO::Open(const char* filename, uint flg)
{
char mode[5] = "rwb";
Close();
strncpy(path, filename, MAX_PATH);
if(flg & readonly)
strcpy(mode, "rb");
else {
if(flg & create)
strcpy(mode, "rwb+");
else
strcpy(mode, "rwb");
}
pfile = fopen(filename, mode);
flags = (flg & readonly) | (pfile == NULL ? 0 : open);
if (pfile == NULL)
error = file_not_found;
SetLogicalOrigin(0);
return !(pfile == NULL);
}
// ---------------------------------------------------------------------------
// t@CȂꍇ͍쐬
// ---------------------------------------------------------------------------
bool FileIO::CreateNew(const char* filename)
{
uint flg = create;
return Open(filename, flg);
}
// ---------------------------------------------------------------------------
// t@C蒼
// ---------------------------------------------------------------------------
bool FileIO::Reopen(uint flg)
{
if (!(flags & open)) return false;
if ((flags & readonly) && (flg & create)) return false;
if (flags & readonly) flg |= readonly;
return Open(path, flg);
}
// ---------------------------------------------------------------------------
// t@C
// ---------------------------------------------------------------------------
void FileIO::Close()
{
if (GetFlags() & open)
{
fclose(pfile);
flags = 0;
}
}
// ---------------------------------------------------------------------------
// t@Ck̓ǂݏo
// ---------------------------------------------------------------------------
int32 FileIO::Read(void* dest, int32 size)
{
if (!(GetFlags() & open))
return -1;
DWORD readsize;
if (!(readsize = fread(dest, 1, size, pfile)))
return -1;
return size;
}
// ---------------------------------------------------------------------------
// t@Cւ̏o
// ---------------------------------------------------------------------------
int32 FileIO::Write(const void* dest, int32 size)
{
if (!(GetFlags() & open) || (GetFlags() & readonly))
return -1;
DWORD writtensize;
if (!(writtensize = fwrite(dest, 1, size, pfile)))
return -1;
return writtensize;
}
// ---------------------------------------------------------------------------
// t@CV[N
// ---------------------------------------------------------------------------
bool FileIO::Seek(int32 pos, SeekMethod method)
{
if (!(GetFlags() & open))
return false;
int origin;
switch (method)
{
case begin:
origin = SEEK_SET;
break;
case current:
origin = SEEK_CUR;
break;
case end:
origin = SEEK_END;
break;
default:
return false;
}
return fseek(pfile, pos, origin);
}
// ---------------------------------------------------------------------------
// t@C̈ʒu
// ---------------------------------------------------------------------------
int32 FileIO::Tellp()
{
if (!(GetFlags() & open))
return 0;
return ftell(pfile);
}
// ---------------------------------------------------------------------------
// ݂̈ʒut@C̏I[Ƃ
// ---------------------------------------------------------------------------
bool FileIO::SetEndOfFile()
{
if (!(GetFlags() & open))
return false;
return Seek(0, end);
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/utf_string_conversions.h"
#include "chrome/browser/content_settings/cookie_settings.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/prefs/scoped_user_pref_update.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_info_cache.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/signin/signin_manager_factory.h"
#include "chrome/browser/signin/signin_manager_fake.h"
#include "chrome/browser/sync/profile_sync_service_mock.h"
#include "chrome/browser/sync/profile_sync_service_factory.h"
#include "chrome/browser/ui/sync/one_click_signin_helper.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/base/testing_browser_process.h"
#include "chrome/test/base/testing_profile.h"
#include "chrome/test/base/testing_profile_manager.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/web_contents.h"
#include "content/public/test/test_browser_thread.h"
#include "content/public/test/test_renderer_host.h"
#include "testing/gtest/include/gtest/gtest.h"
using ::testing::_;
using ::testing::Mock;
using ::testing::Return;
using ::testing::ReturnRef;
using ::testing::Values;
namespace {
class SigninManagerMock : public FakeSigninManager {
public:
explicit SigninManagerMock(Profile* profile)
: FakeSigninManager(profile) {}
MOCK_CONST_METHOD1(IsAllowedUsername, bool(const std::string& username));
};
class OneClickSigninHelperTest : public content::RenderViewHostTestHarness {
public:
OneClickSigninHelperTest();
virtual void SetUp() OVERRIDE;
protected:
// Creates a mock WebContents for tests. If |use_incognito| is true then
// a WebContents for an incognito profile is created. If |username| is
// is not empty, the profile of the mock WebContents will be connected to
// the given account.
content::WebContents* CreateMockWebContents(bool use_incognito,
const std::string& username);
void AddEmailToOneClickRejectedList(const std::string& email);
void EnableOneClick(bool enable);
void AllowSigninCookies(bool enable);
SigninManagerMock* signin_manager_;
private:
// Members to fake that we are on the UI thread.
content::TestBrowserThread ui_thread_;
DISALLOW_COPY_AND_ASSIGN(OneClickSigninHelperTest);
};
OneClickSigninHelperTest::OneClickSigninHelperTest()
: ui_thread_(content::BrowserThread::UI, &message_loop_) {
}
void OneClickSigninHelperTest::SetUp() {
// Don't call base class so that default browser context and test WebContents
// are not created now. They will be created in CreateMockWebContents()
// as needed.
}
static ProfileKeyedService* BuildSigninManagerMock(Profile* profile) {
return new SigninManagerMock(profile);
}
content::WebContents* OneClickSigninHelperTest::CreateMockWebContents(
bool use_incognito,
const std::string& username) {
TestingProfile* testing_profile = new TestingProfile();
browser_context_.reset(testing_profile);
testing_profile->set_incognito(use_incognito);
signin_manager_ = static_cast<SigninManagerMock*>(
SigninManagerFactory::GetInstance()->SetTestingFactoryAndUse(
testing_profile, BuildSigninManagerMock));
if (!username.empty()) {
signin_manager_->StartSignIn(username, std::string(), std::string(),
std::string());
}
return CreateTestWebContents();
}
void OneClickSigninHelperTest::EnableOneClick(bool enable) {
PrefService* pref_service = Profile::FromBrowserContext(
browser_context_.get())->GetPrefs();
pref_service->SetBoolean(prefs::kReverseAutologinEnabled, enable);
}
void OneClickSigninHelperTest::AddEmailToOneClickRejectedList(
const std::string& email) {
PrefService* pref_service = Profile::FromBrowserContext(
browser_context_.get())->GetPrefs();
ListPrefUpdate updater(pref_service,
prefs::kReverseAutologinRejectedEmailList);
updater->AppendIfNotPresent(Value::CreateStringValue(email));
}
void OneClickSigninHelperTest::AllowSigninCookies(bool enable) {
CookieSettings* cookie_settings =
CookieSettings::Factory::GetForProfile(
Profile::FromBrowserContext(browser_context_.get()));
cookie_settings->SetDefaultCookieSetting(
enable ? CONTENT_SETTING_ALLOW : CONTENT_SETTING_BLOCK);
}
} // namespace
TEST_F(OneClickSigninHelperTest, CanOfferNoContents) {
EXPECT_FALSE(OneClickSigninHelper::CanOffer(NULL, "user@gmail.com", true));
EXPECT_FALSE(OneClickSigninHelper::CanOffer(NULL, "", false));
}
#if defined(OS_WIN)
// See http://crbug.com/153741.
#define MAYBE_CanOffer FLAKY_CanOffer
#else
#define MAYBE_CanOffer CanOffer
#endif
TEST_F(OneClickSigninHelperTest, MAYBE_CanOffer) {
content::WebContents* web_contents = CreateMockWebContents(false, "");
EXPECT_CALL(*signin_manager_, IsAllowedUsername(_)).
WillRepeatedly(Return(true));
EnableOneClick(true);
EXPECT_TRUE(OneClickSigninHelper::CanOffer(web_contents, "user@gmail.com",
true));
EXPECT_TRUE(OneClickSigninHelper::CanOffer(web_contents, "", false));
EnableOneClick(false);
EXPECT_FALSE(OneClickSigninHelper::CanOffer(web_contents, "user@gmail.com",
true));
EXPECT_FALSE(OneClickSigninHelper::CanOffer(web_contents, "", false));
}
TEST_F(OneClickSigninHelperTest, CanOfferProfileConnected) {
content::WebContents* web_contents = CreateMockWebContents(false,
"foo@gmail.com");
EXPECT_CALL(*signin_manager_, IsAllowedUsername(_)).
WillRepeatedly(Return(true));
EXPECT_FALSE(OneClickSigninHelper::CanOffer(web_contents,
"foo@gmail.com",
true));
EXPECT_FALSE(OneClickSigninHelper::CanOffer(web_contents,
"user@gmail.com",
true));
EXPECT_TRUE(OneClickSigninHelper::CanOffer(web_contents,
"",
false));
}
TEST_F(OneClickSigninHelperTest, CanOfferUsernameNotAllowed) {
content::WebContents* web_contents = CreateMockWebContents(false,
"foo@gmail.com");
EXPECT_CALL(*signin_manager_, IsAllowedUsername(_)).
WillRepeatedly(Return(false));
EXPECT_FALSE(OneClickSigninHelper::CanOffer(web_contents,
"foo@gmail.com",
true));
EXPECT_TRUE(OneClickSigninHelper::CanOffer(web_contents,
"",
false));
}
TEST_F(OneClickSigninHelperTest, CanOfferWithRejectedEmail) {
content::WebContents* web_contents = CreateMockWebContents(false, "");
EXPECT_CALL(*signin_manager_, IsAllowedUsername(_)).
WillRepeatedly(Return(true));
AddEmailToOneClickRejectedList("foo@gmail.com");
AddEmailToOneClickRejectedList("user@gmail.com");
EXPECT_FALSE(OneClickSigninHelper::CanOffer(web_contents, "foo@gmail.com",
true));
EXPECT_FALSE(OneClickSigninHelper::CanOffer(web_contents, "user@gmail.com",
true));
EXPECT_TRUE(OneClickSigninHelper::CanOffer(web_contents, "john@gmail.com",
true));
}
TEST_F(OneClickSigninHelperTest, CanOfferIncognito) {
content::WebContents* web_contents = CreateMockWebContents(true, "");
EXPECT_FALSE(OneClickSigninHelper::CanOffer(web_contents, "user@gmail.com",
true));
EXPECT_FALSE(OneClickSigninHelper::CanOffer(web_contents, "", false));
}
TEST_F(OneClickSigninHelperTest, CanOfferNoSigninCookies) {
content::WebContents* web_contents = CreateMockWebContents(false, "");
AllowSigninCookies(false);
EXPECT_CALL(*signin_manager_, IsAllowedUsername(_)).
WillRepeatedly(Return(true));
EXPECT_FALSE(OneClickSigninHelper::CanOffer(web_contents, "user@gmail.com",
true));
EXPECT_FALSE(OneClickSigninHelper::CanOffer(web_contents, "", false));
}
<commit_msg>Revert 159881 - Mark OneClickSigninHelperTest.CanOffer flaky on Windows.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/utf_string_conversions.h"
#include "chrome/browser/content_settings/cookie_settings.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/prefs/scoped_user_pref_update.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_info_cache.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/signin/signin_manager_factory.h"
#include "chrome/browser/signin/signin_manager_fake.h"
#include "chrome/browser/sync/profile_sync_service_mock.h"
#include "chrome/browser/sync/profile_sync_service_factory.h"
#include "chrome/browser/ui/sync/one_click_signin_helper.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/base/testing_browser_process.h"
#include "chrome/test/base/testing_profile.h"
#include "chrome/test/base/testing_profile_manager.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/web_contents.h"
#include "content/public/test/test_browser_thread.h"
#include "content/public/test/test_renderer_host.h"
#include "testing/gtest/include/gtest/gtest.h"
using ::testing::_;
using ::testing::Mock;
using ::testing::Return;
using ::testing::ReturnRef;
using ::testing::Values;
namespace {
class SigninManagerMock : public FakeSigninManager {
public:
explicit SigninManagerMock(Profile* profile)
: FakeSigninManager(profile) {}
MOCK_CONST_METHOD1(IsAllowedUsername, bool(const std::string& username));
};
class OneClickSigninHelperTest : public content::RenderViewHostTestHarness {
public:
OneClickSigninHelperTest();
virtual void SetUp() OVERRIDE;
protected:
// Creates a mock WebContents for tests. If |use_incognito| is true then
// a WebContents for an incognito profile is created. If |username| is
// is not empty, the profile of the mock WebContents will be connected to
// the given account.
content::WebContents* CreateMockWebContents(bool use_incognito,
const std::string& username);
void AddEmailToOneClickRejectedList(const std::string& email);
void EnableOneClick(bool enable);
void AllowSigninCookies(bool enable);
SigninManagerMock* signin_manager_;
private:
// Members to fake that we are on the UI thread.
content::TestBrowserThread ui_thread_;
DISALLOW_COPY_AND_ASSIGN(OneClickSigninHelperTest);
};
OneClickSigninHelperTest::OneClickSigninHelperTest()
: ui_thread_(content::BrowserThread::UI, &message_loop_) {
}
void OneClickSigninHelperTest::SetUp() {
// Don't call base class so that default browser context and test WebContents
// are not created now. They will be created in CreateMockWebContents()
// as needed.
}
static ProfileKeyedService* BuildSigninManagerMock(Profile* profile) {
return new SigninManagerMock(profile);
}
content::WebContents* OneClickSigninHelperTest::CreateMockWebContents(
bool use_incognito,
const std::string& username) {
TestingProfile* testing_profile = new TestingProfile();
browser_context_.reset(testing_profile);
testing_profile->set_incognito(use_incognito);
signin_manager_ = static_cast<SigninManagerMock*>(
SigninManagerFactory::GetInstance()->SetTestingFactoryAndUse(
testing_profile, BuildSigninManagerMock));
if (!username.empty()) {
signin_manager_->StartSignIn(username, std::string(), std::string(),
std::string());
}
return CreateTestWebContents();
}
void OneClickSigninHelperTest::EnableOneClick(bool enable) {
PrefService* pref_service = Profile::FromBrowserContext(
browser_context_.get())->GetPrefs();
pref_service->SetBoolean(prefs::kReverseAutologinEnabled, enable);
}
void OneClickSigninHelperTest::AddEmailToOneClickRejectedList(
const std::string& email) {
PrefService* pref_service = Profile::FromBrowserContext(
browser_context_.get())->GetPrefs();
ListPrefUpdate updater(pref_service,
prefs::kReverseAutologinRejectedEmailList);
updater->AppendIfNotPresent(Value::CreateStringValue(email));
}
void OneClickSigninHelperTest::AllowSigninCookies(bool enable) {
CookieSettings* cookie_settings =
CookieSettings::Factory::GetForProfile(
Profile::FromBrowserContext(browser_context_.get()));
cookie_settings->SetDefaultCookieSetting(
enable ? CONTENT_SETTING_ALLOW : CONTENT_SETTING_BLOCK);
}
} // namespace
TEST_F(OneClickSigninHelperTest, CanOfferNoContents) {
EXPECT_FALSE(OneClickSigninHelper::CanOffer(NULL, "user@gmail.com", true));
EXPECT_FALSE(OneClickSigninHelper::CanOffer(NULL, "", false));
}
TEST_F(OneClickSigninHelperTest, CanOffer) {
content::WebContents* web_contents = CreateMockWebContents(false, "");
EXPECT_CALL(*signin_manager_, IsAllowedUsername(_)).
WillRepeatedly(Return(true));
EnableOneClick(true);
EXPECT_TRUE(OneClickSigninHelper::CanOffer(web_contents, "user@gmail.com",
true));
EXPECT_TRUE(OneClickSigninHelper::CanOffer(web_contents, "", false));
EnableOneClick(false);
EXPECT_FALSE(OneClickSigninHelper::CanOffer(web_contents, "user@gmail.com",
true));
EXPECT_FALSE(OneClickSigninHelper::CanOffer(web_contents, "", false));
}
TEST_F(OneClickSigninHelperTest, CanOfferProfileConnected) {
content::WebContents* web_contents = CreateMockWebContents(false,
"foo@gmail.com");
EXPECT_CALL(*signin_manager_, IsAllowedUsername(_)).
WillRepeatedly(Return(true));
EXPECT_FALSE(OneClickSigninHelper::CanOffer(web_contents,
"foo@gmail.com",
true));
EXPECT_FALSE(OneClickSigninHelper::CanOffer(web_contents,
"user@gmail.com",
true));
EXPECT_TRUE(OneClickSigninHelper::CanOffer(web_contents,
"",
false));
}
TEST_F(OneClickSigninHelperTest, CanOfferUsernameNotAllowed) {
content::WebContents* web_contents = CreateMockWebContents(false,
"foo@gmail.com");
EXPECT_CALL(*signin_manager_, IsAllowedUsername(_)).
WillRepeatedly(Return(false));
EXPECT_FALSE(OneClickSigninHelper::CanOffer(web_contents,
"foo@gmail.com",
true));
EXPECT_TRUE(OneClickSigninHelper::CanOffer(web_contents,
"",
false));
}
TEST_F(OneClickSigninHelperTest, CanOfferWithRejectedEmail) {
content::WebContents* web_contents = CreateMockWebContents(false, "");
EXPECT_CALL(*signin_manager_, IsAllowedUsername(_)).
WillRepeatedly(Return(true));
AddEmailToOneClickRejectedList("foo@gmail.com");
AddEmailToOneClickRejectedList("user@gmail.com");
EXPECT_FALSE(OneClickSigninHelper::CanOffer(web_contents, "foo@gmail.com",
true));
EXPECT_FALSE(OneClickSigninHelper::CanOffer(web_contents, "user@gmail.com",
true));
EXPECT_TRUE(OneClickSigninHelper::CanOffer(web_contents, "john@gmail.com",
true));
}
TEST_F(OneClickSigninHelperTest, CanOfferIncognito) {
content::WebContents* web_contents = CreateMockWebContents(true, "");
EXPECT_FALSE(OneClickSigninHelper::CanOffer(web_contents, "user@gmail.com",
true));
EXPECT_FALSE(OneClickSigninHelper::CanOffer(web_contents, "", false));
}
TEST_F(OneClickSigninHelperTest, CanOfferNoSigninCookies) {
content::WebContents* web_contents = CreateMockWebContents(false, "");
AllowSigninCookies(false);
EXPECT_CALL(*signin_manager_, IsAllowedUsername(_)).
WillRepeatedly(Return(true));
EXPECT_FALSE(OneClickSigninHelper::CanOffer(web_contents, "user@gmail.com",
true));
EXPECT_FALSE(OneClickSigninHelper::CanOffer(web_contents, "", false));
}
<|endoftext|> |
<commit_before>#pragma once
#ifndef CATCH_CONFIG_MAIN
# define CATCH_CONFIG_MAIN
#endif
#include "catch.hpp"
<commit_msg>Added TestServer helpers to common.hpp for unit tests<commit_after>#pragma once
#ifndef CATCH_CONFIG_MAIN
# define CATCH_CONFIG_MAIN
#endif
#include "catch.hpp"
#include "internal/curl.hpp"
#include <string>
#include <thread>
namespace {
class TestServer
{
public:
TestServer();
~TestServer();
enum class Condition { Pass, Fail, Clear, Count, Shutdown, ShortCircuit };
static void run();
static std::string address(Condition cond);
private:
std::thread mThread;
};
TestServer::TestServer()
: mThread(TestServer::run)
{}
TestServer::~TestServer()
{
if (mThread.joinable())
mThread.join();
}
void TestServer::run()
{
int status = std::system("node server.js");
}
std::string TestServer::address(Condition cond)
{
std::string url_pass = "http://localhost:8080/pass";
std::string url_fail = "http://localhost:8080/fail";
std::string url_clear = "http://localhost:8080/clear";
std::string url_count = "http://localhost:8080/count";
std::string url_shutdown = "http://localhost:8080/shutdown";
std::string url_sc = "http://localhost:8080/short_circuit";
if (cond == Condition::Pass) return url_pass;
else if (cond == Condition::Fail) return url_fail;
else if (cond == Condition::Clear) return url_clear;
else if (cond == Condition::Count) return url_count;
else if (cond == Condition::Shutdown) return url_shutdown;
else if (cond == Condition::ShortCircuit) return url_sc;
else return url_fail;
}
struct ScopedTestServer
{
ScopedTestServer(libkeen::internal::Curl& curl) : mCurl(curl) {};
~ScopedTestServer() { mCurl.sendEvent(TestServer::address(TestServer::Condition::Shutdown), ""); };
private:
libkeen::internal::Curl& mCurl;
};
}
<|endoftext|> |
<commit_before>#include "testing_suite.h"
using namespace std;
using namespace TOOLS;
using namespace TOOLS::UNIT_TEST;
/// @todo PREPARE_WITH DOES NOT WORK!
Test::Test() : name(""), method(NULL), object(NULL) {}
Test::Test(const string& name, tMethod meth, TestSuite* obj)
: name(name), method(meth), object(obj) {}
TestSuite::TestSuite() : check_count(0), active_test(NULL), show_good_details(false) { }
void TestSuite::add_check(bool expr, int line) {
active_test->res.result &= expr;
active_test->lineno = line;
check_count++;
if(show_good_details || !expr) {
const string lineinfo = (expr) ? " [good]" : " [bad]";
if(XString(active_test->res.details).startswith("Line(s):"))
active_test->res.details.append(", " + str(line) + lineinfo);
else
active_test->res.details.append("Line(s): " + str(line) + lineinfo);
}
}
void TestSuite::add_exc_check(bool res, const std::string& excname, int line) {
add_check(res, line);
if(!res)
active_test->res.details.append("[exc: " + excname + " line: " + str(line) + "] ");
}
void TestSuite::add_iter_check(bool res, int iters, tIntList errs, int line) {
add_check(res, line);
stringstream out;
for(tIntIter i=errs.begin(); i!=errs.end(); ++i) {
out << *i;
if(i+1 != errs.end())
out << ",";
}
if(!res)
active_test->res.details.append("[eq_iter: iterations: " +
str(iters) + " errors in: " + out.str() + "]");
}
void TestSuite::setup() {}
void TestSuite::tear_down() {}
void TestSuite::after_setup() {
//active_test->details.append("Setup finished - ");
}
void TestSuite::after_tear_down() {
//active_test->details.append("TearDown finished!");
}
void TestSuite::execute_tests(const string& suite_name, const string& only_test) {
for(tTestIter i=tests.begin(); i!=tests.end(); ++i) {
i->second.res.id = suite_name + "::" + i->first;
// if executing single test
if(only_test != "" && i->second.res.id != only_test)
continue;
i->second.res.run = true;
active_test = &i->second;
setup();
after_setup();
i->second.res.timer.start();
try {
(i->second.object->*i->second.method)(true);
} catch(TOOLS::BaseException& e) {
i->second.res.details.append(
"[E] test failed - exception caught: " + e.output + " - ");
i->second.res.result = false;
} catch(exception& e) {
i->second.res.details.append(
"[E] test failed - std::exception caught: " + str(e.what()) + " - ");
i->second.res.result = false;
}
i->second.res.timer.stop();
tear_down();
after_tear_down();
active_test = NULL;
i->second.res.show(false);
}
}
TestResult::TestResult(const string& testid, bool res, const string& details)
: id(testid), result(res), details(details) {}
TestResult::TestResult() : id(""), result(true), run(false) {}
void TestResult::show(bool show_details) {
string icon, rating;
if(result) {
rating = "GOOD";
icon = "+";
} else {
rating = "BAD!";
icon = "-";
}
cout << "[" << icon << "] " << left << setw(45) << id << \
setw(20) << right << rating;
cout << " ->" << setw(6) << right << timer.diff_us() << "us" << endl;
if(details != "" && ((!show_details && !result) || show_details))
cout << "[i] " << details << endl;
}
TestFramework::TestFramework(int argc, char* argv[]) {
ConfigManager conf(argv[0]);
ConfigGroup& grp = conf.new_group("Main Options");
grp.new_option<bool>("debug", "Show test details", "d"). \
set_default(false);
grp.new_option<string>("execute-test", "Execute test by name", "t"). \
set_default("");
// ConfigManager init finished, start parsing file, then cmdline
try {
conf.parse_config_file("noname.conf");
conf.parse_cmdline(argc, argv);
cout << "[+] Parsing commandline complete" << endl;
} catch(ConfigManagerException& e) {
e.show();
conf.usage(cout);
exit(1);
}
show_details = conf.get<bool>("debug");
execute_test = conf.get<string>("execute-test");
}
TestFramework::~TestFramework() {
for(tTestSuiteIter i=test_suites.begin(); i!=test_suites.end(); ++i)
delete i->second;
}
void TestFramework::run() {
for(tTestSuiteIter i=test_suites.begin(); i!=test_suites.end(); ++i)
i->second->execute_tests(i->first, execute_test);
}
void TestFramework::show_result_overview() {
int good = 0;
int bad = 0;
int all_tests = 0;
for(tTestSuiteIter i=test_suites.begin(); i!=test_suites.end(); ++i) {
all_tests += i->second->check_count;
for(tTestIter j=i->second->tests.begin(); j!=i->second->tests.end(); ++j) {
if(j->second.res.run)
(j->second.res.result) ? good++ : bad++;
}
}
cout << endl << "[i] Finished TestRun (" <<
all_tests << " checks done) - Tests: good: " << good;
if(bad > 0)
cout << " and bad: " << bad << endl;
else
cout << " and NO bad ones!" << endl;
}
void TestFramework::print_stacktrace(uint max_frames) {
cerr << "[BT] Showing stacktrace: " << endl;
void* addrlist[max_frames+1];
int addrlen = backtrace(addrlist, sizeof(addrlist) / sizeof(void*));
if(addrlen == 0) {
cerr << "[E] backtrace() returned 0 - Error!" << endl;
return;
}
// resolve addresses to -> "filename(function+address)"
// symlist must be free()-ed !
char** symlist = backtrace_symbols(addrlist, addrlen);
size_t funcnamesize = 256;
char* funcname = (char*)malloc(funcnamesize);
// demangle all functionnames
for(int i=1; i<addrlen; ++i) {
char* begin_name = 0;
char* begin_offset = 0;
char* end_offset = 0;
// find parentheses and +address offset surrounding the mangled name:
// ./module(function+0x15c) [0x8048a6d]
for(char* p = symlist[i]; *p; ++p) {
if(*p == '(')
begin_name = p;
else if(*p == '+')
begin_offset = p;
else if(*p == ')' && begin_offset) {
end_offset = p;
break;
}
}
if(begin_name && begin_offset && end_offset
&& begin_name < begin_offset) {
*begin_name++ = '\0';
*begin_offset++ = '\0';
*end_offset = '\0';
// mangled name is now in [begin_name, begin_offset) and caller
// offset in [begin_offset, end_offset). now apply
// __cxa_demangle():
int status;
char* ret = abi::__cxa_demangle(begin_name,
funcname, &funcnamesize, &status);
if(status == 0) {
funcname = ret; // use possibly realloc()-ed string
cerr << "[BT] " << symlist[i] << " " \
<< funcname << "+" << begin_offset << endl;
} else { // demangle failes
cerr << "[BT] " << symlist[i] << " " \
<< begin_name << "+" << begin_offset << endl;
}
} else // parsing failed
cerr << "[BT]" << symlist[i] << endl;
}
free(funcname);
free(symlist);
}
<commit_msg>removed todo<commit_after>#include "testing_suite.h"
using namespace std;
using namespace TOOLS;
using namespace TOOLS::UNIT_TEST;
Test::Test() : name(""), method(NULL), object(NULL) {}
Test::Test(const string& name, tMethod meth, TestSuite* obj)
: name(name), method(meth), object(obj) {}
TestSuite::TestSuite() : check_count(0), active_test(NULL), show_good_details(false) { }
void TestSuite::add_check(bool expr, int line) {
active_test->res.result &= expr;
active_test->lineno = line;
check_count++;
if(show_good_details || !expr) {
const string lineinfo = (expr) ? " [good]" : " [bad]";
if(XString(active_test->res.details).startswith("Line(s):"))
active_test->res.details.append(", " + str(line) + lineinfo);
else
active_test->res.details.append("Line(s): " + str(line) + lineinfo);
}
}
void TestSuite::add_exc_check(bool res, const std::string& excname, int line) {
add_check(res, line);
if(!res)
active_test->res.details.append("[exc: " + excname + " line: " + str(line) + "] ");
}
void TestSuite::add_iter_check(bool res, int iters, tIntList errs, int line) {
add_check(res, line);
stringstream out;
for(tIntIter i=errs.begin(); i!=errs.end(); ++i) {
out << *i;
if(i+1 != errs.end())
out << ",";
}
if(!res)
active_test->res.details.append("[eq_iter: iterations: " +
str(iters) + " errors in: " + out.str() + "]");
}
void TestSuite::setup() {}
void TestSuite::tear_down() {}
void TestSuite::after_setup() {
//active_test->details.append("Setup finished - ");
}
void TestSuite::after_tear_down() {
//active_test->details.append("TearDown finished!");
}
void TestSuite::execute_tests(const string& suite_name, const string& only_test) {
for(tTestIter i=tests.begin(); i!=tests.end(); ++i) {
i->second.res.id = suite_name + "::" + i->first;
// if executing single test
if(only_test != "" && i->second.res.id != only_test)
continue;
i->second.res.run = true;
active_test = &i->second;
setup();
after_setup();
i->second.res.timer.start();
try {
(i->second.object->*i->second.method)(true);
} catch(TOOLS::BaseException& e) {
i->second.res.details.append(
"[E] test failed - exception caught: " + e.output + " - ");
i->second.res.result = false;
} catch(exception& e) {
i->second.res.details.append(
"[E] test failed - std::exception caught: " + str(e.what()) + " - ");
i->second.res.result = false;
}
i->second.res.timer.stop();
tear_down();
after_tear_down();
active_test = NULL;
i->second.res.show(false);
}
}
TestResult::TestResult(const string& testid, bool res, const string& details)
: id(testid), result(res), details(details) {}
TestResult::TestResult() : id(""), result(true), run(false) {}
void TestResult::show(bool show_details) {
string icon, rating;
if(result) {
rating = "GOOD";
icon = "+";
} else {
rating = "BAD!";
icon = "-";
}
cout << "[" << icon << "] " << left << setw(45) << id << \
setw(20) << right << rating;
cout << " ->" << setw(6) << right << timer.diff_us() << "us" << endl;
if(details != "" && ((!show_details && !result) || show_details))
cout << "[i] " << details << endl;
}
TestFramework::TestFramework(int argc, char* argv[]) {
ConfigManager conf(argv[0]);
ConfigGroup& grp = conf.new_group("Main Options");
grp.new_option<bool>("debug", "Show test details", "d"). \
set_default(false);
grp.new_option<string>("execute-test", "Execute test by name", "t"). \
set_default("");
// ConfigManager init finished, start parsing file, then cmdline
try {
conf.parse_config_file("noname.conf");
conf.parse_cmdline(argc, argv);
cout << "[+] Parsing commandline complete" << endl;
} catch(ConfigManagerException& e) {
e.show();
conf.usage(cout);
exit(1);
}
show_details = conf.get<bool>("debug");
execute_test = conf.get<string>("execute-test");
}
TestFramework::~TestFramework() {
for(tTestSuiteIter i=test_suites.begin(); i!=test_suites.end(); ++i)
delete i->second;
}
void TestFramework::run() {
for(tTestSuiteIter i=test_suites.begin(); i!=test_suites.end(); ++i)
i->second->execute_tests(i->first, execute_test);
}
void TestFramework::show_result_overview() {
int good = 0;
int bad = 0;
int all_tests = 0;
for(tTestSuiteIter i=test_suites.begin(); i!=test_suites.end(); ++i) {
all_tests += i->second->check_count;
for(tTestIter j=i->second->tests.begin(); j!=i->second->tests.end(); ++j) {
if(j->second.res.run)
(j->second.res.result) ? good++ : bad++;
}
}
cout << endl << "[i] Finished TestRun (" <<
all_tests << " checks done) - Tests: good: " << good;
if(bad > 0)
cout << " and bad: " << bad << endl;
else
cout << " and NO bad ones!" << endl;
}
void TestFramework::print_stacktrace(uint max_frames) {
cerr << "[BT] Showing stacktrace: " << endl;
void* addrlist[max_frames+1];
int addrlen = backtrace(addrlist, sizeof(addrlist) / sizeof(void*));
if(addrlen == 0) {
cerr << "[E] backtrace() returned 0 - Error!" << endl;
return;
}
// resolve addresses to -> "filename(function+address)"
// symlist must be free()-ed !
char** symlist = backtrace_symbols(addrlist, addrlen);
size_t funcnamesize = 256;
char* funcname = (char*)malloc(funcnamesize);
// demangle all functionnames
for(int i=1; i<addrlen; ++i) {
char* begin_name = 0;
char* begin_offset = 0;
char* end_offset = 0;
// find parentheses and +address offset surrounding the mangled name:
// ./module(function+0x15c) [0x8048a6d]
for(char* p = symlist[i]; *p; ++p) {
if(*p == '(')
begin_name = p;
else if(*p == '+')
begin_offset = p;
else if(*p == ')' && begin_offset) {
end_offset = p;
break;
}
}
if(begin_name && begin_offset && end_offset
&& begin_name < begin_offset) {
*begin_name++ = '\0';
*begin_offset++ = '\0';
*end_offset = '\0';
// mangled name is now in [begin_name, begin_offset) and caller
// offset in [begin_offset, end_offset). now apply
// __cxa_demangle():
int status;
char* ret = abi::__cxa_demangle(begin_name,
funcname, &funcnamesize, &status);
if(status == 0) {
funcname = ret; // use possibly realloc()-ed string
cerr << "[BT] " << symlist[i] << " " \
<< funcname << "+" << begin_offset << endl;
} else { // demangle failes
cerr << "[BT] " << symlist[i] << " " \
<< begin_name << "+" << begin_offset << endl;
}
} else // parsing failed
cerr << "[BT]" << symlist[i] << endl;
}
free(funcname);
free(symlist);
}
<|endoftext|> |
<commit_before>#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <blackhole/attribute.hpp>
#include <blackhole/extensions/facade.hpp>
#include <blackhole/scope/manager.hpp>
#include "mocks/logger.hpp"
#define GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
#if GCC_VERSION < 50000
namespace std {
template<typename T>
auto operator==(const std::reference_wrapper<T>& lhs, const std::reference_wrapper<T>& rhs) -> bool {
return lhs.get() == rhs.get();
}
} // namespace std
#endif
namespace blackhole {
namespace testing {
using ::testing::An;
using ::testing::Invoke;
using ::testing::WithArg;
using ::testing::_;
typedef mock::logger_t logger_type;
TEST(Facade, Constructor) {
logger_type inner;
logger_facade<logger_type> logger(inner);
EXPECT_EQ(&inner, &logger.inner());
}
TEST(Facade, PrimitiveLog) {
logger_type inner;
logger_facade<logger_type> logger(inner);
EXPECT_CALL(inner, log(severity_t(0), string_view("GET /porn.png HTTP/1.0")))
.Times(1);
logger.log(0, "GET /porn.png HTTP/1.0");
}
TEST(Facade, AttributeLog) {
logger_type inner;
logger_facade<logger_type> logger(inner);
const attribute_list attributes{{"key#1", {42}}};
attribute_pack expected{attributes};
EXPECT_CALL(inner, log(severity_t(0), string_view("GET /porn.png HTTP/1.0"), expected))
.Times(1);
logger.log(0, "GET /porn.png HTTP/1.0", attribute_list{
{"key#1", {42}}
});
}
TEST(Facade, FormattedLog) {
logger_type inner;
logger_facade<logger_type> logger(inner);
attribute_pack expected;
writer_t writer;
EXPECT_CALL(inner, log(severity_t(0), An<const lazy_message_t&>(), expected))
.Times(1)
.WillOnce(WithArg<1>(Invoke([](const lazy_message_t& message) {
EXPECT_EQ("GET /porn.png HTTP/1.0 - {}", message.pattern.to_string());
EXPECT_EQ("GET /porn.png HTTP/1.0 - 42", message.supplier().to_string());
})));
logger.log(0, "GET /porn.png HTTP/1.0 - {}", 42);
}
TEST(Facade, FormattedAttributeLog) {
logger_type inner;
logger_facade<logger_type> logger(inner);
const attribute_list attributes{{"key#1", {42}}};
attribute_pack expected{attributes};
EXPECT_CALL(inner, log(severity_t(0), An<const lazy_message_t&>(), expected))
.Times(1)
.WillOnce(WithArg<1>(Invoke([](const lazy_message_t& message) {
EXPECT_EQ("GET /porn.png HTTP/1.0 - {}", message.pattern.to_string());
EXPECT_EQ("GET /porn.png HTTP/1.0 - 2345", message.supplier().to_string());
})));
logger.log(0, "GET /porn.png HTTP/1.0 - {}", 2345, attribute_list{
{"key#1", {42}}
});
}
} // namespace testing
} // namespace blackhole
<commit_msg>feat(tests): add lazy formatter tests<commit_after>#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <blackhole/attribute.hpp>
#include <blackhole/extensions/facade.hpp>
#include <blackhole/scope/manager.hpp>
#include "mocks/logger.hpp"
#define GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
#if GCC_VERSION < 50000
namespace std {
template<typename T>
auto operator==(const std::reference_wrapper<T>& lhs, const std::reference_wrapper<T>& rhs) -> bool {
return lhs.get() == rhs.get();
}
} // namespace std
#endif
namespace blackhole {
namespace testing {
using ::testing::An;
using ::testing::Invoke;
using ::testing::WithArg;
using ::testing::_;
typedef mock::logger_t logger_type;
TEST(Facade, Constructor) {
logger_type inner;
logger_facade<logger_type> logger(inner);
EXPECT_EQ(&inner, &logger.inner());
}
TEST(Facade, PrimitiveLog) {
logger_type inner;
logger_facade<logger_type> logger(inner);
EXPECT_CALL(inner, log(severity_t(0), string_view("GET /porn.png HTTP/1.0")))
.Times(1);
logger.log(0, "GET /porn.png HTTP/1.0");
}
TEST(Facade, AttributeLog) {
logger_type inner;
logger_facade<logger_type> logger(inner);
const attribute_list attributes{{"key#1", {42}}};
attribute_pack expected{attributes};
EXPECT_CALL(inner, log(severity_t(0), string_view("GET /porn.png HTTP/1.0"), expected))
.Times(1);
logger.log(0, "GET /porn.png HTTP/1.0", attribute_list{
{"key#1", {42}}
});
}
TEST(Facade, FormattedLog) {
logger_type inner;
logger_facade<logger_type> logger(inner);
attribute_pack expected;
writer_t writer;
EXPECT_CALL(inner, log(severity_t(0), An<const lazy_message_t&>(), expected))
.Times(1)
.WillOnce(WithArg<1>(Invoke([](const lazy_message_t& message) {
EXPECT_EQ("GET /porn.png HTTP/1.0 - {}", message.pattern.to_string());
EXPECT_EQ("GET /porn.png HTTP/1.0 - 42", message.supplier().to_string());
})));
logger.log(0, "GET /porn.png HTTP/1.0 - {}", 42);
}
TEST(Facade, LazyFormattedLog) {
logger_type inner;
logger_facade<logger_type> logger(inner);
attribute_pack expected;
writer_t writer;
EXPECT_CALL(inner, log(severity_t(0), An<const lazy_message_t&>(), expected))
.Times(1)
.WillOnce(WithArg<1>(Invoke([](const lazy_message_t& message) {
EXPECT_EQ("GET /porn.png HTTP/1.0 - {}", message.pattern.to_string());
EXPECT_EQ("GET /porn.png HTTP/1.0 - 42", message.supplier().to_string());
})));
logger.log(0, "GET /porn.png HTTP/1.0 - {}", [](std::ostream& stream) -> std::ostream& {
return stream << 42;
});
}
TEST(Facade, FormattedAttributeLog) {
logger_type inner;
logger_facade<logger_type> logger(inner);
const attribute_list attributes{{"key#1", {42}}};
attribute_pack expected{attributes};
EXPECT_CALL(inner, log(severity_t(0), An<const lazy_message_t&>(), expected))
.Times(1)
.WillOnce(WithArg<1>(Invoke([](const lazy_message_t& message) {
EXPECT_EQ("GET /porn.png HTTP/1.0 - {}", message.pattern.to_string());
EXPECT_EQ("GET /porn.png HTTP/1.0 - 2345", message.supplier().to_string());
})));
logger.log(0, "GET /porn.png HTTP/1.0 - {}", 2345, attribute_list{
{"key#1", {42}}
});
}
} // namespace testing
} // namespace blackhole
<|endoftext|> |
<commit_before>#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <blackhole/extensions/facade.hpp>
#include <blackhole/logger.hpp>
#include "mocks/logger.hpp"
namespace blackhole {
namespace testing {
using ::testing::_;
typedef mock::logger_t logger_type;
TEST(Facade, PrimitiveLog) {
const logger_type inner{};
const logger_facade<logger_type> logger(inner);
EXPECT_CALL(inner, log(0, string_view("GET /porn.png HTTP/1.0")))
.Times(1);
logger.log(0, "GET /porn.png HTTP/1.0");
}
TEST(Facade, AttributeLog) {
const logger_type inner{};
const logger_facade<logger_type> logger(inner);
const attribute_list attributes{{"key#1", {42}}};
range_t expected{attributes};
EXPECT_CALL(inner, log(0, string_view("GET /porn.png HTTP/1.0"), expected))
.Times(1);
logger.log(0, "GET /porn.png HTTP/1.0", attribute_list{
{"key#1", {42}}
});
}
TEST(Facade, FormattedLog) {
const logger_type inner{};
const logger_facade<logger_type> logger(inner);
range_t expected;
EXPECT_CALL(inner, log(0, string_view("GET /porn.png HTTP/1.0 - {}"), expected, _))
.Times(1);
logger.log(0, "GET /porn.png HTTP/1.0 - {}", 42);
}
TEST(Facade, FormattedAttributeLog) {
const logger_type inner{};
const logger_facade<logger_type> logger(inner);
const attribute_list attributes{{"key#1", {42}}};
range_t expected{attributes};
EXPECT_CALL(inner, log(0, string_view("GET /porn.png HTTP/1.0"), expected, _))
.Times(1);
logger.log(0, "GET /porn.png HTTP/1.0", 2345, attribute_list{
{"key#1", {42}}
});
}
} // namespace testing
} // namespace blackhole
<commit_msg>chore(tests): add format function call checks<commit_after>#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <blackhole/extensions/facade.hpp>
#include <blackhole/logger.hpp>
#include "mocks/logger.hpp"
namespace blackhole {
namespace testing {
using ::testing::ByRef;
using ::testing::InvokeArgument;
using ::testing::_;
typedef mock::logger_t logger_type;
TEST(Facade, PrimitiveLog) {
const logger_type inner{};
const logger_facade<logger_type> logger(inner);
EXPECT_CALL(inner, log(0, string_view("GET /porn.png HTTP/1.0")))
.Times(1);
logger.log(0, "GET /porn.png HTTP/1.0");
}
TEST(Facade, AttributeLog) {
const logger_type inner{};
const logger_facade<logger_type> logger(inner);
const attribute_list attributes{{"key#1", {42}}};
range_t expected{attributes};
EXPECT_CALL(inner, log(0, string_view("GET /porn.png HTTP/1.0"), expected))
.Times(1);
logger.log(0, "GET /porn.png HTTP/1.0", attribute_list{
{"key#1", {42}}
});
}
TEST(Facade, FormattedLog) {
const logger_type inner{};
const logger_facade<logger_type> logger(inner);
range_t expected;
writer_t writer;
EXPECT_CALL(inner, log(0, string_view("GET /porn.png HTTP/1.0 - {}"), expected, _))
.Times(1)
.WillOnce(InvokeArgument<3>(ByRef(writer)));
logger.log(0, "GET /porn.png HTTP/1.0 - {}", 42);
EXPECT_EQ("GET /porn.png HTTP/1.0 - 42", writer.inner.str());
}
TEST(Facade, FormattedAttributeLog) {
const logger_type inner{};
const logger_facade<logger_type> logger(inner);
const attribute_list attributes{{"key#1", {42}}};
range_t expected{attributes};
writer_t writer;
EXPECT_CALL(inner, log(0, string_view("GET /porn.png HTTP/1.0 - {}"), expected, _))
.Times(1)
.WillOnce(InvokeArgument<3>(ByRef(writer)));
logger.log(0, "GET /porn.png HTTP/1.0 - {}", 2345, attribute_list{
{"key#1", {42}}
});
EXPECT_EQ("GET /porn.png HTTP/1.0 - 2345", writer.inner.str());
}
} // namespace testing
} // namespace blackhole
<|endoftext|> |
<commit_before><commit_msg>Simplify visibility after clang format for vertices on Cube<commit_after><|endoftext|> |
<commit_before>#ifndef MINIMAT_AST_MATRIX_HPP
#define MINIMAT_AST_MATRIX_HPP
#include <eigen3/Eigen/Dense>
typedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> Matrix;
#endif<commit_msg>Get with the times; no one uses 'typedef' anymore<commit_after>#ifndef MINIMAT_AST_MATRIX_HPP
#define MINIMAT_AST_MATRIX_HPP
#include <eigen3/Eigen/Dense>
using Matrix = Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;
#endif<|endoftext|> |
<commit_before>/* **********************************************************
* Copyright (c) 2012 Google, Inc. All rights reserved.
* **********************************************************/
/* Dr. Memory: the memory debugger
*
* This library 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;
* version 2.1 of the License, and no later version.
* This library 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
* Library General Public License for more details.
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
/* Tests Windows Handle Leaks */
#ifndef WINDOWS
# error Windows-only
#endif
#include <windows.h>
#include <assert.h>
#include <stdio.h>
#include <process.h> /* for _beginthreadex */
#include <tchar.h> /* for tchar */
#include <strsafe.h> /* for Str* */
#include <tlhelp32.h>
static void
test_gdi_handles(bool close)
{
HDC mydc = GetDC(NULL);
assert(mydc != NULL);
HDC dupdc = CreateCompatibleDC(mydc);
assert(dupdc != NULL);
HPEN mypen = CreatePen(PS_SOLID, 0xab,RGB(0xab,0xcd,0xef));
assert(mypen != NULL);
HBITMAP mybmA = CreateBitmap(30, 30, 1, 16, NULL);
assert(mybmA != NULL);
HBITMAP mybmB = CreateCompatibleBitmap(dupdc, 30, 30);
assert(mybmB != NULL);
if (close) {
DeleteObject(mybmB);
DeleteObject(mybmA);
DeleteObject(mypen);
DeleteDC(dupdc);
ReleaseDC(NULL, mydc);
}
}
static unsigned int WINAPI
thread_func(void *arg)
{
int i;
HANDLE hEvent;
for (i = 0; i < 10; i++) {
hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
if (hEvent == NULL) {
printf("fail to create event\n");
return 0;
}
CloseHandle(hEvent);
}
return 0;
}
static void
test_thread_handles(bool close)
{
unsigned int tid;
HANDLE thread;
thread = (HANDLE) _beginthreadex(NULL, 0, thread_func, NULL, 0, &tid);
thread_func(NULL);
WaitForSingleObject(thread, INFINITE);
if (close)
CloseHandle(thread);
}
static void
test_file_handles(bool close)
{
// the files' handles
HANDLE hFile, dupFile1, dupFile2;
HANDLE hFind;
// filenames, the file is not there...
TCHAR buf[MAX_PATH];
DWORD size;
WIN32_FIND_DATA ffd;
bool create_file_tested = false;
size = GetCurrentDirectory(MAX_PATH, buf);
// check size
if (size == 0) {
printf("fail to get current directory\n");
return;
}
// append
StringCchCat(buf, MAX_PATH, TEXT("\\*"));
// find the first file in the directory.
hFind = FindFirstFile(buf, &ffd);
if (hFind == INVALID_HANDLE_VALUE) {
printf("fail to find the first file\n");
return;
}
// find all the files in the directory
do {
bool test_done = false;
if (!create_file_tested &&
!(ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
hFile = CreateFile(ffd.cFileName, 0, 0, NULL, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, NULL);
create_file_tested = true;
if (hFile == INVALID_HANDLE_VALUE) {
printf("fail to open the file %s\n", ffd.cFileName);
return;
}
// test DuplicateHandle
DuplicateHandle(GetCurrentProcess(),
hFile,
GetCurrentProcess(),
&dupFile1,
0,
FALSE,
DUPLICATE_SAME_ACCESS);
if (dupFile1 == INVALID_HANDLE_VALUE) {
printf("fail to duplicate the file handle\n");
return;
}
// close the handle using DuplicateHandle
DuplicateHandle(GetCurrentProcess(),
dupFile1,
GetCurrentProcess(),
&dupFile2, // NULL would cause another leak
0,
FALSE,
DUPLICATE_CLOSE_SOURCE);
if (dupFile2 == INVALID_HANDLE_VALUE) {
printf("fail to duplicate the file handle\n");
return;
}
CloseHandle(dupFile2);
if (close) {
// test handle leak on syscall
DuplicateHandle(GetCurrentProcess(),
hFile,
GetCurrentProcess(),
NULL, // handle leak
0,
FALSE,
DUPLICATE_SAME_ACCESS);
CloseHandle(hFile);
}
test_done = true;
}
if (test_done)
break;
} while (FindNextFile(hFind, &ffd) != 0);
if (GetLastError() == ERROR_NO_MORE_FILES) {
printf("failed to find the next file\n");
}
if (close)
FindClose(hFind);
}
void
test_window_handles(bool close)
{
HWND hWnd;
hWnd = CreateWindowEx(0L, // ExStyle
"Button", // class name
"Main Window", // window name
WS_OVERLAPPEDWINDOW, // style
CW_USEDEFAULT, CW_USEDEFAULT, // pos
CW_USEDEFAULT, CW_USEDEFAULT, // size
(HWND) NULL, // no parent
(HMENU) NULL, // calls menu
(HINSTANCE) NULL,
NULL);
if (!hWnd) {
printf("fail to create window\n");
}
if (close) {
DestroyWindow(hWnd);
}
}
void
test_process_handles(bool close)
{
HANDLE hSnapshot, hProcess;
PROCESSENTRY32 pe;
BOOL res;
hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPALL, 0);
if (hSnapshot == INVALID_HANDLE_VALUE) {
printf("CreateToolhelp32Snapshot failed\n");
return;
}
pe.dwSize = sizeof(pe);
for (res = Process32First(hSnapshot, &pe);
res;
res = Process32Next(hSnapshot, &pe)) {
hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
if (hProcess == INVALID_HANDLE_VALUE) {
printf("OpenProcess failed\n");
return;
}
#ifdef VERBOSE
printf("Process %6u: %s\n", pe.th32ProcessID, pe.szExeFile);
#endif
if (hProcess != 0 && pe.th32ProcessID != 0) /* skip system process */
break;
}
if (close) {
CloseHandle(hProcess);
CloseHandle(hSnapshot);
}
}
void
test_desktop_handles(bool close)
{
HWINSTA hWinSta1, hWinSta2, hWinSta3;
HDESK hDesk1, hDesk2, hDesk3, hDesk4;
SECURITY_ATTRIBUTES attr1 = {0}, attr2 = {0};
TCHAR buf[MAX_PATH];
hWinSta1 = CreateWindowStationW(NULL, 0, WINSTA_ALL_ACCESS, &attr1);
if (hWinSta1 == NULL) {
DWORD res = GetLastError();
printf("CreateWindowStationW failed, %d\n", res);
return;
}
hWinSta2 = OpenWindowStation(_T("winsta0"), FALSE, READ_CONTROL | WRITE_DAC);
if (hWinSta2 == NULL) {
DWORD res = GetLastError();
printf("OpenWindowStation failed, %d\n", res);
return;
}
hWinSta3 = GetProcessWindowStation(); /* return existing handle */
if (hWinSta3 == NULL) {
DWORD res = GetLastError();
printf("GetProcessWindowStation failed, %d\n", res);
return;
}
hDesk1 = CreateDesktop(_T("Desk1"), 0, 0, 0, GENERIC_ALL , &attr2);
if (hDesk1 == NULL) {
DWORD res = GetLastError();
printf("CreateDesktop failed, %d\n", res);
return;
}
hDesk2 = OpenInputDesktop(0, FALSE, READ_CONTROL);
if (hDesk2 == NULL) {
DWORD res = GetLastError();
printf("OpenInputDesktop failed, %d\n", res);
return;
}
hDesk3 = GetThreadDesktop(GetCurrentThreadId()); /* return existing handle */
if (hDesk3 == NULL) {
DWORD res = GetLastError();
printf("GetThreadDesktop failed, %d\n", res);
return;
}
if (!GetUserObjectInformation(hDesk3, 2, buf, MAX_PATH, NULL)) {
DWORD res = GetLastError();
printf("GetUserObjectInformation failed, %d\n", res);
}
hDesk4 = OpenDesktop(buf, 0, FALSE, READ_CONTROL | WRITE_DAC);
if (hDesk4 == NULL) {
DWORD res = GetLastError();
printf("OpenDesktop failed, %d\n", res);
return;
}
if (close) {
CloseDesktop(hDesk1);
CloseDesktop(hDesk2);
CloseDesktop(hDesk4);
CloseWindowStation(hWinSta1);
CloseWindowStation(hWinSta2);
}
}
int
main()
{
int i;
/* To test -filter_handle_leaks, we must call those test routines with
* and without closing handles at the same place with the same callstack.
*/
printf("test gdi handles\n");
for (i = 0; i < 3/* make sure there is more than one leak */; i++)
test_gdi_handles((i == 0)/* close handle? */);
printf("test file handles\n");
for (i = 0; i < 3; i++)
test_file_handles((i == 0)/* close handle? */);
printf("test thread handles\n");
for (i = 0; i < 3; i++)
test_thread_handles((i == 0)/* close handle? */);
printf("test window handles\n");
for (i = 0; i < 3; i++)
test_window_handles((i == 0)/* close handle? */);
printf("test process handles\n");
for (i = 0; i < 3; i++)
test_process_handles((i == 0)/* close handle? */);
printf("test desktop handles\n");
for (i = 0; i < 3; i++)
test_desktop_handles((i == 0)/* close handle? */);
return 0;
}
<commit_msg>Fixes issue 1548<commit_after>/* **********************************************************
* Copyright (c) 2012-2014 Google, Inc. All rights reserved.
* **********************************************************/
/* Dr. Memory: the memory debugger
*
* This library 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;
* version 2.1 of the License, and no later version.
* This library 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
* Library General Public License for more details.
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
/* Tests Windows Handle Leaks */
#ifndef WINDOWS
# error Windows-only
#endif
#include <windows.h>
#include <assert.h>
#include <stdio.h>
#include <process.h> /* for _beginthreadex */
#include <tchar.h> /* for tchar */
#include <strsafe.h> /* for Str* */
#include <tlhelp32.h>
static void
test_gdi_handles(bool close)
{
HDC mydc = GetDC(NULL);
assert(mydc != NULL);
HDC dupdc = CreateCompatibleDC(mydc);
assert(dupdc != NULL);
HPEN mypen = CreatePen(PS_SOLID, 0xab,RGB(0xab,0xcd,0xef));
assert(mypen != NULL);
HBITMAP mybmA = CreateBitmap(30, 30, 1, 16, NULL);
assert(mybmA != NULL);
HBITMAP mybmB = CreateCompatibleBitmap(dupdc, 30, 30);
assert(mybmB != NULL);
if (close) {
DeleteObject(mybmB);
DeleteObject(mybmA);
DeleteObject(mypen);
DeleteDC(dupdc);
ReleaseDC(NULL, mydc);
}
}
static unsigned int WINAPI
thread_func(void *arg)
{
int i;
HANDLE hEvent;
for (i = 0; i < 10; i++) {
hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
if (hEvent == NULL) {
printf("fail to create event\n");
return 0;
}
CloseHandle(hEvent);
}
return 0;
}
static void
test_thread_handles(bool close)
{
unsigned int tid;
HANDLE thread;
thread = (HANDLE) _beginthreadex(NULL, 0, thread_func, NULL, 0, &tid);
thread_func(NULL);
WaitForSingleObject(thread, INFINITE);
if (close)
CloseHandle(thread);
}
static void
test_file_handles(bool close)
{
// the files' handles
HANDLE hFile, dupFile1, dupFile2;
HANDLE hFind;
// filenames, the file is not there...
TCHAR buf[MAX_PATH];
DWORD size;
WIN32_FIND_DATA ffd;
bool create_file_tested = false;
size = GetCurrentDirectory(MAX_PATH, buf);
// check size
if (size == 0) {
printf("fail to get current directory\n");
return;
}
// append
StringCchCat(buf, MAX_PATH, TEXT("\\*"));
// find the first file in the directory.
hFind = FindFirstFile(buf, &ffd);
if (hFind == INVALID_HANDLE_VALUE) {
printf("fail to find the first file\n");
return;
}
// find all the files in the directory
do {
bool test_done = false;
if (!create_file_tested &&
!(ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
hFile = CreateFile(ffd.cFileName, 0, 0, NULL, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, NULL);
create_file_tested = true;
if (hFile == INVALID_HANDLE_VALUE) {
printf("fail to open the file %s\n", ffd.cFileName);
return;
}
// test DuplicateHandle
DuplicateHandle(GetCurrentProcess(),
hFile,
GetCurrentProcess(),
&dupFile1,
0,
FALSE,
DUPLICATE_SAME_ACCESS);
if (dupFile1 == INVALID_HANDLE_VALUE) {
printf("fail to duplicate the file handle\n");
return;
}
// close the handle using DuplicateHandle
DuplicateHandle(GetCurrentProcess(),
dupFile1,
GetCurrentProcess(),
&dupFile2, // NULL would cause another leak
0,
FALSE,
DUPLICATE_CLOSE_SOURCE);
if (dupFile2 == INVALID_HANDLE_VALUE) {
printf("fail to duplicate the file handle\n");
return;
}
CloseHandle(dupFile2);
if (close) {
// test handle leak on syscall
DuplicateHandle(GetCurrentProcess(),
hFile,
GetCurrentProcess(),
NULL, // handle leak
0,
FALSE,
DUPLICATE_SAME_ACCESS);
CloseHandle(hFile);
}
test_done = true;
}
if (test_done)
break;
} while (FindNextFile(hFind, &ffd) != 0);
if (GetLastError() == ERROR_NO_MORE_FILES) {
printf("failed to find the next file\n");
}
if (close)
FindClose(hFind);
}
void
test_window_handles(bool close)
{
HWND hWnd;
hWnd = CreateWindowEx(0L, // ExStyle
"Button", // class name
"Main Window", // window name
WS_OVERLAPPEDWINDOW, // style
CW_USEDEFAULT, CW_USEDEFAULT, // pos
CW_USEDEFAULT, CW_USEDEFAULT, // size
(HWND) NULL, // no parent
(HMENU) NULL, // calls menu
(HINSTANCE) NULL,
NULL);
if (!hWnd) {
printf("fail to create window\n");
}
if (close) {
DestroyWindow(hWnd);
}
}
void
test_process_handles(bool close)
{
HANDLE hSnapshot, hProcess;
PROCESSENTRY32 pe;
BOOL res;
hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPALL, 0);
if (hSnapshot == INVALID_HANDLE_VALUE) {
printf("CreateToolhelp32Snapshot failed\n");
return;
}
pe.dwSize = sizeof(pe);
for (res = Process32First(hSnapshot, &pe);
res;
res = Process32Next(hSnapshot, &pe)) {
hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
if (hProcess == INVALID_HANDLE_VALUE) {
printf("OpenProcess failed\n");
return;
}
#ifdef VERBOSE
printf("Process %6u: %s\n", pe.th32ProcessID, pe.szExeFile);
#endif
if (hProcess != 0 && pe.th32ProcessID != 0) /* skip system process */
break;
}
if (close) {
CloseHandle(hProcess);
CloseHandle(hSnapshot);
}
}
void
test_desktop_handles(bool close)
{
HWINSTA hWinSta1, hWinSta2, hWinSta3;
HDESK hDesk1, hDesk2, hDesk3, hDesk4;
SECURITY_ATTRIBUTES attr1 = {0}, attr2 = {0};
TCHAR buf[MAX_PATH];
hWinSta1 = CreateWindowStationW(NULL, 0, WINSTA_ALL_ACCESS, &attr1);
if (hWinSta1 == NULL) {
DWORD res = GetLastError();
printf("CreateWindowStationW failed, %d\n", res);
return;
}
hWinSta2 = OpenWindowStation(_T("winsta0"), FALSE, READ_CONTROL | WRITE_DAC);
if (hWinSta2 == NULL) {
DWORD res = GetLastError();
printf("OpenWindowStation failed, %d\n", res);
return;
}
hWinSta3 = GetProcessWindowStation(); /* return existing handle */
if (hWinSta3 == NULL) {
DWORD res = GetLastError();
printf("GetProcessWindowStation failed, %d\n", res);
return;
}
hDesk1 = CreateDesktop(_T("Desk1"), 0, 0, 0, GENERIC_ALL , &attr2);
if (hDesk1 == NULL) {
DWORD res = GetLastError();
printf("CreateDesktop failed, %d\n", res);
return;
}
hDesk2 = OpenInputDesktop(0, FALSE, READ_CONTROL);
if (hDesk2 == NULL) {
DWORD res = GetLastError();
printf("OpenInputDesktop failed, %d\n", res);
return;
}
hDesk3 = GetThreadDesktop(GetCurrentThreadId()); /* return existing handle */
if (hDesk3 == NULL) {
DWORD res = GetLastError();
printf("GetThreadDesktop failed, %d\n", res);
return;
}
if (!GetUserObjectInformation(hDesk3, 2, buf, MAX_PATH, NULL)) {
DWORD res = GetLastError();
printf("GetUserObjectInformation failed, %d\n", res);
}
hDesk4 = OpenDesktop(buf, 0, FALSE, READ_CONTROL | WRITE_DAC);
if (hDesk4 == NULL) {
DWORD res = GetLastError();
printf("OpenDesktop failed, %d\n", res);
return;
}
if (close) {
CloseDesktop(hDesk1);
CloseDesktop(hDesk2);
CloseDesktop(hDesk4);
CloseWindowStation(hWinSta1);
CloseWindowStation(hWinSta2);
}
}
int
main()
{
# define ITERS 4
int i;
/* To test -filter_handle_leaks, we must call those test routines with
* and without closing handles at the same place with the same callstack.
*/
printf("test gdi handles\n");
for (i = 0; i < ITERS/* make sure there is more than one leak */; i++)
test_gdi_handles((i == 0)/* close handle? */);
printf("test file handles\n");
for (i = 0; i < ITERS; i++)
test_file_handles((i == 0)/* close handle? */);
printf("test thread handles\n");
for (i = 0; i < ITERS; i++)
test_thread_handles((i == 0)/* close handle? */);
printf("test window handles\n");
for (i = 0; i < ITERS; i++)
test_window_handles((i == 0)/* close handle? */);
printf("test process handles\n");
for (i = 0; i < ITERS; i++)
test_process_handles((i == 0)/* close handle? */);
printf("test desktop handles\n");
for (i = 0; i < ITERS; i++)
test_desktop_handles((i == 0)/* close handle? */);
return 0;
}
<|endoftext|> |
<commit_before>/*
* Keyman is copyright (C) SIL International. MIT License.
*
* Keyman Core - Debugger API unit tests
*/
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <iterator>
#include <string>
#include "../../../src/kmx/kmx_xstring.h"
#include "../test_assert.h"
using namespace km::kbp::kmx;
using namespace std;
void test_incxstr() {
PKMX_WCHAR p; // pointer input to incxstr()
PKMX_WCHAR q; // pointer output to incxstr()
// --------------------------------------------------------------------------------------------------------------------------------------------------
// ---- NULL, SURROGATE PAIRS, NON_UC_SENTINEL, ONE CHARACTER ---------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------------------------------------------------------------
// --- Test for empty string ------------------------------------------------------------------------------------------------------------------------
p = (PKMX_WCHAR) u"\0";
q = incxstr(p);
assert(q == p);
// --- Test for character ---------------------------------------------------------------------------------------------------------------------------
p = (PKMX_WCHAR) u"\U00001234";
q = incxstr(p);
assert(q == p+1);
// --- Test for surrogate pair ----------------------------------------------------------------------------------------------------------------------
p = (PKMX_WCHAR) u"\U0001F609";
q = incxstr(p);
assert(q == p+2);
// --- Test for one <control> -----------------------------------------------------------------------------------------------------------------------
p = (PKMX_WCHAR)u"\U00000012";
q = incxstr(p);
assert(q == p + 1);
// --- Test for FFFF only -------------------------------------------------------------------------------------------------------
p = (PKMX_WCHAR)u"\U0000FFFF";
q = incxstr(p);
assert(q == p + 1);
// --------------------------------------------------------------------------------------------------------------------------------------------------
// ---- UC_SENTINEL WITHOUT \0 ----------------------------------------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------------------------------------------------------------
// --- Test for FFFF + CODE_ANY ----------------------------------------------------------------------------------------------------
p = (PKMX_WCHAR)u"\U0000FFFF\U00000001\U00000001";
q = incxstr(p);
assert(q == p + 3);
//
// --- Test for FFFF +CODE_NOTANY ----------------------------------------------------------------------------------------------------------------
p = (PKMX_WCHAR)u"\U0000FFFF\U00000012\U00000001";
q = incxstr(p);
assert(q == p + 3);
// --- Test for FFFF +CODE_INDEX --------------------------------------------------------------------------------------------------------------------
p = (PKMX_WCHAR)u"\U0000FFFF\U00000002\U00000002\U00000001";
q = incxstr(p);
assert(q == p + 4);
// --- Test for FFFF +CODE_USE ----------------------------------------------------------------------------------------------------------
p = (PKMX_WCHAR)u"\U0000FFFF\U00000005\U00000001";
q = incxstr(p);
assert(q == p + 3);
// --- Test for FFFF +CODE_DEADKEY ------------------------------------------------------------------------------------------------------------------
p = (PKMX_WCHAR)u"\U0000FFFF\U00000008\U00000001";
q = incxstr(p);
assert(q == p + 3);
// --- Test for FFFF CODE_EXTENDED --------------------------------------------------------------------------------------------------------
p = (PKMX_WCHAR)u"\U0000FFFF\U0000000A\U00000001\U00000002\U00000003\U00000004\U00000005\U00000006\U00000010";
q = incxstr(p);
assert(q == p + 9);
// --- Test for FFFF +CODE_CLEARCONTEXT ------------------------------------------------------------------------------------------------------------
p = (PKMX_WCHAR)u"\U0000FFFF\U0000000E\U00000001";
q = incxstr(p);
assert(q == p + 3);
// --- Test for FFFF +CODE_CALL ----------------------------------------------------------------------------------------------------------
p = (PKMX_WCHAR)u"\U0000FFFF\U0000000F\U00000001";
q = incxstr(p);
assert(q == p + 3);
// --- Test for FFFF +CODE_CONTEXTEX ---------------------------------------------------------------------------------------------------------------
p = (PKMX_WCHAR)u"\U0000FFFF\U00000011\U00000001";
q = incxstr(p);
assert(q == p + 3);
// --- Test for FFFF +CODE_IFOPT -------------------------------------------------------------------------------------------------------------
p = (PKMX_WCHAR)u"\U0000FFFF\U00000014\U00000002\U00000002\U00000001";
q = incxstr(p);
assert(q == p + 5);
// --- Test for FFFF +CODE_IFSYSTEMSTORE ------------------------------------------------------------------------------------------
p = (PKMX_WCHAR)u"\U0000FFFF\U00000017\U00000002\U00000002\U00000001";
q = incxstr(p);
assert(q == p + 5);
// --- Test for FFFF +CODE_SETOPT ----------------------------------------------------------------------------------------------------------------
p = (PKMX_WCHAR)u"\U0000FFFF\U00000013\U00000002\U00000001";
q = incxstr(p);
assert(q == p + 4);
// --- Test for FFFF +CODE_SETSYSTEMRESTORE ---------------------------------------------------------------------------------------------------------
p = (PKMX_WCHAR)u"\U0000FFFF\U00000018\U00000002\U00000001";
q = incxstr(p);
assert(q == p + 4);
// --- Test for FFFF +CODE_RESETOPT -----------------------------------------------------------------------------------------------------------------
p = (PKMX_WCHAR)u"\U0000FFFF\U00000016\U00000001";
q = incxstr(p);
assert(q == p + 3);
// --- Test for FFFF +CODE_SAVEOPT -----------------------------------------------------------------------------------------------------------
p = (PKMX_WCHAR)u"\U0000FFFF\U00000015\U00000001";
q = incxstr(p);
assert(q == p + 3 );
// --- Test for FFFF +default ----------------------------------------------------------------------------------------------------------------
p = (PKMX_WCHAR)u"\U0000FFFF\U00000004";
q = incxstr(p);
assert(q == p + 2);
// --------------------------------------------------------------------------------------------------------------------------------------------------
// ---- UC_SENTINEL WITH \0 AT DIFFERENT POSITIONS --------------------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------------------------------------------------------------
// --- Test for FFFF + control (earlier p+1) with \0 after first position --------------- unit test failed with old version of incxstr() -----
p = (PKMX_WCHAR)u"\U0000FFFF\0\U00000008\U00000001";
q = incxstr(p);
assert(q == p+1);
// --- Test for FFFF +control (earlier p+1) with \0 after second position --------- unit test failed with old version of incxstr() -----
p = (PKMX_WCHAR)u"\U0000FFFF\U00000008\0\U00000001";
q = incxstr(p);
assert(q == p+2);
// --- Test for FFFF +control (earlier p+1) with \0 after third position ----- unit test failed with old version of incxstr() -----
p = (PKMX_WCHAR)u"\U0000FFFF\U00000008\U00000001\0";
q = incxstr(p);
assert(q == p+3)
// --- Test for FFFF +control (earlier p+2) with \0 after fourth position ----- unit test failed with old version of incxstr() ----
p = (PKMX_WCHAR)u"\U0000FFFF\U00000002\U00000001\U00000001\0";
q = incxstr(p);
assert(q == p+4);
// --- Test for FFFF +control (earlier p+3) with \0 after fifth position ----- unit test failed with old version of incxstr() ---------
p = (PKMX_WCHAR)u"\U0000FFFF\U00000014\U00000001\U00000001\U00000001\0";
q = incxstr(p);
assert(q == p+5);
// --- Test for FFFF +control CODE_EXTENDED ----- (earlier p+n) with \0 after 6. position ----- unit test failed with old version of incxstr() -----
p = (PKMX_WCHAR)u"\U0000FFFF\U0000000A\U00000001\U00000002\U00000003\U00000004\0\U00000005\U00000006\U00000007\U00000010";
q = incxstr(p);
assert(q == p + 6);
// --- Test for FFFF +control CODE_EXTENDED ----- (earlier p+n) with \0 after 7. position ----- unit test failed with old version of incxstr()
p = (PKMX_WCHAR)u"\U0000FFFF\U0000000A\U00000001\U00000002\U00000003\U00000004\U00000005\0\U00000006\U00000007\U00000010";
q = incxstr(p);
assert(q == p + 7);
// --- Test for FFFF +control CODE_EXTENDED ----- (earlier p+n) with \0 after 8. position ----- unit test failed with old version of incxstr() ----------
p = (PKMX_WCHAR)u"\U0000FFFF\U0000000A\U00000001\U00000002\U00000003\U00000004\U00000005\U00000006\0\U00000007\U00000010";
q = incxstr(p);
assert(q == p + 8);
// --- Test for FFFF +control CODE_EXTENDED ----- (earlier p+n) with \0 after 9. position ----- unit test failed with old version of incxstr() ---
p = (PKMX_WCHAR)u"\U0000FFFF\U0000000A\U00000001\U00000002\U00000003\U00000004\U00000005\U00000006\U00000007\0\U00000010";
q = incxstr(p);
assert(q == p + 9);
// --- Test for FFFF +control CODE_EXTENDED ----- (earlier p+n) with \0 after 10. position ----- unit test failed with old version of incxstr() -----------
p = (PKMX_WCHAR)u"\U0000FFFF\U0000000A\U00000001\U00000002\U00000003\U00000004\U00000005\U00000006\U00000007\U00000010\0";
q = incxstr(p);
assert(q == p + 10);
// --------------------------------------------------------------------------------------------------------------------------------------------------
// ---- UC_SENTINEL, INCOMPLETE & UNUSUAL SEQUENCES--------------------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------------------------------------------------------------
// --- Test for FFFF + \0 --------------------------------------------------------------------------------------------------------------------
p = (PKMX_WCHAR)u"\U0000FFFF\0";
q = incxstr(p);
assert(q == p + 1);
// --- Test for FFFF +one character ------------------------------------------------------------------------------------------------------------
p = (PKMX_WCHAR)u"\U0000FFFF\U00000062";
q = incxstr(p);
assert(q == p + 2);
// --- Test for FFFF +one <control> -----------------------------------------------------------------------------------------------------------------
p = (PKMX_WCHAR)u"\U0000FFFF\U00000004";
q = incxstr(p);
assert(q == p + 2);
// --- Test for FFFF + one <control> + character -------------------------------------------------------------------------------------------
p = (PKMX_WCHAR)u"\U0000FFFF\U00000004\U00000062";
q = incxstr(p);
assert(q == p + 2);
}
constexpr const auto help_str = "\
debug_api [--color] <SOURCE_PATH>|--print-sizeof\n\
\n\
--color Force color output\n\
--print-sizeof Emit structure sizes for interop debug\n\
SOURCE_PATH Path where debug_api.cpp is found; kmx files are\n\
located relative to this path.\n";
int error_args() {
std::cerr << "debug_api: Invalid arguments." << std::endl;
std::cout << help_str;
return 1;
}
int main(int argc, char *argv []) {
// TODO: choose/create a keyboard which has some rules
// Global setup
//std::string path(argv[1]);
if(argc < 2) {
return error_args();
}
auto arg_color = argc > 1 && std::string(argv[1]) == "--color";
if(arg_color && argc < 3) {
return error_args();
}
console_color::enabled = console_color::isaterminal() || arg_color;
//arg_path = argv[arg_color ? 2 : 1];
test_incxstr();
return 0;
}
<commit_msg>Update common/core/desktop/tests/unit/kmnkbd/test_kmx_xstring.cpp<commit_after>/*
* Keyman is copyright (C) SIL International. MIT License.
*
* Keyman Core - Debugger API unit tests
*/
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <iterator>
#include <string>
#include "../../../src/kmx/kmx_xstring.h"
#include "../test_assert.h"
using namespace km::kbp::kmx;
using namespace std;
void test_incxstr() {
PKMX_WCHAR p; // pointer input to incxstr()
PKMX_WCHAR q; // pointer output to incxstr()
// --------------------------------------------------------------------------------------------------------------------------------------------------
// ---- NULL, SURROGATE PAIRS, NON_UC_SENTINEL, ONE CHARACTER ---------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------------------------------------------------------------
// --- Test for empty string ------------------------------------------------------------------------------------------------------------------------
p = (PKMX_WCHAR) u"\0";
q = incxstr(p);
assert(q == p);
// --- Test for character ---------------------------------------------------------------------------------------------------------------------------
p = (PKMX_WCHAR) u"\U00001234";
q = incxstr(p);
assert(q == p+1);
// --- Test for surrogate pair ----------------------------------------------------------------------------------------------------------------------
p = (PKMX_WCHAR) u"\U0001F609";
q = incxstr(p);
assert(q == p+2);
// --- Test for one <control> -----------------------------------------------------------------------------------------------------------------------
p = (PKMX_WCHAR)u"\U00000012";
q = incxstr(p);
assert(q == p + 1);
// --- Test for FFFF only -------------------------------------------------------------------------------------------------------
p = (PKMX_WCHAR)u"\U0000FFFF";
q = incxstr(p);
assert(q == p + 1);
// --------------------------------------------------------------------------------------------------------------------------------------------------
// ---- UC_SENTINEL WITHOUT \0 ----------------------------------------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------------------------------------------------------------
// --- Test for FFFF + CODE_ANY ----------------------------------------------------------------------------------------------------
p = (PKMX_WCHAR)u"\U0000FFFF\U00000001\U00000001";
q = incxstr(p);
assert(q == p + 3);
//
// --- Test for FFFF +CODE_NOTANY ----------------------------------------------------------------------------------------------------------------
p = (PKMX_WCHAR)u"\U0000FFFF\U00000012\U00000001";
q = incxstr(p);
assert(q == p + 3);
// --- Test for FFFF +CODE_INDEX --------------------------------------------------------------------------------------------------------------------
p = (PKMX_WCHAR)u"\U0000FFFF\U00000002\U00000002\U00000001";
q = incxstr(p);
assert(q == p + 4);
// --- Test for FFFF +CODE_USE ----------------------------------------------------------------------------------------------------------
p = (PKMX_WCHAR)u"\U0000FFFF\U00000005\U00000001";
q = incxstr(p);
assert(q == p + 3);
// --- Test for FFFF +CODE_DEADKEY ------------------------------------------------------------------------------------------------------------------
p = (PKMX_WCHAR)u"\U0000FFFF\U00000008\U00000001";
q = incxstr(p);
assert(q == p + 3);
// --- Test for FFFF CODE_EXTENDED --------------------------------------------------------------------------------------------------------
p = (PKMX_WCHAR)u"\U0000FFFF\U0000000A\U00000001\U00000002\U00000003\U00000004\U00000005\U00000006\U00000010";
q = incxstr(p);
assert(q == p + 9);
// --- Test for FFFF +CODE_CLEARCONTEXT ------------------------------------------------------------------------------------------------------------
p = (PKMX_WCHAR)u"\U0000FFFF\U0000000E\U00000001";
q = incxstr(p);
assert(q == p + 3);
// --- Test for FFFF +CODE_CALL ----------------------------------------------------------------------------------------------------------
p = (PKMX_WCHAR)u"\U0000FFFF\U0000000F\U00000001";
q = incxstr(p);
assert(q == p + 3);
// --- Test for FFFF +CODE_CONTEXTEX ---------------------------------------------------------------------------------------------------------------
p = (PKMX_WCHAR)u"\U0000FFFF\U00000011\U00000001";
q = incxstr(p);
assert(q == p + 3);
// --- Test for FFFF +CODE_IFOPT -------------------------------------------------------------------------------------------------------------
p = (PKMX_WCHAR)u"\U0000FFFF\U00000014\U00000002\U00000002\U00000001";
q = incxstr(p);
assert(q == p + 5);
// --- Test for FFFF +CODE_IFSYSTEMSTORE ------------------------------------------------------------------------------------------
p = (PKMX_WCHAR)u"\U0000FFFF\U00000017\U00000002\U00000002\U00000001";
q = incxstr(p);
assert(q == p + 5);
// --- Test for FFFF +CODE_SETOPT ----------------------------------------------------------------------------------------------------------------
p = (PKMX_WCHAR)u"\U0000FFFF\U00000013\U00000002\U00000001";
q = incxstr(p);
assert(q == p + 4);
// --- Test for FFFF +CODE_SETSYSTEMRESTORE ---------------------------------------------------------------------------------------------------------
p = (PKMX_WCHAR)u"\U0000FFFF\U00000018\U00000002\U00000001";
q = incxstr(p);
assert(q == p + 4);
// --- Test for FFFF +CODE_RESETOPT -----------------------------------------------------------------------------------------------------------------
p = (PKMX_WCHAR)u"\U0000FFFF\U00000016\U00000001";
q = incxstr(p);
assert(q == p + 3);
// --- Test for FFFF +CODE_SAVEOPT -----------------------------------------------------------------------------------------------------------
p = (PKMX_WCHAR)u"\U0000FFFF\U00000015\U00000001";
q = incxstr(p);
assert(q == p + 3 );
// --- Test for FFFF +default ----------------------------------------------------------------------------------------------------------------
p = (PKMX_WCHAR)u"\U0000FFFF\U00000004";
q = incxstr(p);
assert(q == p + 2);
// --------------------------------------------------------------------------------------------------------------------------------------------------
// ---- UC_SENTINEL WITH \0 AT DIFFERENT POSITIONS --------------------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------------------------------------------------------------
// --- Test for FFFF + control (earlier p+1) with \0 after first position --------------- unit test failed with old version of incxstr() -----
p = (PKMX_WCHAR)u"\U0000FFFF\0\U00000008\U00000001";
q = incxstr(p);
assert(q == p+1);
// --- Test for FFFF +control (earlier p+1) with \0 after second position --------- unit test failed with old version of incxstr() -----
p = (PKMX_WCHAR)u"\U0000FFFF\U00000008\0\U00000001";
q = incxstr(p);
assert(q == p+2);
// --- Test for FFFF +control (earlier p+1) with \0 after third position ----- unit test failed with old version of incxstr() -----
p = (PKMX_WCHAR)u"\U0000FFFF\U00000008\U00000001\0";
q = incxstr(p);
assert(q == p+3)
// --- Test for FFFF +control (earlier p+2) with \0 after fourth position ----- unit test failed with old version of incxstr() ----
p = (PKMX_WCHAR)u"\U0000FFFF\U00000002\U00000001\U00000001\0";
q = incxstr(p);
assert(q == p+4);
// --- Test for FFFF +control (earlier p+3) with \0 after fifth position ----- unit test failed with old version of incxstr() ---------
p = (PKMX_WCHAR)u"\U0000FFFF\U00000014\U00000001\U00000001\U00000001\0";
q = incxstr(p);
assert(q == p+5);
// --- Test for FFFF +control CODE_EXTENDED ----- (earlier p+n) with \0 after 6. position ----- unit test failed with old version of incxstr() -----
p = (PKMX_WCHAR)u"\U0000FFFF\U0000000A\U00000001\U00000002\U00000003\U00000004\0\U00000005\U00000006\U00000007\U00000010";
q = incxstr(p);
assert(q == p + 6);
// --- Test for FFFF +control CODE_EXTENDED ----- (earlier p+n) with \0 after 7. position ----- unit test failed with old version of incxstr()
p = (PKMX_WCHAR)u"\U0000FFFF\U0000000A\U00000001\U00000002\U00000003\U00000004\U00000005\0\U00000006\U00000007\U00000010";
q = incxstr(p);
assert(q == p + 7);
// --- Test for FFFF +control CODE_EXTENDED ----- (earlier p+n) with \0 after 8. position ----- unit test failed with old version of incxstr() ----------
p = (PKMX_WCHAR)u"\U0000FFFF\U0000000A\U00000001\U00000002\U00000003\U00000004\U00000005\U00000006\0\U00000007\U00000010";
q = incxstr(p);
assert(q == p + 8);
// --- Test for FFFF +control CODE_EXTENDED ----- (earlier p+n) with \0 after 9. position ----- unit test failed with old version of incxstr() ---
p = (PKMX_WCHAR)u"\U0000FFFF\U0000000A\U00000001\U00000002\U00000003\U00000004\U00000005\U00000006\U00000007\0\U00000010";
q = incxstr(p);
assert(q == p + 9);
// --- Test for FFFF +control CODE_EXTENDED ----- (earlier p+n) with \0 after 10. position ----- unit test failed with old version of incxstr() -----------
p = (PKMX_WCHAR)u"\U0000FFFF\U0000000A\U00000001\U00000002\U00000003\U00000004\U00000005\U00000006\U00000007\U00000010\0";
q = incxstr(p);
assert(q == p + 10);
// --------------------------------------------------------------------------------------------------------------------------------------------------
// ---- UC_SENTINEL, INCOMPLETE & UNUSUAL SEQUENCES--------------------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------------------------------------------------------------
// --- Test for FFFF + \0 --------------------------------------------------------------------------------------------------------------------
p = (PKMX_WCHAR)u"\U0000FFFF\0";
q = incxstr(p);
assert(q == p + 1);
// --- Test for FFFF +one character ------------------------------------------------------------------------------------------------------------
p = (PKMX_WCHAR)u"\U0000FFFF\U00000062";
q = incxstr(p);
assert(q == p + 2);
// --- Test for FFFF +one <control> -----------------------------------------------------------------------------------------------------------------
p = (PKMX_WCHAR)u"\U0000FFFF\U00000004";
q = incxstr(p);
assert(q == p + 2);
// --- Test for FFFF + one <control> + character -------------------------------------------------------------------------------------------
p = (PKMX_WCHAR)u"\U0000FFFF\U00000004\U00000062";
q = incxstr(p);
assert(q == p + 2);
}
constexpr const auto help_str = "\
debug_api [--color] <SOURCE_PATH>|--print-sizeof\n\
\n\
--color Force color output\n\
--print-sizeof Emit structure sizes for interop debug\n\
SOURCE_PATH Path where debug_api.cpp is found; kmx files are\n\
located relative to this path.\n";
int error_args() {
std::cerr << "debug_api: Invalid arguments." << std::endl;
std::cout << help_str;
return 1;
}
int main(int argc, char *argv []) {
// TODO: choose/create a keyboard which has some rules
// Global setup
//std::string path(argv[1]);
if(argc < 2) {
return error_args();
}
auto arg_color = argc > 1 && std::string(argv[1]) == "--color";
if(arg_color && argc < 3) {
return error_args();
}
console_color::enabled = console_color::isaterminal() || arg_color;
test_incxstr();
return 0;
}
<|endoftext|> |
<commit_before>#pragma once
#include "socket/udp.hpp"
#include "socket/tcp.hpp"
#include "blackhole/repository/factory/traits.hpp"
#include "blackhole/sink/thread.hpp"
namespace blackhole {
namespace sink {
namespace socket {
struct config_t {
std::string host;
std::uint16_t port;
};
} // namespace socket
template<typename Protocol, typename Backend = socket::boost_backend_t<Protocol> >
class socket_t {
Backend m_backend;
public:
typedef socket::config_t config_type;
socket_t(const config_type& config) :
m_backend(config.host, config.port)
{}
socket_t(const std::string& host, std::uint16_t port) :
m_backend(host, port)
{}
static const char* name() {
return Backend::name();
}
void consume(const std::string& message) {
m_backend.write(message);
}
Backend& backend() {
return m_backend;
}
};
template<>
struct thread_safety<socket_t<boost::asio::ip::udp>> :
public std::integral_constant<
thread::safety_t,
thread::safety_t::safe
>::type
{};
} // namespace sink
template<typename Protocol>
struct factory_traits<sink::socket_t<Protocol>> {
typedef sink::socket_t<Protocol> sink_type;
typedef typename sink_type::config_type config_type;
static void map_config(const aux::extractor<sink_type>& ex, config_type& config) {
ex["host"].to(config.host);
ex["port"].to(config.port);
}
};
} // namespace blackhole
<commit_msg>[Aux] Refactoring over socket sink.<commit_after>#pragma once
#include "socket/udp.hpp"
#include "socket/tcp.hpp"
#include "blackhole/repository/factory/traits.hpp"
#include "blackhole/sink/thread.hpp"
namespace blackhole {
namespace sink {
namespace socket {
struct config_t {
std::string host;
std::uint16_t port;
};
} // namespace socket
template<typename Protocol, typename Backend = socket::boost_backend_t<Protocol>>
class socket_t {
public:
typedef Protocol protocol_type;
typedef Backend backend_type;
typedef socket::config_t config_type;
private:
backend_type backend_;
public:
socket_t(const config_type& config) :
backend_(config.host, config.port)
{}
socket_t(std::string host, std::uint16_t port) :
backend_(std::move(host), port)
{}
static const char* name() {
return backend_type::name();
}
void consume(const std::string& message) {
backend_.write(message);
}
#ifdef BLACKHOLE_TESTING
backend_type& backend() {
return backend_;
}
#endif
};
template<>
struct thread_safety<socket_t<boost::asio::ip::udp>> :
public std::integral_constant<
thread::safety_t,
thread::safety_t::safe
>::type
{};
} // namespace sink
template<typename Protocol>
struct factory_traits<sink::socket_t<Protocol>> {
typedef sink::socket_t<Protocol> sink_type;
typedef typename sink_type::config_type config_type;
static void map_config(const aux::extractor<sink_type>& ex, config_type& config) {
ex["host"].to(config.host);
ex["port"].to(config.port);
}
};
} // namespace blackhole
<|endoftext|> |
<commit_before>#include <gtest/gtest.h>
#include <blackhole/record.hpp>
namespace blackhole {
namespace testing {
TEST(Record, Severity) {
attribute_pack pack{};
record_t record(42, "GET /porn.png HTTP/1.1", pack);
EXPECT_EQ(42, record.severity());
}
TEST(Record, Message) {
attribute_pack pack{};
record_t record(42, "GET /porn.png HTTP/1.1", pack);
EXPECT_EQ("GET /porn.png HTTP/1.1", record.message().to_string());
}
TEST(Record, Attributes) {
const view_of<attributes_t>::type attributes{{"key#1", {42}}};
attribute_pack pack{attributes};
record_t record(42, "GET /porn.png HTTP/1.1", pack);
ASSERT_EQ(1, record.attributes().size());
EXPECT_EQ(attributes, record.attributes().at(0));
}
TEST(Record, Pid) {
attribute_pack pack;
record_t record(42, "GET /porn.png HTTP/1.1", pack);
EXPECT_EQ(::getpid(), record.pid());
}
TEST(Record, Tid) {
attribute_pack pack;
record_t record(42, "GET /porn.png HTTP/1.1", pack);
// TODO: Fail for now, need to check platform dependent behavior.
// EXPECT_EQ(std::this_thread::get_id(), record.tid())
}
TEST(Record, Timestamp) {
attribute_pack pack;
const auto min = std::chrono::high_resolution_clock::now();
record_t record(42, "GET /porn.png HTTP/1.1", pack);
const auto max = std::chrono::high_resolution_clock::now();
EXPECT_TRUE(min <= record.timestamp());
EXPECT_TRUE(max >= record.timestamp());
}
} // namespace testing
} // namespace blackhole
<commit_msg>chore(tests): make tiny cleanup<commit_after>#include <gtest/gtest.h>
#include <blackhole/record.hpp>
namespace blackhole {
namespace testing {
TEST(Record, Severity) {
attribute_pack pack{};
record_t record(42, "GET /porn.png HTTP/1.1", pack);
EXPECT_EQ(42, record.severity());
}
TEST(Record, Message) {
attribute_pack pack{};
record_t record(42, "GET /porn.png HTTP/1.1", pack);
EXPECT_EQ("GET /porn.png HTTP/1.1", record.message().to_string());
}
TEST(Record, Attributes) {
const view_of<attributes_t>::type attributes{{"key#1", {42}}};
attribute_pack pack{attributes};
record_t record(42, "GET /porn.png HTTP/1.1", pack);
ASSERT_EQ(1, record.attributes().size());
EXPECT_EQ(attributes, record.attributes().at(0));
}
TEST(Record, Pid) {
attribute_pack pack;
record_t record(42, "GET /porn.png HTTP/1.1", pack);
EXPECT_EQ(::getpid(), record.pid());
}
TEST(Record, Tid) {
attribute_pack pack;
record_t record(42, "GET /porn.png HTTP/1.1", pack);
// TODO: Fail for now, need to check platform dependent behavior.
// EXPECT_EQ(std::this_thread::get_id(), record.tid())
}
TEST(Record, Timestamp) {
typedef std::chrono::high_resolution_clock clock_type;
attribute_pack pack;
const auto min = clock_type::now();
record_t record(42, "GET /porn.png HTTP/1.1", pack);
const auto max = clock_type::now();
EXPECT_TRUE(min <= record.timestamp());
EXPECT_TRUE(max >= record.timestamp());
}
} // namespace testing
} // namespace blackhole
<|endoftext|> |
<commit_before>// Copyright (c) 2007-2010 Paul Hodge. All rights reserved.
#include "circa.h"
namespace circa {
namespace map_function {
void evaluate(EvalContext* cxt, Term* caller)
{
Term* func = caller->input(0);
Branch& inputs = as_branch(caller->input(1));
Branch& output = as_branch(caller);
if (is_function_stateful(func)) {
error_occurred(cxt, caller, "map() not yet supported on a stateful function");
return;
}
// Create term if necessary
for (int i=output.length(); i < inputs.length(); i++)
apply(output, func, RefList(inputs[i]));
// Remove extra terms if necessary
for (int i=inputs.length(); i < output.length(); i++)
output.set(i, NULL);
output.removeNulls();
evaluate_branch(cxt, output);
}
void setup(Branch& kernel)
{
import_function(kernel, evaluate, "def map(any,Indexable) -> List");
}
}
} // namespace circa
<commit_msg>map() is no longer branch-based<commit_after>// Copyright (c) 2007-2010 Paul Hodge. All rights reserved.
#include "circa.h"
namespace circa {
namespace map_function {
void evaluate(EvalContext* cxt, Term* caller)
{
Term* func = caller->input(0);
List* inputs = (List*) caller->input(1);
Branch& output = as_branch(caller);
if (is_function_stateful(func)) {
error_occurred(cxt, caller, "map() not yet supported on a stateful function");
return;
}
int numInputs = inputs->numElements();
Branch evaluationBranch;
Term* evalInput = apply(evaluationBranch, INPUT_PLACEHOLDER_FUNC, RefList());
Term* evalResult = apply(evaluationBranch, func, RefList(evalInput));
output.clear();
for (int i=0; i < numInputs; i++) {
copy(inputs->getIndex(i), evalInput);
evaluate_branch(evaluationBranch);
Term* outputElement = create_value(output, evalResult->type);
copy(evalResult, outputElement);
}
#if 0
Old branch-based version:
// Create term if necessary
for (int i=output.length(); i < inputs.length(); i++)
apply(output, func, RefList(inputs[i]));
// Remove extra terms if necessary
for (int i=inputs.length(); i < output.length(); i++)
output.set(i, NULL);
output.removeNulls();
evaluate_branch(cxt, output);
#endif
}
void setup(Branch& kernel)
{
import_function(kernel, evaluate, "def map(any,Indexable) -> List");
}
}
} // namespace circa
<|endoftext|> |
<commit_before>//===- FuzzerLoop.cpp - Fuzzer's main loop --------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// Fuzzer's main loop.
//===----------------------------------------------------------------------===//
#include "FuzzerInternal.h"
#include <sanitizer/coverage_interface.h>
#include <algorithm>
#include <iostream>
namespace fuzzer {
// Only one Fuzzer per process.
static Fuzzer *F;
Fuzzer::Fuzzer(UserCallback Callback, FuzzingOptions Options)
: Callback(Callback), Options(Options) {
SetDeathCallback();
InitializeTraceState();
assert(!F);
F = this;
}
void Fuzzer::SetDeathCallback() {
__sanitizer_set_death_callback(StaticDeathCallback);
}
void Fuzzer::PrintUnitInASCIIOrTokens(const Unit &U, const char *PrintAfter) {
if (Options.Tokens.empty()) {
PrintASCII(U, PrintAfter);
} else {
auto T = SubstituteTokens(U);
T.push_back(0);
std::cerr << T.data();
std::cerr << PrintAfter;
}
}
void Fuzzer::StaticDeathCallback() {
assert(F);
F->DeathCallback();
}
void Fuzzer::DeathCallback() {
std::cerr << "DEATH: " << std::endl;
Print(CurrentUnit, "\n");
PrintUnitInASCIIOrTokens(CurrentUnit, "\n");
WriteToCrash(CurrentUnit, "crash-");
}
void Fuzzer::StaticAlarmCallback() {
assert(F);
F->AlarmCallback();
}
void Fuzzer::AlarmCallback() {
size_t Seconds =
duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
std::cerr << "ALARM: working on the last Unit for " << Seconds << " seconds"
<< std::endl;
if (Seconds >= 3) {
Print(CurrentUnit, "\n");
PrintUnitInASCIIOrTokens(CurrentUnit, "\n");
WriteToCrash(CurrentUnit, "timeout-");
}
exit(1);
}
void Fuzzer::PrintStats(const char *Where, size_t Cov, const char *End) {
if (!Options.Verbosity) return;
size_t Seconds = secondsSinceProcessStartUp();
size_t ExecPerSec = (Seconds ? TotalNumberOfRuns / Seconds : 0);
std::cerr
<< "#" << TotalNumberOfRuns
<< "\t" << Where
<< " cov " << Cov
<< " bits " << TotalBits()
<< " units " << Corpus.size()
<< " exec/s " << ExecPerSec
<< End;
}
void Fuzzer::RereadOutputCorpus() {
if (Options.OutputCorpus.empty()) return;
std::vector<Unit> AdditionalCorpus;
ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
&EpochOfLastReadOfOutputCorpus);
if (Corpus.empty()) {
Corpus = AdditionalCorpus;
return;
}
if (!Options.Reload) return;
for (auto &X : AdditionalCorpus) {
if (X.size() > (size_t)Options.MaxLen)
X.resize(Options.MaxLen);
if (UnitsAddedAfterInitialLoad.insert(X).second) {
Corpus.push_back(X);
CurrentUnit.clear();
CurrentUnit.insert(CurrentUnit.begin(), X.begin(), X.end());
size_t NewCoverage = RunOne(CurrentUnit);
if (NewCoverage && Options.Verbosity >= 1)
PrintStats("RELOAD", NewCoverage);
}
}
}
void Fuzzer::ShuffleAndMinimize() {
size_t MaxCov = 0;
bool PreferSmall =
(Options.PreferSmallDuringInitialShuffle == 1 ||
(Options.PreferSmallDuringInitialShuffle == -1 && rand() % 2));
if (Options.Verbosity)
std::cerr << "PreferSmall: " << PreferSmall << "\n";
PrintStats("READ ", 0);
std::vector<Unit> NewCorpus;
std::random_shuffle(Corpus.begin(), Corpus.end());
if (PreferSmall)
std::stable_sort(
Corpus.begin(), Corpus.end(),
[](const Unit &A, const Unit &B) { return A.size() < B.size(); });
Unit &U = CurrentUnit;
for (const auto &C : Corpus) {
for (size_t First = 0; First < 1; First++) {
U.clear();
size_t Last = std::min(First + Options.MaxLen, C.size());
U.insert(U.begin(), C.begin() + First, C.begin() + Last);
size_t NewCoverage = RunOne(U);
if (NewCoverage) {
MaxCov = NewCoverage;
NewCorpus.push_back(U);
if (Options.Verbosity >= 2)
std::cerr << "NEW0: " << NewCoverage
<< " L " << U.size()
<< "\n";
}
}
}
Corpus = NewCorpus;
PrintStats("INITED", MaxCov);
}
size_t Fuzzer::RunOne(const Unit &U) {
UnitStartTime = system_clock::now();
TotalNumberOfRuns++;
size_t Res = 0;
if (Options.UseFullCoverageSet)
Res = RunOneMaximizeFullCoverageSet(U);
else if (Options.UseCoveragePairs)
Res = RunOneMaximizeCoveragePairs(U);
else
Res = RunOneMaximizeTotalCoverage(U);
auto UnitStopTime = system_clock::now();
auto TimeOfUnit =
duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
if (TimeOfUnit > TimeOfLongestUnitInSeconds) {
TimeOfLongestUnitInSeconds = TimeOfUnit;
std::cerr << "Longest unit: " << TimeOfLongestUnitInSeconds
<< " s:\n";
Print(U, "\n");
}
return Res;
}
void Fuzzer::RunOneAndUpdateCorpus(const Unit &U) {
if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
return;
ReportNewCoverage(RunOne(U), U);
}
static uintptr_t HashOfArrayOfPCs(uintptr_t *PCs, uintptr_t NumPCs) {
uintptr_t Res = 0;
for (uintptr_t i = 0; i < NumPCs; i++) {
Res = (Res + PCs[i]) * 7;
}
return Res;
}
Unit Fuzzer::SubstituteTokens(const Unit &U) const {
Unit Res;
for (auto Idx : U) {
if (Idx < Options.Tokens.size()) {
std::string Token = Options.Tokens[Idx];
Res.insert(Res.end(), Token.begin(), Token.end());
} else {
Res.push_back(' ');
}
}
// FIXME: Apply DFSan labels.
return Res;
}
void Fuzzer::ExecuteCallback(const Unit &U) {
if (Options.Tokens.empty()) {
Callback(U.data(), U.size());
} else {
auto T = SubstituteTokens(U);
Callback(T.data(), T.size());
}
}
// Experimental. Does not yet scale.
// Fuly reset the current coverage state, run a single unit,
// collect all coverage pairs and return non-zero if a new pair is observed.
size_t Fuzzer::RunOneMaximizeCoveragePairs(const Unit &U) {
__sanitizer_reset_coverage();
ExecuteCallback(U);
uintptr_t *PCs;
uintptr_t NumPCs = __sanitizer_get_coverage_guards(&PCs);
bool HasNewPairs = false;
for (uintptr_t i = 0; i < NumPCs; i++) {
if (!PCs[i]) continue;
for (uintptr_t j = 0; j < NumPCs; j++) {
if (!PCs[j]) continue;
uint64_t Pair = (i << 32) | j;
HasNewPairs |= CoveragePairs.insert(Pair).second;
}
}
if (HasNewPairs)
return CoveragePairs.size();
return 0;
}
// Experimental.
// Fuly reset the current coverage state, run a single unit,
// compute a hash function from the full coverage set,
// return non-zero if the hash value is new.
// This produces tons of new units and as is it's only suitable for small tests,
// e.g. test/FullCoverageSetTest.cpp. FIXME: make it scale.
size_t Fuzzer::RunOneMaximizeFullCoverageSet(const Unit &U) {
__sanitizer_reset_coverage();
ExecuteCallback(U);
uintptr_t *PCs;
uintptr_t NumPCs =__sanitizer_get_coverage_guards(&PCs);
if (FullCoverageSets.insert(HashOfArrayOfPCs(PCs, NumPCs)).second)
return FullCoverageSets.size();
return 0;
}
size_t Fuzzer::RunOneMaximizeTotalCoverage(const Unit &U) {
size_t NumCounters = __sanitizer_get_number_of_counters();
if (Options.UseCounters) {
CounterBitmap.resize(NumCounters);
__sanitizer_update_counter_bitset_and_clear_counters(0);
}
size_t OldCoverage = __sanitizer_get_total_unique_coverage();
ExecuteCallback(U);
size_t NewCoverage = __sanitizer_get_total_unique_coverage();
size_t NumNewBits = 0;
if (Options.UseCounters)
NumNewBits = __sanitizer_update_counter_bitset_and_clear_counters(
CounterBitmap.data());
if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) && Options.Verbosity)
PrintStats("pulse ", NewCoverage);
if (NewCoverage > OldCoverage || NumNewBits)
return NewCoverage;
return 0;
}
void Fuzzer::WriteToOutputCorpus(const Unit &U) {
if (Options.OutputCorpus.empty()) return;
std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
WriteToFile(U, Path);
if (Options.Verbosity >= 2)
std::cerr << "Written to " << Path << std::endl;
}
void Fuzzer::WriteToCrash(const Unit &U, const char *Prefix) {
std::string Path = Prefix + Hash(U);
WriteToFile(U, Path);
std::cerr << "CRASHED; file written to " << Path << std::endl;
std::cerr << "Base64: ";
PrintFileAsBase64(Path);
}
void Fuzzer::SaveCorpus() {
if (Options.OutputCorpus.empty()) return;
for (const auto &U : Corpus)
WriteToFile(U, DirPlusFile(Options.OutputCorpus, Hash(U)));
if (Options.Verbosity)
std::cerr << "Written corpus of " << Corpus.size() << " files to "
<< Options.OutputCorpus << "\n";
}
void Fuzzer::ReportNewCoverage(size_t NewCoverage, const Unit &U) {
if (!NewCoverage) return;
Corpus.push_back(U);
UnitsAddedAfterInitialLoad.insert(U);
PrintStats("NEW ", NewCoverage, "");
if (Options.Verbosity) {
std::cerr << " L: " << U.size();
if (U.size() < 30) {
std::cerr << " ";
PrintUnitInASCIIOrTokens(U, "\t");
Print(U);
}
std::cerr << "\n";
}
WriteToOutputCorpus(U);
if (Options.ExitOnFirst)
exit(0);
}
void Fuzzer::MutateAndTestOne(Unit *U) {
for (int i = 0; i < Options.MutateDepth; i++) {
StartTraceRecording();
Mutate(U, Options.MaxLen);
RunOneAndUpdateCorpus(*U);
size_t NumTraceBasedMutations = StopTraceRecording();
for (size_t j = 0; j < NumTraceBasedMutations; j++) {
ApplyTraceBasedMutation(j, U);
RunOneAndUpdateCorpus(*U);
}
}
}
void Fuzzer::Loop(size_t NumIterations) {
for (size_t i = 1; i <= NumIterations; i++) {
for (size_t J1 = 0; J1 < Corpus.size(); J1++) {
RereadOutputCorpus();
if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
return;
// First, simply mutate the unit w/o doing crosses.
CurrentUnit = Corpus[J1];
MutateAndTestOne(&CurrentUnit);
// Now, cross with others.
if (Options.DoCrossOver) {
for (size_t J2 = 0; J2 < Corpus.size(); J2++) {
CurrentUnit.clear();
CrossOver(Corpus[J1], Corpus[J2], &CurrentUnit, Options.MaxLen);
MutateAndTestOne(&CurrentUnit);
}
}
}
}
}
} // namespace fuzzer
<commit_msg>Code cleanup: Reindent Fuzzer::MutateAndTestOne.<commit_after>//===- FuzzerLoop.cpp - Fuzzer's main loop --------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// Fuzzer's main loop.
//===----------------------------------------------------------------------===//
#include "FuzzerInternal.h"
#include <sanitizer/coverage_interface.h>
#include <algorithm>
#include <iostream>
namespace fuzzer {
// Only one Fuzzer per process.
static Fuzzer *F;
Fuzzer::Fuzzer(UserCallback Callback, FuzzingOptions Options)
: Callback(Callback), Options(Options) {
SetDeathCallback();
InitializeTraceState();
assert(!F);
F = this;
}
void Fuzzer::SetDeathCallback() {
__sanitizer_set_death_callback(StaticDeathCallback);
}
void Fuzzer::PrintUnitInASCIIOrTokens(const Unit &U, const char *PrintAfter) {
if (Options.Tokens.empty()) {
PrintASCII(U, PrintAfter);
} else {
auto T = SubstituteTokens(U);
T.push_back(0);
std::cerr << T.data();
std::cerr << PrintAfter;
}
}
void Fuzzer::StaticDeathCallback() {
assert(F);
F->DeathCallback();
}
void Fuzzer::DeathCallback() {
std::cerr << "DEATH: " << std::endl;
Print(CurrentUnit, "\n");
PrintUnitInASCIIOrTokens(CurrentUnit, "\n");
WriteToCrash(CurrentUnit, "crash-");
}
void Fuzzer::StaticAlarmCallback() {
assert(F);
F->AlarmCallback();
}
void Fuzzer::AlarmCallback() {
size_t Seconds =
duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
std::cerr << "ALARM: working on the last Unit for " << Seconds << " seconds"
<< std::endl;
if (Seconds >= 3) {
Print(CurrentUnit, "\n");
PrintUnitInASCIIOrTokens(CurrentUnit, "\n");
WriteToCrash(CurrentUnit, "timeout-");
}
exit(1);
}
void Fuzzer::PrintStats(const char *Where, size_t Cov, const char *End) {
if (!Options.Verbosity) return;
size_t Seconds = secondsSinceProcessStartUp();
size_t ExecPerSec = (Seconds ? TotalNumberOfRuns / Seconds : 0);
std::cerr
<< "#" << TotalNumberOfRuns
<< "\t" << Where
<< " cov " << Cov
<< " bits " << TotalBits()
<< " units " << Corpus.size()
<< " exec/s " << ExecPerSec
<< End;
}
void Fuzzer::RereadOutputCorpus() {
if (Options.OutputCorpus.empty()) return;
std::vector<Unit> AdditionalCorpus;
ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus,
&EpochOfLastReadOfOutputCorpus);
if (Corpus.empty()) {
Corpus = AdditionalCorpus;
return;
}
if (!Options.Reload) return;
for (auto &X : AdditionalCorpus) {
if (X.size() > (size_t)Options.MaxLen)
X.resize(Options.MaxLen);
if (UnitsAddedAfterInitialLoad.insert(X).second) {
Corpus.push_back(X);
CurrentUnit.clear();
CurrentUnit.insert(CurrentUnit.begin(), X.begin(), X.end());
size_t NewCoverage = RunOne(CurrentUnit);
if (NewCoverage && Options.Verbosity >= 1)
PrintStats("RELOAD", NewCoverage);
}
}
}
void Fuzzer::ShuffleAndMinimize() {
size_t MaxCov = 0;
bool PreferSmall =
(Options.PreferSmallDuringInitialShuffle == 1 ||
(Options.PreferSmallDuringInitialShuffle == -1 && rand() % 2));
if (Options.Verbosity)
std::cerr << "PreferSmall: " << PreferSmall << "\n";
PrintStats("READ ", 0);
std::vector<Unit> NewCorpus;
std::random_shuffle(Corpus.begin(), Corpus.end());
if (PreferSmall)
std::stable_sort(
Corpus.begin(), Corpus.end(),
[](const Unit &A, const Unit &B) { return A.size() < B.size(); });
Unit &U = CurrentUnit;
for (const auto &C : Corpus) {
for (size_t First = 0; First < 1; First++) {
U.clear();
size_t Last = std::min(First + Options.MaxLen, C.size());
U.insert(U.begin(), C.begin() + First, C.begin() + Last);
size_t NewCoverage = RunOne(U);
if (NewCoverage) {
MaxCov = NewCoverage;
NewCorpus.push_back(U);
if (Options.Verbosity >= 2)
std::cerr << "NEW0: " << NewCoverage
<< " L " << U.size()
<< "\n";
}
}
}
Corpus = NewCorpus;
PrintStats("INITED", MaxCov);
}
size_t Fuzzer::RunOne(const Unit &U) {
UnitStartTime = system_clock::now();
TotalNumberOfRuns++;
size_t Res = 0;
if (Options.UseFullCoverageSet)
Res = RunOneMaximizeFullCoverageSet(U);
else if (Options.UseCoveragePairs)
Res = RunOneMaximizeCoveragePairs(U);
else
Res = RunOneMaximizeTotalCoverage(U);
auto UnitStopTime = system_clock::now();
auto TimeOfUnit =
duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
if (TimeOfUnit > TimeOfLongestUnitInSeconds) {
TimeOfLongestUnitInSeconds = TimeOfUnit;
std::cerr << "Longest unit: " << TimeOfLongestUnitInSeconds
<< " s:\n";
Print(U, "\n");
}
return Res;
}
void Fuzzer::RunOneAndUpdateCorpus(const Unit &U) {
if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
return;
ReportNewCoverage(RunOne(U), U);
}
static uintptr_t HashOfArrayOfPCs(uintptr_t *PCs, uintptr_t NumPCs) {
uintptr_t Res = 0;
for (uintptr_t i = 0; i < NumPCs; i++) {
Res = (Res + PCs[i]) * 7;
}
return Res;
}
Unit Fuzzer::SubstituteTokens(const Unit &U) const {
Unit Res;
for (auto Idx : U) {
if (Idx < Options.Tokens.size()) {
std::string Token = Options.Tokens[Idx];
Res.insert(Res.end(), Token.begin(), Token.end());
} else {
Res.push_back(' ');
}
}
// FIXME: Apply DFSan labels.
return Res;
}
void Fuzzer::ExecuteCallback(const Unit &U) {
if (Options.Tokens.empty()) {
Callback(U.data(), U.size());
} else {
auto T = SubstituteTokens(U);
Callback(T.data(), T.size());
}
}
// Experimental. Does not yet scale.
// Fuly reset the current coverage state, run a single unit,
// collect all coverage pairs and return non-zero if a new pair is observed.
size_t Fuzzer::RunOneMaximizeCoveragePairs(const Unit &U) {
__sanitizer_reset_coverage();
ExecuteCallback(U);
uintptr_t *PCs;
uintptr_t NumPCs = __sanitizer_get_coverage_guards(&PCs);
bool HasNewPairs = false;
for (uintptr_t i = 0; i < NumPCs; i++) {
if (!PCs[i]) continue;
for (uintptr_t j = 0; j < NumPCs; j++) {
if (!PCs[j]) continue;
uint64_t Pair = (i << 32) | j;
HasNewPairs |= CoveragePairs.insert(Pair).second;
}
}
if (HasNewPairs)
return CoveragePairs.size();
return 0;
}
// Experimental.
// Fuly reset the current coverage state, run a single unit,
// compute a hash function from the full coverage set,
// return non-zero if the hash value is new.
// This produces tons of new units and as is it's only suitable for small tests,
// e.g. test/FullCoverageSetTest.cpp. FIXME: make it scale.
size_t Fuzzer::RunOneMaximizeFullCoverageSet(const Unit &U) {
__sanitizer_reset_coverage();
ExecuteCallback(U);
uintptr_t *PCs;
uintptr_t NumPCs =__sanitizer_get_coverage_guards(&PCs);
if (FullCoverageSets.insert(HashOfArrayOfPCs(PCs, NumPCs)).second)
return FullCoverageSets.size();
return 0;
}
size_t Fuzzer::RunOneMaximizeTotalCoverage(const Unit &U) {
size_t NumCounters = __sanitizer_get_number_of_counters();
if (Options.UseCounters) {
CounterBitmap.resize(NumCounters);
__sanitizer_update_counter_bitset_and_clear_counters(0);
}
size_t OldCoverage = __sanitizer_get_total_unique_coverage();
ExecuteCallback(U);
size_t NewCoverage = __sanitizer_get_total_unique_coverage();
size_t NumNewBits = 0;
if (Options.UseCounters)
NumNewBits = __sanitizer_update_counter_bitset_and_clear_counters(
CounterBitmap.data());
if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) && Options.Verbosity)
PrintStats("pulse ", NewCoverage);
if (NewCoverage > OldCoverage || NumNewBits)
return NewCoverage;
return 0;
}
void Fuzzer::WriteToOutputCorpus(const Unit &U) {
if (Options.OutputCorpus.empty()) return;
std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
WriteToFile(U, Path);
if (Options.Verbosity >= 2)
std::cerr << "Written to " << Path << std::endl;
}
void Fuzzer::WriteToCrash(const Unit &U, const char *Prefix) {
std::string Path = Prefix + Hash(U);
WriteToFile(U, Path);
std::cerr << "CRASHED; file written to " << Path << std::endl;
std::cerr << "Base64: ";
PrintFileAsBase64(Path);
}
void Fuzzer::SaveCorpus() {
if (Options.OutputCorpus.empty()) return;
for (const auto &U : Corpus)
WriteToFile(U, DirPlusFile(Options.OutputCorpus, Hash(U)));
if (Options.Verbosity)
std::cerr << "Written corpus of " << Corpus.size() << " files to "
<< Options.OutputCorpus << "\n";
}
void Fuzzer::ReportNewCoverage(size_t NewCoverage, const Unit &U) {
if (!NewCoverage) return;
Corpus.push_back(U);
UnitsAddedAfterInitialLoad.insert(U);
PrintStats("NEW ", NewCoverage, "");
if (Options.Verbosity) {
std::cerr << " L: " << U.size();
if (U.size() < 30) {
std::cerr << " ";
PrintUnitInASCIIOrTokens(U, "\t");
Print(U);
}
std::cerr << "\n";
}
WriteToOutputCorpus(U);
if (Options.ExitOnFirst)
exit(0);
}
void Fuzzer::MutateAndTestOne(Unit *U) {
for (int i = 0; i < Options.MutateDepth; i++) {
StartTraceRecording();
Mutate(U, Options.MaxLen);
RunOneAndUpdateCorpus(*U);
size_t NumTraceBasedMutations = StopTraceRecording();
for (size_t j = 0; j < NumTraceBasedMutations; j++) {
ApplyTraceBasedMutation(j, U);
RunOneAndUpdateCorpus(*U);
}
}
}
void Fuzzer::Loop(size_t NumIterations) {
for (size_t i = 1; i <= NumIterations; i++) {
for (size_t J1 = 0; J1 < Corpus.size(); J1++) {
RereadOutputCorpus();
if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
return;
// First, simply mutate the unit w/o doing crosses.
CurrentUnit = Corpus[J1];
MutateAndTestOne(&CurrentUnit);
// Now, cross with others.
if (Options.DoCrossOver) {
for (size_t J2 = 0; J2 < Corpus.size(); J2++) {
CurrentUnit.clear();
CrossOver(Corpus[J1], Corpus[J2], &CurrentUnit, Options.MaxLen);
MutateAndTestOne(&CurrentUnit);
}
}
}
}
}
} // namespace fuzzer
<|endoftext|> |
<commit_before>// -*- mode: c++; coding: utf-8 -*-
#ifndef MWG_BIO_TAPE_H_stdio
#define MWG_BIO_TAPE_H_stdio
#include <cstdio>
#include <cstring>
#ifdef _MSC_VER
# include <io.h>
#else
# include <sys/types.h>
# include <sys/stat.h>
# include <unistd.h>
#endif
#if defined(MSDOS)||defined(OS2)||defined(WIN32)||defined(__CYGWIN__)
# include <fcntl.h>
# include <io.h>
# define MWG_BIO_TAPE_H_stdio__require_setmode
#endif
#include <mwg/except.h>
#include <mwg/std/memory>
#include "defs.h"
#include "tape.h"
namespace mwg{
namespace bio{
//NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN
class cstd_file_tape;
typedef cstd_file_tape ftape;
class cstd_file_tape:public itape{
stdm::shared_ptr<FILE> _file;
std::FILE* file;
bool f_read;
bool f_write;
bool f_seek;
//------------------------------------------------------------------------------
// Initialization
//------------------------------------------------------------------------------
public:
cstd_file_tape():
file(nullptr),
f_read(false), f_write(false), f_seek(false)
{}
cstd_file_tape(FILE* file,const char* mode){
//std::printf("dbg:cstd_file_tape: file\n");
this->file=file;
f_read = nullptr!=std::strchr(mode,'r');
f_write = nullptr!=std::strchr(mode,'w');
f_seek = nullptr!=std::strchr(mode,'s');
#ifdef MWG_BIO_TAPE_H_stdio__require_setmode
if(nullptr!=std::strchr(mode,'b'))
setmode(fileno(file), O_BINARY);
#endif
}
// ディスク上のファイルから
cstd_file_tape(const char* filepath,const char* mode) {
this->open(filepath, mode);
}
public:
bool open(const char* filepath, const char* mode) {
this->close();
#ifdef _MSC_VER
file=std::fopen(filepath,mode);
#elif defined(__MINGW32__)
file=::fopen64(filepath,mode);
#elif defined(__GNUC__)&&(defined(__USE_FILE_OFFSET64)||defined(__USE_LARGEFILE64))
file=::fopen64(filepath,mode);
#else
file=std::fopen(filepath,mode);
#endif
if(file!=nullptr)
_file.reset(file,std::fclose);
bool is_a=nullptr!=std::strchr(mode,'a');
bool is_r=nullptr!=std::strchr(mode,'r');
bool is_w=nullptr!=std::strchr(mode,'w');
bool is_p=nullptr!=std::strchr(mode,'+');
f_read=is_r||is_p;
f_write=is_w||is_p||is_a;
f_seek=!is_a;
return is_alive();
}
bool is_alive() const{
return file!=nullptr;
}
//bool is_eof() const{return feof(file);}
void close(){
if(this->_file){
this->_file.reset();
this->file=nullptr;
}
}
//------------------------------------------------------------------------------
// itape implementation
//------------------------------------------------------------------------------
public:
bool can_read() const{return f_read;}
bool can_write() const{return f_write;}
bool can_seek() const{return f_seek;}
bool can_trunc() const{return f_seek&&f_write;}
int read(void* buff,int size,int n=1) const{
mwg_assert(this->f_read,"must be can_read.");
return std::fread(buff,size,n,file);
}
int write(const void* buff,int size,int n=1) const{
mwg_assert(this->f_write,"must be can_write.");
return std::fwrite(buff,size,n,file);
}
int flush() const{
return std::fflush(file);
}
int seek(i8t offset,int whence=SEEK_SET) const{
mwg_assert(this->f_seek,"must be can_seek.");
#ifdef _MSC_VER
//if(whence==SEEK_CUR)
// std::printf("dbg: offset=%lld whence=SEEK_CUR\n",offset);
return ::_fseeki64(file,offset,whence);
#elif defined(__GNUC__)&&defined(_LARGEFILE_SOURCE)
std::fflush(file); // 特定の環境ではこれがないと変な事に?
return ::fseeko(file,offset,whence);
#else
return std::fseek(file,offset,whence);
#endif
}
i8t tell() const{
mwg_assert(this->f_seek,"must be can_seek.");
#ifdef _MSC_VER
return ::_ftelli64(file);
#elif defined(__GNUC__)&&defined(_LARGEFILE_SOURCE)
return ::ftello(file);
#elif defined(__GNUC__)
fpos_t ret;
::fgetpos(file,&ret);
return (i8t)ret;
#else
return std::ftell(file);
#endif
}
u8t size() const{
mwg_assert(this->f_seek,"must be can_seek.");
std::fflush(file);
#ifdef _MSC_VER
return ::_filelengthi64(::_fileno(file));
#elif defined(__MINGW32__)
struct _stati64 st;
::_fstati64(_fileno(file),&st); // MinGW では fileno はマクロ
return st.st_size;
#elif defined(__GNUC__)&&(defined(__USE_FILE_OFFSET64)||defined(__USE_LARGEFILE64))
// ↑条件分岐が之で正しいのかは不明 (何も宣言しなくても使える環境も多い)
struct stat64 st;
::fstat64(::fileno(file),&st);
return st.st_size;
#else
struct stat st;
::fstat(::fileno(file),&st);
return st.st_size;
#endif
}
int trunc(u8t size) const{
mwg_assert(this->can_trunc(),"must be can_trunc.");
std::fflush(file);
#if defined(_MSC_VER)
return ::_chsize_s(::_fileno(file),size);
#elif defined(__MINGW32__)
// 何故か MinGW では _chsize_s にも ftruncate64 にも対応していない...??
if(size>0x100000000LL)return errno=EFBIG;
return ::_chsize(_fileno(file),size); // MinGW では fileno はマクロ
#elif defined(__GNUC__)&&(defined(__USE_FILE_OFFSET64)||defined(__USE_LARGEFILE64))
return ::ftruncate64(::fileno(file),size);
#else
return ::ftruncate(::fileno(file),size);
#endif
}
};
//NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN
}
}
#endif
<commit_msg>mwg/bio/tape (ftape): inactivate on ferror<commit_after>// -*- mode: c++; coding: utf-8 -*-
#ifndef MWG_BIO_TAPE_H_stdio
#define MWG_BIO_TAPE_H_stdio
#include <cstdio>
#include <cstring>
#ifdef _MSC_VER
# include <io.h>
#else
# include <sys/types.h>
# include <sys/stat.h>
# include <unistd.h>
#endif
#if defined(MSDOS)||defined(OS2)||defined(WIN32)||defined(__CYGWIN__)
# include <fcntl.h>
# include <io.h>
# define MWG_BIO_TAPE_H_stdio__require_setmode
#endif
#include <mwg/except.h>
#include <mwg/std/memory>
#include "defs.h"
#include "tape.h"
namespace mwg{
namespace bio{
//NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN
class cstd_file_tape;
typedef cstd_file_tape ftape;
class cstd_file_tape:public itape{
stdm::shared_ptr<FILE> _file;
std::FILE* file;
bool f_read;
bool f_write;
bool f_seek;
//------------------------------------------------------------------------------
// Initialization
//------------------------------------------------------------------------------
public:
cstd_file_tape():
file(nullptr),
f_read(false), f_write(false), f_seek(false)
{}
cstd_file_tape(FILE* file,const char* mode){
//std::printf("dbg:cstd_file_tape: file\n");
this->file=file;
f_read = nullptr!=std::strchr(mode,'r');
f_write = nullptr!=std::strchr(mode,'w');
f_seek = nullptr!=std::strchr(mode,'s');
#ifdef MWG_BIO_TAPE_H_stdio__require_setmode
if(nullptr!=std::strchr(mode,'b'))
setmode(fileno(file), O_BINARY);
#endif
}
// ディスク上のファイルから
cstd_file_tape(const char* filepath,const char* mode) {
this->open(filepath, mode);
}
public:
bool open(const char* filepath, const char* mode) {
this->close();
#ifdef _MSC_VER
file=std::fopen(filepath,mode);
#elif defined(__MINGW32__)
file=::fopen64(filepath,mode);
#elif defined(__GNUC__)&&(defined(__USE_FILE_OFFSET64)||defined(__USE_LARGEFILE64))
file=::fopen64(filepath,mode);
#else
file=std::fopen(filepath,mode);
#endif
if(file!=nullptr)
_file.reset(file,std::fclose);
bool is_a=nullptr!=std::strchr(mode,'a');
bool is_r=nullptr!=std::strchr(mode,'r');
bool is_w=nullptr!=std::strchr(mode,'w');
bool is_p=nullptr!=std::strchr(mode,'+');
f_read=is_r||is_p;
f_write=is_w||is_p||is_a;
f_seek=!is_a;
return is_alive();
}
bool is_alive() const{
return file != nullptr && std::ferror(file) == 0;
}
//bool is_eof() const{return feof(file);}
void close(){
if(this->_file){
this->_file.reset();
this->file=nullptr;
}
}
//------------------------------------------------------------------------------
// itape implementation
//------------------------------------------------------------------------------
public:
bool can_read() const{return f_read;}
bool can_write() const{return f_write;}
bool can_seek() const{return f_seek;}
bool can_trunc() const{return f_seek&&f_write;}
int read(void* buff,int size,int n=1) const{
mwg_assert(this->f_read,"must be can_read.");
return std::fread(buff,size,n,file);
}
int write(const void* buff,int size,int n=1) const{
mwg_assert(this->f_write,"must be can_write.");
return std::fwrite(buff,size,n,file);
}
int flush() const{
return std::fflush(file);
}
int seek(i8t offset,int whence=SEEK_SET) const{
mwg_assert(this->f_seek,"must be can_seek.");
#ifdef _MSC_VER
//if(whence==SEEK_CUR)
// std::printf("dbg: offset=%lld whence=SEEK_CUR\n",offset);
return ::_fseeki64(file,offset,whence);
#elif defined(__GNUC__)&&defined(_LARGEFILE_SOURCE)
std::fflush(file); // 特定の環境ではこれがないと変な事に?
return ::fseeko(file,offset,whence);
#else
return std::fseek(file,offset,whence);
#endif
}
i8t tell() const{
mwg_assert(this->f_seek,"must be can_seek.");
#ifdef _MSC_VER
return ::_ftelli64(file);
#elif defined(__GNUC__)&&defined(_LARGEFILE_SOURCE)
return ::ftello(file);
#elif defined(__GNUC__)
fpos_t ret;
::fgetpos(file,&ret);
return (i8t)ret;
#else
return std::ftell(file);
#endif
}
u8t size() const{
mwg_assert(this->f_seek,"must be can_seek.");
std::fflush(file);
#ifdef _MSC_VER
return ::_filelengthi64(::_fileno(file));
#elif defined(__MINGW32__)
struct _stati64 st;
::_fstati64(_fileno(file),&st); // MinGW では fileno はマクロ
return st.st_size;
#elif defined(__GNUC__)&&(defined(__USE_FILE_OFFSET64)||defined(__USE_LARGEFILE64))
// ↑条件分岐が之で正しいのかは不明 (何も宣言しなくても使える環境も多い)
struct stat64 st;
::fstat64(::fileno(file),&st);
return st.st_size;
#else
struct stat st;
::fstat(::fileno(file),&st);
return st.st_size;
#endif
}
int trunc(u8t size) const{
mwg_assert(this->can_trunc(),"must be can_trunc.");
std::fflush(file);
#if defined(_MSC_VER)
return ::_chsize_s(::_fileno(file),size);
#elif defined(__MINGW32__)
// 何故か MinGW では _chsize_s にも ftruncate64 にも対応していない...??
if(size>0x100000000LL)return errno=EFBIG;
return ::_chsize(_fileno(file),size); // MinGW では fileno はマクロ
#elif defined(__GNUC__)&&(defined(__USE_FILE_OFFSET64)||defined(__USE_LARGEFILE64))
return ::ftruncate64(::fileno(file),size);
#else
return ::ftruncate(::fileno(file),size);
#endif
}
};
//NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN
}
}
#endif
<|endoftext|> |
<commit_before>#include "command.hh"
#include "eval.hh"
#include "eval-inline.hh"
#include "derivations.hh"
#include "common-args.hh"
#include "json.hh"
#include "get-drvs.hh"
#include "attr-path.hh"
#include <nlohmann/json.hpp>
#include <sys/resource.h>
using namespace nix;
static std::string queryMetaStrings(EvalState & state, DrvInfo & drv, const string & name, const string & subAttribute)
{
Strings res;
std::function<void(Value & v)> rec;
rec = [&](Value & v) {
state.forceValue(v);
if (v.type == tString)
res.push_back(v.string.s);
else if (v.isList())
for (unsigned int n = 0; n < v.listSize(); ++n)
rec(*v.listElems()[n]);
else if (v.type == tAttrs) {
auto a = v.attrs->find(state.symbols.create(subAttribute));
if (a != v.attrs->end())
res.push_back(state.forceString(*a->value));
}
};
Value * v = drv.queryMeta(name);
if (v) rec(*v);
return concatStringsSep(", ", res);
}
struct CmdEvalHydraJobs : MixJSON, MixDryRun, InstallableCommand
{
std::optional<Path> gcRootsDir;
size_t nrWorkers = 1;
size_t maxMemorySize = 4ULL * 1024;
CmdEvalHydraJobs()
{
mkFlag()
.longName("gc-roots-dir")
.description("garbage collector roots directory")
.labels({"path"})
.dest(&gcRootsDir);
mkIntFlag(0, "workers", "number of concurrent worker processes", &nrWorkers);
mkIntFlag(0, "max-memory-size", "maximum memory usage per worker process (in MiB)", &maxMemorySize);
}
std::string description() override
{
return "evaluate a Hydra jobset";
}
Examples examples() override
{
return {
Example{
"Evaluate Nixpkgs' release-combined jobset:",
"nix eval-hydra-jobs -f '<nixpkgs/nixos/release-combined.nix>' '' --json"
},
};
}
Strings getDefaultFlakeAttrPaths() override
{
return {"hydraJobs", "checks"};
}
void worker(AutoCloseFD & to, AutoCloseFD & from)
{
auto state = getEvalState();
// FIXME: should re-open state->store.
if (dryRun) settings.readOnlyMode = true;
/* Prevent access to paths outside of the Nix search path and
to the environment. */
evalSettings.restrictEval = true;
auto autoArgs = getAutoArgs(*state);
auto vTop = installable->toValue(*state).first;
auto vRoot = state->allocValue();
state->autoCallFunction(*autoArgs, *vTop, *vRoot);
while (true) {
/* Wait for the master to send us a job name. */
writeLine(to.get(), "next");
auto s = readLine(from.get());
if (s == "exit") break;
if (!hasPrefix(s, "do ")) abort();
std::string attrPath(s, 3);
debug("worker process %d at '%s'", getpid(), attrPath);
/* Evaluate it and send info back to the master. */
nlohmann::json reply;
try {
auto v = findAlongAttrPath(*state, attrPath, *autoArgs, *vRoot).first;
state->forceValue(*v);
if (auto drv = getDerivation(*state, *v, false)) {
DrvInfo::Outputs outputs = drv->queryOutputs();
if (drv->querySystem() == "unknown")
throw EvalError("derivation must have a 'system' attribute");
auto drvPath = drv->queryDrvPath();
nlohmann::json job;
job["nixName"] = drv->queryName();
job["system"] =drv->querySystem();
job["drvPath"] = drvPath;
job["description"] = drv->queryMetaString("description");
job["license"] = queryMetaStrings(*state, *drv, "license", "shortName");
job["homepage"] = drv->queryMetaString("homepage");
job["maintainers"] = queryMetaStrings(*state, *drv, "maintainers", "email");
job["schedulingPriority"] = drv->queryMetaInt("schedulingPriority", 100);
job["timeout"] = drv->queryMetaInt("timeout", 36000);
job["maxSilent"] = drv->queryMetaInt("maxSilent", 7200);
job["isChannel"] = drv->queryMetaBool("isHydraChannel", false);
/* If this is an aggregate, then get its constituents. */
auto a = v->attrs->get(state->symbols.create("_hydraAggregate"));
if (a && state->forceBool(*a->value, *a->pos)) {
auto a = v->attrs->get(state->symbols.create("constituents"));
if (!a)
throw EvalError("derivation must have a ‘constituents’ attribute");
PathSet context;
state->coerceToString(*a->pos, *a->value, context, true, false);
for (auto & i : context)
if (i.at(0) == '!') {
size_t index = i.find("!", 1);
job["constituents"].push_back(string(i, index + 1));
}
state->forceList(*a->value, *a->pos);
for (unsigned int n = 0; n < a->value->listSize(); ++n) {
auto v = a->value->listElems()[n];
state->forceValue(*v);
if (v->type == tString)
job["namedConstituents"].push_back(state->forceStringNoCtx(*v));
}
}
/* Register the derivation as a GC root. !!! This
registers roots for jobs that we may have already
done. */
auto localStore = state->store.dynamic_pointer_cast<LocalFSStore>();
if (gcRootsDir && localStore) {
Path root = *gcRootsDir + "/" + std::string(baseNameOf(drvPath));
if (!pathExists(root))
localStore->addPermRoot(localStore->parseStorePath(drvPath), root, false);
}
nlohmann::json out;
for (auto & j : outputs)
out[j.first] = j.second;
job["outputs"] = std::move(out);
reply["job"] = std::move(job);
}
else if (v->type == tAttrs) {
auto attrs = nlohmann::json::array();
StringSet ss;
for (auto & i : v->attrs->lexicographicOrder()) {
std::string name(i->name);
if (name.find('.') != std::string::npos || name.find(' ') != std::string::npos) {
printError("skipping job with illegal name '%s'", name);
continue;
}
attrs.push_back(name);
}
reply["attrs"] = std::move(attrs);
}
} catch (EvalError & e) {
reply["error"] = filterANSIEscapes(e.msg(), true);
}
writeLine(to.get(), reply.dump());
/* If our RSS exceeds the maximum, exit. The master will
start a new process. */
struct rusage r;
getrusage(RUSAGE_SELF, &r);
if ((size_t) r.ru_maxrss > maxMemorySize * 1024) break;
}
writeLine(to.get(), "restart");
}
void run(ref<Store> store) override
{
if (!gcRootsDir) warn("'--gc-roots-dir' not specified");
struct State
{
std::set<std::string> todo{""};
std::set<std::string> active;
nlohmann::json jobs;
std::exception_ptr exc;
};
std::condition_variable wakeup;
Sync<State> state_;
/* Start a handler thread per worker process. */
auto handler = [this, &state_, &wakeup]()
{
try {
pid_t pid = -1;
AutoCloseFD from, to;
while (true) {
/* Start a new worker process if necessary. */
if (pid == -1) {
Pipe toPipe, fromPipe;
toPipe.create();
fromPipe.create();
pid = startProcess(
[this,
to{std::make_shared<AutoCloseFD>(std::move(fromPipe.writeSide))},
from{std::make_shared<AutoCloseFD>(std::move(toPipe.readSide))}
]()
{
try {
worker(*to, *from);
} catch (std::exception & e) {
nlohmann::json err;
err["error"] = e.what();
writeLine(to->get(), err.dump());
}
},
ProcessOptions { .allowVfork = false });
from = std::move(fromPipe.readSide);
to = std::move(toPipe.writeSide);
debug("created worker process %d", pid);
}
/* Check whether the existing worker process is still there. */
auto s = readLine(from.get());
if (s == "restart") {
pid = -1;
continue;
} else if (s != "next") {
auto json = nlohmann::json::parse(s);
throw Error("worker error: %s", (std::string) json["error"]);
}
/* Wait for a job name to become available. */
std::string attrPath;
while (true) {
checkInterrupt();
auto state(state_.lock());
if ((state->todo.empty() && state->active.empty()) || state->exc) {
writeLine(to.get(), "exit");
return;
}
if (!state->todo.empty()) {
attrPath = *state->todo.begin();
state->todo.erase(state->todo.begin());
state->active.insert(attrPath);
break;
} else
state.wait(wakeup);
}
Activity act(*logger, lvlInfo, actUnknown, fmt("evaluating '%s'", attrPath));
/* Tell the worker to evaluate it. */
writeLine(to.get(), "do " + attrPath);
/* Wait for the response. */
auto response = nlohmann::json::parse(readLine(from.get()));
/* Handle the response. */
StringSet newAttrs;
if (response.find("job") != response.end()) {
auto state(state_.lock());
if (json)
state->jobs[attrPath] = response["job"];
else
std::cout << fmt("%d: %d\n", attrPath, (std::string) response["job"]["drvPath"]);
}
if (response.find("attrs") != response.end()) {
for (auto & i : response["attrs"]) {
auto s = (attrPath.empty() ? "" : attrPath + ".") + (std::string) i;
newAttrs.insert(s);
}
}
if (response.find("error") != response.end()) {
auto state(state_.lock());
if (json)
state->jobs[attrPath]["error"] = response["error"];
else
printError("error in job '%s': %s",
attrPath, (std::string) response["error"]);
}
/* Add newly discovered job names to the queue. */
{
auto state(state_.lock());
state->active.erase(attrPath);
for (auto & s : newAttrs)
state->todo.insert(s);
wakeup.notify_all();
}
}
} catch (...) {
auto state(state_.lock());
state->exc = std::current_exception();
wakeup.notify_all();
}
};
std::vector<std::thread> threads;
for (size_t i = 0; i < nrWorkers; i++)
threads.emplace_back(std::thread(handler));
for (auto & thread : threads)
thread.join();
auto state(state_.lock());
if (state->exc)
std::rethrow_exception(state->exc);
/* For aggregate jobs that have named consistuents
(i.e. constituents that are a job name rather than a
derivation), look up the referenced job and add it to the
dependencies of the aggregate derivation. */
for (auto i = state->jobs.begin(); i != state->jobs.end(); ++i) {
auto jobName = i.key();
auto & job = i.value();
auto named = job.find("namedConstituents");
if (named == job.end()) continue;
if (dryRun) {
for (std::string jobName2 : *named) {
auto job2 = state->jobs.find(jobName2);
if (job2 == state->jobs.end())
throw Error("aggregate job '%s' references non-existent job '%s'", jobName, jobName2);
std::string drvPath2 = (*job2)["drvPath"];
job["constituents"].push_back(drvPath2);
}
} else {
std::string drvPath = job["drvPath"];
auto drv = readDerivation(*store, drvPath);
for (std::string jobName2 : *named) {
auto job2 = state->jobs.find(jobName2);
if (job2 == state->jobs.end())
throw Error("aggregate job '%s' references non-existent job '%s'", jobName, jobName2);
std::string drvPath2 = (*job2)["drvPath"];
auto drv2 = readDerivation(*store, drvPath2);
job["constituents"].push_back(drvPath2);
drv.inputDrvs[store->parseStorePath(drvPath2)] = {drv2.outputs.begin()->first};
}
std::string drvName(store->parseStorePath(drvPath).name());
assert(hasSuffix(drvName, drvExtension));
drvName.resize(drvName.size() - drvExtension.size());
auto h = hashDerivationModulo(*store, drv, true);
auto outPath = store->makeOutputPath("out", h, drvName);
drv.env["out"] = store->printStorePath(outPath);
drv.outputs.insert_or_assign("out", DerivationOutput(outPath.clone(), "", ""));
auto newDrvPath = store->printStorePath(writeDerivation(store, drv, drvName));
debug("rewrote aggregate derivation %s -> %s", drvPath, newDrvPath);
job["drvPath"] = newDrvPath;
job["outputs"]["out"] = store->printStorePath(outPath);
}
job.erase("namedConstituents");
}
if (json) std::cout << state->jobs.dump(2) << "\n";
}
};
static auto r1 = registerCommand<CmdEvalHydraJobs>("eval-hydra-jobs");
<commit_msg>nix eval-hydra-jobs: Add feature<commit_after>#include "command.hh"
#include "eval.hh"
#include "eval-inline.hh"
#include "derivations.hh"
#include "common-args.hh"
#include "json.hh"
#include "get-drvs.hh"
#include "attr-path.hh"
#include <nlohmann/json.hpp>
#include <sys/resource.h>
using namespace nix;
static std::string queryMetaStrings(EvalState & state, DrvInfo & drv, const string & name, const string & subAttribute)
{
Strings res;
std::function<void(Value & v)> rec;
rec = [&](Value & v) {
state.forceValue(v);
if (v.type == tString)
res.push_back(v.string.s);
else if (v.isList())
for (unsigned int n = 0; n < v.listSize(); ++n)
rec(*v.listElems()[n]);
else if (v.type == tAttrs) {
auto a = v.attrs->find(state.symbols.create(subAttribute));
if (a != v.attrs->end())
res.push_back(state.forceString(*a->value));
}
};
Value * v = drv.queryMeta(name);
if (v) rec(*v);
return concatStringsSep(", ", res);
}
struct CmdEvalHydraJobs : MixJSON, MixDryRun, InstallableCommand
{
std::optional<Path> gcRootsDir;
size_t nrWorkers = 1;
size_t maxMemorySize = 4ULL * 1024;
CmdEvalHydraJobs()
{
mkFlag()
.longName("gc-roots-dir")
.description("garbage collector roots directory")
.labels({"path"})
.dest(&gcRootsDir);
mkIntFlag(0, "workers", "number of concurrent worker processes", &nrWorkers);
mkIntFlag(0, "max-memory-size", "maximum memory usage per worker process (in MiB)", &maxMemorySize);
}
std::string description() override
{
return "evaluate a Hydra jobset";
}
Examples examples() override
{
return {
Example{
"Evaluate Nixpkgs' release-combined jobset:",
"nix eval-hydra-jobs -f '<nixpkgs/nixos/release-combined.nix>' '' --json"
},
};
}
Strings getDefaultFlakeAttrPaths() override
{
return {"hydraJobs", "checks"};
}
void worker(AutoCloseFD & to, AutoCloseFD & from)
{
auto state = getEvalState();
// FIXME: should re-open state->store.
if (dryRun) settings.readOnlyMode = true;
/* Prevent access to paths outside of the Nix search path and
to the environment. */
evalSettings.restrictEval = true;
auto autoArgs = getAutoArgs(*state);
auto vTop = installable->toValue(*state).first;
auto vRoot = state->allocValue();
state->autoCallFunction(*autoArgs, *vTop, *vRoot);
while (true) {
/* Wait for the master to send us a job name. */
writeLine(to.get(), "next");
auto s = readLine(from.get());
if (s == "exit") break;
if (!hasPrefix(s, "do ")) abort();
std::string attrPath(s, 3);
debug("worker process %d at '%s'", getpid(), attrPath);
/* Evaluate it and send info back to the master. */
nlohmann::json reply;
try {
auto v = findAlongAttrPath(*state, attrPath, *autoArgs, *vRoot).first;
state->forceValue(*v);
if (auto drv = getDerivation(*state, *v, false)) {
DrvInfo::Outputs outputs = drv->queryOutputs();
if (drv->querySystem() == "unknown")
throw EvalError("derivation must have a 'system' attribute");
auto drvPath = drv->queryDrvPath();
nlohmann::json job;
job["nixName"] = drv->queryName();
job["system"] =drv->querySystem();
job["drvPath"] = drvPath;
job["description"] = drv->queryMetaString("description");
job["license"] = queryMetaStrings(*state, *drv, "license", "shortName");
job["homepage"] = drv->queryMetaString("homepage");
job["maintainers"] = queryMetaStrings(*state, *drv, "maintainers", "email");
job["schedulingPriority"] = drv->queryMetaInt("schedulingPriority", 100);
job["timeout"] = drv->queryMetaInt("timeout", 36000);
job["maxSilent"] = drv->queryMetaInt("maxSilent", 7200);
job["isChannel"] = drv->queryMetaBool("isHydraChannel", false);
/* If this is an aggregate, then get its constituents. */
auto a = v->attrs->get(state->symbols.create("_hydraAggregate"));
if (a && state->forceBool(*a->value, *a->pos)) {
auto a = v->attrs->get(state->symbols.create("constituents"));
if (!a)
throw EvalError("derivation must have a ‘constituents’ attribute");
PathSet context;
state->coerceToString(*a->pos, *a->value, context, true, false);
for (auto & i : context)
if (i.at(0) == '!') {
size_t index = i.find("!", 1);
job["constituents"].push_back(string(i, index + 1));
}
state->forceList(*a->value, *a->pos);
for (unsigned int n = 0; n < a->value->listSize(); ++n) {
auto v = a->value->listElems()[n];
state->forceValue(*v);
if (v->type == tString)
job["namedConstituents"].push_back(state->forceStringNoCtx(*v));
}
}
/* Register the derivation as a GC root. !!! This
registers roots for jobs that we may have already
done. */
auto localStore = state->store.dynamic_pointer_cast<LocalFSStore>();
if (gcRootsDir && localStore) {
Path root = *gcRootsDir + "/" + std::string(baseNameOf(drvPath));
if (!pathExists(root))
localStore->addPermRoot(localStore->parseStorePath(drvPath), root, false);
}
nlohmann::json out;
for (auto & j : outputs)
out[j.first] = j.second;
job["outputs"] = std::move(out);
reply["job"] = std::move(job);
}
else if (v->type == tAttrs) {
auto attrs = nlohmann::json::array();
StringSet ss;
for (auto & i : v->attrs->lexicographicOrder()) {
std::string name(i->name);
if (name.find('.') != std::string::npos || name.find(' ') != std::string::npos) {
printError("skipping job with illegal name '%s'", name);
continue;
}
attrs.push_back(name);
}
reply["attrs"] = std::move(attrs);
}
} catch (EvalError & e) {
reply["error"] = filterANSIEscapes(e.msg(), true);
}
writeLine(to.get(), reply.dump());
/* If our RSS exceeds the maximum, exit. The master will
start a new process. */
struct rusage r;
getrusage(RUSAGE_SELF, &r);
if ((size_t) r.ru_maxrss > maxMemorySize * 1024) break;
}
writeLine(to.get(), "restart");
}
void run(ref<Store> store) override
{
settings.requireExperimentalFeature("eval-hydra-jobs");
if (!gcRootsDir) warn("'--gc-roots-dir' not specified");
struct State
{
std::set<std::string> todo{""};
std::set<std::string> active;
nlohmann::json jobs;
std::exception_ptr exc;
};
std::condition_variable wakeup;
Sync<State> state_;
/* Start a handler thread per worker process. */
auto handler = [this, &state_, &wakeup]()
{
try {
pid_t pid = -1;
AutoCloseFD from, to;
while (true) {
/* Start a new worker process if necessary. */
if (pid == -1) {
Pipe toPipe, fromPipe;
toPipe.create();
fromPipe.create();
pid = startProcess(
[this,
to{std::make_shared<AutoCloseFD>(std::move(fromPipe.writeSide))},
from{std::make_shared<AutoCloseFD>(std::move(toPipe.readSide))}
]()
{
try {
worker(*to, *from);
} catch (std::exception & e) {
nlohmann::json err;
err["error"] = e.what();
writeLine(to->get(), err.dump());
}
},
ProcessOptions { .allowVfork = false });
from = std::move(fromPipe.readSide);
to = std::move(toPipe.writeSide);
debug("created worker process %d", pid);
}
/* Check whether the existing worker process is still there. */
auto s = readLine(from.get());
if (s == "restart") {
pid = -1;
continue;
} else if (s != "next") {
auto json = nlohmann::json::parse(s);
throw Error("worker error: %s", (std::string) json["error"]);
}
/* Wait for a job name to become available. */
std::string attrPath;
while (true) {
checkInterrupt();
auto state(state_.lock());
if ((state->todo.empty() && state->active.empty()) || state->exc) {
writeLine(to.get(), "exit");
return;
}
if (!state->todo.empty()) {
attrPath = *state->todo.begin();
state->todo.erase(state->todo.begin());
state->active.insert(attrPath);
break;
} else
state.wait(wakeup);
}
Activity act(*logger, lvlInfo, actUnknown, fmt("evaluating '%s'", attrPath));
/* Tell the worker to evaluate it. */
writeLine(to.get(), "do " + attrPath);
/* Wait for the response. */
auto response = nlohmann::json::parse(readLine(from.get()));
/* Handle the response. */
StringSet newAttrs;
if (response.find("job") != response.end()) {
auto state(state_.lock());
if (json)
state->jobs[attrPath] = response["job"];
else
std::cout << fmt("%d: %d\n", attrPath, (std::string) response["job"]["drvPath"]);
}
if (response.find("attrs") != response.end()) {
for (auto & i : response["attrs"]) {
auto s = (attrPath.empty() ? "" : attrPath + ".") + (std::string) i;
newAttrs.insert(s);
}
}
if (response.find("error") != response.end()) {
auto state(state_.lock());
if (json)
state->jobs[attrPath]["error"] = response["error"];
else
printError("error in job '%s': %s",
attrPath, (std::string) response["error"]);
}
/* Add newly discovered job names to the queue. */
{
auto state(state_.lock());
state->active.erase(attrPath);
for (auto & s : newAttrs)
state->todo.insert(s);
wakeup.notify_all();
}
}
} catch (...) {
auto state(state_.lock());
state->exc = std::current_exception();
wakeup.notify_all();
}
};
std::vector<std::thread> threads;
for (size_t i = 0; i < nrWorkers; i++)
threads.emplace_back(std::thread(handler));
for (auto & thread : threads)
thread.join();
auto state(state_.lock());
if (state->exc)
std::rethrow_exception(state->exc);
/* For aggregate jobs that have named consistuents
(i.e. constituents that are a job name rather than a
derivation), look up the referenced job and add it to the
dependencies of the aggregate derivation. */
for (auto i = state->jobs.begin(); i != state->jobs.end(); ++i) {
auto jobName = i.key();
auto & job = i.value();
auto named = job.find("namedConstituents");
if (named == job.end()) continue;
if (dryRun) {
for (std::string jobName2 : *named) {
auto job2 = state->jobs.find(jobName2);
if (job2 == state->jobs.end())
throw Error("aggregate job '%s' references non-existent job '%s'", jobName, jobName2);
std::string drvPath2 = (*job2)["drvPath"];
job["constituents"].push_back(drvPath2);
}
} else {
std::string drvPath = job["drvPath"];
auto drv = readDerivation(*store, drvPath);
for (std::string jobName2 : *named) {
auto job2 = state->jobs.find(jobName2);
if (job2 == state->jobs.end())
throw Error("aggregate job '%s' references non-existent job '%s'", jobName, jobName2);
std::string drvPath2 = (*job2)["drvPath"];
auto drv2 = readDerivation(*store, drvPath2);
job["constituents"].push_back(drvPath2);
drv.inputDrvs[store->parseStorePath(drvPath2)] = {drv2.outputs.begin()->first};
}
std::string drvName(store->parseStorePath(drvPath).name());
assert(hasSuffix(drvName, drvExtension));
drvName.resize(drvName.size() - drvExtension.size());
auto h = hashDerivationModulo(*store, drv, true);
auto outPath = store->makeOutputPath("out", h, drvName);
drv.env["out"] = store->printStorePath(outPath);
drv.outputs.insert_or_assign("out", DerivationOutput(outPath.clone(), "", ""));
auto newDrvPath = store->printStorePath(writeDerivation(store, drv, drvName));
debug("rewrote aggregate derivation %s -> %s", drvPath, newDrvPath);
job["drvPath"] = newDrvPath;
job["outputs"]["out"] = store->printStorePath(outPath);
}
job.erase("namedConstituents");
}
if (json) std::cout << state->jobs.dump(2) << "\n";
}
};
static auto r1 = registerCommand<CmdEvalHydraJobs>("eval-hydra-jobs");
<|endoftext|> |
<commit_before>#include "command.hh"
#include "eval.hh"
#include "eval-inline.hh"
#include "derivations.hh"
#include "common-args.hh"
#include "json.hh"
#include "get-drvs.hh"
#include "attr-path.hh"
#include <nlohmann/json.hpp>
#include <sys/resource.h>
using namespace nix;
static std::string queryMetaStrings(EvalState & state, DrvInfo & drv, const string & name, const string & subAttribute)
{
Strings res;
std::function<void(Value & v)> rec;
rec = [&](Value & v) {
state.forceValue(v);
if (v.type == tString)
res.push_back(v.string.s);
else if (v.isList())
for (unsigned int n = 0; n < v.listSize(); ++n)
rec(*v.listElems()[n]);
else if (v.type == tAttrs) {
auto a = v.attrs->find(state.symbols.create(subAttribute));
if (a != v.attrs->end())
res.push_back(state.forceString(*a->value));
}
};
Value * v = drv.queryMeta(name);
if (v) rec(*v);
return concatStringsSep(", ", res);
}
struct CmdEvalHydraJobs : MixJSON, MixDryRun, InstallableCommand
{
std::optional<Path> gcRootsDir;
size_t nrWorkers = 1;
size_t maxMemorySize = 4ULL * 1024;
CmdEvalHydraJobs()
{
mkFlag()
.longName("gc-roots-dir")
.description("garbage collector roots directory")
.labels({"path"})
.dest(&gcRootsDir);
mkIntFlag(0, "workers", "number of concurrent worker processes", &nrWorkers);
mkIntFlag(0, "max-memory-size", "maximum memory usage per worker process (in MiB)", &maxMemorySize);
}
std::string description() override
{
return "evaluate a Hydra jobset";
}
Examples examples() override
{
return {
Example{
"Evaluate Nixpkgs' release-combined jobset:",
"nix eval-hydra-jobs -f '<nixpkgs/nixos/release-combined.nix>' '' --json"
},
};
}
Strings getDefaultFlakeAttrPaths() override
{
return {"hydraJobs", "checks"};
}
void worker(AutoCloseFD & to, AutoCloseFD & from)
{
auto state = getEvalState();
// FIXME: should re-open state->store.
if (dryRun) settings.readOnlyMode = true;
/* Prevent access to paths outside of the Nix search path and
to the environment. */
evalSettings.restrictEval = true;
auto autoArgs = getAutoArgs(*state);
auto vTop = installable->toValue(*state).first;
auto vRoot = state->allocValue();
state->autoCallFunction(*autoArgs, *vTop, *vRoot);
while (true) {
/* Wait for the master to send us a job name. */
writeLine(to.get(), "next");
auto s = readLine(from.get());
if (s == "exit") break;
if (!hasPrefix(s, "do ")) abort();
std::string attrPath(s, 3);
debug("worker process %d at '%s'", getpid(), attrPath);
/* Evaluate it and send info back to the master. */
nlohmann::json reply;
try {
auto v = findAlongAttrPath(*state, attrPath, *autoArgs, *vRoot).first;
state->forceValue(*v);
if (auto drv = getDerivation(*state, *v, false)) {
DrvInfo::Outputs outputs = drv->queryOutputs();
if (drv->querySystem() == "unknown")
throw EvalError("derivation must have a 'system' attribute");
auto drvPath = drv->queryDrvPath();
nlohmann::json job;
job["nixName"] = drv->queryName();
job["system"] =drv->querySystem();
job["drvPath"] = drvPath;
job["description"] = drv->queryMetaString("description");
job["license"] = queryMetaStrings(*state, *drv, "license", "shortName");
job["homepage"] = drv->queryMetaString("homepage");
job["maintainers"] = queryMetaStrings(*state, *drv, "maintainers", "email");
job["schedulingPriority"] = drv->queryMetaInt("schedulingPriority", 100);
job["timeout"] = drv->queryMetaInt("timeout", 36000);
job["maxSilent"] = drv->queryMetaInt("maxSilent", 7200);
job["isChannel"] = drv->queryMetaBool("isHydraChannel", false);
/* If this is an aggregate, then get its constituents. */
auto a = v->attrs->get(state->symbols.create("_hydraAggregate"));
if (a && state->forceBool(*a->value, *a->pos)) {
auto a = v->attrs->get(state->symbols.create("constituents"));
if (!a)
throw EvalError("derivation must have a ‘constituents’ attribute");
PathSet context;
state->coerceToString(*a->pos, *a->value, context, true, false);
PathSet drvs;
for (auto & i : context)
if (i.at(0) == '!') {
size_t index = i.find("!", 1);
drvs.insert(string(i, index + 1));
}
job["constituents"] = concatStringsSep(" ", drvs);
}
/* Register the derivation as a GC root. !!! This
registers roots for jobs that we may have already
done. */
auto localStore = state->store.dynamic_pointer_cast<LocalFSStore>();
if (gcRootsDir && localStore) {
Path root = *gcRootsDir + "/" + std::string(baseNameOf(drvPath));
if (!pathExists(root))
localStore->addPermRoot(localStore->parseStorePath(drvPath), root, false);
}
nlohmann::json out;
for (auto & j : outputs)
out[j.first] = j.second;
job["outputs"] = std::move(out);
reply["job"] = std::move(job);
}
else if (v->type == tAttrs) {
auto attrs = nlohmann::json::array();
StringSet ss;
for (auto & i : v->attrs->lexicographicOrder()) {
std::string name(i->name);
if (name.find('.') != std::string::npos || name.find(' ') != std::string::npos) {
printError("skipping job with illegal name '%s'", name);
continue;
}
attrs.push_back(name);
}
reply["attrs"] = std::move(attrs);
}
} catch (EvalError & e) {
reply["error"] = filterANSIEscapes(e.msg(), true);
}
writeLine(to.get(), reply.dump());
/* If our RSS exceeds the maximum, exit. The master will
start a new process. */
struct rusage r;
getrusage(RUSAGE_SELF, &r);
if ((size_t) r.ru_maxrss > maxMemorySize * 1024) break;
}
writeLine(to.get(), "restart");
}
void run(ref<Store> store) override
{
if (!gcRootsDir) warn("'--gc-roots-dir' not specified");
struct State
{
std::set<std::string> todo{""};
std::set<std::string> active;
nlohmann::json result;
std::exception_ptr exc;
};
std::condition_variable wakeup;
Sync<State> state_;
/* Start a handler thread per worker process. */
auto handler = [this, &state_, &wakeup]()
{
try {
pid_t pid = -1;
AutoCloseFD from, to;
while (true) {
/* Start a new worker process if necessary. */
if (pid == -1) {
Pipe toPipe, fromPipe;
toPipe.create();
fromPipe.create();
pid = startProcess(
[this,
to{std::make_shared<AutoCloseFD>(std::move(fromPipe.writeSide))},
from{std::make_shared<AutoCloseFD>(std::move(toPipe.readSide))}
]()
{
try {
worker(*to, *from);
} catch (std::exception & e) {
nlohmann::json err;
err["error"] = e.what();
writeLine(to->get(), err.dump());
}
},
ProcessOptions { .allowVfork = false });
from = std::move(fromPipe.readSide);
to = std::move(toPipe.writeSide);
debug("created worker process %d", pid);
}
/* Check whether the existing worker process is still there. */
auto s = readLine(from.get());
if (s == "restart") {
pid = -1;
continue;
} else if (s != "next") {
auto json = nlohmann::json::parse(s);
throw Error("worker error: %s", (std::string) json["error"]);
}
/* Wait for a job name to become available. */
std::string attrPath;
while (true) {
checkInterrupt();
auto state(state_.lock());
if ((state->todo.empty() && state->active.empty()) || state->exc) {
writeLine(to.get(), "exit");
return;
}
if (!state->todo.empty()) {
attrPath = *state->todo.begin();
state->todo.erase(state->todo.begin());
state->active.insert(attrPath);
break;
} else
state.wait(wakeup);
}
/* Tell the worker to evaluate it. */
writeLine(to.get(), "do " + attrPath);
/* Wait for the response. */
auto response = nlohmann::json::parse(readLine(from.get()));
/* Handle the response. */
StringSet newAttrs;
if (response.find("job") != response.end()) {
auto state(state_.lock());
if (json)
state->result[attrPath] = response["job"];
else
std::cout << fmt("%d: %d\n", attrPath, (std::string) response["job"]["drvPath"]);
}
if (response.find("attrs") != response.end()) {
for (auto & i : response["attrs"]) {
auto s = (attrPath.empty() ? "" : attrPath + ".") + (std::string) i;
newAttrs.insert(s);
}
}
if (response.find("error") != response.end()) {
auto state(state_.lock());
if (json)
state->result[attrPath]["error"] = response["error"];
else
printError("error in job '%s': %s",
attrPath, (std::string) response["error"]);
}
/* Add newly discovered job names to the queue. */
{
auto state(state_.lock());
state->active.erase(attrPath);
for (auto & s : newAttrs)
state->todo.insert(s);
wakeup.notify_all();
}
}
} catch (...) {
auto state(state_.lock());
state->exc = std::current_exception();
wakeup.notify_all();
}
};
std::vector<std::thread> threads;
for (size_t i = 0; i < nrWorkers; i++)
threads.emplace_back(std::thread(handler));
for (auto & thread : threads)
thread.join();
auto state(state_.lock());
if (state->exc)
std::rethrow_exception(state->exc);
if (json) std::cout << state->result.dump(2) << "\n";
}
};
static auto r1 = registerCommand<CmdEvalHydraJobs>("eval-hydra-jobs");
<commit_msg>nix eval-hydra-job: Progress indicator<commit_after>#include "command.hh"
#include "eval.hh"
#include "eval-inline.hh"
#include "derivations.hh"
#include "common-args.hh"
#include "json.hh"
#include "get-drvs.hh"
#include "attr-path.hh"
#include <nlohmann/json.hpp>
#include <sys/resource.h>
using namespace nix;
static std::string queryMetaStrings(EvalState & state, DrvInfo & drv, const string & name, const string & subAttribute)
{
Strings res;
std::function<void(Value & v)> rec;
rec = [&](Value & v) {
state.forceValue(v);
if (v.type == tString)
res.push_back(v.string.s);
else if (v.isList())
for (unsigned int n = 0; n < v.listSize(); ++n)
rec(*v.listElems()[n]);
else if (v.type == tAttrs) {
auto a = v.attrs->find(state.symbols.create(subAttribute));
if (a != v.attrs->end())
res.push_back(state.forceString(*a->value));
}
};
Value * v = drv.queryMeta(name);
if (v) rec(*v);
return concatStringsSep(", ", res);
}
struct CmdEvalHydraJobs : MixJSON, MixDryRun, InstallableCommand
{
std::optional<Path> gcRootsDir;
size_t nrWorkers = 1;
size_t maxMemorySize = 4ULL * 1024;
CmdEvalHydraJobs()
{
mkFlag()
.longName("gc-roots-dir")
.description("garbage collector roots directory")
.labels({"path"})
.dest(&gcRootsDir);
mkIntFlag(0, "workers", "number of concurrent worker processes", &nrWorkers);
mkIntFlag(0, "max-memory-size", "maximum memory usage per worker process (in MiB)", &maxMemorySize);
}
std::string description() override
{
return "evaluate a Hydra jobset";
}
Examples examples() override
{
return {
Example{
"Evaluate Nixpkgs' release-combined jobset:",
"nix eval-hydra-jobs -f '<nixpkgs/nixos/release-combined.nix>' '' --json"
},
};
}
Strings getDefaultFlakeAttrPaths() override
{
return {"hydraJobs", "checks"};
}
void worker(AutoCloseFD & to, AutoCloseFD & from)
{
auto state = getEvalState();
// FIXME: should re-open state->store.
if (dryRun) settings.readOnlyMode = true;
/* Prevent access to paths outside of the Nix search path and
to the environment. */
evalSettings.restrictEval = true;
auto autoArgs = getAutoArgs(*state);
auto vTop = installable->toValue(*state).first;
auto vRoot = state->allocValue();
state->autoCallFunction(*autoArgs, *vTop, *vRoot);
while (true) {
/* Wait for the master to send us a job name. */
writeLine(to.get(), "next");
auto s = readLine(from.get());
if (s == "exit") break;
if (!hasPrefix(s, "do ")) abort();
std::string attrPath(s, 3);
debug("worker process %d at '%s'", getpid(), attrPath);
/* Evaluate it and send info back to the master. */
nlohmann::json reply;
try {
auto v = findAlongAttrPath(*state, attrPath, *autoArgs, *vRoot).first;
state->forceValue(*v);
if (auto drv = getDerivation(*state, *v, false)) {
DrvInfo::Outputs outputs = drv->queryOutputs();
if (drv->querySystem() == "unknown")
throw EvalError("derivation must have a 'system' attribute");
auto drvPath = drv->queryDrvPath();
nlohmann::json job;
job["nixName"] = drv->queryName();
job["system"] =drv->querySystem();
job["drvPath"] = drvPath;
job["description"] = drv->queryMetaString("description");
job["license"] = queryMetaStrings(*state, *drv, "license", "shortName");
job["homepage"] = drv->queryMetaString("homepage");
job["maintainers"] = queryMetaStrings(*state, *drv, "maintainers", "email");
job["schedulingPriority"] = drv->queryMetaInt("schedulingPriority", 100);
job["timeout"] = drv->queryMetaInt("timeout", 36000);
job["maxSilent"] = drv->queryMetaInt("maxSilent", 7200);
job["isChannel"] = drv->queryMetaBool("isHydraChannel", false);
/* If this is an aggregate, then get its constituents. */
auto a = v->attrs->get(state->symbols.create("_hydraAggregate"));
if (a && state->forceBool(*a->value, *a->pos)) {
auto a = v->attrs->get(state->symbols.create("constituents"));
if (!a)
throw EvalError("derivation must have a ‘constituents’ attribute");
PathSet context;
state->coerceToString(*a->pos, *a->value, context, true, false);
PathSet drvs;
for (auto & i : context)
if (i.at(0) == '!') {
size_t index = i.find("!", 1);
drvs.insert(string(i, index + 1));
}
job["constituents"] = concatStringsSep(" ", drvs);
}
/* Register the derivation as a GC root. !!! This
registers roots for jobs that we may have already
done. */
auto localStore = state->store.dynamic_pointer_cast<LocalFSStore>();
if (gcRootsDir && localStore) {
Path root = *gcRootsDir + "/" + std::string(baseNameOf(drvPath));
if (!pathExists(root))
localStore->addPermRoot(localStore->parseStorePath(drvPath), root, false);
}
nlohmann::json out;
for (auto & j : outputs)
out[j.first] = j.second;
job["outputs"] = std::move(out);
reply["job"] = std::move(job);
}
else if (v->type == tAttrs) {
auto attrs = nlohmann::json::array();
StringSet ss;
for (auto & i : v->attrs->lexicographicOrder()) {
std::string name(i->name);
if (name.find('.') != std::string::npos || name.find(' ') != std::string::npos) {
printError("skipping job with illegal name '%s'", name);
continue;
}
attrs.push_back(name);
}
reply["attrs"] = std::move(attrs);
}
} catch (EvalError & e) {
reply["error"] = filterANSIEscapes(e.msg(), true);
}
writeLine(to.get(), reply.dump());
/* If our RSS exceeds the maximum, exit. The master will
start a new process. */
struct rusage r;
getrusage(RUSAGE_SELF, &r);
if ((size_t) r.ru_maxrss > maxMemorySize * 1024) break;
}
writeLine(to.get(), "restart");
}
void run(ref<Store> store) override
{
if (!gcRootsDir) warn("'--gc-roots-dir' not specified");
struct State
{
std::set<std::string> todo{""};
std::set<std::string> active;
nlohmann::json result;
std::exception_ptr exc;
};
std::condition_variable wakeup;
Sync<State> state_;
/* Start a handler thread per worker process. */
auto handler = [this, &state_, &wakeup]()
{
try {
pid_t pid = -1;
AutoCloseFD from, to;
while (true) {
/* Start a new worker process if necessary. */
if (pid == -1) {
Pipe toPipe, fromPipe;
toPipe.create();
fromPipe.create();
pid = startProcess(
[this,
to{std::make_shared<AutoCloseFD>(std::move(fromPipe.writeSide))},
from{std::make_shared<AutoCloseFD>(std::move(toPipe.readSide))}
]()
{
try {
worker(*to, *from);
} catch (std::exception & e) {
nlohmann::json err;
err["error"] = e.what();
writeLine(to->get(), err.dump());
}
},
ProcessOptions { .allowVfork = false });
from = std::move(fromPipe.readSide);
to = std::move(toPipe.writeSide);
debug("created worker process %d", pid);
}
/* Check whether the existing worker process is still there. */
auto s = readLine(from.get());
if (s == "restart") {
pid = -1;
continue;
} else if (s != "next") {
auto json = nlohmann::json::parse(s);
throw Error("worker error: %s", (std::string) json["error"]);
}
/* Wait for a job name to become available. */
std::string attrPath;
while (true) {
checkInterrupt();
auto state(state_.lock());
if ((state->todo.empty() && state->active.empty()) || state->exc) {
writeLine(to.get(), "exit");
return;
}
if (!state->todo.empty()) {
attrPath = *state->todo.begin();
state->todo.erase(state->todo.begin());
state->active.insert(attrPath);
break;
} else
state.wait(wakeup);
}
Activity act(*logger, lvlInfo, actUnknown, fmt("evaluating '%s'", attrPath));
/* Tell the worker to evaluate it. */
writeLine(to.get(), "do " + attrPath);
/* Wait for the response. */
auto response = nlohmann::json::parse(readLine(from.get()));
/* Handle the response. */
StringSet newAttrs;
if (response.find("job") != response.end()) {
auto state(state_.lock());
if (json)
state->result[attrPath] = response["job"];
else
std::cout << fmt("%d: %d\n", attrPath, (std::string) response["job"]["drvPath"]);
}
if (response.find("attrs") != response.end()) {
for (auto & i : response["attrs"]) {
auto s = (attrPath.empty() ? "" : attrPath + ".") + (std::string) i;
newAttrs.insert(s);
}
}
if (response.find("error") != response.end()) {
auto state(state_.lock());
if (json)
state->result[attrPath]["error"] = response["error"];
else
printError("error in job '%s': %s",
attrPath, (std::string) response["error"]);
}
/* Add newly discovered job names to the queue. */
{
auto state(state_.lock());
state->active.erase(attrPath);
for (auto & s : newAttrs)
state->todo.insert(s);
wakeup.notify_all();
}
}
} catch (...) {
auto state(state_.lock());
state->exc = std::current_exception();
wakeup.notify_all();
}
};
std::vector<std::thread> threads;
for (size_t i = 0; i < nrWorkers; i++)
threads.emplace_back(std::thread(handler));
for (auto & thread : threads)
thread.join();
auto state(state_.lock());
if (state->exc)
std::rethrow_exception(state->exc);
if (json) std::cout << state->result.dump(2) << "\n";
}
};
static auto r1 = registerCommand<CmdEvalHydraJobs>("eval-hydra-jobs");
<|endoftext|> |
<commit_before>//===-- iOperators.cpp - Implement binary Operators ------------*- C++ -*--===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the nontrivial binary operator instructions.
//
//===----------------------------------------------------------------------===//
#include "llvm/iOperators.h"
#include "llvm/Type.h"
#include "llvm/Constants.h"
#include "llvm/BasicBlock.h"
using namespace llvm;
//===----------------------------------------------------------------------===//
// BinaryOperator Class
//===----------------------------------------------------------------------===//
BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
const Type *Ty, const std::string &Name,
Instruction *InsertBefore)
: Instruction(Ty, iType, Name, InsertBefore) {
Operands.reserve(2);
Operands.push_back(Use(S1, this));
Operands.push_back(Use(S2, this));
assert(S1 && S2 && S1->getType() == S2->getType());
#ifndef NDEBUG
switch (iType) {
case Add: case Sub:
case Mul: case Div:
case Rem:
assert(Ty == S1->getType() &&
"Arithmetic operation should return same type as operands!");
assert((Ty->isInteger() || Ty->isFloatingPoint()) &&
"Tried to create an arithmetic operation on a non-arithmetic type!");
break;
case And: case Or:
case Xor:
assert(Ty == S1->getType() &&
"Logical operation should return same type as operands!");
assert(Ty->isIntegral() &&
"Tried to create an logical operation on a non-integral type!");
break;
case SetLT: case SetGT: case SetLE:
case SetGE: case SetEQ: case SetNE:
assert(Ty == Type::BoolTy && "Setcc must return bool!");
default:
break;
}
#endif
}
BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
const std::string &Name,
Instruction *InsertBefore) {
assert(S1->getType() == S2->getType() &&
"Cannot create binary operator with two operands of differing type!");
switch (Op) {
// Binary comparison operators...
case SetLT: case SetGT: case SetLE:
case SetGE: case SetEQ: case SetNE:
return new SetCondInst(Op, S1, S2, Name, InsertBefore);
default:
return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
}
}
BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
Instruction *InsertBefore) {
return new BinaryOperator(Instruction::Sub,
Constant::getNullValue(Op->getType()), Op,
Op->getType(), Name, InsertBefore);
}
BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
Instruction *InsertBefore) {
return new BinaryOperator(Instruction::Xor, Op,
ConstantIntegral::getAllOnesValue(Op->getType()),
Op->getType(), Name, InsertBefore);
}
// isConstantAllOnes - Helper function for several functions below
static inline bool isConstantAllOnes(const Value *V) {
return isa<ConstantIntegral>(V) &&cast<ConstantIntegral>(V)->isAllOnesValue();
}
bool BinaryOperator::isNeg(const Value *V) {
if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
return Bop->getOpcode() == Instruction::Sub &&
Bop->getOperand(0) == Constant::getNullValue(Bop->getType());
return false;
}
bool BinaryOperator::isNot(const Value *V) {
if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
return (Bop->getOpcode() == Instruction::Xor &&
(isConstantAllOnes(Bop->getOperand(1)) ||
isConstantAllOnes(Bop->getOperand(0))));
return false;
}
Value *BinaryOperator::getNegArgument(BinaryOperator *Bop) {
assert(isNeg(Bop) && "getNegArgument from non-'neg' instruction!");
return Bop->getOperand(1);
}
const Value *BinaryOperator::getNegArgument(const BinaryOperator *Bop) {
return getNegArgument((BinaryOperator*)Bop);
}
Value *BinaryOperator::getNotArgument(BinaryOperator *Bop) {
assert(isNot(Bop) && "getNotArgument on non-'not' instruction!");
Value *Op0 = Bop->getOperand(0);
Value *Op1 = Bop->getOperand(1);
if (isConstantAllOnes(Op0)) return Op1;
assert(isConstantAllOnes(Op1));
return Op0;
}
const Value *BinaryOperator::getNotArgument(const BinaryOperator *Bop) {
return getNotArgument((BinaryOperator*)Bop);
}
// swapOperands - Exchange the two operands to this instruction. This
// instruction is safe to use on any binary instruction and does not
// modify the semantics of the instruction. If the instruction is
// order dependent (SetLT f.e.) the opcode is changed.
//
bool BinaryOperator::swapOperands() {
if (isCommutative())
; // If the instruction is commutative, it is safe to swap the operands
else if (SetCondInst *SCI = dyn_cast<SetCondInst>(this))
iType = SCI->getSwappedCondition();
else
return true; // Can't commute operands
std::swap(Operands[0], Operands[1]);
return false;
}
//===----------------------------------------------------------------------===//
// SetCondInst Class
//===----------------------------------------------------------------------===//
SetCondInst::SetCondInst(BinaryOps Opcode, Value *S1, Value *S2,
const std::string &Name, Instruction *InsertBefore)
: BinaryOperator(Opcode, S1, S2, Type::BoolTy, Name, InsertBefore) {
// Make sure it's a valid type... getInverseCondition will assert out if not.
assert(getInverseCondition(Opcode));
}
// getInverseCondition - Return the inverse of the current condition opcode.
// For example seteq -> setne, setgt -> setle, setlt -> setge, etc...
//
Instruction::BinaryOps SetCondInst::getInverseCondition(BinaryOps Opcode) {
switch (Opcode) {
default:
assert(0 && "Unknown setcc opcode!");
case SetEQ: return SetNE;
case SetNE: return SetEQ;
case SetGT: return SetLE;
case SetLT: return SetGE;
case SetGE: return SetLT;
case SetLE: return SetGT;
}
}
// getSwappedCondition - Return the condition opcode that would be the result
// of exchanging the two operands of the setcc instruction without changing
// the result produced. Thus, seteq->seteq, setle->setge, setlt->setgt, etc.
//
Instruction::BinaryOps SetCondInst::getSwappedCondition(BinaryOps Opcode) {
switch (Opcode) {
default: assert(0 && "Unknown setcc instruction!");
case SetEQ: case SetNE: return Opcode;
case SetGT: return SetLT;
case SetLT: return SetGT;
case SetGE: return SetLE;
case SetLE: return SetGE;
}
}
<commit_msg>Floating point negates are -0.0 - X, not 0.0 - X<commit_after>//===-- iOperators.cpp - Implement binary Operators ------------*- C++ -*--===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the nontrivial binary operator instructions.
//
//===----------------------------------------------------------------------===//
#include "llvm/iOperators.h"
#include "llvm/Type.h"
#include "llvm/Constants.h"
#include "llvm/BasicBlock.h"
using namespace llvm;
//===----------------------------------------------------------------------===//
// BinaryOperator Class
//===----------------------------------------------------------------------===//
BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
const Type *Ty, const std::string &Name,
Instruction *InsertBefore)
: Instruction(Ty, iType, Name, InsertBefore) {
Operands.reserve(2);
Operands.push_back(Use(S1, this));
Operands.push_back(Use(S2, this));
assert(S1 && S2 && S1->getType() == S2->getType());
#ifndef NDEBUG
switch (iType) {
case Add: case Sub:
case Mul: case Div:
case Rem:
assert(Ty == S1->getType() &&
"Arithmetic operation should return same type as operands!");
assert((Ty->isInteger() || Ty->isFloatingPoint()) &&
"Tried to create an arithmetic operation on a non-arithmetic type!");
break;
case And: case Or:
case Xor:
assert(Ty == S1->getType() &&
"Logical operation should return same type as operands!");
assert(Ty->isIntegral() &&
"Tried to create an logical operation on a non-integral type!");
break;
case SetLT: case SetGT: case SetLE:
case SetGE: case SetEQ: case SetNE:
assert(Ty == Type::BoolTy && "Setcc must return bool!");
default:
break;
}
#endif
}
BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
const std::string &Name,
Instruction *InsertBefore) {
assert(S1->getType() == S2->getType() &&
"Cannot create binary operator with two operands of differing type!");
switch (Op) {
// Binary comparison operators...
case SetLT: case SetGT: case SetLE:
case SetGE: case SetEQ: case SetNE:
return new SetCondInst(Op, S1, S2, Name, InsertBefore);
default:
return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
}
}
BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
Instruction *InsertBefore) {
if (!Op->getType()->isFloatingPoint())
return new BinaryOperator(Instruction::Sub,
Constant::getNullValue(Op->getType()), Op,
Op->getType(), Name, InsertBefore);
else
return new BinaryOperator(Instruction::Sub,
ConstantFP::get(Op->getType(), -0.0), Op,
Op->getType(), Name, InsertBefore);
}
BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
Instruction *InsertBefore) {
return new BinaryOperator(Instruction::Xor, Op,
ConstantIntegral::getAllOnesValue(Op->getType()),
Op->getType(), Name, InsertBefore);
}
// isConstantAllOnes - Helper function for several functions below
static inline bool isConstantAllOnes(const Value *V) {
return isa<ConstantIntegral>(V) &&cast<ConstantIntegral>(V)->isAllOnesValue();
}
bool BinaryOperator::isNeg(const Value *V) {
if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
if (Bop->getOpcode() == Instruction::Sub)
if (!V->getType()->isFloatingPoint())
return Bop->getOperand(0) == Constant::getNullValue(Bop->getType());
else
return Bop->getOperand(0) == ConstantFP::get(Bop->getType(), -0.0);
return false;
}
bool BinaryOperator::isNot(const Value *V) {
if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
return (Bop->getOpcode() == Instruction::Xor &&
(isConstantAllOnes(Bop->getOperand(1)) ||
isConstantAllOnes(Bop->getOperand(0))));
return false;
}
Value *BinaryOperator::getNegArgument(BinaryOperator *Bop) {
assert(isNeg(Bop) && "getNegArgument from non-'neg' instruction!");
return Bop->getOperand(1);
}
const Value *BinaryOperator::getNegArgument(const BinaryOperator *Bop) {
return getNegArgument((BinaryOperator*)Bop);
}
Value *BinaryOperator::getNotArgument(BinaryOperator *Bop) {
assert(isNot(Bop) && "getNotArgument on non-'not' instruction!");
Value *Op0 = Bop->getOperand(0);
Value *Op1 = Bop->getOperand(1);
if (isConstantAllOnes(Op0)) return Op1;
assert(isConstantAllOnes(Op1));
return Op0;
}
const Value *BinaryOperator::getNotArgument(const BinaryOperator *Bop) {
return getNotArgument((BinaryOperator*)Bop);
}
// swapOperands - Exchange the two operands to this instruction. This
// instruction is safe to use on any binary instruction and does not
// modify the semantics of the instruction. If the instruction is
// order dependent (SetLT f.e.) the opcode is changed.
//
bool BinaryOperator::swapOperands() {
if (isCommutative())
; // If the instruction is commutative, it is safe to swap the operands
else if (SetCondInst *SCI = dyn_cast<SetCondInst>(this))
iType = SCI->getSwappedCondition();
else
return true; // Can't commute operands
std::swap(Operands[0], Operands[1]);
return false;
}
//===----------------------------------------------------------------------===//
// SetCondInst Class
//===----------------------------------------------------------------------===//
SetCondInst::SetCondInst(BinaryOps Opcode, Value *S1, Value *S2,
const std::string &Name, Instruction *InsertBefore)
: BinaryOperator(Opcode, S1, S2, Type::BoolTy, Name, InsertBefore) {
// Make sure it's a valid type... getInverseCondition will assert out if not.
assert(getInverseCondition(Opcode));
}
// getInverseCondition - Return the inverse of the current condition opcode.
// For example seteq -> setne, setgt -> setle, setlt -> setge, etc...
//
Instruction::BinaryOps SetCondInst::getInverseCondition(BinaryOps Opcode) {
switch (Opcode) {
default:
assert(0 && "Unknown setcc opcode!");
case SetEQ: return SetNE;
case SetNE: return SetEQ;
case SetGT: return SetLE;
case SetLT: return SetGE;
case SetGE: return SetLT;
case SetLE: return SetGT;
}
}
// getSwappedCondition - Return the condition opcode that would be the result
// of exchanging the two operands of the setcc instruction without changing
// the result produced. Thus, seteq->seteq, setle->setge, setlt->setgt, etc.
//
Instruction::BinaryOps SetCondInst::getSwappedCondition(BinaryOps Opcode) {
switch (Opcode) {
default: assert(0 && "Unknown setcc instruction!");
case SetEQ: case SetNE: return Opcode;
case SetGT: return SetLT;
case SetLT: return SetGT;
case SetGE: return SetLE;
case SetLE: return SetGE;
}
}
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright (C) 2018 Kitsune Ral <kitsune-ral@users.sf.net>
*
* This library 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 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "util.h"
#include <QtCore/QRegularExpression>
#include <QtCore/QStandardPaths>
#include <QtCore/QDir>
#include <QtCore/QStringBuilder>
static const auto RegExpOptions =
QRegularExpression::CaseInsensitiveOption
| QRegularExpression::OptimizeOnFirstUsageOption
| QRegularExpression::UseUnicodePropertiesOption;
// Converts all that looks like a URL into HTML links
static void linkifyUrls(QString& htmlEscapedText)
{
// regexp is originally taken from Konsole (https://github.com/KDE/konsole)
// full url:
// protocolname:// or www. followed by anything other than whitespaces,
// <, >, ' or ", and ends before whitespaces, <, >, ', ", ], !, ), :,
// comma or dot
// Note: outer parentheses are a part of C++ raw string delimiters, not of
// the regex (see http://en.cppreference.com/w/cpp/language/string_literal).
static const QRegularExpression FullUrlRegExp(QStringLiteral(
R"(((www\.(?!\.)|[a-z][a-z0-9+.-]*://)(&(?![lg]t;)|[^&\s<>'"])+(&(?![lg]t;)|[^&!,.\s<>'"\]):])))"
), RegExpOptions);
// email address:
// [word chars, dots or dashes]@[word chars, dots or dashes].[word chars]
static const QRegularExpression EmailAddressRegExp(QStringLiteral(
R"((mailto:)?(\b(\w|\.|-)+@(\w|\.|-)+\.\w+\b))"
), RegExpOptions);
// NOTE: htmlEscapedText is already HTML-escaped! No literal <,>,&
htmlEscapedText.replace(EmailAddressRegExp,
QStringLiteral(R"(<a href="mailto:\2">\1\2</a>)"));
htmlEscapedText.replace(FullUrlRegExp,
QStringLiteral(R"(<a href="\1">\1</a>)"));
}
QString QMatrixClient::prettyPrint(const QString& plainText)
{
auto pt = QStringLiteral("<span style='white-space:pre-wrap'>") +
plainText.toHtmlEscaped() + QStringLiteral("</span>");
pt.replace('\n', QStringLiteral("<br/>"));
linkifyUrls(pt);
return pt;
}
QString QMatrixClient::cacheLocation(const QString& dirName)
{
const auto cachePath =
QStandardPaths::writableLocation(QStandardPaths::CacheLocation)
% '/' % dirName % '/';
QDir dir;
if (!dir.exists(cachePath))
dir.mkpath(cachePath);
return cachePath;
}
<commit_msg>Fix QString initialisation from QStringBuilder<commit_after>/******************************************************************************
* Copyright (C) 2018 Kitsune Ral <kitsune-ral@users.sf.net>
*
* This library 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 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "util.h"
#include <QtCore/QRegularExpression>
#include <QtCore/QStandardPaths>
#include <QtCore/QDir>
#include <QtCore/QStringBuilder>
static const auto RegExpOptions =
QRegularExpression::CaseInsensitiveOption
| QRegularExpression::OptimizeOnFirstUsageOption
| QRegularExpression::UseUnicodePropertiesOption;
// Converts all that looks like a URL into HTML links
static void linkifyUrls(QString& htmlEscapedText)
{
// regexp is originally taken from Konsole (https://github.com/KDE/konsole)
// full url:
// protocolname:// or www. followed by anything other than whitespaces,
// <, >, ' or ", and ends before whitespaces, <, >, ', ", ], !, ), :,
// comma or dot
// Note: outer parentheses are a part of C++ raw string delimiters, not of
// the regex (see http://en.cppreference.com/w/cpp/language/string_literal).
static const QRegularExpression FullUrlRegExp(QStringLiteral(
R"(((www\.(?!\.)|[a-z][a-z0-9+.-]*://)(&(?![lg]t;)|[^&\s<>'"])+(&(?![lg]t;)|[^&!,.\s<>'"\]):])))"
), RegExpOptions);
// email address:
// [word chars, dots or dashes]@[word chars, dots or dashes].[word chars]
static const QRegularExpression EmailAddressRegExp(QStringLiteral(
R"((mailto:)?(\b(\w|\.|-)+@(\w|\.|-)+\.\w+\b))"
), RegExpOptions);
// NOTE: htmlEscapedText is already HTML-escaped! No literal <,>,&
htmlEscapedText.replace(EmailAddressRegExp,
QStringLiteral(R"(<a href="mailto:\2">\1\2</a>)"));
htmlEscapedText.replace(FullUrlRegExp,
QStringLiteral(R"(<a href="\1">\1</a>)"));
}
QString QMatrixClient::prettyPrint(const QString& plainText)
{
auto pt = QStringLiteral("<span style='white-space:pre-wrap'>") +
plainText.toHtmlEscaped() + QStringLiteral("</span>");
pt.replace('\n', QStringLiteral("<br/>"));
linkifyUrls(pt);
return pt;
}
QString QMatrixClient::cacheLocation(const QString& dirName)
{
const QString cachePath =
QStandardPaths::writableLocation(QStandardPaths::CacheLocation)
% '/' % dirName % '/';
QDir dir;
if (!dir.exists(cachePath))
dir.mkpath(cachePath);
return cachePath;
}
<|endoftext|> |
<commit_before>#include "ofxLineStripObject.h"
ofxLineStripObject::ofxLineStripObject(int iNumVerts)
{
lineWidth = 1.0;
for(int i=0; i < iNumVerts; i++){
addVertex(0,0,0);
}
isVertexColoringEnabled = false;
}
ofxLineStripObject::ofxLineStripObject(){}
void ofxLineStripObject::render()
{
glLineWidth(lineWidth);
glBegin(GL_LINE_STRIP);
for(int i=0; i < vertices.size(); i++){
if(isVertexColoringEnabled) glColor4f(vertices[i]->color.x/255.0f, vertices[i]->color.y/255.0f, vertices[i]->color.z/255.0f, vertices[i]->color.w/255.0f);
glVertex3f(vertices[i]->position.x, vertices[i]->position.y, vertices[i]->position.z);
}
glEnd();
}
void ofxLineStripObject::setLineWidth(float iWidth)
{
lineWidth = iWidth;
}
void ofxLineStripObject::setVertexPos(int iVertNum, float iX, float iY, float iZ)
{
if(ofInRange(iVertNum, 0, vertices.size()-1)){
vertices[iVertNum]->position.set(iX, iY, iZ);
}
}
void ofxLineStripObject::setVertexColor(int iVertNum, float iR, float iG, float iB, float iA)
{
if(ofInRange(iVertNum, 0, vertices.size()-1)){
vertices[iVertNum]->color.set(iR, iG, iB, iA);
}
}
void ofxLineStripObject::addVertex(float iX, float iY, float iZ)
{
ofxLineStripVertex *vert = new ofxLineStripVertex();
vert->position.set(iX, iY, iZ);
vert->color.set(255, 255, 255, 255);
vertices.push_back(vert);
}
void ofxLineStripObject::addVertex(float iX, float iY, float iZ, ofVec4f iColor)
{
ofxLineStripVertex *vert = new ofxLineStripVertex();
vert->position.set(iX, iY, iZ);
vert->color = iColor;
vertices.push_back(vert);
}
void ofxLineStripObject::enableVertexColoring(bool iEnable)
{
isVertexColoringEnabled = iEnable;
}<commit_msg>killed printf in ofxLineStripObject<commit_after>#include "ofxLineStripObject.h"
ofxLineStripObject::ofxLineStripObject(int iNumVerts)
{
lineWidth = 1.0;
for(int i=0; i < iNumVerts; i++){
addVertex(0,0,0);
}
isVertexColoringEnabled = false;
}
ofxLineStripObject::ofxLineStripObject(){}
void ofxLineStripObject::render()
{
glLineWidth(lineWidth);
glBegin(GL_LINE_STRIP);
for(int i=0; i < vertices.size(); i++){
if(isVertexColoringEnabled)
glColor4f(vertices[i]->color.x/255.0f, vertices[i]->color.y/255.0f, vertices[i]->color.z/255.0f, drawMaterial->color.w/255.0f * vertices[i]->color.w/255.0f);
glVertex3f(vertices[i]->position.x, vertices[i]->position.y, vertices[i]->position.z);
}
glEnd();
}
void ofxLineStripObject::setLineWidth(float iWidth)
{
lineWidth = iWidth;
}
void ofxLineStripObject::setVertexPos(int iVertNum, float iX, float iY, float iZ)
{
if(ofInRange(iVertNum, 0, vertices.size()-1)){
vertices[iVertNum]->position.set(iX, iY, iZ);
}
}
void ofxLineStripObject::setVertexColor(int iVertNum, float iR, float iG, float iB, float iA)
{
if(ofInRange(iVertNum, 0, vertices.size()-1)){
vertices[iVertNum]->color.set(iR, iG, iB, iA);
}
}
void ofxLineStripObject::addVertex(float iX, float iY, float iZ)
{
ofxLineStripVertex *vert = new ofxLineStripVertex();
vert->position.set(iX, iY, iZ);
vert->color.set(255, 255, 255, 255);
vertices.push_back(vert);
}
void ofxLineStripObject::addVertex(float iX, float iY, float iZ, ofVec4f iColor)
{
ofxLineStripVertex *vert = new ofxLineStripVertex();
vert->position.set(iX, iY, iZ);
vert->color = iColor;
vertices.push_back(vert);
}
void ofxLineStripObject::enableVertexColoring(bool iEnable)
{
isVertexColoringEnabled = iEnable;
}<|endoftext|> |
<commit_before>/*
* ofxShivaVG
* A 2d rendering library for openFrameworks, based on the ShivaVG library
* by Bjørn Gunnar Staal
*
* This library 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 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library in the file COPYING;
* if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include "ofxShivaVGRenderer.h"
#include "vgu.h"
#include "simpleVGPath.h"
// TODO: Implement resize!
ofxShivaVGRenderer::ofxShivaVGRenderer ()
{
_vg.create(ofGetWidth(), ofGetHeight());
}
void ofxShivaVGRenderer::setLineCapStyle(VGCapStyle cap)
{
_vg.setStrokeCapStyle(cap);
}
void ofxShivaVGRenderer::setLineJoinStyle(VGJoinStyle join)
{
_vg.setStrokeJoinStyle(join);
}
VGCapStyle ofxShivaVGRenderer::getLineCapStyle()
{
return _vg.getStrokeCapStyle();
}
VGJoinStyle ofxShivaVGRenderer::getLineJoinStyle()
{
return _vg.getStrokeJoinStyle();
}
void ofxShivaVGRenderer::background(const ofColor & c)
{
_bgColor = c;
glClearColor(_bgColor[0],_bgColor[1],_bgColor[2], _bgColor[3]);
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
}
// --------------------------------------------
// DRAWING
// --------------------------------------------
void ofxShivaVGRenderer::draw(ofPolyline & poly)
{
ofStyle style = ofGetStyle();
_vg.setStrokeWidth(style.lineWidth);
ofColor c = style.color;
_vg.setStrokeColor(c.r, c.g, c.b, c.a);
simpleVGPath p;
vector<ofVec3f> &verts = poly.getVertices();
p.moveTo(verts[0].x, verts[0].y);
for (vector<ofVec3f>::iterator v = verts.begin()+1; v != verts.end(); ++v)
{
p.lineTo(v->x, v->y);
}
if(poly.isClosed())
{
p.close();
}
_vg.strokePath(p);
}
void ofxShivaVGRenderer::draw(ofPath &path)
{
ofStyle style = ofGetStyle();
// TODO: fill or stroke?
// vector<ofSubPath> & paths = path.getSubPaths();
simpleVGPath p;
_doDrawPath(path, p);
ofColor prevColor;
if(path.getUseShapeColor()) prevColor = style.color;
ofColor c = style.color;
if (path.isFilled())
{
if (path.getUseShapeColor())
{
c = path.getFillColor();
}
_vg.setFillColor(c.r, c.g, c.b, c.a);
_vg.fillPath(p);
}
if (path.hasOutline())
{
if (path.getUseShapeColor())
{
c = path.getStrokeColor();
}
_vg.setStrokeColor(c.r, c.g, c.b, c.a);
_vg.setStrokeWidth(path.getStrokeWidth());
_vg.strokePath(p);
}
if(path.getUseShapeColor()) setColor(prevColor);
}
void ofxShivaVGRenderer::_doDrawPath(ofPath &path, simpleVGPath &p)
{
const vector<ofPath::Command> &commands = path.getCommands();
int i = 0;
for(vector<ofPath::Command>::const_iterator c = commands.begin(); c != commands.end(); ++c)
{
switch(c->type)
{
case ofPath::Command::moveTo:
p.moveTo(c->to.x, c->to.y);
_curvePoints.push_back(c->to);
break;
case ofPath::Command::lineTo:
_curvePoints.clear();
p.lineTo(c->to.x, c->to.y);
break;
case ofPath::Command::curveTo:
_curvePoints.push_back(c->to);
//code from ofCairoRenderer to convert from catmull rom to bezier
if(_curvePoints.size() == 4)
{
ofPoint p1=_curvePoints[0];
ofPoint p2=_curvePoints[1];
ofPoint p3=_curvePoints[2];
ofPoint p4=_curvePoints[3];
ofPoint cp1 = p2 + ( p3 - p1 ) * (1.0/6);
ofPoint cp2 = p3 + ( p2 - p4 ) * (1.0/6);
p.cubicTo(cp1.x, cp1.y, cp2.x, cp2.y, p3.x, p3.y);
//cairo_curve_to( cr, cp1.x, cp1.y, cp2.x, cp2.y, p3.x, p3.y );
_curvePoints.pop_front();
}
break;
case ofPath::Command::bezierTo:
_curvePoints.clear();
p.cubicTo(c->cp1.x, c->cp1.y, c->cp2.x, c->cp2.y, c->to.x, c->to.y);
break;
case ofPath::Command::quadBezierTo:
_curvePoints.clear();
p.cubicTo(c->cp1.x, c->cp1.y, c->cp2.x, c->cp2.y, c->to.x, c->to.y);
break;
case ofPath::Command::arc:
ofLog(OF_LOG_WARNING, "Arcs are not implemented in the ofxShivaRenderer yet. Sorry :-(");
break;
case ofPath::Command::arcNegative:
ofLog(OF_LOG_WARNING, "Arcs are not implemented in the ofxShivaRenderer yet. Sorry :-(");
break;
case ofPath::Command::close:
p.close();
break;
}
i++;
}
}
void ofxShivaVGRenderer::drawCircle(float x, float y, float z, float radius)
{
drawEllipse(x, y, z, radius*2, radius*2);
}
void ofxShivaVGRenderer::drawEllipse(float x, float y, float z, float width, float height)
{
ofColor c = ofGetStyle().color;
_vg.setFillColor(c.r, c.g, c.b, c.a);
simpleVGPath p;
p.ellipse(x, y, width, height);
if (z != 0.0f)
{
pushMatrix();
translate(0, 0, z);
}
_vg.fillPath(p);
if (z != 0.0f)
{
pushMatrix();
}
}
void ofxShivaVGRenderer::drawLine(float x1, float y1, float z1, float x2, float y2, float z2)
{
ofStyle style = ofGetStyle();
_vg.setStrokeWidth(style.lineWidth);
ofColor c = style.color;
_vg.setStrokeColor(c.r, c.g, c.b, c.a);
simpleVGPath p;
p.moveTo(x1, y1);
p.lineTo(x2, y2);
_vg.strokePath(p);
}
<commit_msg>fixed bug when moveTo and curveTo commands where combined<commit_after>/*
* ofxShivaVG
* A 2d rendering library for openFrameworks, based on the ShivaVG library
* by Bjørn Gunnar Staal
*
* This library 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 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library in the file COPYING;
* if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include "ofxShivaVGRenderer.h"
#include "vgu.h"
#include "simpleVGPath.h"
// TODO: Implement resize!
ofxShivaVGRenderer::ofxShivaVGRenderer ()
{
_vg.create(ofGetWidth(), ofGetHeight());
}
void ofxShivaVGRenderer::setLineCapStyle(VGCapStyle cap)
{
_vg.setStrokeCapStyle(cap);
}
void ofxShivaVGRenderer::setLineJoinStyle(VGJoinStyle join)
{
_vg.setStrokeJoinStyle(join);
}
VGCapStyle ofxShivaVGRenderer::getLineCapStyle()
{
return _vg.getStrokeCapStyle();
}
VGJoinStyle ofxShivaVGRenderer::getLineJoinStyle()
{
return _vg.getStrokeJoinStyle();
}
void ofxShivaVGRenderer::background(const ofColor & c)
{
_bgColor = c;
glClearColor(_bgColor[0],_bgColor[1],_bgColor[2], _bgColor[3]);
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
}
// --------------------------------------------
// DRAWING
// --------------------------------------------
void ofxShivaVGRenderer::draw(ofPolyline & poly)
{
ofStyle style = ofGetStyle();
_vg.setStrokeWidth(style.lineWidth);
ofColor c = style.color;
_vg.setStrokeColor(c.r, c.g, c.b, c.a);
simpleVGPath p;
vector<ofVec3f> &verts = poly.getVertices();
p.moveTo(verts[0].x, verts[0].y);
for (vector<ofVec3f>::iterator v = verts.begin()+1; v != verts.end(); ++v)
{
p.lineTo(v->x, v->y);
}
if(poly.isClosed())
{
p.close();
}
_vg.strokePath(p);
}
void ofxShivaVGRenderer::draw(ofPath &path)
{
ofStyle style = ofGetStyle();
// TODO: fill or stroke?
// vector<ofSubPath> & paths = path.getSubPaths();
simpleVGPath p;
_doDrawPath(path, p);
ofColor prevColor;
if(path.getUseShapeColor()) prevColor = style.color;
ofColor c = style.color;
if (path.isFilled())
{
if (path.getUseShapeColor())
{
c = path.getFillColor();
}
_vg.setFillColor(c.r, c.g, c.b, c.a);
_vg.fillPath(p);
}
if (path.hasOutline())
{
if (path.getUseShapeColor())
{
c = path.getStrokeColor();
}
_vg.setStrokeColor(c.r, c.g, c.b, c.a);
_vg.setStrokeWidth(path.getStrokeWidth());
_vg.strokePath(p);
}
if(path.getUseShapeColor()) setColor(prevColor);
}
void ofxShivaVGRenderer::_doDrawPath(ofPath &path, simpleVGPath &p)
{
const vector<ofPath::Command> &commands = path.getCommands();
int i = 0;
for(vector<ofPath::Command>::const_iterator c = commands.begin(); c != commands.end(); ++c)
{
switch(c->type)
{
case ofPath::Command::moveTo:
p.moveTo(c->to.x, c->to.y);
_curvePoints.clear();
_curvePoints.push_back(c->to);
break;
case ofPath::Command::lineTo:
_curvePoints.clear();
p.lineTo(c->to.x, c->to.y);
break;
case ofPath::Command::curveTo:
_curvePoints.push_back(c->to);
//code from ofCairoRenderer to convert from catmull rom to bezier
if(_curvePoints.size() == 4)
{
ofPoint p1=_curvePoints[0];
ofPoint p2=_curvePoints[1];
ofPoint p3=_curvePoints[2];
ofPoint p4=_curvePoints[3];
ofPoint cp1 = p2 + ( p3 - p1 ) * (1.0/6);
ofPoint cp2 = p3 + ( p2 - p4 ) * (1.0/6);
p.cubicTo(cp1.x, cp1.y, cp2.x, cp2.y, p3.x, p3.y);
//cairo_curve_to( cr, cp1.x, cp1.y, cp2.x, cp2.y, p3.x, p3.y );
_curvePoints.pop_front();
}
break;
case ofPath::Command::bezierTo:
_curvePoints.clear();
p.cubicTo(c->cp1.x, c->cp1.y, c->cp2.x, c->cp2.y, c->to.x, c->to.y);
break;
case ofPath::Command::quadBezierTo:
_curvePoints.clear();
p.cubicTo(c->cp1.x, c->cp1.y, c->cp2.x, c->cp2.y, c->to.x, c->to.y);
break;
case ofPath::Command::arc:
ofLog(OF_LOG_WARNING, "Arcs are not implemented in the ofxShivaRenderer yet. Sorry :-(");
break;
case ofPath::Command::arcNegative:
ofLog(OF_LOG_WARNING, "Arcs are not implemented in the ofxShivaRenderer yet. Sorry :-(");
break;
case ofPath::Command::close:
p.close();
break;
}
i++;
}
}
void ofxShivaVGRenderer::drawCircle(float x, float y, float z, float radius)
{
drawEllipse(x, y, z, radius*2, radius*2);
}
void ofxShivaVGRenderer::drawEllipse(float x, float y, float z, float width, float height)
{
ofColor c = ofGetStyle().color;
_vg.setFillColor(c.r, c.g, c.b, c.a);
simpleVGPath p;
p.ellipse(x, y, width, height);
if (z != 0.0f)
{
pushMatrix();
translate(0, 0, z);
}
_vg.fillPath(p);
if (z != 0.0f)
{
pushMatrix();
}
}
void ofxShivaVGRenderer::drawLine(float x1, float y1, float z1, float x2, float y2, float z2)
{
ofStyle style = ofGetStyle();
_vg.setStrokeWidth(style.lineWidth);
ofColor c = style.color;
_vg.setStrokeColor(c.r, c.g, c.b, c.a);
simpleVGPath p;
p.moveTo(x1, y1);
p.lineTo(x2, y2);
_vg.strokePath(p);
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.