commit
stringlengths 40
40
| old_file
stringlengths 2
205
| new_file
stringlengths 2
205
| old_contents
stringlengths 0
32.9k
| new_contents
stringlengths 1
38.9k
| subject
stringlengths 3
9.4k
| message
stringlengths 6
9.84k
| lang
stringlengths 3
13
| license
stringclasses 13
values | repos
stringlengths 6
115k
|
---|---|---|---|---|---|---|---|---|---|
d79db5eac05172256364f082b01788b192b92562
|
common_types/src/common_types_serialize.cpp
|
common_types/src/common_types_serialize.cpp
|
/// @file common_types_serialize.cpp
/// @brief Various common types serialization implementation
/// @author uentity
/// @version
/// @date 27.01.2012
/// @copyright This source code is released under the terms of
/// the BSD License. See LICENSE for more details.
#include "common_types_serialize.h"
#include "table.h"
#include "prop.h"
#include <boost/serialization/vector.hpp>
#include <boost/serialization/string.hpp>
using namespace blue_sky;
namespace boser = boost::serialization;
//BLUE_SKY_CLASS_SRZ_FCN_DECL(serialize, blue_sky::table)
//BLUE_SKY_CLASS_SRZ_FCN_DECL(serialize, blue_sky::prop)
//BLUE_SKY_CLASS_SRZ_FCN_DECL_T(serialize, blue_sky::vartype_table, 1)
/*-----------------------------------------------------------------
* serialize table_iface
*----------------------------------------------------------------*/
BLUE_SKY_CLASS_SRZ_FCN_BEGIN(save, table)
// dump all info to string and save it
ar << (const std::string&)t.to_str();
BLUE_SKY_CLASS_SRZ_FCN_END
BLUE_SKY_CLASS_SRZ_FCN_BEGIN(load, table)
// dump all info to string and save it
std::string prop_data;
ar >> prop_data;
t.from_str(prop_data);
BLUE_SKY_CLASS_SRZ_FCN_END
BLUE_SKY_CLASS_SRZ_FCN_BEGIN(serialize, table)
boser::bs_void_cast_register(
static_cast< table* >(NULL),
static_cast< table_iface* >(NULL)
);
boser::split_free(ar, t, version);
BLUE_SKY_CLASS_SRZ_FCN_END
//BLUE_SKY_CLASS_SERIALIZE_SPLIT(table_iface)
// instantiate code using _BYNAME macro
BOOST_SERIALIZATION_ASSUME_ABSTRACT(table_iface)
BLUE_SKY_TYPE_SERIALIZE_IMPL(table)
//BLUE_SKY_TYPE_SERIALIZE_IMPL_BYNAME(table_iface, "table")
/*-----------------------------------------------------------------
* serialize prop_iface
*----------------------------------------------------------------*/
BLUE_SKY_CLASS_SRZ_FCN_BEGIN(save, prop)
// dump all info to string and save it
ar << (const std::string&)t.to_str();
BLUE_SKY_CLASS_SRZ_FCN_END
BLUE_SKY_CLASS_SRZ_FCN_BEGIN(load, prop)
// dump all info to string and save it
std::string prop_data;
ar >> prop_data;
t.from_str(prop_data);
BLUE_SKY_CLASS_SRZ_FCN_END
BLUE_SKY_CLASS_SRZ_FCN_BEGIN(serialize, prop)
boser::bs_void_cast_register(
static_cast< prop* >(NULL),
static_cast< prop_iface* >(NULL)
);
boser::split_free(ar, t, version);
BLUE_SKY_CLASS_SRZ_FCN_END
//BLUE_SKY_CLASS_SERIALIZE_SPLIT(prop_iface)
// instantiate code using _BYNAME macro
BOOST_SERIALIZATION_ASSUME_ABSTRACT(prop_iface)
BLUE_SKY_TYPE_SERIALIZE_IMPL(prop)
//BLUE_SKY_TYPE_SERIALIZE_IMPL_BYNAME(prop, "prop")
/*-----------------------------------------------------------------
* serialize vartype_table_iface
*----------------------------------------------------------------*/
BLUE_SKY_CLASS_SRZ_FCN_BEGIN_T(save, vartype_table, 1)
// save columns number
t_long num_cols = t.get_n_cols();
ar << num_cols;
// save data
for(t_long i = 0; i < num_cols; ++i) {
ar << (const std::string&)t.get_col_name(i);
ar << const_cast< type& >(t).get_col_vector(i);
}
BLUE_SKY_CLASS_SRZ_FCN_END
BLUE_SKY_CLASS_SRZ_FCN_BEGIN_T(load, vartype_table, 1)
// load columns number
t_long num_cols;
ar >> num_cols;
t.init(num_cols);
// buffer column vector for adding columns
typename type::sp_var_type_array_t column = BS_KERNEL.create_object(
type::var_type_array_t::bs_type()
);
// load data
typename type::vector_t v;
std::string col_name;
for(t_long i = 0; i < num_cols; ++i) {
ar >> col_name;
ar >> v;
// column = v
if(column->size() != v.size())
column->resize(v.size());
if(column->size()) {
std::copy(v.begin(), v.end(), column->begin());
// add column
t.add_col_vector(i, col_name, column);
}
BLUE_SKY_CLASS_SRZ_FCN_END
BLUE_SKY_CLASS_SRZ_FCN_BEGIN_T(serialize, vartype_table, 1)
typedef typename type::vector_t::value_type var_type_t;
boser::bs_void_cast_register(
static_cast< type* >(NULL),
static_cast< vartype_table_iface< var_type_t >* >(NULL)
);
boser::split_free(ar, t, version);
BLUE_SKY_CLASS_SRZ_FCN_END
//BLUE_SKY_CLASS_SERIALIZE_SPLIT_T(vartype_table_iface, 1)
BOOST_SERIALIZATION_ASSUME_ABSTRACT(vartype_table_iface)
//BLUE_SKY_TYPE_SERIALIZE_IMPL_T(vartype_table, 1)
// instantiate for t_float
BLUE_SKY_TYPE_SERIALIZE_IMPL_T(vartype_table, t_float)
|
/// @file common_types_serialize.cpp
/// @brief Various common types serialization implementation
/// @author uentity
/// @version
/// @date 27.01.2012
/// @copyright This source code is released under the terms of
/// the BSD License. See LICENSE for more details.
#include "common_types_serialize.h"
#include "table.h"
#include "prop.h"
#include <boost/serialization/vector.hpp>
#include <boost/serialization/string.hpp>
using namespace blue_sky;
namespace boser = boost::serialization;
//BLUE_SKY_CLASS_SRZ_FCN_DECL(serialize, blue_sky::table)
//BLUE_SKY_CLASS_SRZ_FCN_DECL(serialize, blue_sky::prop)
//BLUE_SKY_CLASS_SRZ_FCN_DECL_T(serialize, blue_sky::vartype_table, 1)
/*-----------------------------------------------------------------
* serialize table_iface
*----------------------------------------------------------------*/
BLUE_SKY_CLASS_SRZ_FCN_BEGIN(save, table)
// dump all info to string and save it
ar << (const std::string&)t.to_str();
BLUE_SKY_CLASS_SRZ_FCN_END
BLUE_SKY_CLASS_SRZ_FCN_BEGIN(load, table)
// dump all info to string and save it
std::string prop_data;
ar >> prop_data;
t.from_str(prop_data);
BLUE_SKY_CLASS_SRZ_FCN_END
BLUE_SKY_CLASS_SRZ_FCN_BEGIN(serialize, table)
boser::bs_void_cast_register(
static_cast< table* >(NULL),
static_cast< table_iface* >(NULL)
);
boser::split_free(ar, t, version);
BLUE_SKY_CLASS_SRZ_FCN_END
//BLUE_SKY_CLASS_SERIALIZE_SPLIT(table_iface)
// instantiate code using _BYNAME macro
BOOST_SERIALIZATION_ASSUME_ABSTRACT(table_iface)
BLUE_SKY_TYPE_SERIALIZE_IMPL(table)
//BLUE_SKY_TYPE_SERIALIZE_IMPL_BYNAME(table_iface, "table")
/*-----------------------------------------------------------------
* serialize prop_iface
*----------------------------------------------------------------*/
BLUE_SKY_CLASS_SRZ_FCN_BEGIN(save, prop)
// dump all info to string and save it
ar << (const std::string&)t.to_str();
BLUE_SKY_CLASS_SRZ_FCN_END
BLUE_SKY_CLASS_SRZ_FCN_BEGIN(load, prop)
// dump all info to string and save it
std::string prop_data;
ar >> prop_data;
t.from_str(prop_data);
BLUE_SKY_CLASS_SRZ_FCN_END
BLUE_SKY_CLASS_SRZ_FCN_BEGIN(serialize, prop)
boser::bs_void_cast_register(
static_cast< prop* >(NULL),
static_cast< prop_iface* >(NULL)
);
boser::split_free(ar, t, version);
BLUE_SKY_CLASS_SRZ_FCN_END
//BLUE_SKY_CLASS_SERIALIZE_SPLIT(prop_iface)
// instantiate code using _BYNAME macro
BOOST_SERIALIZATION_ASSUME_ABSTRACT(prop_iface)
BLUE_SKY_TYPE_SERIALIZE_IMPL(prop)
//BLUE_SKY_TYPE_SERIALIZE_IMPL_BYNAME(prop, "prop")
/*-----------------------------------------------------------------
* serialize vartype_table_iface
*----------------------------------------------------------------*/
BLUE_SKY_CLASS_SRZ_FCN_BEGIN_T(save, vartype_table, 1)
// save columns number
t_long num_cols = t.get_n_cols();
ar << num_cols;
// save data
for(t_long i = 0; i < num_cols; ++i) {
ar << (const std::string&)t.get_col_name(i);
ar << const_cast< type& >(t).get_col_vector(i);
}
BLUE_SKY_CLASS_SRZ_FCN_END
BLUE_SKY_CLASS_SRZ_FCN_BEGIN_T(load, vartype_table, 1)
// load columns number
t_long num_cols;
ar >> num_cols;
t.init(num_cols);
// buffer column vector for adding columns
typename type::sp_var_type_array_t column = BS_KERNEL.create_object(
type::var_type_array_t::bs_type()
);
// load data
typename type::vector_t v;
std::string col_name;
for(t_long i = 0; i < num_cols; ++i) {
ar >> col_name;
ar >> v;
// column = v
if(column->size() != v.size())
column->resize(v.size());
if(column->size())
std::copy(v.begin(), v.end(), column->begin());
// add column
t.add_col_vector(i, col_name, column);
}
BLUE_SKY_CLASS_SRZ_FCN_END
BLUE_SKY_CLASS_SRZ_FCN_BEGIN_T(serialize, vartype_table, 1)
typedef typename type::vector_t::value_type var_type_t;
boser::bs_void_cast_register(
static_cast< type* >(NULL),
static_cast< vartype_table_iface< var_type_t >* >(NULL)
);
boser::split_free(ar, t, version);
BLUE_SKY_CLASS_SRZ_FCN_END
//BLUE_SKY_CLASS_SERIALIZE_SPLIT_T(vartype_table_iface, 1)
BOOST_SERIALIZATION_ASSUME_ABSTRACT(vartype_table_iface)
//BLUE_SKY_TYPE_SERIALIZE_IMPL_T(vartype_table, 1)
// instantiate for t_float
BLUE_SKY_TYPE_SERIALIZE_IMPL_T(vartype_table, t_float)
|
fix prev commit
|
SRZ: fix prev commit
|
C++
|
bsd-3-clause
|
bs-eagle/bs-eagle,bs-eagle/bs-eagle,bs-eagle/bs-eagle
|
f48c4b37ad24e517c452359bb7786f63734d2961
|
copasi/function/CEvaluationNodeObject.cpp
|
copasi/function/CEvaluationNodeObject.cpp
|
// Copyright (C) 2010 - 2014 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.
// Copyright (C) 2008 - 2009 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., EML Research, gGmbH, University of Heidelberg,
// and The University of Manchester.
// All rights reserved.
// Copyright (C) 2005 - 2007 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.
#include "copasi.h"
#include "CEvaluationNode.h"
#include "CEvaluationTree.h"
#include "CExpression.h"
#include "report/CCopasiObjectName.h"
#include "report/CCopasiObject.h"
#include "report/CCopasiContainer.h"
#include "model/CModel.h"
#include "CopasiDataModel/CCopasiDataModel.h"
#include "math/CMathObject.h"
#include "sbml/math/ASTNode.h"
#include "sbml/SBase.h"
#include "sbml/SBMLTypeCodes.h"
#include "sbml/Compartment.h"
#include "sbml/Species.h"
#include "sbml/Parameter.h"
#include "sbml/Reaction.h"
CEvaluationNodeObject::CEvaluationNodeObject():
CEvaluationNode(CEvaluationNode::INVALID, ""),
mpObject(NULL),
mRegisteredObjectCN("")
{mPrecedence = PRECEDENCE_NUMBER;}
CEvaluationNodeObject::CEvaluationNodeObject(const SubType & subType,
const Data & data):
CEvaluationNode((Type)(CEvaluationNode::OBJECT | subType), data),
mpObject(NULL),
mRegisteredObjectCN(data.substr(1, data.length() - 2))
{
mPrecedence = PRECEDENCE_NUMBER;
}
CEvaluationNodeObject::CEvaluationNodeObject(const C_FLOAT64 * pValue):
CEvaluationNode((Type)(CEvaluationNode::OBJECT | POINTER), "pointer"),
mpObject(NULL),
mRegisteredObjectCN("")
{
mPrecedence = PRECEDENCE_NUMBER;
mpValue = pValue;
mData = pointerToString(pValue);
}
CEvaluationNodeObject::CEvaluationNodeObject(const CEvaluationNodeObject & src):
CEvaluationNode(src),
mpObject(src.mpObject),
mRegisteredObjectCN(src.mRegisteredObjectCN)
{
mpValue = src.mpValue;
}
CEvaluationNodeObject::~CEvaluationNodeObject() {}
bool CEvaluationNodeObject::compile(const CEvaluationTree * pTree)
{
mpObject = NULL;
mpValue = NULL;
switch ((int) subType(mType))
{
case CN:
{
const CExpression * pExpression = dynamic_cast< const CExpression * >(pTree);
if (!pExpression) return false;
mpObject =
pExpression->getNodeObject(mRegisteredObjectCN);
const CCopasiObject * pDataObject = dynamic_cast< const CCopasiObject * >(mpObject);
if (pDataObject != NULL)
{
// We may have some container objects for which the value is an included
// reference. For the math model to work this needs to be corrected.
const CObjectInterface * pObject = pDataObject->getValueObject();
if (mpObject != pObject && pObject != NULL)
{
mpObject = pObject;
mRegisteredObjectCN = mpObject->getCN();
mData = getData();
}
if (pDataObject->isValueDbl())
{
mpValue = (C_FLOAT64 *) mpObject->getValuePointer();
}
}
else if (mpObject != NULL)
{
mpValue = (C_FLOAT64 *) mpObject->getValuePointer();
}
if (mpValue == NULL)
{
mValue = std::numeric_limits<C_FLOAT64>::quiet_NaN();
mpValue = &mValue;
return false;
}
mData = "<" + mRegisteredObjectCN + ">";
}
break;
case POINTER:
// We need to convert the data into a pointer
{
mpValue = (const C_FLOAT64 *) stringToPointer(mData);
}
break;
case INVALID:
break;
}
return (getChild() == NULL); // We must not have any children.
}
const CEvaluationNode::Data & CEvaluationNodeObject::getData() const
{
static std::string data;
switch ((int) subType(mType))
{
case CN:
return data = "<" + mRegisteredObjectCN + ">";
break;
case POINTER:
return mData;
break;
}
return mData;
}
bool CEvaluationNodeObject::setData(const Data & data)
{
mData = data;
if ((int) subType(mType) == (int) CN)
mRegisteredObjectCN = data.substr(1, data.length() - 2);
return true;
}
// virtual
std::string CEvaluationNodeObject::getInfix(const std::vector< std::string > & /* children */) const
{
switch ((int) subType(mType))
{
case CN:
return "<" + mRegisteredObjectCN + ">";
break;
case POINTER:
return mData;
break;
}
return mData;
}
#if 0
std::string CEvaluationNodeObject::getDisplayString(const CEvaluationTree * pTree) const
{
const CExpression * pExpression = dynamic_cast< const CExpression * >(pTree);
if (!pExpression) return false;
const CCopasiObject * pObject =
CCopasiContainer::ObjectFromCN(mRegisteredObjectCN);
if (pObject == NULL) return "<" + mRegisteredObjectCN + ">";
return "<" + pObject->getObjectDisplayName() + ">";
}
#endif
// virtual
std::string CEvaluationNodeObject::getDisplayString(const std::vector< std::string > & /* children */) const
{
const CCopasiObject* object = dynamic_cast<const CCopasiObject*>(mpObject);
if (object != NULL)
return object->getObjectDisplayName();
return "<" + mRegisteredObjectCN + ">";
}
// virtual
std::string CEvaluationNodeObject::getCCodeString(const std::vector< std::string > & /* children */) const
{
return mData;
}
// virtual
std::string CEvaluationNodeObject::getBerkeleyMadonnaString(const std::vector< std::string > & /* children */) const
{
return mData;
}
// virtual
std::string CEvaluationNodeObject::getXPPString(const std::vector< std::string > & /* children */) const
{
return mData;
}
// static
CEvaluationNode * CEvaluationNodeObject::fromAST(const ASTNode * pASTNode, const std::vector< CEvaluationNode * > & children)
{
assert(pASTNode->getNumChildren() == children.size());
CEvaluationNodeObject* pNode = NULL;
switch (pASTNode->getType())
{
case AST_NAME_AVOGADRO:
case AST_NAME_TIME:
case AST_NAME:
pNode = new CEvaluationNodeObject(CN, CCopasiObjectName(std::string("<") + pASTNode->getName() + std::string(">")));
break;
default:
break;
}
return pNode;
}
ASTNode* CEvaluationNodeObject::toAST(const CCopasiDataModel* pDataModel) const
{
ASTNode* node = new ASTNode();
node->setType(AST_NAME);
if (mRegisteredObjectCN == "rateOf")
{
node->setType(AST_FUNCTION);
const CEvaluationNode* child = dynamic_cast<const CEvaluationNode*>(this->getChild());
if (child == NULL) fatalError();
const CEvaluationNodeObject* sibling = dynamic_cast<const CEvaluationNodeObject*>(this->getChild()->getSibling());
if (sibling == NULL) fatalError();
node->setName(sibling->getObjectCN().c_str());
node->addChild(child->toAST(pDataModel));
return node;
}
// since I can not get the model in which this node is located, I just
// assume that it will always be the current global model.
const CCopasiObject* pOrigObject = pDataModel->getDataObject(mRegisteredObjectCN);
if (pOrigObject == NULL)
{
node->setName(mRegisteredObjectCN.c_str());
return node;
}
const CCopasiObject* pObject = pOrigObject;
// if it is a reference, we get the parent of the reference
if (pObject->isReference())
{
pObject = pObject->getObjectParent();
}
const CModelEntity* pME = dynamic_cast<const CModelEntity*>(pObject);
if (pME != NULL)
{
const CModel* pModel = dynamic_cast<const CModel*>(pME);
if (pModel != NULL)
{
#if LIBSBML_VERSION >= 40100
if (pOrigObject->getObjectName() == "Avogadro Constant")
{
node->setType(AST_NAME_AVOGADRO);
node->setName("avogadro");
}
else
{
#endif // LIBSBML_VERSION >= 40100
node->setType(AST_NAME_TIME);
node->setName("time");
if (pModel->getInitialTime() != 0.0)
{
CCopasiMessage(CCopasiMessage::WARNING, MCSBML + 1);
}
#if LIBSBML_VERSION >= 40100
}
#endif // LIBSBML_VERSION >= 40100
}
else
{
node->setName(pME->getSBMLId().c_str());
}
}
else
{
const CCopasiParameter* pPara = dynamic_cast<const CCopasiParameter*>(pObject);
if (pPara != NULL)
{
// now we have to use the common name as the name for the
// node since we need to be able to identify local parameters
// in arbitrary expressions for the export
node->setName(pPara->getCN().c_str());
}
else
{
const CReaction* pReaction = dynamic_cast<const CReaction*>(pObject);
if (pReaction)
{
node->setName(pReaction->getSBMLId().c_str());
}
else
{
fatalError();
}
}
}
return node;
}
const CRegisteredObjectName & CEvaluationNodeObject::getObjectCN() const
{return mRegisteredObjectCN;}
const CObjectInterface * CEvaluationNodeObject::getObjectInterfacePtr() const
{
return mpObject;
}
const C_FLOAT64 * CEvaluationNodeObject::getObjectValuePtr() const
{
return mpValue;
}
void CEvaluationNodeObject::setObjectValuePtr(C_FLOAT64 * pObjectValue)
{
assert(pObjectValue);
switch ((int) subType(mType))
{
case CN:
break;
case POINTER:
if (mpValue != pObjectValue)
{
mpValue = pObjectValue;
mData = pointerToString(mpValue);
}
break;
}
return;
}
#include "utilities/copasimathml.h"
// virtual
std::string CEvaluationNodeObject::getMMLString(const std::vector< std::string > & /* children */ ,
bool /* expand */,
const std::vector< std::vector< std::string > > & /* variables */) const
{
std::ostringstream out;
const CCopasiObject * pDataObject = CObjectInterface::DataObject(mpObject);
out << CMathMl::getMMLName(pDataObject) << std::endl;
return out.str();
}
|
// Copyright (C) 2010 - 2014 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.
// Copyright (C) 2008 - 2009 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., EML Research, gGmbH, University of Heidelberg,
// and The University of Manchester.
// All rights reserved.
// Copyright (C) 2005 - 2007 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.
#include "copasi.h"
#include "CEvaluationNode.h"
#include "CEvaluationTree.h"
#include "CExpression.h"
#include "report/CCopasiObjectName.h"
#include "report/CCopasiObject.h"
#include "report/CCopasiContainer.h"
#include "model/CModel.h"
#include "CopasiDataModel/CCopasiDataModel.h"
#include "math/CMathObject.h"
#include "sbml/math/ASTNode.h"
#include "sbml/SBase.h"
#include "sbml/SBMLTypeCodes.h"
#include "sbml/Compartment.h"
#include "sbml/Species.h"
#include "sbml/Parameter.h"
#include "sbml/Reaction.h"
CEvaluationNodeObject::CEvaluationNodeObject():
CEvaluationNode(CEvaluationNode::INVALID, ""),
mpObject(NULL),
mRegisteredObjectCN("")
{mPrecedence = PRECEDENCE_NUMBER;}
CEvaluationNodeObject::CEvaluationNodeObject(const SubType & subType,
const Data & data):
CEvaluationNode((Type)(CEvaluationNode::OBJECT | subType), data),
mpObject(NULL),
mRegisteredObjectCN(data.substr(1, data.length() - 2))
{
mPrecedence = PRECEDENCE_NUMBER;
}
CEvaluationNodeObject::CEvaluationNodeObject(const C_FLOAT64 * pValue):
CEvaluationNode((Type)(CEvaluationNode::OBJECT | POINTER), "pointer"),
mpObject(NULL),
mRegisteredObjectCN("")
{
mPrecedence = PRECEDENCE_NUMBER;
mpValue = pValue;
mData = pointerToString(pValue);
}
CEvaluationNodeObject::CEvaluationNodeObject(const CEvaluationNodeObject & src):
CEvaluationNode(src),
mpObject(src.mpObject),
mRegisteredObjectCN(src.mRegisteredObjectCN)
{
mpValue = src.mpValue;
}
CEvaluationNodeObject::~CEvaluationNodeObject() {}
bool CEvaluationNodeObject::compile(const CEvaluationTree * pTree)
{
mpObject = NULL;
mpValue = NULL;
switch ((int) subType(mType))
{
case CN:
{
const CExpression * pExpression = dynamic_cast< const CExpression * >(pTree);
if (!pExpression) return false;
mpObject =
pExpression->getNodeObject(mRegisteredObjectCN);
const CCopasiObject * pDataObject = dynamic_cast< const CCopasiObject * >(mpObject);
if (pDataObject != NULL)
{
// We may have some container objects for which the value is an included
// reference. For the math model to work this needs to be corrected.
const CObjectInterface * pObject = pDataObject->getValueObject();
if(!pObject)
return false;
if (mpObject != pObject && pObject != NULL)
{
mpObject = pObject;
mRegisteredObjectCN = mpObject->getCN();
mData = getData();
}
if (pDataObject->isValueDbl())
{
mpValue = (C_FLOAT64 *) mpObject->getValuePointer();
}
}
else if (mpObject != NULL)
{
mpValue = (C_FLOAT64 *) mpObject->getValuePointer();
}
if (mpValue == NULL)
{
mValue = std::numeric_limits<C_FLOAT64>::quiet_NaN();
mpValue = &mValue;
return false;
}
mData = "<" + mRegisteredObjectCN + ">";
}
break;
case POINTER:
// We need to convert the data into a pointer
{
mpValue = (const C_FLOAT64 *) stringToPointer(mData);
}
break;
case INVALID:
break;
}
return (getChild() == NULL); // We must not have any children.
}
const CEvaluationNode::Data & CEvaluationNodeObject::getData() const
{
static std::string data;
switch ((int) subType(mType))
{
case CN:
return data = "<" + mRegisteredObjectCN + ">";
break;
case POINTER:
return mData;
break;
}
return mData;
}
bool CEvaluationNodeObject::setData(const Data & data)
{
mData = data;
if ((int) subType(mType) == (int) CN)
mRegisteredObjectCN = data.substr(1, data.length() - 2);
return true;
}
// virtual
std::string CEvaluationNodeObject::getInfix(const std::vector< std::string > & /* children */) const
{
switch ((int) subType(mType))
{
case CN:
return "<" + mRegisteredObjectCN + ">";
break;
case POINTER:
return mData;
break;
}
return mData;
}
#if 0
std::string CEvaluationNodeObject::getDisplayString(const CEvaluationTree * pTree) const
{
const CExpression * pExpression = dynamic_cast< const CExpression * >(pTree);
if (!pExpression) return false;
const CCopasiObject * pObject =
CCopasiContainer::ObjectFromCN(mRegisteredObjectCN);
if (pObject == NULL) return "<" + mRegisteredObjectCN + ">";
return "<" + pObject->getObjectDisplayName() + ">";
}
#endif
// virtual
std::string CEvaluationNodeObject::getDisplayString(const std::vector< std::string > & /* children */) const
{
const CCopasiObject* object = dynamic_cast<const CCopasiObject*>(mpObject);
if (object != NULL)
return object->getObjectDisplayName();
return "<" + mRegisteredObjectCN + ">";
}
// virtual
std::string CEvaluationNodeObject::getCCodeString(const std::vector< std::string > & /* children */) const
{
return mData;
}
// virtual
std::string CEvaluationNodeObject::getBerkeleyMadonnaString(const std::vector< std::string > & /* children */) const
{
return mData;
}
// virtual
std::string CEvaluationNodeObject::getXPPString(const std::vector< std::string > & /* children */) const
{
return mData;
}
// static
CEvaluationNode * CEvaluationNodeObject::fromAST(const ASTNode * pASTNode, const std::vector< CEvaluationNode * > & children)
{
assert(pASTNode->getNumChildren() == children.size());
CEvaluationNodeObject* pNode = NULL;
switch (pASTNode->getType())
{
case AST_NAME_AVOGADRO:
case AST_NAME_TIME:
case AST_NAME:
pNode = new CEvaluationNodeObject(CN, CCopasiObjectName(std::string("<") + pASTNode->getName() + std::string(">")));
break;
default:
break;
}
return pNode;
}
ASTNode* CEvaluationNodeObject::toAST(const CCopasiDataModel* pDataModel) const
{
ASTNode* node = new ASTNode();
node->setType(AST_NAME);
if (mRegisteredObjectCN == "rateOf")
{
node->setType(AST_FUNCTION);
const CEvaluationNode* child = dynamic_cast<const CEvaluationNode*>(this->getChild());
if (child == NULL) fatalError();
const CEvaluationNodeObject* sibling = dynamic_cast<const CEvaluationNodeObject*>(this->getChild()->getSibling());
if (sibling == NULL) fatalError();
node->setName(sibling->getObjectCN().c_str());
node->addChild(child->toAST(pDataModel));
return node;
}
// since I can not get the model in which this node is located, I just
// assume that it will always be the current global model.
const CCopasiObject* pOrigObject = pDataModel->getDataObject(mRegisteredObjectCN);
if (pOrigObject == NULL)
{
node->setName(mRegisteredObjectCN.c_str());
return node;
}
const CCopasiObject* pObject = pOrigObject;
// if it is a reference, we get the parent of the reference
if (pObject->isReference())
{
pObject = pObject->getObjectParent();
}
const CModelEntity* pME = dynamic_cast<const CModelEntity*>(pObject);
if (pME != NULL)
{
const CModel* pModel = dynamic_cast<const CModel*>(pME);
if (pModel != NULL)
{
#if LIBSBML_VERSION >= 40100
if (pOrigObject->getObjectName() == "Avogadro Constant")
{
node->setType(AST_NAME_AVOGADRO);
node->setName("avogadro");
}
else
{
#endif // LIBSBML_VERSION >= 40100
node->setType(AST_NAME_TIME);
node->setName("time");
if (pModel->getInitialTime() != 0.0)
{
CCopasiMessage(CCopasiMessage::WARNING, MCSBML + 1);
}
#if LIBSBML_VERSION >= 40100
}
#endif // LIBSBML_VERSION >= 40100
}
else
{
node->setName(pME->getSBMLId().c_str());
}
}
else
{
const CCopasiParameter* pPara = dynamic_cast<const CCopasiParameter*>(pObject);
if (pPara != NULL)
{
// now we have to use the common name as the name for the
// node since we need to be able to identify local parameters
// in arbitrary expressions for the export
node->setName(pPara->getCN().c_str());
}
else
{
const CReaction* pReaction = dynamic_cast<const CReaction*>(pObject);
if (pReaction)
{
node->setName(pReaction->getSBMLId().c_str());
}
else
{
fatalError();
}
}
}
return node;
}
const CRegisteredObjectName & CEvaluationNodeObject::getObjectCN() const
{return mRegisteredObjectCN;}
const CObjectInterface * CEvaluationNodeObject::getObjectInterfacePtr() const
{
return mpObject;
}
const C_FLOAT64 * CEvaluationNodeObject::getObjectValuePtr() const
{
return mpValue;
}
void CEvaluationNodeObject::setObjectValuePtr(C_FLOAT64 * pObjectValue)
{
assert(pObjectValue);
switch ((int) subType(mType))
{
case CN:
break;
case POINTER:
if (mpValue != pObjectValue)
{
mpValue = pObjectValue;
mData = pointerToString(mpValue);
}
break;
}
return;
}
#include "utilities/copasimathml.h"
// virtual
std::string CEvaluationNodeObject::getMMLString(const std::vector< std::string > & /* children */ ,
bool /* expand */,
const std::vector< std::vector< std::string > > & /* variables */) const
{
std::ostringstream out;
const CCopasiObject * pDataObject = CObjectInterface::DataObject(mpObject);
out << CMathMl::getMMLName(pDataObject) << std::endl;
return out.str();
}
|
add a null pointer check in object nodes
|
add a null pointer check in object nodes
|
C++
|
artistic-2.0
|
copasi/COPASI,copasi/COPASI,jonasfoe/COPASI,jonasfoe/COPASI,jonasfoe/COPASI,copasi/COPASI,copasi/COPASI,copasi/COPASI,copasi/COPASI,jonasfoe/COPASI,jonasfoe/COPASI,jonasfoe/COPASI,jonasfoe/COPASI,copasi/COPASI,copasi/COPASI,jonasfoe/COPASI,jonasfoe/COPASI,copasi/COPASI
|
2b527db90bdbce08a22e8042b9808310d0f407d2
|
src/App.cpp
|
src/App.cpp
|
#include "App.h"
#include "ProgramOptions.h"
#include <string>
#include <iomanip>
#include "FontInfo.h"
#include "utils/extractFileName.h"
#include "external/lodepng/lodepng.h"
#include "utils/getNumberLen.h"
std::vector<rbp::RectSize> App::getGlyphRectangles(const Glyphs &glyphs, const std::uint32_t additionalWidth, const std::uint32_t additionalHeight)
{
std::vector<rbp::RectSize> result;
for (const auto& kv : glyphs)
{
const auto& glyphInfo = kv.second;
if (!glyphInfo.isEmpty())
result.emplace_back(glyphInfo.width + additionalWidth, glyphInfo.height + additionalHeight, kv.first);
}
return result;
}
App::Glyphs App::collectGlyphInfo(const std::vector<ft::Font>& fonts, const std::set<std::uint32_t>& codes)
{
Glyphs result;
for (const auto& id : codes)
{
GlyphInfo glyphInfo;
for (size_t i = 0; i < fonts.size(); ++i)
{
if (fonts[i].isGlyphProvided(id))
{
ft::Font::GlyphMetrics glyphMetrics = fonts[i].renderGlyph(nullptr, 0, 0, 0, 0, id, 0);
glyphInfo.fontIndex = i;
glyphInfo.width = glyphMetrics.width;
glyphInfo.height = glyphMetrics.height;
glyphInfo.xAdvance = glyphMetrics.horiAdvance;
glyphInfo.xOffset = glyphMetrics.horiBearingX;
glyphInfo.yOffset = fonts[i].ascent - glyphMetrics.horiBearingY;
break;
}
}
//TODO: add more checks for glyph.
if (glyphInfo.fontIndex == -1)
{
std::cout << "warning: glyph " << id << " not found";
if (id == 65279)
std::cout << " (it looks like Unicode byte order mark (BOM))";
std::cout << "." << std::endl;
}
else
result[id] = glyphInfo;
}
return result;
}
std::uint32_t App::arrangeGlyphs(Glyphs& glyphs, const Config& config)
{
const auto additionalWidth = config.spacing.hor + config.padding.left + config.padding.right;
const auto additionalHeight = config.spacing.ver + config.padding.up + config.padding.down;
//TODO: check workAreaW,H
const auto workAreaW = config.textureSize.w - config.spacing.hor;
const auto workAreaH = config.textureSize.h - config.spacing.ver;
auto glyphRectangles = getGlyphRectangles(glyphs, additionalWidth, additionalHeight);
rbp::MaxRectsBinPack mrbp;
std::uint32_t pageCount = 0;
for (;;)
{
mrbp.Init(workAreaW, workAreaH);
std::vector<rbp::Rect> arrangedRectangles;
mrbp.Insert( glyphRectangles, arrangedRectangles, rbp::MaxRectsBinPack::RectBestAreaFit );
if ( arrangedRectangles.empty() )
{
if ( !glyphRectangles.empty() )
throw std::runtime_error("can not fit glyphs into texture");
break;
}
for ( const auto& r: arrangedRectangles )
{
glyphs[r.tag].x = r.x + config.spacing.hor;
glyphs[r.tag].y = r.y + config.spacing.ver;
glyphs[r.tag].page = pageCount;
}
++pageCount;
}
return pageCount;
}
void App::savePng(const std::string& fileName, const std::uint32_t* buffer, const std::uint32_t w, const std::uint32_t h, const bool withAlpha)
{
std::vector<std::uint8_t> png;
lodepng::State state;
state.encoder.add_id = 0; // Don't add LodePNG version chunk to save more bytes
state.encoder.auto_convert = 0;
state.info_png.color.colortype = withAlpha ? LCT_RGBA : LCT_RGB;
///state.encoder.text_compression = 1; //Not needed because we don't add text chunks, but this demonstrates another optimization setting
//state.encoder.zlibsettings.nicematch = 258; //Set this to the max possible, otherwise it can hurt compression
//state.encoder.zlibsettings.lazymatching = 1; //Definitely use lazy matching for better compression
//state.encoder.zlibsettings.windowsize = 32768; //Use maximum possible window size for best compression
auto error = lodepng::encode(png, reinterpret_cast<const unsigned char*>(buffer), w, h, state);
if (error)
throw std::runtime_error("png encoder error " + std::to_string(error) + ": " + lodepng_error_text(error));
error = lodepng::save_file(png, fileName);
if (error)
throw std::runtime_error("png save to file error " + std::to_string(error) + ": " + lodepng_error_text(error));
}
std::vector<std::string> App::renderTextures(const Glyphs& glyphs, const Config& config, const std::vector<ft::Font>& fonts, const std::uint32_t pageCount)
{
std::vector<std::string> fileNames;
//TODO: should we decrement pageCount before calculate?
const auto pageNameDigits = getNumberLen(pageCount);
for (std::uint32_t page = 0; page < pageCount; ++page)
{
std::vector<std::uint32_t> surface(config.textureSize.w * config.textureSize.h);
memset(&surface[0], 0, surface.size() * sizeof(std::uint32_t));
// Render every glyph
//TODO: do not repeat same glyphs (with same index)
for (const auto& kv: glyphs)
{
const auto& glyph = kv.second;
if (glyph.page != page)
continue;
if (!glyph.isEmpty())
{
const auto x = glyph.x + config.padding.left;
const auto y = glyph.y + config.padding.up;
fonts[glyph.fontIndex].renderGlyph(&surface[0], config.textureSize.w, config.textureSize.h, x, y, kv.first, config.color.getBGR());
}
}
if (!config.backgroundTransparent)
{
auto cur = surface.data();
const auto end = &surface.back();
const auto fgColor = config.color.getBGR();
const auto bgColor = config.backgroundColor.getBGR();
while (cur <= end)
{
const std::uint32_t a0 = (*cur) >> 24;
const std::uint32_t a1 = 256 - a0;
const std::uint32_t rb1 = (a1 * (bgColor & 0xFF00FF)) >> 8;
const std::uint32_t rb2 = (a0 * (fgColor & 0xFF00FF)) >> 8;
const std::uint32_t g1 = (a1 * (bgColor & 0x00FF00)) >> 8;
const std::uint32_t g2 = (a0 * (fgColor & 0x00FF00)) >> 8;
*cur = ((rb1 | rb2) & 0xFF00FF) + ((g1 | g2) & 0x00FF00);
++cur;
}
}
std::stringstream ss;
ss << config.output << "_" << std::setfill ('0') << std::setw(pageNameDigits) << page << ".png";
const auto fileName = ss.str();
fileNames.push_back(extractFileName(fileName));
savePng(fileName, &surface[0], config.textureSize.w, config.textureSize.h, config.backgroundTransparent);
}
return fileNames;
}
void App::writeFontInfoFile(const Glyphs& glyphs, const Config& config, const std::vector<ft::Font>& fonts, const std::vector<std::string>& fileNames)
{
FontInfo f;
f.info.face = fonts[0].getFamilyNameOr("unknown");
f.info.size = config.fontSize;
f.info.unicode = true;
f.info.aa = 1;
f.info.padding.up = static_cast<std::uint8_t>(config.padding.up);
f.info.padding.right = static_cast<std::uint8_t>(config.padding.right);
f.info.padding.down = static_cast<std::uint8_t>(config.padding.down);
f.info.padding.left = static_cast<std::uint8_t>(config.padding.left);
f.info.spacing.horizontal = static_cast<std::uint8_t>(config.spacing.hor);
f.info.spacing.vertical = static_cast<std::uint8_t>(config.spacing.ver);
f.common.lineHeight = static_cast<std::uint16_t>(fonts[0].lineskip);
f.common.base = static_cast<std::uint16_t>(fonts[0].ascent);
f.common.scaleW = static_cast<std::uint16_t>(config.textureSize.w);
f.common.scaleH = static_cast<std::uint16_t>(config.textureSize.h);
f.pages = fileNames;
for (const auto kv: glyphs)
{
//TODO: page = 0 for empty glyphs.
const auto &glyph = kv.second;
FontInfo::Char c;
c.id = kv.first;
if (!glyph.isEmpty())
{
c.x = static_cast<std::uint16_t>(glyph.x);
c.y = static_cast<std::uint16_t>(glyph.y);
c.width = static_cast<std::uint16_t>(glyph.width + config.padding.left + config.padding.right);
c.height = static_cast<std::uint16_t>(glyph.height + config.padding.up + config.padding.down);
c.page = static_cast<std::uint8_t>(glyph.page);
c.xoffset = static_cast<std::int16_t>(glyph.xOffset - config.padding.left);
c.yoffset = static_cast<std::int16_t>(glyph.yOffset - config.padding.up);
}
c.xadvance = static_cast<std::int16_t>(glyph.xAdvance);
c.chnl = 15;
f.chars.push_back(c);
}
if (config.includeKerningPairs)
{
auto chars(config.chars);
for (const auto& ch0 : config.chars)
{
for (const auto& ch1 : chars)
{
const auto k = static_cast<std::int16_t>(fonts[0].getKerning(ch0, ch1));
if (k)
{
FontInfo::Kerning kerning;
kerning.first = ch0;
kerning.second = ch1;
kerning.amount = k;
f.kernings.push_back(kerning);
}
}
}
}
const auto dataFileName = config.output + ".fnt";
switch (config.dataFormat) {
case Config::DataFormat::Xml:
f.writeToXmlFile(dataFileName);
break;
case Config::DataFormat::Text:
f.writeToTextFile(dataFileName);
break;
case Config::DataFormat::Bin:
f.writeToBinFile(dataFileName);
break;
case Config::DataFormat::Json:
f.writeToJsonFile(dataFileName);
break;
}
}
void App::execute(const int argc, char* argv[])
{
ProgramOptions po;
const auto config = po.parseCommandLine(argc, argv);
ft::Library library;
std::vector<ft::Font> fonts;
for (auto& f: config.fontFile)
fonts.emplace_back(library, f, config.fontSize);
auto glyphs = collectGlyphInfo(fonts, config.chars);
const auto pageCount = arrangeGlyphs(glyphs, config);
if (config.maxTextureCount != 0 && pageCount > config.maxTextureCount)
throw std::runtime_error("too many generated textures (more than --max-texture-count)");
const auto fileNames = renderTextures(glyphs, config, fonts, pageCount);
writeFontInfoFile(glyphs, config, fonts, fileNames);
}
|
#include "App.h"
#include "ProgramOptions.h"
#include <string>
#include <iomanip>
#include "FontInfo.h"
#include "utils/extractFileName.h"
#include "external/lodepng/lodepng.h"
#include "utils/getNumberLen.h"
std::vector<rbp::RectSize> App::getGlyphRectangles(const Glyphs &glyphs, const std::uint32_t additionalWidth, const std::uint32_t additionalHeight)
{
std::vector<rbp::RectSize> result;
for (const auto& kv : glyphs)
{
const auto& glyphInfo = kv.second;
if (!glyphInfo.isEmpty())
result.emplace_back(glyphInfo.width + additionalWidth, glyphInfo.height + additionalHeight, kv.first);
}
return result;
}
App::Glyphs App::collectGlyphInfo(const std::vector<ft::Font>& fonts, const std::set<std::uint32_t>& codes)
{
Glyphs result;
for (const auto& id : codes)
{
GlyphInfo glyphInfo;
for (size_t i = 0; i < fonts.size(); ++i)
{
if (fonts[i].isGlyphProvided(id))
{
ft::Font::GlyphMetrics glyphMetrics = fonts[i].renderGlyph(nullptr, 0, 0, 0, 0, id, 0);
glyphInfo.fontIndex = i;
glyphInfo.width = glyphMetrics.width;
glyphInfo.height = glyphMetrics.height;
glyphInfo.xAdvance = glyphMetrics.horiAdvance;
glyphInfo.xOffset = glyphMetrics.horiBearingX;
glyphInfo.yOffset = fonts[i].ascent - glyphMetrics.horiBearingY;
break;
}
}
//TODO: add more checks for glyph.
if (glyphInfo.fontIndex == -1)
{
std::cout << "warning: glyph " << id << " not found";
if (id == 65279)
std::cout << " (it looks like Unicode byte order mark (BOM))";
std::cout << "." << std::endl;
}
else
result[id] = glyphInfo;
}
return result;
}
std::uint32_t App::arrangeGlyphs(Glyphs& glyphs, const Config& config)
{
const auto additionalWidth = config.spacing.hor + config.padding.left + config.padding.right;
const auto additionalHeight = config.spacing.ver + config.padding.up + config.padding.down;
//TODO: check workAreaW,H
const auto workAreaW = config.textureSize.w - config.spacing.hor;
const auto workAreaH = config.textureSize.h - config.spacing.ver;
auto glyphRectangles = getGlyphRectangles(glyphs, additionalWidth, additionalHeight);
rbp::MaxRectsBinPack mrbp;
std::uint32_t pageCount = 0;
for (;;)
{
mrbp.Init(workAreaW, workAreaH);
std::vector<rbp::Rect> arrangedRectangles;
mrbp.Insert( glyphRectangles, arrangedRectangles, rbp::MaxRectsBinPack::RectBestAreaFit );
if ( arrangedRectangles.empty() )
{
if ( !glyphRectangles.empty() )
throw std::runtime_error("can not fit glyphs into texture");
break;
}
for ( const auto& r: arrangedRectangles )
{
glyphs[r.tag].x = r.x + config.spacing.hor;
glyphs[r.tag].y = r.y + config.spacing.ver;
glyphs[r.tag].page = pageCount;
}
++pageCount;
}
return pageCount;
}
void App::savePng(const std::string& fileName, const std::uint32_t* buffer, const std::uint32_t w, const std::uint32_t h, const bool withAlpha)
{
std::vector<std::uint8_t> png;
lodepng::State state;
state.encoder.add_id = 0; // Don't add LodePNG version chunk to save more bytes
state.encoder.auto_convert = 0;
state.info_png.color.colortype = withAlpha ? LCT_RGBA : LCT_RGB;
state.encoder.zlibsettings.windowsize = 32768; // Use maximum possible window size for best compression
auto error = lodepng::encode(png, reinterpret_cast<const unsigned char*>(buffer), w, h, state);
if (error)
throw std::runtime_error("png encoder error " + std::to_string(error) + ": " + lodepng_error_text(error));
error = lodepng::save_file(png, fileName);
if (error)
throw std::runtime_error("png save to file error " + std::to_string(error) + ": " + lodepng_error_text(error));
}
std::vector<std::string> App::renderTextures(const Glyphs& glyphs, const Config& config, const std::vector<ft::Font>& fonts, const std::uint32_t pageCount)
{
std::vector<std::string> fileNames;
//TODO: should we decrement pageCount before calculate?
const auto pageNameDigits = getNumberLen(pageCount);
for (std::uint32_t page = 0; page < pageCount; ++page)
{
std::vector<std::uint32_t> surface(config.textureSize.w * config.textureSize.h);
memset(&surface[0], 0, surface.size() * sizeof(std::uint32_t));
// Render every glyph
//TODO: do not repeat same glyphs (with same index)
for (const auto& kv: glyphs)
{
const auto& glyph = kv.second;
if (glyph.page != page)
continue;
if (!glyph.isEmpty())
{
const auto x = glyph.x + config.padding.left;
const auto y = glyph.y + config.padding.up;
fonts[glyph.fontIndex].renderGlyph(&surface[0], config.textureSize.w, config.textureSize.h, x, y, kv.first, config.color.getBGR());
}
}
if (!config.backgroundTransparent)
{
auto cur = surface.data();
const auto end = &surface.back();
const auto fgColor = config.color.getBGR();
const auto bgColor = config.backgroundColor.getBGR();
while (cur <= end)
{
const std::uint32_t a0 = (*cur) >> 24;
const std::uint32_t a1 = 256 - a0;
const std::uint32_t rb1 = (a1 * (bgColor & 0xFF00FF)) >> 8;
const std::uint32_t rb2 = (a0 * (fgColor & 0xFF00FF)) >> 8;
const std::uint32_t g1 = (a1 * (bgColor & 0x00FF00)) >> 8;
const std::uint32_t g2 = (a0 * (fgColor & 0x00FF00)) >> 8;
*cur = ((rb1 | rb2) & 0xFF00FF) + ((g1 | g2) & 0x00FF00);
++cur;
}
}
std::stringstream ss;
ss << config.output << "_" << std::setfill ('0') << std::setw(pageNameDigits) << page << ".png";
const auto fileName = ss.str();
fileNames.push_back(extractFileName(fileName));
savePng(fileName, &surface[0], config.textureSize.w, config.textureSize.h, config.backgroundTransparent);
}
return fileNames;
}
void App::writeFontInfoFile(const Glyphs& glyphs, const Config& config, const std::vector<ft::Font>& fonts, const std::vector<std::string>& fileNames)
{
FontInfo f;
f.info.face = fonts[0].getFamilyNameOr("unknown");
f.info.size = config.fontSize;
f.info.unicode = true;
f.info.aa = 1;
f.info.padding.up = static_cast<std::uint8_t>(config.padding.up);
f.info.padding.right = static_cast<std::uint8_t>(config.padding.right);
f.info.padding.down = static_cast<std::uint8_t>(config.padding.down);
f.info.padding.left = static_cast<std::uint8_t>(config.padding.left);
f.info.spacing.horizontal = static_cast<std::uint8_t>(config.spacing.hor);
f.info.spacing.vertical = static_cast<std::uint8_t>(config.spacing.ver);
f.common.lineHeight = static_cast<std::uint16_t>(fonts[0].lineskip);
f.common.base = static_cast<std::uint16_t>(fonts[0].ascent);
f.common.scaleW = static_cast<std::uint16_t>(config.textureSize.w);
f.common.scaleH = static_cast<std::uint16_t>(config.textureSize.h);
f.pages = fileNames;
for (const auto kv: glyphs)
{
//TODO: page = 0 for empty glyphs.
const auto &glyph = kv.second;
FontInfo::Char c;
c.id = kv.first;
if (!glyph.isEmpty())
{
c.x = static_cast<std::uint16_t>(glyph.x);
c.y = static_cast<std::uint16_t>(glyph.y);
c.width = static_cast<std::uint16_t>(glyph.width + config.padding.left + config.padding.right);
c.height = static_cast<std::uint16_t>(glyph.height + config.padding.up + config.padding.down);
c.page = static_cast<std::uint8_t>(glyph.page);
c.xoffset = static_cast<std::int16_t>(glyph.xOffset - config.padding.left);
c.yoffset = static_cast<std::int16_t>(glyph.yOffset - config.padding.up);
}
c.xadvance = static_cast<std::int16_t>(glyph.xAdvance);
c.chnl = 15;
f.chars.push_back(c);
}
if (config.includeKerningPairs)
{
auto chars(config.chars);
for (const auto& ch0 : config.chars)
{
for (const auto& ch1 : chars)
{
const auto k = static_cast<std::int16_t>(fonts[0].getKerning(ch0, ch1));
if (k)
{
FontInfo::Kerning kerning;
kerning.first = ch0;
kerning.second = ch1;
kerning.amount = k;
f.kernings.push_back(kerning);
}
}
}
}
const auto dataFileName = config.output + ".fnt";
switch (config.dataFormat) {
case Config::DataFormat::Xml:
f.writeToXmlFile(dataFileName);
break;
case Config::DataFormat::Text:
f.writeToTextFile(dataFileName);
break;
case Config::DataFormat::Bin:
f.writeToBinFile(dataFileName);
break;
case Config::DataFormat::Json:
f.writeToJsonFile(dataFileName);
break;
}
}
void App::execute(const int argc, char* argv[])
{
ProgramOptions po;
const auto config = po.parseCommandLine(argc, argv);
ft::Library library;
std::vector<ft::Font> fonts;
for (auto& f: config.fontFile)
fonts.emplace_back(library, f, config.fontSize);
auto glyphs = collectGlyphInfo(fonts, config.chars);
const auto pageCount = arrangeGlyphs(glyphs, config);
if (config.maxTextureCount != 0 && pageCount > config.maxTextureCount)
throw std::runtime_error("too many generated textures (more than --max-texture-count)");
const auto fileNames = renderTextures(glyphs, config, fonts, pageCount);
writeFontInfoFile(glyphs, config, fonts, fileNames);
}
|
Optimize PNG compression
|
Optimize PNG compression
|
C++
|
mit
|
vladimirgamalian/fontbm,vladimirgamalian/fontbm,vladimirgamalian/fontbm
|
aef76ac99b69570023a088fd83837f8e372c9919
|
examples/miscellaneous/miscellaneous_ex6/miscellaneous_ex6.C
|
examples/miscellaneous/miscellaneous_ex6/miscellaneous_ex6.C
|
/* The Next Great Finite Element Library. */
/* Copyright (C) 2003 Benjamin S. Kirk */
/* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
// <h1>Miscellaneous Example 6 - Meshing with LibMesh's TetGen and Triangle Interfaces</h1>
//
// LibMesh provides interfaces to both Triangle and TetGen for generating
// Delaunay triangulations and tetrahedralizations in two and three dimensions
// (respectively).
// Local header files
#include "mesh.h"
#include "mesh_triangle_interface.h"
#include "mesh_generation.h"
#include "elem.h"
#include "mesh_tetgen_interface.h"
#include "node.h"
#include "face_tri3.h"
#include "mesh_triangle_holes.h"
// Bring in everything from the libMesh namespace
using namespace libMesh;
// Major functions called by main
void triangulate_domain();
void tetrahedralize_domain();
// Helper routine for tetrahedralize_domain(). Adds the points and elements
// of a convex hull generated by TetGen to the input mesh
void add_cube_convex_hull_to_mesh(MeshBase& mesh, Point lower_limit, Point upper_limit);
// Begin the main program.
int main (int argc, char** argv)
{
// Initialize libMesh and any dependent libaries, like in example 2.
LibMeshInit init (argc, argv);
libmesh_example_assert(2 <= LIBMESH_DIM, "2D support");
std::cout << "Triangulating an L-shaped domain with holes" << std::endl;
// 1.) 2D triangulation of L-shaped domain with three holes of different shape
triangulate_domain();
libmesh_example_assert(3 <= LIBMESH_DIM, "3D support");
std::cout << "Tetrahedralizing a prismatic domain with a hole" << std::endl;
// 2.) 3D tetrahedralization of rectangular domain with hole.
tetrahedralize_domain();
return 0;
}
void triangulate_domain()
{
#ifdef LIBMESH_HAVE_TRIANGLE
// Use typedefs for slightly less typing.
typedef TriangleInterface::Hole Hole;
typedef TriangleInterface::PolygonHole PolygonHole;
typedef TriangleInterface::ArbitraryHole ArbitraryHole;
// Libmesh mesh that will eventually be created.
Mesh mesh(2);
// The points which make up the L-shape:
mesh.add_point(Point( 0. , 0.));
mesh.add_point(Point( 0. , -1.));
mesh.add_point(Point(-1. , -1.));
mesh.add_point(Point(-1. , 1.));
mesh.add_point(Point( 1. , 1.));
mesh.add_point(Point( 1. , 0.));
// Declare the TriangleInterface object. This is where
// we can set parameters of the triangulation and where the
// actual triangulate function lives.
TriangleInterface t(mesh);
// Customize the variables for the triangulation
t.desired_area() = .01;
// A Planar Straight Line Graph (PSLG) is essentially a list
// of segments which have to exist in the final triangulation.
// For an L-shaped domain, Triangle will compute the convex
// hull of boundary points if we do not specify the PSLG.
// The PSLG algorithm is also required for triangulating domains
// containing holes
t.triangulation_type() = TriangleInterface::PSLG;
// Turn on/off Laplacian mesh smoothing after generation.
// By default this is on.
t.smooth_after_generating() = true;
// Define holes...
// hole_1 is a circle (discretized by 50 points)
PolygonHole hole_1(Point(-0.5, 0.5), // center
0.25, // radius
50); // n. points
// hole_2 is itself a triangle
PolygonHole hole_2(Point(0.5, 0.5), // center
0.1, // radius
3); // n. points
// hole_3 is an ellipse of 100 points which we define here
Point ellipse_center(-0.5, -0.5);
const unsigned int n_ellipse_points=100;
std::vector<Point> ellipse_points(n_ellipse_points);
const Real
dtheta = 2*libMesh::pi / static_cast<Real>(n_ellipse_points),
a = .1,
b = .2;
for (unsigned int i=0; i<n_ellipse_points; ++i)
ellipse_points[i]= Point(ellipse_center(0)+a*cos(i*dtheta),
ellipse_center(1)+b*sin(i*dtheta));
ArbitraryHole hole_3(ellipse_center, ellipse_points);
// Create the vector of Hole*'s ...
std::vector<Hole*> holes;
holes.push_back(&hole_1);
holes.push_back(&hole_2);
holes.push_back(&hole_3);
// ... and attach it to the triangulator object
t.attach_hole_list(&holes);
// Triangulate!
t.triangulate();
// Write the result to file
mesh.write("delaunay_l_shaped_hole.e");
#endif // LIBMESH_HAVE_TRIANGLE
}
void tetrahedralize_domain()
{
#ifdef LIBMESH_HAVE_TETGEN
// The algorithm is broken up into several steps:
// 1.) A convex hull is constructed for a rectangular hole.
// 2.) A convex hull is constructed for the domain exterior.
// 3.) Neighbor information is updated so TetGen knows there is a convex hull
// 4.) A vector of hole points is created.
// 5.) The domain is tetrahedralized, the mesh is written out, etc.
// The mesh we will eventually generate
Mesh mesh(3);
// Lower and Upper bounding box limits for a rectangular hole within the unit cube.
Point hole_lower_limit(0.2, 0.2, 0.4);
Point hole_upper_limit(0.8, 0.8, 0.6);
// 1.) Construct a convex hull for the hole
add_cube_convex_hull_to_mesh(mesh, hole_lower_limit, hole_upper_limit);
// 2.) Generate elements comprising the outer boundary of the domain.
add_cube_convex_hull_to_mesh(mesh, Point(0.,0.,0.), Point(1., 1., 1.));
// 3.) Update neighbor information so that TetGen can verify there is a convex hull.
mesh.find_neighbors();
// 4.) Set up vector of hole points
std::vector<Point> hole(1);
hole[0] = Point( 0.5*(hole_lower_limit + hole_upper_limit) );
// 5.) Set parameters and tetrahedralize the domain
// 0 means "use TetGen default value"
Real quality_constraint = 2.0;
// The volume constraint determines the max-allowed tetrahedral
// volume in the Mesh. TetGen will split cells which are larger than
// this size
Real volume_constraint = 0.001;
// Construct the Delaunay tetrahedralization
TetGenMeshInterface t(mesh);
t.triangulate_conformingDelaunayMesh_carvehole(hole,
quality_constraint,
volume_constraint);
// Find neighbors, etc in preparation for writing out the Mesh
mesh.prepare_for_use();
// Finally, write out the result
mesh.write("hole_3D.e");
#endif // LIBMESH_HAVE_TETGEN
}
void add_cube_convex_hull_to_mesh(MeshBase& mesh, Point lower_limit, Point upper_limit)
{
#ifdef LIBMESH_HAVE_TETGEN
Mesh cube_mesh(3);
unsigned n_elem = 1;
MeshTools::Generation::build_cube(cube_mesh,
n_elem,n_elem,n_elem, // n. elements in each direction
lower_limit(0), upper_limit(0),
lower_limit(1), upper_limit(1),
lower_limit(2), upper_limit(2),
HEX8);
// The pointset_convexhull() algorithm will ignore the Hex8s
// in the Mesh, and just construct the triangulation
// of the convex hull.
TetGenMeshInterface t(cube_mesh);
t.pointset_convexhull();
// Now add all nodes from the boundary of the cube_mesh to the input mesh.
// Map from "node id in cube_mesh" -> "node id in mesh". Initially inserted
// with a dummy value, later to be assigned a value by the input mesh.
std::map<unsigned,unsigned> node_id_map;
typedef std::map<unsigned,unsigned>::iterator iterator;
{
MeshBase::element_iterator it = cube_mesh.elements_begin();
const MeshBase::element_iterator end = cube_mesh.elements_end();
for ( ; it != end; ++it)
{
Elem* elem = *it;
for (unsigned s=0; s<elem->n_sides(); ++s)
if (elem->neighbor(s) == NULL)
{
// Add the node IDs of this side to the set
AutoPtr<Elem> side = elem->side(s);
for (unsigned n=0; n<side->n_nodes(); ++n)
node_id_map.insert( std::make_pair(side->node(n), /*dummy_value=*/0) );
}
}
}
// For each node in the map, insert it into the input mesh and keep
// track of the ID assigned.
for (iterator it=node_id_map.begin(); it != node_id_map.end(); ++it)
{
// Id of the node in the cube mesh
unsigned id = (*it).first;
// Pointer to node in the cube mesh
Node* old_node = cube_mesh.node_ptr(id);
// Add geometric point to input mesh
Node* new_node = mesh.add_point ( *old_node );
// Track ID value of new_node in map
(*it).second = new_node->id();
}
// With the points added and the map data structure in place, we are
// ready to add each TRI3 element of the cube_mesh to the input Mesh
// with proper node assignments
{
MeshBase::element_iterator el = cube_mesh.elements_begin();
const MeshBase::element_iterator end_el = cube_mesh.elements_end();
for (; el != end_el; ++el)
{
Elem* old_elem = *el;
if (old_elem->type() == TRI3)
{
Elem* new_elem = mesh.add_elem(new Tri3);
// Assign nodes in new elements. Since this is an example,
// we'll do it in several steps.
for (unsigned i=0; i<old_elem->n_nodes(); ++i)
{
// Locate old node ID in the map
iterator it = node_id_map.find(old_elem->node(i));
// Check for not found
if (it == node_id_map.end())
{
libMesh::err << "Node id " << old_elem->node(i) << " not found in map!" << std::endl;
libmesh_error();
}
// Mapping to node ID in input mesh
unsigned new_node_id = (*it).second;
// Node pointer assigned from input mesh
new_elem->set_node(i) = mesh.node_ptr(new_node_id);
}
}
}
}
#endif // LIBMESH_HAVE_TETGEN
}
|
/* The Next Great Finite Element Library. */
/* Copyright (C) 2003 Benjamin S. Kirk */
/* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
// <h1>Miscellaneous Example 6 - Meshing with LibMesh's TetGen and Triangle Interfaces</h1>
//
// LibMesh provides interfaces to both Triangle and TetGen for generating
// Delaunay triangulations and tetrahedralizations in two and three dimensions
// (respectively).
// Local header files
#include "elem.h"
#include "face_tri3.h"
#include "mesh.h"
#include "mesh_generation.h"
#include "mesh_tetgen_interface.h"
#include "mesh_triangle_holes.h"
#include "mesh_triangle_interface.h"
#include "node.h"
#include "serial_mesh.h"
// Bring in everything from the libMesh namespace
using namespace libMesh;
// Major functions called by main
void triangulate_domain();
void tetrahedralize_domain();
// Helper routine for tetrahedralize_domain(). Adds the points and elements
// of a convex hull generated by TetGen to the input mesh
void add_cube_convex_hull_to_mesh(MeshBase& mesh, Point lower_limit, Point upper_limit);
// Begin the main program.
int main (int argc, char** argv)
{
// Initialize libMesh and any dependent libaries, like in example 2.
LibMeshInit init (argc, argv);
libmesh_example_assert(2 <= LIBMESH_DIM, "2D support");
std::cout << "Triangulating an L-shaped domain with holes" << std::endl;
// 1.) 2D triangulation of L-shaped domain with three holes of different shape
triangulate_domain();
libmesh_example_assert(3 <= LIBMESH_DIM, "3D support");
std::cout << "Tetrahedralizing a prismatic domain with a hole" << std::endl;
// 2.) 3D tetrahedralization of rectangular domain with hole.
tetrahedralize_domain();
return 0;
}
void triangulate_domain()
{
#ifdef LIBMESH_HAVE_TRIANGLE
// Use typedefs for slightly less typing.
typedef TriangleInterface::Hole Hole;
typedef TriangleInterface::PolygonHole PolygonHole;
typedef TriangleInterface::ArbitraryHole ArbitraryHole;
// Libmesh mesh that will eventually be created.
Mesh mesh(2);
// The points which make up the L-shape:
mesh.add_point(Point( 0. , 0.));
mesh.add_point(Point( 0. , -1.));
mesh.add_point(Point(-1. , -1.));
mesh.add_point(Point(-1. , 1.));
mesh.add_point(Point( 1. , 1.));
mesh.add_point(Point( 1. , 0.));
// Declare the TriangleInterface object. This is where
// we can set parameters of the triangulation and where the
// actual triangulate function lives.
TriangleInterface t(mesh);
// Customize the variables for the triangulation
t.desired_area() = .01;
// A Planar Straight Line Graph (PSLG) is essentially a list
// of segments which have to exist in the final triangulation.
// For an L-shaped domain, Triangle will compute the convex
// hull of boundary points if we do not specify the PSLG.
// The PSLG algorithm is also required for triangulating domains
// containing holes
t.triangulation_type() = TriangleInterface::PSLG;
// Turn on/off Laplacian mesh smoothing after generation.
// By default this is on.
t.smooth_after_generating() = true;
// Define holes...
// hole_1 is a circle (discretized by 50 points)
PolygonHole hole_1(Point(-0.5, 0.5), // center
0.25, // radius
50); // n. points
// hole_2 is itself a triangle
PolygonHole hole_2(Point(0.5, 0.5), // center
0.1, // radius
3); // n. points
// hole_3 is an ellipse of 100 points which we define here
Point ellipse_center(-0.5, -0.5);
const unsigned int n_ellipse_points=100;
std::vector<Point> ellipse_points(n_ellipse_points);
const Real
dtheta = 2*libMesh::pi / static_cast<Real>(n_ellipse_points),
a = .1,
b = .2;
for (unsigned int i=0; i<n_ellipse_points; ++i)
ellipse_points[i]= Point(ellipse_center(0)+a*cos(i*dtheta),
ellipse_center(1)+b*sin(i*dtheta));
ArbitraryHole hole_3(ellipse_center, ellipse_points);
// Create the vector of Hole*'s ...
std::vector<Hole*> holes;
holes.push_back(&hole_1);
holes.push_back(&hole_2);
holes.push_back(&hole_3);
// ... and attach it to the triangulator object
t.attach_hole_list(&holes);
// Triangulate!
t.triangulate();
// Write the result to file
mesh.write("delaunay_l_shaped_hole.e");
#endif // LIBMESH_HAVE_TRIANGLE
}
void tetrahedralize_domain()
{
#ifdef LIBMESH_HAVE_TETGEN
// The algorithm is broken up into several steps:
// 1.) A convex hull is constructed for a rectangular hole.
// 2.) A convex hull is constructed for the domain exterior.
// 3.) Neighbor information is updated so TetGen knows there is a convex hull
// 4.) A vector of hole points is created.
// 5.) The domain is tetrahedralized, the mesh is written out, etc.
// The mesh we will eventually generate
SerialMesh mesh(3);
// Lower and Upper bounding box limits for a rectangular hole within the unit cube.
Point hole_lower_limit(0.2, 0.2, 0.4);
Point hole_upper_limit(0.8, 0.8, 0.6);
// 1.) Construct a convex hull for the hole
add_cube_convex_hull_to_mesh(mesh, hole_lower_limit, hole_upper_limit);
// 2.) Generate elements comprising the outer boundary of the domain.
add_cube_convex_hull_to_mesh(mesh, Point(0.,0.,0.), Point(1., 1., 1.));
// 3.) Update neighbor information so that TetGen can verify there is a convex hull.
mesh.find_neighbors();
// 4.) Set up vector of hole points
std::vector<Point> hole(1);
hole[0] = Point( 0.5*(hole_lower_limit + hole_upper_limit) );
// 5.) Set parameters and tetrahedralize the domain
// 0 means "use TetGen default value"
Real quality_constraint = 2.0;
// The volume constraint determines the max-allowed tetrahedral
// volume in the Mesh. TetGen will split cells which are larger than
// this size
Real volume_constraint = 0.001;
// Construct the Delaunay tetrahedralization
TetGenMeshInterface t(mesh);
t.triangulate_conformingDelaunayMesh_carvehole(hole,
quality_constraint,
volume_constraint);
// Find neighbors, etc in preparation for writing out the Mesh
mesh.prepare_for_use();
// Finally, write out the result
mesh.write("hole_3D.e");
#endif // LIBMESH_HAVE_TETGEN
}
void add_cube_convex_hull_to_mesh(MeshBase& mesh, Point lower_limit, Point upper_limit)
{
#ifdef LIBMESH_HAVE_TETGEN
Mesh cube_mesh(3);
unsigned n_elem = 1;
MeshTools::Generation::build_cube(cube_mesh,
n_elem,n_elem,n_elem, // n. elements in each direction
lower_limit(0), upper_limit(0),
lower_limit(1), upper_limit(1),
lower_limit(2), upper_limit(2),
HEX8);
// The pointset_convexhull() algorithm will ignore the Hex8s
// in the Mesh, and just construct the triangulation
// of the convex hull.
TetGenMeshInterface t(cube_mesh);
t.pointset_convexhull();
// Now add all nodes from the boundary of the cube_mesh to the input mesh.
// Map from "node id in cube_mesh" -> "node id in mesh". Initially inserted
// with a dummy value, later to be assigned a value by the input mesh.
std::map<unsigned,unsigned> node_id_map;
typedef std::map<unsigned,unsigned>::iterator iterator;
{
MeshBase::element_iterator it = cube_mesh.elements_begin();
const MeshBase::element_iterator end = cube_mesh.elements_end();
for ( ; it != end; ++it)
{
Elem* elem = *it;
for (unsigned s=0; s<elem->n_sides(); ++s)
if (elem->neighbor(s) == NULL)
{
// Add the node IDs of this side to the set
AutoPtr<Elem> side = elem->side(s);
for (unsigned n=0; n<side->n_nodes(); ++n)
node_id_map.insert( std::make_pair(side->node(n), /*dummy_value=*/0) );
}
}
}
// For each node in the map, insert it into the input mesh and keep
// track of the ID assigned.
for (iterator it=node_id_map.begin(); it != node_id_map.end(); ++it)
{
// Id of the node in the cube mesh
unsigned id = (*it).first;
// Pointer to node in the cube mesh
Node* old_node = cube_mesh.node_ptr(id);
// Add geometric point to input mesh
Node* new_node = mesh.add_point ( *old_node );
// Track ID value of new_node in map
(*it).second = new_node->id();
}
// With the points added and the map data structure in place, we are
// ready to add each TRI3 element of the cube_mesh to the input Mesh
// with proper node assignments
{
MeshBase::element_iterator el = cube_mesh.elements_begin();
const MeshBase::element_iterator end_el = cube_mesh.elements_end();
for (; el != end_el; ++el)
{
Elem* old_elem = *el;
if (old_elem->type() == TRI3)
{
Elem* new_elem = mesh.add_elem(new Tri3);
// Assign nodes in new elements. Since this is an example,
// we'll do it in several steps.
for (unsigned i=0; i<old_elem->n_nodes(); ++i)
{
// Locate old node ID in the map
iterator it = node_id_map.find(old_elem->node(i));
// Check for not found
if (it == node_id_map.end())
{
libMesh::err << "Node id " << old_elem->node(i) << " not found in map!" << std::endl;
libmesh_error();
}
// Mapping to node ID in input mesh
unsigned new_node_id = (*it).second;
// Node pointer assigned from input mesh
new_elem->set_node(i) = mesh.node_ptr(new_node_id);
}
}
}
}
#endif // LIBMESH_HAVE_TETGEN
}
|
Use SerialMesh with tetgen until I can track down the (not recent!) ParallelMesh regression there
|
Use SerialMesh with tetgen until I can track down the (not recent!)
ParallelMesh regression there
git-svn-id: ffc1bc5b3feaf8644044862cc38c386ade156493@5792 434f946d-2f3d-0410-ba4c-cb9f52fb0dbf
|
C++
|
lgpl-2.1
|
certik/libmesh,certik/libmesh,certik/libmesh,certik/libmesh,certik/libmesh,certik/libmesh,certik/libmesh
|
f6cdc2eee5c664d440261c75af5e8df4eaad1505
|
src/containers.hh
|
src/containers.hh
|
#ifndef containers_hh_INCLUDED
#define containers_hh_INCLUDED
#include <algorithm>
#include <utility>
#include <iterator>
namespace Kakoune
{
template<typename Factory>
struct ContainerView { Factory factory; };
template<typename Container, typename Factory>
auto operator| (Container&& container, ContainerView<Factory> view) ->
decltype(view.factory(std::forward<Container>(container)))
{
return view.factory(std::forward<Container>(container));
}
template<typename Container>
struct ReverseView
{
using iterator = decltype(std::declval<Container>().rbegin());
iterator begin() { return m_container.rbegin(); }
iterator end() { return m_container.rend(); }
Container m_container;
};
template<typename C>
using RemoveReference = typename std::remove_reference<C>::type;
struct ReverseFactory
{
template<typename Container>
ReverseView<RemoveReference<Container>> operator()(Container&& container) const
{
return {std::move(container)};
}
template<typename Container>
ReverseView<Container&> operator()(Container& container) const
{
return {container};
}
};
inline ContainerView<ReverseFactory> reverse() { return {}; }
template<typename Container>
using IteratorOf = decltype(std::begin(std::declval<Container>()));
template<typename Container>
using ValueOf = typename Container::value_type;
template<typename Container, typename Filter>
struct FilterView
{
using ContainerIt = IteratorOf<Container>;
struct Iterator : std::iterator<std::forward_iterator_tag,
typename ContainerIt::value_type>
{
Iterator(const FilterView& view, ContainerIt it, ContainerIt end)
: m_it{std::move(it)}, m_end{std::move(end)}, m_view{view}
{
do_filter();
}
auto operator*() -> decltype(*std::declval<ContainerIt>()) { return *m_it; }
Iterator& operator++() { ++m_it; do_filter(); return *this; }
Iterator operator++(int) { auto copy = *this; ++(*this); return copy; }
friend bool operator==(const Iterator& lhs, const Iterator& rhs)
{
return lhs.m_it == rhs.m_it;
}
friend bool operator!=(const Iterator& lhs, const Iterator& rhs)
{
return not (lhs == rhs);
}
const ContainerIt& base() const { return m_it; }
private:
void do_filter()
{
while (m_it != m_end and not m_view.m_filter(*m_it))
++m_it;
}
ContainerIt m_it;
ContainerIt m_end;
const FilterView& m_view;
};
Iterator begin() const { return {*this, m_container.begin(), m_container.end()}; }
Iterator end() const { return {*this, m_container.end(), m_container.end()}; }
Container m_container;
Filter m_filter;
};
template<typename Filter>
struct FilterFactory
{
template<typename Container>
FilterView<Container&, Filter> operator()(Container& container) const { return {container, std::move(m_filter)}; }
template<typename Container>
FilterView<RemoveReference<Container>, Filter> operator()(Container&& container) const { return {std::move(container), std::move(m_filter)}; }
Filter m_filter;
};
template<typename Filter>
inline ContainerView<FilterFactory<Filter>> filter(Filter f) { return {{std::move(f)}}; }
template<typename I, typename T>
using TransformedResult = decltype(std::declval<T>()(*std::declval<I>()));
template<typename Container, typename Transform>
struct TransformView
{
using ContainerIt = IteratorOf<Container>;
struct Iterator : std::iterator<std::forward_iterator_tag,
typename std::remove_reference<TransformedResult<ContainerIt, Transform>>::type>
{
Iterator(const TransformView& view, ContainerIt it)
: m_it{std::move(it)}, m_view{view} {}
auto operator*() -> TransformedResult<ContainerIt, Transform> { return m_view.m_transform(*m_it); }
Iterator& operator++() { ++m_it; return *this; }
Iterator operator++(int) { auto copy = *this; ++m_it; return copy; }
friend bool operator==(const Iterator& lhs, const Iterator& rhs)
{
return lhs.m_it == rhs.m_it;
}
friend bool operator!=(const Iterator& lhs, const Iterator& rhs)
{
return not (lhs == rhs);
}
ContainerIt base() const { return m_it; }
private:
ContainerIt m_it;
const TransformView& m_view;
};
Iterator begin() const { return {*this, m_container.begin()}; }
Iterator end() const { return {*this, m_container.end()}; }
Container m_container;
Transform m_transform;
};
template<typename Transform>
struct TransformFactory
{
template<typename Container>
TransformView<Container&, Transform> operator()(Container& container) const { return {container, std::move(m_transform)}; }
template<typename Container>
TransformView<RemoveReference<Container>, Transform> operator()(Container&& container) const { return {std::move(container), std::move(m_transform)}; }
Transform m_transform;
};
template<typename Transform>
inline ContainerView<TransformFactory<Transform>> transform(Transform t) { return {{std::move(t)}}; }
template<typename Container, typename Separator = ValueOf<Container>,
typename ValueTypeParam = void>
struct SplitView
{
using ContainerIt = IteratorOf<Container>;
using ValueType = typename std::conditional<std::is_same<void, ValueTypeParam>::value,
std::pair<IteratorOf<Container>, IteratorOf<Container>>,
ValueTypeParam>::type;
struct Iterator : std::iterator<std::forward_iterator_tag, ValueType>
{
Iterator(ContainerIt pos, ContainerIt end, char separator)
: pos(pos), sep(pos), end(end), separator(separator)
{
while (sep != end and *sep != separator)
++sep;
}
Iterator& operator++() { advance(); return *this; }
Iterator operator++(int) { auto copy = *this; advance(); return copy; }
bool operator==(const Iterator& other) const { return pos == other.pos; }
bool operator!=(const Iterator& other) const { return pos != other.pos; }
ValueType operator*() { return {pos, sep}; }
private:
void advance()
{
if (sep == end)
{
pos = end;
return;
}
pos = sep+1;
for (sep = pos; sep != end; ++sep)
{
if (*sep == separator)
break;
}
}
ContainerIt pos;
ContainerIt sep;
ContainerIt end;
Separator separator;
};
Iterator begin() const { return {m_container.begin(), m_container.end(), m_separator}; }
Iterator end() const { return {m_container.end(), m_container.end(), m_separator}; }
Container m_container;
Separator m_separator;
};
template<typename ValueType, typename Separator>
struct SplitViewFactory
{
template<typename Container>
SplitView<RemoveReference<Container>, Separator, ValueType>
operator()(Container&& container) const { return {std::move(container), std::move(separator)}; }
template<typename Container>
SplitView<Container&, Separator, ValueType>
operator()(Container& container) const { return {container, std::move(separator)}; }
Separator separator;
};
template<typename ValueType = void, typename Separator>
ContainerView<SplitViewFactory<ValueType, Separator>> split(Separator separator) { return {{std::move(separator)}}; }
template<typename Container1, typename Container2>
struct ConcatView
{
using ContainerIt1 = decltype(begin(std::declval<Container1>()));
using ContainerIt2 = decltype(begin(std::declval<Container2>()));
using ValueType = typename std::common_type<typename ContainerIt1::value_type, typename ContainerIt2::value_type>::type;
struct Iterator : std::iterator<std::forward_iterator_tag, ValueType>
{
static_assert(std::is_convertible<typename ContainerIt1::value_type, ValueType>::value, "");
static_assert(std::is_convertible<typename ContainerIt2::value_type, ValueType>::value, "");
Iterator(ContainerIt1 it1, ContainerIt1 end1, ContainerIt2 it2)
: m_it1(std::move(it1)), m_end1(std::move(end1)),
m_it2(std::move(it2)) {}
ValueType operator*() { return is2() ? *m_it2 : *m_it1; }
Iterator& operator++() { if (is2()) ++m_it2; else ++m_it1; return *this; }
Iterator operator++(int) { auto copy = *this; ++*this; return copy; }
friend bool operator==(const Iterator& lhs, const Iterator& rhs)
{
return lhs.m_it1 == rhs.m_it1 and lhs.m_end1 == rhs.m_end1 and
lhs.m_it2 == rhs.m_it2;
}
friend bool operator!=(const Iterator& lhs, const Iterator& rhs)
{
return not (lhs == rhs);
}
private:
bool is2() const { return m_it1 == m_end1; }
ContainerIt1 m_it1;
ContainerIt1 m_end1;
ContainerIt2 m_it2;
};
ConcatView(Container1& container1, Container2& container2)
: m_container1(container1), m_container2(container2) {}
Iterator begin() const { return {m_container1.begin(), m_container1.end(), m_container2.begin()}; }
Iterator end() const { return {m_container1.end(), m_container1.end(), m_container2.end()}; }
private:
Container1& m_container1;
Container2& m_container2;
};
template<typename Container1, typename Container2>
ConcatView<Container1, Container2> concatenated(Container1&& container1, Container2&& container2)
{
return {container1, container2};
}
// Todo: move that into the following functions once we can remove the decltype
// return type.
using std::begin;
using std::end;
template<typename Container, typename T>
auto find(Container&& container, const T& value) -> decltype(begin(container))
{
return std::find(begin(container), end(container), value);
}
template<typename Container, typename T>
auto find_if(Container&& container, T op) -> decltype(begin(container))
{
return std::find_if(begin(container), end(container), op);
}
template<typename Container, typename T>
bool contains(Container&& container, const T& value)
{
return find(container, value) != end(container);
}
template<typename Container, typename T>
bool contains_that(Container&& container, T op)
{
return find_if(container, op) != end(container);
}
template<typename Container, typename U>
void unordered_erase(Container&& vec, U&& value)
{
auto it = find(vec, std::forward<U>(value));
if (it != vec.end())
{
using std::swap;
swap(vec.back(), *it);
vec.pop_back();
}
}
}
#endif // containers_hh_INCLUDED
|
#ifndef containers_hh_INCLUDED
#define containers_hh_INCLUDED
#include <algorithm>
#include <utility>
#include <iterator>
namespace Kakoune
{
template<typename Factory>
struct ContainerView { Factory factory; };
template<typename Container, typename Factory>
auto operator| (Container&& container, ContainerView<Factory> view) ->
decltype(view.factory(std::forward<Container>(container)))
{
return view.factory(std::forward<Container>(container));
}
template<typename Container>
struct ReverseView
{
using iterator = decltype(std::declval<Container>().rbegin());
iterator begin() { return m_container.rbegin(); }
iterator end() { return m_container.rend(); }
Container m_container;
};
template<typename C>
using RemoveReference = typename std::remove_reference<C>::type;
struct ReverseFactory
{
template<typename Container>
ReverseView<RemoveReference<Container>> operator()(Container&& container) const
{
return {std::move(container)};
}
template<typename Container>
ReverseView<Container&> operator()(Container& container) const
{
return {container};
}
};
inline ContainerView<ReverseFactory> reverse() { return {}; }
template<typename Container>
using IteratorOf = decltype(std::begin(std::declval<Container>()));
template<typename Container>
using ValueOf = typename Container::value_type;
template<typename Container, typename Filter>
struct FilterView
{
using ContainerIt = IteratorOf<Container>;
struct Iterator : std::iterator<std::forward_iterator_tag,
typename ContainerIt::value_type>
{
Iterator(const FilterView& view, ContainerIt it, ContainerIt end)
: m_it{std::move(it)}, m_end{std::move(end)}, m_view{view}
{
do_filter();
}
auto operator*() -> decltype(*std::declval<ContainerIt>()) { return *m_it; }
Iterator& operator++() { ++m_it; do_filter(); return *this; }
Iterator operator++(int) { auto copy = *this; ++(*this); return copy; }
friend bool operator==(const Iterator& lhs, const Iterator& rhs)
{
return lhs.m_it == rhs.m_it;
}
friend bool operator!=(const Iterator& lhs, const Iterator& rhs)
{
return not (lhs == rhs);
}
const ContainerIt& base() const { return m_it; }
private:
void do_filter()
{
while (m_it != m_end and not m_view.m_filter(*m_it))
++m_it;
}
ContainerIt m_it;
ContainerIt m_end;
const FilterView& m_view;
};
Iterator begin() const { return {*this, std::begin(m_container), std::end(m_container)}; }
Iterator end() const { return {*this, std::end(m_container), std::end(m_container)}; }
Container m_container;
Filter m_filter;
};
template<typename Filter>
struct FilterFactory
{
template<typename Container>
FilterView<Container&, Filter> operator()(Container& container) const { return {container, std::move(m_filter)}; }
template<typename Container>
FilterView<RemoveReference<Container>, Filter> operator()(Container&& container) const { return {std::move(container), std::move(m_filter)}; }
Filter m_filter;
};
template<typename Filter>
inline ContainerView<FilterFactory<Filter>> filter(Filter f) { return {{std::move(f)}}; }
template<typename I, typename T>
using TransformedResult = decltype(std::declval<T>()(*std::declval<I>()));
template<typename Container, typename Transform>
struct TransformView
{
using ContainerIt = IteratorOf<Container>;
struct Iterator : std::iterator<std::forward_iterator_tag,
typename std::remove_reference<TransformedResult<ContainerIt, Transform>>::type>
{
Iterator(const TransformView& view, ContainerIt it)
: m_it{std::move(it)}, m_view{view} {}
auto operator*() -> TransformedResult<ContainerIt, Transform> { return m_view.m_transform(*m_it); }
Iterator& operator++() { ++m_it; return *this; }
Iterator operator++(int) { auto copy = *this; ++m_it; return copy; }
friend bool operator==(const Iterator& lhs, const Iterator& rhs)
{
return lhs.m_it == rhs.m_it;
}
friend bool operator!=(const Iterator& lhs, const Iterator& rhs)
{
return not (lhs == rhs);
}
ContainerIt base() const { return m_it; }
private:
ContainerIt m_it;
const TransformView& m_view;
};
Iterator begin() const { return {*this, std::begin(m_container)}; }
Iterator end() const { return {*this, std::end(m_container)}; }
Container m_container;
Transform m_transform;
};
template<typename Transform>
struct TransformFactory
{
template<typename Container>
TransformView<Container&, Transform> operator()(Container& container) const { return {container, std::move(m_transform)}; }
template<typename Container>
TransformView<RemoveReference<Container>, Transform> operator()(Container&& container) const { return {std::move(container), std::move(m_transform)}; }
Transform m_transform;
};
template<typename Transform>
inline ContainerView<TransformFactory<Transform>> transform(Transform t) { return {{std::move(t)}}; }
template<typename Container, typename Separator = ValueOf<Container>,
typename ValueTypeParam = void>
struct SplitView
{
using ContainerIt = IteratorOf<Container>;
using ValueType = typename std::conditional<std::is_same<void, ValueTypeParam>::value,
std::pair<IteratorOf<Container>, IteratorOf<Container>>,
ValueTypeParam>::type;
struct Iterator : std::iterator<std::forward_iterator_tag, ValueType>
{
Iterator(ContainerIt pos, ContainerIt end, char separator)
: pos(pos), sep(pos), end(end), separator(separator)
{
while (sep != end and *sep != separator)
++sep;
}
Iterator& operator++() { advance(); return *this; }
Iterator operator++(int) { auto copy = *this; advance(); return copy; }
bool operator==(const Iterator& other) const { return pos == other.pos; }
bool operator!=(const Iterator& other) const { return pos != other.pos; }
ValueType operator*() { return {pos, sep}; }
private:
void advance()
{
if (sep == end)
{
pos = end;
return;
}
pos = sep+1;
for (sep = pos; sep != end; ++sep)
{
if (*sep == separator)
break;
}
}
ContainerIt pos;
ContainerIt sep;
ContainerIt end;
Separator separator;
};
Iterator begin() const { return {std::begin(m_container), std::end(m_container), m_separator}; }
Iterator end() const { return {std::end(m_container), std::end(m_container), m_separator}; }
Container m_container;
Separator m_separator;
};
template<typename ValueType, typename Separator>
struct SplitViewFactory
{
template<typename Container>
SplitView<RemoveReference<Container>, Separator, ValueType>
operator()(Container&& container) const { return {std::move(container), std::move(separator)}; }
template<typename Container>
SplitView<Container&, Separator, ValueType>
operator()(Container& container) const { return {container, std::move(separator)}; }
Separator separator;
};
template<typename ValueType = void, typename Separator>
ContainerView<SplitViewFactory<ValueType, Separator>> split(Separator separator) { return {{std::move(separator)}}; }
template<typename Container1, typename Container2>
struct ConcatView
{
using ContainerIt1 = decltype(begin(std::declval<Container1>()));
using ContainerIt2 = decltype(begin(std::declval<Container2>()));
using ValueType = typename std::common_type<typename ContainerIt1::value_type, typename ContainerIt2::value_type>::type;
struct Iterator : std::iterator<std::forward_iterator_tag, ValueType>
{
static_assert(std::is_convertible<typename ContainerIt1::value_type, ValueType>::value, "");
static_assert(std::is_convertible<typename ContainerIt2::value_type, ValueType>::value, "");
Iterator(ContainerIt1 it1, ContainerIt1 end1, ContainerIt2 it2)
: m_it1(std::move(it1)), m_end1(std::move(end1)),
m_it2(std::move(it2)) {}
ValueType operator*() { return is2() ? *m_it2 : *m_it1; }
Iterator& operator++() { if (is2()) ++m_it2; else ++m_it1; return *this; }
Iterator operator++(int) { auto copy = *this; ++*this; return copy; }
friend bool operator==(const Iterator& lhs, const Iterator& rhs)
{
return lhs.m_it1 == rhs.m_it1 and lhs.m_end1 == rhs.m_end1 and
lhs.m_it2 == rhs.m_it2;
}
friend bool operator!=(const Iterator& lhs, const Iterator& rhs)
{
return not (lhs == rhs);
}
private:
bool is2() const { return m_it1 == m_end1; }
ContainerIt1 m_it1;
ContainerIt1 m_end1;
ContainerIt2 m_it2;
};
ConcatView(Container1& container1, Container2& container2)
: m_container1(container1), m_container2(container2) {}
Iterator begin() const { return {m_container1.begin(), m_container1.end(), m_container2.begin()}; }
Iterator end() const { return {m_container1.end(), m_container1.end(), m_container2.end()}; }
private:
Container1& m_container1;
Container2& m_container2;
};
template<typename Container1, typename Container2>
ConcatView<Container1, Container2> concatenated(Container1&& container1, Container2&& container2)
{
return {container1, container2};
}
// Todo: move that into the following functions once we can remove the decltype
// return type.
using std::begin;
using std::end;
template<typename Container, typename T>
auto find(Container&& container, const T& value) -> decltype(begin(container))
{
return std::find(begin(container), end(container), value);
}
template<typename Container, typename T>
auto find_if(Container&& container, T op) -> decltype(begin(container))
{
return std::find_if(begin(container), end(container), op);
}
template<typename Container, typename T>
bool contains(Container&& container, const T& value)
{
return find(container, value) != end(container);
}
template<typename Container, typename T>
bool contains_that(Container&& container, T op)
{
return find_if(container, op) != end(container);
}
template<typename Container, typename U>
void unordered_erase(Container&& vec, U&& value)
{
auto it = find(vec, std::forward<U>(value));
if (it != vec.end())
{
using std::swap;
swap(vec.back(), *it);
vec.pop_back();
}
}
}
#endif // containers_hh_INCLUDED
|
Use std::begin/std::end in containers.hh instead of the method version
|
Use std::begin/std::end in containers.hh instead of the method version
|
C++
|
unlicense
|
lenormf/kakoune,alexherbo2/kakoune,mawww/kakoune,Somasis/kakoune,occivink/kakoune,lenormf/kakoune,flavius/kakoune,casimir/kakoune,flavius/kakoune,alexherbo2/kakoune,ekie/kakoune,danr/kakoune,casimir/kakoune,danr/kakoune,Somasis/kakoune,ekie/kakoune,jjthrash/kakoune,lenormf/kakoune,flavius/kakoune,danr/kakoune,flavius/kakoune,mawww/kakoune,ekie/kakoune,alexherbo2/kakoune,alexherbo2/kakoune,mawww/kakoune,lenormf/kakoune,jkonecny12/kakoune,jkonecny12/kakoune,jkonecny12/kakoune,occivink/kakoune,jjthrash/kakoune,casimir/kakoune,danr/kakoune,ekie/kakoune,Somasis/kakoune,occivink/kakoune,casimir/kakoune,jjthrash/kakoune,Somasis/kakoune,jkonecny12/kakoune,jjthrash/kakoune,mawww/kakoune,occivink/kakoune
|
12dbb8e0ea9e847ac1c4cfd7f6d187fe6afe581b
|
src/core/area.cpp
|
src/core/area.cpp
|
/***************************************
** Tsunagari Tile Engine **
** area.cpp **
** Copyright 2011-2015 Michael Reiley **
** Copyright 2011-2018 Paul Merrill **
***************************************/
// **********
// 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 "core/area.h"
#include <math.h>
#include "core/algorithm.h"
#include "core/client-conf.h"
#include "core/display-list.h"
#include "core/entity.h"
#include "core/formatter.h"
#include "core/log.h"
#include "core/images.h"
#include "core/music.h"
#include "core/npc.h"
#include "core/overlay.h"
#include "core/player.h"
#include "core/tile.h"
#include "core/viewport.h"
#include "core/window.h"
#include "core/world.h"
#include "util/assert.h"
#include "util/math2.h"
#include "data/data-world.h"
#define CHECK(x) if (!(x)) { return false; }
/* NOTE: In the TMX map format used by Tiled, tileset tiles start counting
their Y-positions from 0, while layer tiles start counting from 1. I
can't imagine why the author did this, but we have to take it into
account.
*/
Area::Area(Player* player,
const std::string& descriptor)
: dataArea(DataWorld::instance().area(descriptor)),
player(player),
colorOverlayARGB(0),
beenFocused(false),
redraw(true),
descriptor(descriptor) {
grid.dim = ivec3(0, 0, 0);
grid.tileDim = ivec2(0, 0);
grid.loopX = false;
grid.loopY = false;
}
void Area::focus() {
if (!beenFocused) {
beenFocused = true;
if (dataArea) {
dataArea->onLoad();
}
}
if (musicPath) {
Music::instance().play(*musicPath);
}
if (dataArea) {
dataArea->onFocus();
}
}
void Area::buttonDown(KeyboardKey key) {
switch (key) {
case KBLeftArrow:
player->startMovement(ivec2(-1, 0));
break;
case KBRightArrow:
player->startMovement(ivec2(1, 0));
break;
case KBUpArrow:
player->startMovement(ivec2(0, -1));
break;
case KBDownArrow:
player->startMovement(ivec2(0, 1));
break;
case KBSpace:
player->useTile();
break;
default:
break;
}
}
void Area::buttonUp(KeyboardKey key) {
switch (key) {
case KBLeftArrow:
player->stopMovement(ivec2(-1, 0));
break;
case KBRightArrow:
player->stopMovement(ivec2(1, 0));
break;
case KBUpArrow:
player->stopMovement(ivec2(0, -1));
break;
case KBDownArrow:
player->stopMovement(ivec2(0, 1));
break;
default:
break;
}
}
void Area::draw(DisplayList* display) {
icube tiles = visibleTiles();
int maxZ = grid.dim.z;
assert_(tiles.z1 == 0);
assert_(tiles.z2 == maxZ);
for (int z = 0; z < maxZ; z++) {
drawTiles(display, tiles, z);
drawEntities(display, tiles, z);
}
redraw = false;
}
bool Area::needsRedraw() const {
if (redraw) {
return true;
}
const icube tiles = visibleTiles();
const icube pixels = {
tiles.x1 * grid.tileDim.x,
tiles.y1 * grid.tileDim.y,
tiles.z1,
tiles.x2 * grid.tileDim.x,
tiles.y2 * grid.tileDim.y,
tiles.z2,
};
if (player->needsRedraw(pixels)) {
return true;
}
for (const auto& character : characters) {
if (character->needsRedraw(pixels)) {
return true;
}
}
for (const auto& overlay : overlays) {
if (overlay->needsRedraw(pixels)) {
return true;
}
}
// Do any on-screen tile types need to update their animations?
BitRecord tileTypes(static_cast<size_t>(maxTileTypeId));
for (int z = tiles.z1; z < tiles.z2; z++) {
for (int y = tiles.y1; y < tiles.y2; y++) {
for (int x = tiles.x1; x < tiles.x2; x++) {
const Tile* tile = getTile(icoord(x, y, z));
const TileType* type = tile->getType();
if (!type) {
continue;
}
if (tileTypes[type->id]) {
continue;
}
tileTypes[type->id] = true;
if (type->needsRedraw()) {
return true;
}
}
}
}
return false;
}
void Area::requestRedraw() {
redraw = true;
}
void Area::tick(time_t dt) {
if (dataArea) {
dataArea->tick(dt);
}
for (auto& overlay : overlays) {
overlay->tick(dt);
}
erase_if(overlays, [] (const Rc<Overlay>& o) {
bool dead = o->isDead();
if (dead) {
o->setArea(nullptr);
}
return dead;
});
if (conf.moveMode != TURN) {
player->tick(dt);
for (auto& character : characters) {
character->tick(dt);
}
erase_if(characters, [] (const Rc<Character>& c) {
bool dead = c->isDead();
if (dead) {
c->setArea(nullptr);
}
return dead;
});
}
Viewport::instance().tick(dt);
}
void Area::turn() {
if (dataArea) {
dataArea->turn();
}
player->turn();
for (auto& character : characters) {
character->turn();
}
erase_if(characters, [] (const Rc<Character>& c) {
bool dead = c->isDead();
if (dead) {
c->setArea(nullptr);
}
return dead;
});
Viewport::instance().turn();
}
uint32_t Area::getColorOverlay() {
return colorOverlayARGB;
}
void Area::setColorOverlay(uint8_t a, uint8_t r, uint8_t g, uint8_t b) {
colorOverlayARGB = (uint32_t)(a << 24) + (uint32_t)(r << 16) +
(uint32_t)(g << 8) + (uint32_t)b;
redraw = true;
}
const Tile* Area::getTile(icoord phys) const {
return grid.getTile(phys);
}
const Tile* Area::getTile(vicoord virt) const {
return grid.getTile(virt);
}
const Tile* Area::getTile(rcoord virt) const {
return grid.getTile(virt);
}
Tile* Area::getTile(icoord phys) {
return grid.getTile(phys);
}
Tile* Area::getTile(vicoord virt) {
return grid.getTile(virt);
}
Tile* Area::getTile(rcoord virt) {
return grid.getTile(virt);
}
TileSet* Area::getTileSet(const std::string& imagePath) {
std::unordered_map<std::string, TileSet>::iterator it;
it = tileSets.find(imagePath);
if (it == tileSets.end()) {
Log::err("Area", "tileset " + imagePath + " not found");
return nullptr;
}
return &tileSets[imagePath];
}
ivec3 Area::getDimensions() const {
return grid.dim;
}
ivec2 Area::getTileDimensions() const {
return grid.tileDim;
}
icube Area::visibleTiles() const {
Viewport& viewport = Viewport::instance();
rvec2 screen = viewport.getVirtRes();
rvec2 off = viewport.getMapOffset();
int x1 = static_cast<int>(floor(off.x / grid.tileDim.x));
int y1 = static_cast<int>(floor(off.y / grid.tileDim.y));
int x2 = static_cast<int>(ceil((screen.x + off.x) / grid.tileDim.x));
int y2 = static_cast<int>(ceil((screen.y + off.y) / grid.tileDim.y));
if (!grid.loopX) {
x1 = bound(x1, 0, grid.dim.x);
x2 = bound(x2, 0, grid.dim.x);
}
if (!grid.loopY) {
y1 = bound(y1, 0, grid.dim.y);
y2 = bound(y2, 0, grid.dim.y);
}
return icube{x1, y1, 0, x2, y2, grid.dim.z};
}
bool Area::inBounds(icoord phys) const {
return grid.inBounds(phys);
}
bool Area::inBounds(vicoord virt) const {
return grid.inBounds(virt);
}
bool Area::inBounds(rcoord virt) const {
return grid.inBounds(virt);
}
bool Area::inBounds(Entity* ent) const {
return inBounds(ent->getPixelCoord());
}
bool Area::loopsInX() const {
return grid.loopX;
}
bool Area::loopsInY() const {
return grid.loopY;
}
Rc<NPC> Area::spawnNPC(const std::string& descriptor,
vicoord coord,
const std::string& phase) {
auto c = Rc<NPC>(new NPC);
if (!c->init(descriptor, phase)) {
// Error logged.
return Rc<NPC>();
}
c->setArea(this);
c->setTileCoords(coord);
characters.insert(c);
return c;
}
Rc<Overlay> Area::spawnOverlay(const std::string& descriptor,
vicoord coord,
const std::string& phase) {
auto o = Rc<Overlay>(new Overlay);
if (!o->init(descriptor, phase)) {
// Error logged.
return Rc<Overlay>();
}
o->setArea(this);
o->teleport(coord);
overlays.insert(o);
return o;
}
vicoord Area::phys2virt_vi(icoord phys) const {
return grid.phys2virt_vi(phys);
}
rcoord Area::phys2virt_r(icoord phys) const {
return grid.phys2virt_r(phys);
}
icoord Area::virt2phys(vicoord virt) const {
return grid.virt2phys(virt);
}
icoord Area::virt2phys(rcoord virt) const {
return grid.virt2phys(virt);
}
rcoord Area::virt2virt(vicoord virt) const {
return grid.virt2virt(virt);
}
vicoord Area::virt2virt(rcoord virt) const {
return grid.virt2virt(virt);
}
DataArea* Area::getDataArea() {
return dataArea;
}
static void drawTile(DisplayList* display, const TileType* type,
int x, int y, double depth, int tileDimY) {
Image* img = type->anim.frame();
if (img) {
rvec2 drawPos(
double(x * (int)img->width()),
double(y * (int)img->height())
);
//drawPos.z = depth + drawPos.y / tileDimY * ISOMETRIC_ZOFF_PER_TILE;
display->items.push_back(DisplayItem{img, drawPos});
}
}
void Area::drawTiles(DisplayList* display, const icube& tiles, int z) {
time_t now = World::instance().time();
BitRecord tilesAnimated(static_cast<size_t>(maxTileTypeId));
double depth = grid.idx2depth[(size_t)z];
for (int y = tiles.y1; y < tiles.y2; y++) {
for (int x = tiles.x1; x < tiles.x2; x++) {
Tile* tile = getTile(icoord(x, y, z));
// We are certain the Tile exists.
TileType* type = tile->getType();
if (!type) {
continue;
}
if (!tilesAnimated[type->id]) {
type->anim.frame(now);
}
drawTile(display, type, x, y, depth, grid.tileDim.y);
}
}
}
void Area::drawEntities(DisplayList* display, const icube& tiles, int z) {
double depth = grid.idx2depth[(size_t)z];
for (auto& character : characters) {
if (character->getTileCoords_i().z == z) {
character->draw(display);
}
}
for (auto& overlay : overlays) {
if (overlay->getPixelCoord().z == depth) {
overlay->draw(display);
}
}
if (player->getTileCoords_i().z == z) {
player->draw(display);
}
}
|
/***************************************
** Tsunagari Tile Engine **
** area.cpp **
** Copyright 2011-2015 Michael Reiley **
** Copyright 2011-2018 Paul Merrill **
***************************************/
// **********
// 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 "core/area.h"
#include <math.h>
#include "core/algorithm.h"
#include "core/client-conf.h"
#include "core/display-list.h"
#include "core/entity.h"
#include "core/formatter.h"
#include "core/log.h"
#include "core/images.h"
#include "core/music.h"
#include "core/npc.h"
#include "core/overlay.h"
#include "core/player.h"
#include "core/tile.h"
#include "core/viewport.h"
#include "core/window.h"
#include "core/world.h"
#include "util/assert.h"
#include "util/math2.h"
#include "data/data-world.h"
#define CHECK(x) if (!(x)) { return false; }
/* NOTE: In the TMX map format used by Tiled, tileset tiles start counting
their Y-positions from 0, while layer tiles start counting from 1. I
can't imagine why the author did this, but we have to take it into
account.
*/
Area::Area(Player* player,
const std::string& descriptor)
: dataArea(DataWorld::instance().area(descriptor)),
player(player),
colorOverlayARGB(0),
beenFocused(false),
redraw(true),
descriptor(descriptor) {
grid.dim = ivec3(0, 0, 0);
grid.tileDim = ivec2(0, 0);
grid.loopX = false;
grid.loopY = false;
}
void Area::focus() {
if (!beenFocused) {
beenFocused = true;
if (dataArea) {
dataArea->onLoad();
}
}
if (musicPath) {
Music::instance().play(*musicPath);
}
if (dataArea) {
dataArea->onFocus();
}
}
void Area::buttonDown(KeyboardKey key) {
switch (key) {
case KBLeftArrow:
player->startMovement(ivec2(-1, 0));
break;
case KBRightArrow:
player->startMovement(ivec2(1, 0));
break;
case KBUpArrow:
player->startMovement(ivec2(0, -1));
break;
case KBDownArrow:
player->startMovement(ivec2(0, 1));
break;
case KBSpace:
player->useTile();
break;
default:
break;
}
}
void Area::buttonUp(KeyboardKey key) {
switch (key) {
case KBLeftArrow:
player->stopMovement(ivec2(-1, 0));
break;
case KBRightArrow:
player->stopMovement(ivec2(1, 0));
break;
case KBUpArrow:
player->stopMovement(ivec2(0, -1));
break;
case KBDownArrow:
player->stopMovement(ivec2(0, 1));
break;
default:
break;
}
}
void Area::draw(DisplayList* display) {
icube tiles = visibleTiles();
int maxZ = grid.dim.z;
assert_(tiles.z1 == 0);
assert_(tiles.z2 == maxZ);
for (int z = 0; z < maxZ; z++) {
drawTiles(display, tiles, z);
drawEntities(display, tiles, z);
}
redraw = false;
}
bool Area::needsRedraw() const {
if (redraw) {
return true;
}
const icube tiles = visibleTiles();
const icube pixels = {
tiles.x1 * grid.tileDim.x,
tiles.y1 * grid.tileDim.y,
tiles.z1,
tiles.x2 * grid.tileDim.x,
tiles.y2 * grid.tileDim.y,
tiles.z2,
};
if (player->needsRedraw(pixels)) {
return true;
}
for (const auto& character : characters) {
if (character->needsRedraw(pixels)) {
return true;
}
}
for (const auto& overlay : overlays) {
if (overlay->needsRedraw(pixels)) {
return true;
}
}
// Do any on-screen tile types need to update their animations?
BitRecord tileTypes(static_cast<size_t>(maxTileTypeId));
for (int z = tiles.z1; z < tiles.z2; z++) {
for (int y = tiles.y1; y < tiles.y2; y++) {
for (int x = tiles.x1; x < tiles.x2; x++) {
const Tile* tile = getTile(icoord(x, y, z));
const TileType* type = tile->getType();
if (!type) {
continue;
}
if (tileTypes[type->id]) {
continue;
}
tileTypes[type->id] = true;
if (type->needsRedraw()) {
return true;
}
}
}
}
return false;
}
void Area::requestRedraw() {
redraw = true;
}
void Area::tick(time_t dt) {
if (dataArea) {
dataArea->tick(dt);
}
for (auto& overlay : overlays) {
overlay->tick(dt);
}
erase_if(overlays, [] (const Rc<Overlay>& o) {
bool dead = o->isDead();
if (dead) {
o->setArea(nullptr);
}
return dead;
});
if (conf.moveMode != TURN) {
player->tick(dt);
for (auto& character : characters) {
character->tick(dt);
}
erase_if(characters, [] (const Rc<Character>& c) {
bool dead = c->isDead();
if (dead) {
c->setArea(nullptr);
}
return dead;
});
}
Viewport::instance().tick(dt);
}
void Area::turn() {
if (dataArea) {
dataArea->turn();
}
player->turn();
for (auto& character : characters) {
character->turn();
}
erase_if(characters, [] (const Rc<Character>& c) {
bool dead = c->isDead();
if (dead) {
c->setArea(nullptr);
}
return dead;
});
Viewport::instance().turn();
}
uint32_t Area::getColorOverlay() {
return colorOverlayARGB;
}
void Area::setColorOverlay(uint8_t a, uint8_t r, uint8_t g, uint8_t b) {
colorOverlayARGB = (uint32_t)(a << 24u) + (uint32_t)(r << 16u) +
(uint32_t)(g << 8u) + (uint32_t)b;
redraw = true;
}
const Tile* Area::getTile(icoord phys) const {
return grid.getTile(phys);
}
const Tile* Area::getTile(vicoord virt) const {
return grid.getTile(virt);
}
const Tile* Area::getTile(rcoord virt) const {
return grid.getTile(virt);
}
Tile* Area::getTile(icoord phys) {
return grid.getTile(phys);
}
Tile* Area::getTile(vicoord virt) {
return grid.getTile(virt);
}
Tile* Area::getTile(rcoord virt) {
return grid.getTile(virt);
}
TileSet* Area::getTileSet(const std::string& imagePath) {
std::unordered_map<std::string, TileSet>::iterator it;
it = tileSets.find(imagePath);
if (it == tileSets.end()) {
Log::err("Area", "tileset " + imagePath + " not found");
return nullptr;
}
return &tileSets[imagePath];
}
ivec3 Area::getDimensions() const {
return grid.dim;
}
ivec2 Area::getTileDimensions() const {
return grid.tileDim;
}
icube Area::visibleTiles() const {
Viewport& viewport = Viewport::instance();
rvec2 screen = viewport.getVirtRes();
rvec2 off = viewport.getMapOffset();
int x1 = static_cast<int>(floor(off.x / grid.tileDim.x));
int y1 = static_cast<int>(floor(off.y / grid.tileDim.y));
int x2 = static_cast<int>(ceil((screen.x + off.x) / grid.tileDim.x));
int y2 = static_cast<int>(ceil((screen.y + off.y) / grid.tileDim.y));
if (!grid.loopX) {
x1 = bound(x1, 0, grid.dim.x);
x2 = bound(x2, 0, grid.dim.x);
}
if (!grid.loopY) {
y1 = bound(y1, 0, grid.dim.y);
y2 = bound(y2, 0, grid.dim.y);
}
return icube{x1, y1, 0, x2, y2, grid.dim.z};
}
bool Area::inBounds(icoord phys) const {
return grid.inBounds(phys);
}
bool Area::inBounds(vicoord virt) const {
return grid.inBounds(virt);
}
bool Area::inBounds(rcoord virt) const {
return grid.inBounds(virt);
}
bool Area::inBounds(Entity* ent) const {
return inBounds(ent->getPixelCoord());
}
bool Area::loopsInX() const {
return grid.loopX;
}
bool Area::loopsInY() const {
return grid.loopY;
}
Rc<NPC> Area::spawnNPC(const std::string& descriptor,
vicoord coord,
const std::string& phase) {
auto c = Rc<NPC>(new NPC);
if (!c->init(descriptor, phase)) {
// Error logged.
return Rc<NPC>();
}
c->setArea(this);
c->setTileCoords(coord);
characters.insert(c);
return c;
}
Rc<Overlay> Area::spawnOverlay(const std::string& descriptor,
vicoord coord,
const std::string& phase) {
auto o = Rc<Overlay>(new Overlay);
if (!o->init(descriptor, phase)) {
// Error logged.
return Rc<Overlay>();
}
o->setArea(this);
o->teleport(coord);
overlays.insert(o);
return o;
}
vicoord Area::phys2virt_vi(icoord phys) const {
return grid.phys2virt_vi(phys);
}
rcoord Area::phys2virt_r(icoord phys) const {
return grid.phys2virt_r(phys);
}
icoord Area::virt2phys(vicoord virt) const {
return grid.virt2phys(virt);
}
icoord Area::virt2phys(rcoord virt) const {
return grid.virt2phys(virt);
}
rcoord Area::virt2virt(vicoord virt) const {
return grid.virt2virt(virt);
}
vicoord Area::virt2virt(rcoord virt) const {
return grid.virt2virt(virt);
}
DataArea* Area::getDataArea() {
return dataArea;
}
static void drawTile(DisplayList* display, const TileType* type,
int x, int y /*, double depth, int tileDimY */) {
Image* img = type->anim.frame();
if (img) {
rvec2 drawPos(
double(x * (int)img->width()),
double(y * (int)img->height())
);
//drawPos.z = depth + drawPos.y / tileDimY * ISOMETRIC_ZOFF_PER_TILE;
display->items.push_back(DisplayItem{img, drawPos});
}
}
void Area::drawTiles(DisplayList* display, const icube& tiles, int z) {
time_t now = World::instance().time();
BitRecord tilesAnimated(static_cast<size_t>(maxTileTypeId));
// double depth = grid.idx2depth[(size_t)z];
for (int y = tiles.y1; y < tiles.y2; y++) {
for (int x = tiles.x1; x < tiles.x2; x++) {
Tile* tile = getTile(icoord(x, y, z));
// We are certain the Tile exists.
TileType* type = tile->getType();
if (!type) {
continue;
}
if (!tilesAnimated[type->id]) {
type->anim.frame(now);
}
drawTile(display, type, x, y /*, depth, grid.tileDim.y */);
}
}
}
void Area::drawEntities(DisplayList* display, const icube& tiles, int z) {
double depth = grid.idx2depth[(size_t)z];
for (auto& character : characters) {
if (character->getTileCoords_i().z == z) {
character->draw(display);
}
}
for (auto& overlay : overlays) {
if (overlay->getPixelCoord().z == depth) {
overlay->draw(display);
}
}
if (player->getTileCoords_i().z == z) {
player->draw(display);
}
}
|
Remove unused parameters
|
Area: Remove unused parameters
|
C++
|
mit
|
pmer/TsunagariC,pmer/TsunagariC,pmer/TsunagariC
|
a8268d7f773b7e3ed8d22c6fbcc0347910bc00de
|
src/SSL.cpp
|
src/SSL.cpp
|
/* Copyright (C) 2005-2010, Thorvald Natvig <[email protected]>
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 the Mumble Developers 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 FOUNDATION 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 <QtNetwork>
#include "SSL.h"
#include "Version.h"
void MumbleSSL::addSystemCA() {
#ifndef NO_SYSTEM_CA_OVERRIDE
#if defined(Q_OS_WIN)
QStringList qsl;
qsl << QLatin1String("Ca");
qsl << QLatin1String("Root");
qsl << QLatin1String("AuthRoot");
foreach(const QString &store, qsl) {
HCERTSTORE hCertStore;
PCCERT_CONTEXT pCertContext = NULL;
bool found = false;
hCertStore = CertOpenSystemStore(NULL, store.utf16());
if (! hCertStore) {
qWarning("SSL: Failed to open CA store %s", qPrintable(store));
continue;
}
while (pCertContext = CertEnumCertificatesInStore(hCertStore, pCertContext)) {
QByteArray qba(reinterpret_cast<const char *>(pCertContext->pbCertEncoded), pCertContext->cbCertEncoded);
QList<QSslCertificate> ql = QSslCertificate::fromData(qba, QSsl::Pem);
ql += QSslCertificate::fromData(qba, QSsl::Der);
if (! ql.isEmpty()) {
found = true;
QSslSocket::addDefaultCaCertificates(ql);
}
}
if (found)
qWarning("SSL: Added CA certificates from system store '%s'", qPrintable(store));
CertCloseStore(hCertStore, 0);
}
#elif defined(Q_OS_MAC)
CFArrayRef certs = NULL;
bool found = false;
if (SecTrustCopyAnchorCertificates(&certs) == noErr) {
int ncerts = CFArrayGetCount(certs);
for (int i = 0; i < ncerts; i++) {
CFDataRef data = NULL;
SecCertificateRef cert = reinterpret_cast<SecCertificateRef>(const_cast<void *>(CFArrayGetValueAtIndex(certs, i)));
if (! cert)
continue;
if (SecKeychainItemExport(cert, kSecFormatX509Cert, kSecItemPemArmour, NULL, &data) == noErr) {
const char *ptr = reinterpret_cast<const char *>(CFDataGetBytePtr(data));
int len = CFDataGetLength(data);
QByteArray qba(ptr, len);
QList<QSslCertificate> ql = QSslCertificate::fromData(qba, QSsl::Pem);
if (! ql.isEmpty()) {
found = true;
QSslSocket::addDefaultCaCertificates(ql);
}
}
}
CFRelease(certs);
if (found)
qWarning("SSL: Added CA certificates from 'System Roots' store.");
}
#elif defined(Q_OS_UNIX)
QStringList qsl;
#ifdef SYSTEM_CA_DIR
QSslSocket::addDefaultCaCertificates(MUMTEXT(SYSTEM_CA_DIR));
#else
#ifdef SYSTEM_CA_BUNDLE
qsl << QLatin1String(MUMTEXT(SYSTEM_CA_BUNDLE));
#else
qsl << QLatin1String("/etc/pki/tls/certs/ca-bundle.crt");
qsl << QLatin1String("/etc/ssl/certs/ca-certificates.crt");
#endif
foreach(const QString &filename, qsl) {
QFile f(filename);
if (f.exists() && f.open(QIODevice::ReadOnly)) {
QList<QSslCertificate> ql = QSslCertificate::fromDevice(&f, QSsl::Pem);
ql += QSslCertificate::fromDevice(&f, QSsl::Der);
if (! ql.isEmpty()) {
qWarning("SSL: Added CA certificates from '%s'", qPrintable(filename));
QSslSocket::addDefaultCaCertificates(ql);
}
}
}
#endif // SYSTEM_CA_DIR
#endif // Q_OS_UNIX
QSet<QByteArray> digests;
QList<QSslCertificate> ql;
foreach(const QSslCertificate &crt, QSslSocket::defaultCaCertificates()) {
QByteArray digest = crt.digest(QCryptographicHash::Sha1);
if (! digests.contains(digest) && crt.isValid()) {
ql << crt;
digests.insert(digest);
}
}
QSslSocket::setDefaultCaCertificates(ql);
#endif // NO_SYSTEM_CA_OVERRIDE
}
|
/* Copyright (C) 2005-2010, Thorvald Natvig <[email protected]>
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 the Mumble Developers 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 FOUNDATION 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 <QtNetwork>
#include "SSL.h"
#include "Version.h"
/* CAs we recommend to end users, so support these */
static const char *recommended_cas[] = {
/* StartSSL */
"-----BEGIN CERTIFICATE-----\n"
"MIIHyTCCBbGgAwIBAgIBATANBgkqhkiG9w0BAQUFADB9MQswCQYDVQQGEwJJTDEW\n"
"MBQGA1UEChMNU3RhcnRDb20gTHRkLjErMCkGA1UECxMiU2VjdXJlIERpZ2l0YWwg\n"
"Q2VydGlmaWNhdGUgU2lnbmluZzEpMCcGA1UEAxMgU3RhcnRDb20gQ2VydGlmaWNh\n"
"dGlvbiBBdXRob3JpdHkwHhcNMDYwOTE3MTk0NjM2WhcNMzYwOTE3MTk0NjM2WjB9\n"
"MQswCQYDVQQGEwJJTDEWMBQGA1UEChMNU3RhcnRDb20gTHRkLjErMCkGA1UECxMi\n"
"U2VjdXJlIERpZ2l0YWwgQ2VydGlmaWNhdGUgU2lnbmluZzEpMCcGA1UEAxMgU3Rh\n"
"cnRDb20gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwggIiMA0GCSqGSIb3DQEBAQUA\n"
"A4ICDwAwggIKAoICAQDBiNsJvGxGfHiflXu1M5DycmLWwTYgIiRezul38kMKogZk\n"
"pMyONvg45iPwbm2xPN1yo4UcodM9tDMr0y+v/uqwQVlntsQGfQqedIXWeUyAN3rf\n"
"OQVSWff0G0ZDpNKFhdLDcfN1YjS6LIp/Ho/u7TTQEceWzVI9ujPW3U3eCztKS5/C\n"
"Ji/6tRYccjV3yjxd5srhJosaNnZcAdt0FCX+7bWgiA/deMotHweXMAEtcnn6RtYT\n"
"Kqi5pquDSR3l8u/d5AGOGAqPY1MWhWKpDhk6zLVmpsJrdAfkK+F2PrRt2PZE4XNi\n"
"HzvEvqBTViVsUQn3qqvKv3b9bZvzndu/PWa8DFaqr5hIlTpL36dYUNk4dalb6kMM\n"
"Av+Z6+hsTXBbKWWc3apdzK8BMewM69KN6Oqce+Zu9ydmDBpI125C4z/eIT574Q1w\n"
"+2OqqGwaVLRcJXrJosmLFqa7LH4XXgVNWG4SHQHuEhANxjJ/GP/89PrNbpHoNkm+\n"
"Gkhpi8KWTRoSsmkXwQqQ1vp5Iki/untp+HDH+no32NgN0nZPV/+Qt+OR0t3vwmC3\n"
"Zzrd/qqc8NSLf3Iizsafl7b4r4qgEKjZ+xjGtrVcUjyJthkqcwEKDwOzEmDyei+B\n"
"26Nu/yYwl/WL3YlXtq09s68rxbd2AvCl1iuahhQqcvbjM4xdCUsT37uMdBNSSwID\n"
"AQABo4ICUjCCAk4wDAYDVR0TBAUwAwEB/zALBgNVHQ8EBAMCAa4wHQYDVR0OBBYE\n"
"FE4L7xqkQFulF2mHMMo0aEPQQa7yMGQGA1UdHwRdMFswLKAqoCiGJmh0dHA6Ly9j\n"
"ZXJ0LnN0YXJ0Y29tLm9yZy9zZnNjYS1jcmwuY3JsMCugKaAnhiVodHRwOi8vY3Js\n"
"LnN0YXJ0Y29tLm9yZy9zZnNjYS1jcmwuY3JsMIIBXQYDVR0gBIIBVDCCAVAwggFM\n"
"BgsrBgEEAYG1NwEBATCCATswLwYIKwYBBQUHAgEWI2h0dHA6Ly9jZXJ0LnN0YXJ0\n"
"Y29tLm9yZy9wb2xpY3kucGRmMDUGCCsGAQUFBwIBFilodHRwOi8vY2VydC5zdGFy\n"
"dGNvbS5vcmcvaW50ZXJtZWRpYXRlLnBkZjCB0AYIKwYBBQUHAgIwgcMwJxYgU3Rh\n"
"cnQgQ29tbWVyY2lhbCAoU3RhcnRDb20pIEx0ZC4wAwIBARqBl0xpbWl0ZWQgTGlh\n"
"YmlsaXR5LCByZWFkIHRoZSBzZWN0aW9uICpMZWdhbCBMaW1pdGF0aW9ucyogb2Yg\n"
"dGhlIFN0YXJ0Q29tIENlcnRpZmljYXRpb24gQXV0aG9yaXR5IFBvbGljeSBhdmFp\n"
"bGFibGUgYXQgaHR0cDovL2NlcnQuc3RhcnRjb20ub3JnL3BvbGljeS5wZGYwEQYJ\n"
"YIZIAYb4QgEBBAQDAgAHMDgGCWCGSAGG+EIBDQQrFilTdGFydENvbSBGcmVlIFNT\n"
"TCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTANBgkqhkiG9w0BAQUFAAOCAgEAFmyZ\n"
"9GYMNPXQhV59CuzaEE44HF7fpiUFS5Eyweg78T3dRAlbB0mKKctmArexmvclmAk8\n"
"jhvh3TaHK0u7aNM5Zj2gJsfyOZEdUauCe37Vzlrk4gNXcGmXCPleWKYK34wGmkUW\n"
"FjgKXlf2Ysd6AgXmvB618p70qSmD+LIU424oh0TDkBreOKk8rENNZEXO3SipXPJz\n"
"ewT4F+irsfMuXGRuczE6Eri8sxHkfY+BUZo7jYn0TZNmezwD7dOaHZrzZVD1oNB1\n"
"ny+v8OqCQ5j4aZyJecRDjkZy42Q2Eq/3JR44iZB3fsNrarnDy0RLrHiQi+fHLB5L\n"
"EUTINFInzQpdn4XBidUaePKVEFMy3YCEZnXZtWgo+2EuvoSoOMCZEoalHmdkrQYu\n"
"L6lwhceWD3yJZfWOQ1QOq92lgDmUYMA0yZZwLKMS9R9Ie70cfmu3nZD0Ijuu+Pwq\n"
"yvqCUqDvr0tVk+vBtfAii6w0TiYiBKGHLHVKt+V9E9e4DGTANtLJL4YSjCMJwRuC\n"
"O3NJo2pXh5Tl1njFmUNj403gdy3hZZlyaQQaRwnmDwFWJPsfvw55qVguucQJAX6V\n"
"um0ABj6y6koQOdjQK/W/7HW/lwLFCRsI3FU34oH7N4RDYiDK51ZLZer+bMEkkySh\n"
"NOsF/5oirpt9P/FlUQqmMGqz9IgcgA38corog14=\n"
"-----END CERTIFICATE-----\n"
,
/* Comodo */
"-----BEGIN CERTIFICATE-----\n"
"MIIEMjCCAxqgAwIBAgIBATANBgkqhkiG9w0BAQUFADB7MQswCQYDVQQGEwJHQjEb\n"
"MBkGA1UECAwSR3JlYXRlciBNYW5jaGVzdGVyMRAwDgYDVQQHDAdTYWxmb3JkMRow\n"
"GAYDVQQKDBFDb21vZG8gQ0EgTGltaXRlZDEhMB8GA1UEAwwYQUFBIENlcnRpZmlj\n"
"YXRlIFNlcnZpY2VzMB4XDTA0MDEwMTAwMDAwMFoXDTI4MTIzMTIzNTk1OVowezEL\n"
"MAkGA1UEBhMCR0IxGzAZBgNVBAgMEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UE\n"
"BwwHU2FsZm9yZDEaMBgGA1UECgwRQ29tb2RvIENBIExpbWl0ZWQxITAfBgNVBAMM\n"
"GEFBQSBDZXJ0aWZpY2F0ZSBTZXJ2aWNlczCCASIwDQYJKoZIhvcNAQEBBQADggEP\n"
"ADCCAQoCggEBAL5AnfRu4ep2hxxNRUSOvkbIgwadwSr+GB+O5AL686tdUIoWMQua\n"
"BtDFcCLNSS1UY8y2bmhGC1Pqy0wkwLxyTurxFa70VJoSCsN6sjNg4tqJVfMiWPPe\n"
"3M/vg4aijJRPn2jymJBGhCfHdr/jzDUsi14HZGWCwEiwqJH5YZ92IFCokcdmtet4\n"
"YgNW8IoaE+oxox6gmf049vYnMlhvB/VruPsUK6+3qszWY19zjNoFmag4qMsXeDZR\n"
"rOme9Hg6jc8P2ULimAyrL58OAd7vn5lJ8S3frHRNG5i1R8XlKdH5kBjHYpy+g8cm\n"
"ez6KJcfA3Z3mNWgQIJ2P2N7Sw4ScDV7oL8kCAwEAAaOBwDCBvTAdBgNVHQ4EFgQU\n"
"oBEKIz6W8Qfs4q8p74Klf9AwpLQwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQF\n"
"MAMBAf8wewYDVR0fBHQwcjA4oDagNIYyaHR0cDovL2NybC5jb21vZG9jYS5jb20v\n"
"QUFBQ2VydGlmaWNhdGVTZXJ2aWNlcy5jcmwwNqA0oDKGMGh0dHA6Ly9jcmwuY29t\n"
"b2RvLm5ldC9BQUFDZXJ0aWZpY2F0ZVNlcnZpY2VzLmNybDANBgkqhkiG9w0BAQUF\n"
"AAOCAQEACFb8AvCb6P+k+tZ7xkSAzk/ExfYAWMymtrwUSWgEdujm7l3sAg9g1o1Q\n"
"GE8mTgHj5rCl7r+8dFRBv/38ErjHT1r0iWAFf2C3BUrz9vHCv8S5dIa2LX1rzNLz\n"
"Rt0vxuBqw8M0Ayx9lt1awg6nCpnBBYurDC/zXDrPbDdVCYfeU0BsWO/8tqtlbgT2\n"
"G9w84FoVxp7Z8VlIMCFlA2zs6SFz7JsDoeA3raAVGI/6ugLOpyypEBMs1OUIJqsi\n"
"l2D4kF501KKaU73yqWjgom7C12yxow+ev+to51byrvLjKzg6CYG1a4XXvi3tPxq3\n"
"smPi9WIsgtRqAEFQ8TmDn5XpNpaYbg==\n"
"-----END CERTIFICATE-----\n"
,
/* Comodo UserTrust */
"-----BEGIN CERTIFICATE-----\n"
"MIIE3TCCA8WgAwIBAgIQcZL75hlfrE0ShXRxNKIYpzANBgkqhkiG9w0BAQUFADB7\n"
"MQswCQYDVQQGEwJHQjEbMBkGA1UECAwSR3JlYXRlciBNYW5jaGVzdGVyMRAwDgYD\n"
"VQQHDAdTYWxmb3JkMRowGAYDVQQKDBFDb21vZG8gQ0EgTGltaXRlZDEhMB8GA1UE\n"
"AwwYQUFBIENlcnRpZmljYXRlIFNlcnZpY2VzMB4XDTA0MDEwMTAwMDAwMFoXDTI4\n"
"MTIzMTIzNTk1OVowga4xCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJVVDEXMBUGA1UE\n"
"BxMOU2FsdCBMYWtlIENpdHkxHjAcBgNVBAoTFVRoZSBVU0VSVFJVU1QgTmV0d29y\n"
"azEhMB8GA1UECxMYaHR0cDovL3d3dy51c2VydHJ1c3QuY29tMTYwNAYDVQQDEy1V\n"
"VE4tVVNFUkZpcnN0LUNsaWVudCBBdXRoZW50aWNhdGlvbiBhbmQgRW1haWwwggEi\n"
"MA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCyOYWk8n2rQTtiRjeuzcFgdbw5\n"
"ZflKGkeiucxIzGqY1U01GbmkQuXOSeKKLx580jEHx060g2SdLinVomTEhb2FUTV5\n"
"pE5okHsceqSSqBfymBXyk8zJpDKVuwxPML2YoAuL5W4bokb6eLyib6tZXqUvz8ra\n"
"baov66yhs2qqty5nNYt54R5piOLmRs2gpeq+C852OnoOm+r82idbPXMfIuZIYcZM\n"
"82mxqC4bttQxICy8goqOpA6l14lD/BZarx1x1xFZ2rqHDa/68+HC8KTFZ4zW1lQ6\n"
"3gqkugN3s2XI/R7TdGKqGMpokx6hhX71R2XL+E1XKHTSNP8wtu72YjAUjCzrAgMB\n"
"AAGjggEnMIIBIzAfBgNVHSMEGDAWgBSgEQojPpbxB+zirynvgqV/0DCktDAdBgNV\n"
"HQ4EFgQUiYJnfcSdJnAAS7RQSHzePa4Ebn0wDgYDVR0PAQH/BAQDAgEGMA8GA1Ud\n"
"EwEB/wQFMAMBAf8wHQYDVR0lBBYwFAYIKwYBBQUHAwIGCCsGAQUFBwMEMBEGA1Ud\n"
"IAQKMAgwBgYEVR0gADB7BgNVHR8EdDByMDigNqA0hjJodHRwOi8vY3JsLmNvbW9k\n"
"b2NhLmNvbS9BQUFDZXJ0aWZpY2F0ZVNlcnZpY2VzLmNybDA2oDSgMoYwaHR0cDov\n"
"L2NybC5jb21vZG8ubmV0L0FBQUNlcnRpZmljYXRlU2VydmljZXMuY3JsMBEGCWCG\n"
"SAGG+EIBAQQEAwIBBjANBgkqhkiG9w0BAQUFAAOCAQEAnZXLPLh+pQnEHr8Lwsd2\n"
"jjk8lMYQqk8MyeCrhF2JVOBlO/NtHHw3LCVUX5Yh/DeEkZ0V3BRPgc9UHWtsRWDH\n"
"LfmXUUz5Zso8oIKMpsjw4unUSvnsP1bJ3XaMw4IBT2wA8x4aYXQERwOpxkBXkbxl\n"
"IsUnZ09X22Ra2Y0fuoYv9AaunGnt6fTPKRfY4EqfGiAvl0xRu0YHxIo3TiDjCTFo\n"
"x57Ei53ofhG8MmgQlhGYRNgqUWBNiOt0Ot9DBjLIOVaMOhFS00GkQwP07e8zJ9s5\n"
"4BROJsnY9TniibiTXbcpJkHqs5uug/x3dcroyrX+4mVKYz5ExNDDXodzqZgcr38V\n"
"fw==\n"
"-----END CERTIFICATE-----\n"
};
void MumbleSSL::addSystemCA() {
#ifndef NO_SYSTEM_CA_OVERRIDE
#if defined(Q_OS_WIN)
QStringList qsl;
qsl << QLatin1String("Ca");
qsl << QLatin1String("Root");
qsl << QLatin1String("AuthRoot");
foreach(const QString &store, qsl) {
HCERTSTORE hCertStore;
PCCERT_CONTEXT pCertContext = NULL;
bool found = false;
hCertStore = CertOpenSystemStore(NULL, store.utf16());
if (! hCertStore) {
qWarning("SSL: Failed to open CA store %s", qPrintable(store));
continue;
}
while (pCertContext = CertEnumCertificatesInStore(hCertStore, pCertContext)) {
QByteArray qba(reinterpret_cast<const char *>(pCertContext->pbCertEncoded), pCertContext->cbCertEncoded);
QList<QSslCertificate> ql = QSslCertificate::fromData(qba, QSsl::Pem);
ql += QSslCertificate::fromData(qba, QSsl::Der);
if (! ql.isEmpty()) {
found = true;
QSslSocket::addDefaultCaCertificates(ql);
}
}
if (found)
qWarning("SSL: Added CA certificates from system store '%s'", qPrintable(store));
CertCloseStore(hCertStore, 0);
}
#elif defined(Q_OS_MAC)
CFArrayRef certs = NULL;
bool found = false;
if (SecTrustCopyAnchorCertificates(&certs) == noErr) {
int ncerts = CFArrayGetCount(certs);
for (int i = 0; i < ncerts; i++) {
CFDataRef data = NULL;
SecCertificateRef cert = reinterpret_cast<SecCertificateRef>(const_cast<void *>(CFArrayGetValueAtIndex(certs, i)));
if (! cert)
continue;
if (SecKeychainItemExport(cert, kSecFormatX509Cert, kSecItemPemArmour, NULL, &data) == noErr) {
const char *ptr = reinterpret_cast<const char *>(CFDataGetBytePtr(data));
int len = CFDataGetLength(data);
QByteArray qba(ptr, len);
QList<QSslCertificate> ql = QSslCertificate::fromData(qba, QSsl::Pem);
if (! ql.isEmpty()) {
found = true;
QSslSocket::addDefaultCaCertificates(ql);
}
}
}
CFRelease(certs);
if (found)
qWarning("SSL: Added CA certificates from 'System Roots' store.");
}
#elif defined(Q_OS_UNIX)
QStringList qsl;
#ifdef SYSTEM_CA_DIR
QSslSocket::addDefaultCaCertificates(MUMTEXT(SYSTEM_CA_DIR));
#else
#ifdef SYSTEM_CA_BUNDLE
qsl << QLatin1String(MUMTEXT(SYSTEM_CA_BUNDLE));
#else
qsl << QLatin1String("/etc/pki/tls/certs/ca-bundle.crt");
qsl << QLatin1String("/etc/ssl/certs/ca-certificates.crt");
#endif
foreach(const QString &filename, qsl) {
QFile f(filename);
if (f.exists() && f.open(QIODevice::ReadOnly)) {
QList<QSslCertificate> ql = QSslCertificate::fromDevice(&f, QSsl::Pem);
ql += QSslCertificate::fromDevice(&f, QSsl::Der);
if (! ql.isEmpty()) {
qWarning("SSL: Added CA certificates from '%s'", qPrintable(filename));
QSslSocket::addDefaultCaCertificates(ql);
}
}
}
#endif // SYSTEM_CA_DIR
#endif // Q_OS_UNIX
for(unsigned int i=0;i<sizeof(recommended_cas)/sizeof(recommended_cas[0]);++i) {
QSslCertificate cert(recommended_cas[i]);
if (! QSslSocket::defaultCaCertificates().contains(cert)) {
qWarning("SSL: Adding recommended CA %s", qPrintable(cert.subjectInfo(QSslCertificate::CommonName)));
QSslSocket::addDefaultCaCertificates(QList<QSslCertificate>() << cert);
}
}
QSet<QByteArray> digests;
QList<QSslCertificate> ql;
foreach(const QSslCertificate &crt, QSslSocket::defaultCaCertificates()) {
QByteArray digest = crt.digest(QCryptographicHash::Sha1);
if (! digests.contains(digest) && crt.isValid()) {
ql << crt;
digests.insert(digest);
}
}
QSslSocket::setDefaultCaCertificates(ql);
#endif // NO_SYSTEM_CA_OVERRIDE
}
|
Add recommended user CAs explicitly
|
Add recommended user CAs explicitly
|
C++
|
bsd-3-clause
|
Keridos/mumble,feld/mumble,chancegarcia/mumble,feld/mumble,bheart/mumble,niko20010/mumble,LuAPi/mumble,Zopieux/mumble,Zopieux/mumble,ccpgames/mumble,richard227/mumble,Zopieux/mumble,SuperNascher/mumble,Lartza/mumble,richard227/mumble,ccpgames/mumble,SuperNascher/mumble,Natenom/mumble,unascribed/mumble,unascribed/mumble,SuperNascher/mumble,SuperNascher/mumble,Githlar/mumble,unascribed/mumble,panaschieren/mumble-test,Githlar/mumble,mkrautz/mumble-sbcelt,Keridos/mumble,feld/mumble,niko20010/mumble,bheart/mumble,Lartza/mumble,Keridos/mumble,chancegarcia/mumble,chiefdome/mumble-code,LuAPi/mumble,feld/mumble,mbax/mumble,mkrautz/mumble-sbcelt,bheart/mumble,Lartza/mumble,bheart/mumble,LuAPi/mumble,ccpgames/mumble,arrai/mumble-record,niko20010/mumble,mkrautz/mumble-sbcelt,feld/mumble,mbax/mumble,feld/mumble,panaschieren/mumble-test,austinliou/mumble,panaschieren/mumble-test,panaschieren/mumble-test,panaschieren/mumble-test,mkrautz/mumble-sbcelt,chiefdome/mumble-code,mkrautz/mumble-sbcelt,chancegarcia/mumble,Githlar/mumble,mbax/mumble,unascribed/mumble,ccpgames/mumble,bheart/mumble,Lartza/mumble,arrai/mumble-record,LuAPi/mumble,Zopieux/mumble,chiefdome/mumble-code,chancegarcia/mumble,chancegarcia/mumble,feld/mumble,unascribed/mumble,niko20010/mumble,chiefdome/mumble-code,Githlar/mumble,richard227/mumble,Zopieux/mumble,arrai/mumble-record,austinliou/mumble,mbax/mumble,mbax/mumble,mbax/mumble,chiefdome/mumble-code,chancegarcia/mumble,chiefdome/mumble-code,chancegarcia/mumble,Natenom/mumble,richard227/mumble,ccpgames/mumble,chancegarcia/mumble,arrai/mumble-record,ccpgames/mumble,chiefdome/mumble-code,niko20010/mumble,Keridos/mumble,richard227/mumble,arrai/mumble-record,bheart/mumble,richard227/mumble,mbax/mumble,richard227/mumble,mkrautz/mumble-sbcelt,bheart/mumble,panaschieren/mumble-test,ccpgames/mumble,Githlar/mumble,austinliou/mumble,Githlar/mumble,Lartza/mumble,arrai/mumble-record,LuAPi/mumble,austinliou/mumble,richard227/mumble,mkrautz/mumble-sbcelt,arrai/mumble-record,mkrautz/mumble-sbcelt,Natenom/mumble,austinliou/mumble,LuAPi/mumble,niko20010/mumble,unascribed/mumble,SuperNascher/mumble,bheart/mumble,Keridos/mumble,Natenom/mumble,SuperNascher/mumble,arrai/mumble-record,Githlar/mumble,Lartza/mumble,chiefdome/mumble-code,unascribed/mumble,chancegarcia/mumble,austinliou/mumble,Natenom/mumble,LuAPi/mumble,Natenom/mumble,feld/mumble,Natenom/mumble,unascribed/mumble,Zopieux/mumble,Natenom/mumble,niko20010/mumble,SuperNascher/mumble,Githlar/mumble,SuperNascher/mumble,SuperNascher/mumble,Lartza/mumble,ccpgames/mumble,LuAPi/mumble,austinliou/mumble,Zopieux/mumble,Keridos/mumble,mbax/mumble,Keridos/mumble,Keridos/mumble,Lartza/mumble,panaschieren/mumble-test,Zopieux/mumble,panaschieren/mumble-test,LuAPi/mumble,niko20010/mumble,austinliou/mumble
|
f3d97bc560e020ed4698634c2c5fd37dabd61b3d
|
src/XPM.cxx
|
src/XPM.cxx
|
// Scintilla source code edit control
/** @file XPM.cxx
** Define a class that holds data in the X Pixmap (XPM) format.
**/
// Copyright 1998-2003 by Neil Hodgson <[email protected]>
// The License.txt file describes the conditions under which this software may be distributed.
#include <string.h>
#include <stdlib.h>
#include "Platform.h"
#include "XPM.h"
static const char *NextField(const char *s) {
// In case there are leading spaces in the string
while (*s && *s == ' ') {
s++;
}
while (*s && *s != ' ') {
s++;
}
while (*s && *s == ' ') {
s++;
}
return s;
}
// Data lines in XPM can be terminated either with NUL or "
static size_t MeasureLength(const char *s) {
size_t i = 0;
while (s[i] && (s[i] != '\"'))
i++;
return i;
}
ColourAllocated XPM::ColourFromCode(int ch) {
return colourCodeTable[ch]->allocated;
#ifdef SLOW
for (int i=0; i<nColours; i++) {
if (codes[i] == ch) {
return colours[i].allocated;
}
}
return colours[0].allocated;
#endif
}
void XPM::FillRun(Surface *surface, int code, int startX, int y, int x) {
if ((code != codeTransparent) && (startX != x)) {
PRectangle rc(startX, y, x, y+1);
surface->FillRectangle(rc, ColourFromCode(code));
}
}
XPM::XPM(const char *textForm) :
data(0), codes(0), colours(0), lines(0) {
Init(textForm);
}
XPM::XPM(const char * const *linesForm) :
data(0), codes(0), colours(0), lines(0) {
Init(linesForm);
}
XPM::~XPM() {
Clear();
}
void XPM::Init(const char *textForm) {
Clear();
// Test done is two parts to avoid possibility of overstepping the memory
// if memcmp implemented strangely. Must be 4 bytes at least at destination.
if ((0 == memcmp(textForm, "/* X", 4)) && (0 == memcmp(textForm, "/* XPM */", 9))) {
// Build the lines form out of the text form
const char **linesForm = LinesFormFromTextForm(textForm);
if (linesForm != 0) {
Init(linesForm);
delete []linesForm;
}
} else {
// It is really in line form
Init(reinterpret_cast<const char * const *>(textForm));
}
}
void XPM::Init(const char * const *linesForm) {
Clear();
height = 1;
width = 1;
nColours = 1;
data = NULL;
codeTransparent = ' ';
codes = NULL;
colours = NULL;
lines = NULL;
if (!linesForm)
return;
const char *line0 = linesForm[0];
width = atoi(line0);
line0 = NextField(line0);
height = atoi(line0);
line0 = NextField(line0);
nColours = atoi(line0);
codes = new char[nColours];
colours = new ColourPair[nColours];
int strings = 1+height+nColours;
lines = new char *[strings];
size_t allocation = 0;
for (int i=0; i<strings; i++) {
allocation += MeasureLength(linesForm[i]) + 1;
}
data = new char[allocation];
char *nextBit = data;
for (int j=0; j<strings; j++) {
lines[j] = nextBit;
size_t len = MeasureLength(linesForm[j]);
memcpy(nextBit, linesForm[j], len);
nextBit += len;
*nextBit++ = '\0';
}
for (int code=0; code<256; code++) {
colourCodeTable[code] = 0;
}
for (int c=0; c<nColours; c++) {
const char *colourDef = linesForm[c+1];
codes[c] = colourDef[0];
colourDef += 4;
if (*colourDef == '#') {
colours[c].desired.Set(colourDef);
} else {
colours[c].desired = ColourDesired(0xff, 0xff, 0xff);
codeTransparent = codes[c];
}
colourCodeTable[static_cast<unsigned char>(codes[c])] = &(colours[c]);
}
}
void XPM::Clear() {
delete []data;
data = 0;
delete []codes;
codes = 0;
delete []colours;
colours = 0;
delete []lines;
lines = 0;
}
void XPM::RefreshColourPalette(Palette &pal, bool want) {
if (!data || !codes || !colours || !lines) {
return;
}
for (int i=0; i<nColours; i++) {
pal.WantFind(colours[i], want);
}
}
void XPM::CopyDesiredColours() {
if (!data || !codes || !colours || !lines) {
return;
}
for (int i=0; i<nColours; i++) {
colours[i].Copy();
}
}
void XPM::Draw(Surface *surface, PRectangle &rc) {
if (!data || !codes || !colours || !lines) {
return;
}
// Centre the pixmap
int startY = rc.top + (rc.Height() - height) / 2;
int startX = rc.left + (rc.Width() - width) / 2;
for (int y=0;y<height;y++) {
int prevCode = 0;
int xStartRun = 0;
for (int x=0; x<width; x++) {
int code = lines[y+nColours+1][x];
if (code != prevCode) {
FillRun(surface, prevCode, startX + xStartRun, startY + y, startX + x);
xStartRun = x;
prevCode = code;
}
}
FillRun(surface, prevCode, startX + xStartRun, startY + y, startX + width);
}
}
const char **XPM::LinesFormFromTextForm(const char *textForm) {
// Build the lines form out of the text form
const char **linesForm = 0;
int countQuotes = 0;
int strings=1;
int j=0;
for (; countQuotes < (2*strings) && textForm[j] != '\0'; j++) {
if (textForm[j] == '\"') {
if (countQuotes == 0) {
// First field: width, height, number of colors, chars per pixel
const char *line0 = textForm + j + 1;
// Skip width
line0 = NextField(line0);
// Add 1 line for each pixel of height
strings += atoi(line0);
line0 = NextField(line0);
// Add 1 line for each colour
strings += atoi(line0);
linesForm = new const char *[strings];
if (linesForm == 0) {
break; // Memory error!
}
}
if (countQuotes / 2 >= strings) {
break; // Bad height or number of colors!
}
if ((countQuotes & 1) == 0) {
linesForm[countQuotes / 2] = textForm + j + 1;
}
countQuotes++;
}
}
if (textForm[j] == '\0' || countQuotes / 2 > strings) {
// Malformed XPM! Height + number of colors too high or too low
delete []linesForm;
linesForm = 0;
}
return linesForm;
}
// In future, may want to minimize search time by sorting and using a binary search.
XPMSet::XPMSet() : set(0), len(0), maximum(0), height(-1), width(-1) {
}
XPMSet::~XPMSet() {
Clear();
}
void XPMSet::Clear() {
for (int i = 0; i < len; i++) {
delete set[i];
}
delete []set;
set = 0;
len = 0;
maximum = 0;
height = -1;
width = -1;
}
void XPMSet::Add(int id, const char *textForm) {
// Invalidate cached dimensions
height = -1;
width = -1;
// Replace if this id already present
for (int i = 0; i < len; i++) {
if (set[i]->GetId() == id) {
set[i]->Init(textForm);
return;
}
}
// Not present, so add to end
XPM *pxpm = new XPM(textForm);
if (pxpm) {
pxpm->SetId(id);
pxpm->CopyDesiredColours();
if (len == maximum) {
maximum += 64;
XPM **setNew = new XPM *[maximum];
for (int i = 0; i < len; i++) {
setNew[i] = set[i];
}
delete []set;
set = setNew;
}
set[len] = pxpm;
len++;
}
}
XPM *XPMSet::Get(int id) {
for (int i = 0; i < len; i++) {
if (set[i]->GetId() == id) {
return set[i];
}
}
return 0;
}
int XPMSet::GetHeight() {
if (height < 0) {
for (int i = 0; i < len; i++) {
if (height < set[i]->GetHeight()) {
height = set[i]->GetHeight();
}
}
}
return (height > 0) ? height : 0;
}
int XPMSet::GetWidth() {
if (width < 0) {
for (int i = 0; i < len; i++) {
if (width < set[i]->GetWidth()) {
width = set[i]->GetWidth();
}
}
}
return (width > 0) ? width : 0;
}
|
// Scintilla source code edit control
/** @file XPM.cxx
** Define a class that holds data in the X Pixmap (XPM) format.
**/
// Copyright 1998-2003 by Neil Hodgson <[email protected]>
// The License.txt file describes the conditions under which this software may be distributed.
#include <string.h>
#include <stdlib.h>
#include "Platform.h"
#include "XPM.h"
static const char *NextField(const char *s) {
// In case there are leading spaces in the string
while (*s && *s == ' ') {
s++;
}
while (*s && *s != ' ') {
s++;
}
while (*s && *s == ' ') {
s++;
}
return s;
}
// Data lines in XPM can be terminated either with NUL or "
static size_t MeasureLength(const char *s) {
size_t i = 0;
while (s[i] && (s[i] != '\"'))
i++;
return i;
}
ColourAllocated XPM::ColourFromCode(int ch) {
return colourCodeTable[ch]->allocated;
#ifdef SLOW
for (int i=0; i<nColours; i++) {
if (codes[i] == ch) {
return colours[i].allocated;
}
}
return colours[0].allocated;
#endif
}
void XPM::FillRun(Surface *surface, int code, int startX, int y, int x) {
if ((code != codeTransparent) && (startX != x)) {
PRectangle rc(startX, y, x, y+1);
surface->FillRectangle(rc, ColourFromCode(code));
}
}
XPM::XPM(const char *textForm) :
data(0), codes(0), colours(0), lines(0) {
Init(textForm);
}
XPM::XPM(const char * const *linesForm) :
data(0), codes(0), colours(0), lines(0) {
Init(linesForm);
}
XPM::~XPM() {
Clear();
}
void XPM::Init(const char *textForm) {
Clear();
// Test done is two parts to avoid possibility of overstepping the memory
// if memcmp implemented strangely. Must be 4 bytes at least at destination.
if ((0 == memcmp(textForm, "/* X", 4)) && (0 == memcmp(textForm, "/* XPM */", 9))) {
// Build the lines form out of the text form
const char **linesForm = LinesFormFromTextForm(textForm);
if (linesForm != 0) {
Init(linesForm);
delete []linesForm;
}
} else {
// It is really in line form
Init(reinterpret_cast<const char * const *>(textForm));
}
}
void XPM::Init(const char * const *linesForm) {
Clear();
height = 1;
width = 1;
nColours = 1;
data = NULL;
codeTransparent = ' ';
codes = NULL;
colours = NULL;
lines = NULL;
if (!linesForm)
return;
const char *line0 = linesForm[0];
width = atoi(line0);
line0 = NextField(line0);
height = atoi(line0);
line0 = NextField(line0);
nColours = atoi(line0);
codes = new char[nColours];
colours = new ColourPair[nColours];
int strings = 1+height+nColours;
lines = new char *[strings];
size_t allocation = 0;
for (int i=0; i<strings; i++) {
allocation += MeasureLength(linesForm[i]) + 1;
}
data = new char[allocation];
char *nextBit = data;
for (int j=0; j<strings; j++) {
lines[j] = nextBit;
size_t len = MeasureLength(linesForm[j]);
memcpy(nextBit, linesForm[j], len);
nextBit += len;
*nextBit++ = '\0';
}
for (int code=0; code<256; code++) {
colourCodeTable[code] = 0;
}
for (int c=0; c<nColours; c++) {
const char *colourDef = linesForm[c+1];
codes[c] = colourDef[0];
colourDef += 4;
if (*colourDef == '#') {
colours[c].desired.Set(colourDef);
} else {
colours[c].desired = ColourDesired(0xff, 0xff, 0xff);
codeTransparent = codes[c];
}
colourCodeTable[static_cast<unsigned char>(codes[c])] = &(colours[c]);
}
}
void XPM::Clear() {
delete []data;
data = 0;
delete []codes;
codes = 0;
delete []colours;
colours = 0;
delete []lines;
lines = 0;
}
void XPM::RefreshColourPalette(Palette &pal, bool want) {
if (!data || !codes || !colours || !lines) {
return;
}
for (int i=0; i<nColours; i++) {
pal.WantFind(colours[i], want);
}
}
void XPM::CopyDesiredColours() {
if (!data || !codes || !colours || !lines) {
return;
}
for (int i=0; i<nColours; i++) {
colours[i].Copy();
}
}
void XPM::Draw(Surface *surface, PRectangle &rc) {
if (!data || !codes || !colours || !lines) {
return;
}
// Centre the pixmap
int startY = rc.top + (rc.Height() - height) / 2;
int startX = rc.left + (rc.Width() - width) / 2;
for (int y=0;y<height;y++) {
int prevCode = 0;
int xStartRun = 0;
for (int x=0; x<width; x++) {
int code = lines[y+nColours+1][x];
if (code != prevCode) {
FillRun(surface, prevCode, startX + xStartRun, startY + y, startX + x);
xStartRun = x;
prevCode = code;
}
}
FillRun(surface, prevCode, startX + xStartRun, startY + y, startX + width);
}
}
const char **XPM::LinesFormFromTextForm(const char *textForm) {
// Build the lines form out of the text form
const char **linesForm = 0;
int countQuotes = 0;
int strings=1;
int j=0;
for (; countQuotes < (2*strings) && textForm[j] != '\0'; j++) {
if (textForm[j] == '\"') {
if (countQuotes == 0) {
// First field: width, height, number of colors, chars per pixel
const char *line0 = textForm + j + 1;
// Skip width
line0 = NextField(line0);
// Add 1 line for each pixel of height
strings += atoi(line0);
line0 = NextField(line0);
// Add 1 line for each colour
strings += atoi(line0);
linesForm = new const char *[strings];
if (linesForm == 0) {
break; // Memory error!
}
}
if (countQuotes / 2 >= strings) {
break; // Bad height or number of colors!
}
if ((countQuotes & 1) == 0) {
linesForm[countQuotes / 2] = textForm + j + 1;
}
countQuotes++;
}
}
if (textForm[j] == '\0' || countQuotes / 2 > strings) {
// Malformed XPM! Height + number of colors too high or too low
delete []linesForm;
linesForm = 0;
}
return linesForm;
}
// In future, may want to minimize search time by sorting and using a binary search.
XPMSet::XPMSet() : set(0), len(0), maximum(0), height(-1), width(-1) {
}
XPMSet::~XPMSet() {
Clear();
}
void XPMSet::Clear() {
for (int i = 0; i < len; i++) {
delete set[i];
}
delete []set;
set = 0;
len = 0;
maximum = 0;
height = -1;
width = -1;
}
void XPMSet::Add(int id, const char *textForm) {
// Invalidate cached dimensions
height = -1;
width = -1;
// Replace if this id already present
for (int i = 0; i < len; i++) {
if (set[i]->GetId() == id) {
set[i]->Init(textForm);
set[i]->CopyDesiredColours();
return;
}
}
// Not present, so add to end
XPM *pxpm = new XPM(textForm);
if (pxpm) {
pxpm->SetId(id);
pxpm->CopyDesiredColours();
if (len == maximum) {
maximum += 64;
XPM **setNew = new XPM *[maximum];
for (int i = 0; i < len; i++) {
setNew[i] = set[i];
}
delete []set;
set = setNew;
}
set[len] = pxpm;
len++;
}
}
XPM *XPMSet::Get(int id) {
for (int i = 0; i < len; i++) {
if (set[i]->GetId() == id) {
return set[i];
}
}
return 0;
}
int XPMSet::GetHeight() {
if (height < 0) {
for (int i = 0; i < len; i++) {
if (height < set[i]->GetHeight()) {
height = set[i]->GetHeight();
}
}
}
return (height > 0) ? height : 0;
}
int XPMSet::GetWidth() {
if (width < 0) {
for (int i = 0; i < len; i++) {
if (width < set[i]->GetWidth()) {
width = set[i]->GetWidth();
}
}
}
return (width > 0) ? width : 0;
}
|
Patch from Blair McGlashan in bug #1168430 to reallocate colours when changing a pixmap.
|
Patch from Blair McGlashan in bug #1168430 to reallocate colours when changing a pixmap.
|
C++
|
isc
|
timonwong/foo_uie_wsh_panel_mod.scintilla,timonwong/foo_uie_wsh_panel_mod.scintilla,timonwong/foo_uie_wsh_panel_mod.scintilla,timonwong/foo_uie_wsh_panel_mod.scintilla,timonwong/foo_uie_wsh_panel_mod.scintilla,timonwong/foo_uie_wsh_panel_mod.scintilla,timonwong/foo_uie_wsh_panel_mod.scintilla,timonwong/foo_uie_wsh_panel_mod.scintilla
|
6749fa0cd906db34416fde17d9bca698ad6eec57
|
modules/vrjuggler/vrj/Draw/Pf/PfUtil.cpp
|
modules/vrjuggler/vrj/Draw/Pf/PfUtil.cpp
|
/*************** <auto-copyright.pl BEGIN do not edit this line> **************
*
* VR Juggler is (C) Copyright 1998, 1999, 2000 by Iowa State University
*
* Original Authors:
* Allen Bierbaum, Christopher Just,
* Patrick Hartling, Kevin Meinert,
* Carolina Cruz-Neira, Albert Baker
*
* 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., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*
* -----------------------------------------------------------------
* File: $RCSfile$
* Date modified: $Date$
* Version: $Revision$
* -----------------------------------------------------------------
*
*************** <auto-copyright.pl END do not edit this line> ***************/
#include <vrj/vrjConfig.h>
#include <vrj/Draw/Pf/PfUtil.h>
#include <gmtl/Vec.h>
#include <gmtl/Generate.h>
#include <gmtl/MatrixOps.h>
#include <gmtl/VecOps.h>
namespace vrj
{
/**< Converts Performer matrix to Juggler (GMTL) matrix. */
gmtl::Matrix44f GetVjMatrix( const pfMatrix& perfMat )
{
gmtl::Matrix44f mat;
gmtl::Vec3f x_axis( 1,0,0 );
mat.set( &(perfMat.mat[0][0]) );
gmtl::postMult(mat, gmtl::makeRot<gmtl::Matrix44f>(gmtl::deg2Rad(90), x_axis ));
gmtl::preMult(mat, gmtl::makeRot<gmtl::Matrix44f>(gmtl::deg2Rad(-90), x_axis ));
return mat;
}
/**< Converts Juggler (GMTL) matrix to Pf Matrix. */
pfMatrix GetPfMatrix( const gmtl::Matrix44f& mat )
{
pfMatrix perf_mat;
// NOTE: the man page and the pfLinMath.h header file disagree.
// the man page says const float* and the header says float*
// the man page is correct, there is no reason for a set func to
// change the source data (unless you're ref counting or something weird)
// ...this may change in the future so that this cast can someday be removed.
float* floatPtr = const_cast<float *>( mat.mData );
perf_mat.set( floatPtr );
perf_mat.preRot( -90, 1, 0, 0, perf_mat );
perf_mat.postRot( perf_mat, 90, 1, 0, 0 );
return perf_mat;
}
/**< Converts Performer 3-element vector to Juggler (GMTL) vector. */
gmtl::Vec3f GetVjVec( const pfVec3& vec )
{
// Perf x z -y
return gmtl::Vec3f( vec[0], vec[2], -vec[1] );
}
/**< Converts Juggler (GMTL) vector to Pf vector. */
pfVec3 GetPfVec( const gmtl::Vec3f& vec )
{
// Juggler x -z y
return pfVec3( vec[0], -vec[2], vec[1] );
}
};
|
/*************** <auto-copyright.pl BEGIN do not edit this line> **************
*
* VR Juggler is (C) Copyright 1998, 1999, 2000 by Iowa State University
*
* Original Authors:
* Allen Bierbaum, Christopher Just,
* Patrick Hartling, Kevin Meinert,
* Carolina Cruz-Neira, Albert Baker
*
* 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., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*
* -----------------------------------------------------------------
* File: $RCSfile$
* Date modified: $Date$
* Version: $Revision$
* -----------------------------------------------------------------
*
*************** <auto-copyright.pl END do not edit this line> ***************/
#include <vrj/vrjConfig.h>
#include <vrj/Draw/Pf/PfUtil.h>
#include <gmtl/Vec.h>
#include <gmtl/Generate.h>
#include <gmtl/MatrixOps.h>
#include <gmtl/VecOps.h>
namespace vrj
{
/**< Converts Performer matrix to Juggler (GMTL) matrix. */
gmtl::Matrix44f GetVjMatrix( const pfMatrix& perfMat )
{
gmtl::Matrix44f mat;
gmtl::Vec3f x_axis( 1.0f, 0.0f, 0.0f );
mat.set( &(perfMat.mat[0][0]) );
gmtl::postMult(mat, gmtl::makeRot<gmtl::Matrix44f>(gmtl::deg2Rad(90.0f), x_axis ));
gmtl::preMult(mat, gmtl::makeRot<gmtl::Matrix44f>(gmtl::deg2Rad(-90.0f), x_axis ));
return mat;
}
/**< Converts Juggler (GMTL) matrix to Pf Matrix. */
pfMatrix GetPfMatrix( const gmtl::Matrix44f& mat )
{
pfMatrix perf_mat;
// NOTE: the man page and the pfLinMath.h header file disagree.
// the man page says const float* and the header says float*
// the man page is correct, there is no reason for a set func to
// change the source data (unless you're ref counting or something weird)
// ...this may change in the future so that this cast can someday be removed.
float* floatPtr = const_cast<float *>( mat.mData );
perf_mat.set( floatPtr );
perf_mat.preRot( -90.0f, 1.0f, 0.0f, 0.0f, perf_mat );
perf_mat.postRot( perf_mat, 90.0f, 1.0f, 0.0f, 0.0f );
return perf_mat;
}
/**< Converts Performer 3-element vector to Juggler (GMTL) vector. */
gmtl::Vec3f GetVjVec( const pfVec3& vec )
{
// Perf x z -y
return gmtl::Vec3f( vec[0], vec[2], -vec[1] );
}
/**< Converts Juggler (GMTL) vector to Pf vector. */
pfVec3 GetPfVec( const gmtl::Vec3f& vec )
{
// Juggler x -z y
return pfVec3( vec[0], -vec[2], vec[1] );
}
};
|
use floating point constants where floating point inputs are required...
|
use floating point constants where floating point inputs are required...
git-svn-id: 769d22dfa2d22aad706b9a451492fb87c0735f19@8947 08b38cba-cd3b-11de-854e-f91c5b6e4272
|
C++
|
lgpl-2.1
|
godbyk/vrjuggler-upstream-old,LiuKeHua/vrjuggler,godbyk/vrjuggler-upstream-old,MichaelMcDonnell/vrjuggler,vancegroup-mirrors/vrjuggler,vrjuggler/vrjuggler,LiuKeHua/vrjuggler,godbyk/vrjuggler-upstream-old,LiuKeHua/vrjuggler,vrjuggler/vrjuggler,vancegroup-mirrors/vrjuggler,godbyk/vrjuggler-upstream-old,LiuKeHua/vrjuggler,godbyk/vrjuggler-upstream-old,vrjuggler/vrjuggler,MichaelMcDonnell/vrjuggler,vrjuggler/vrjuggler,LiuKeHua/vrjuggler,MichaelMcDonnell/vrjuggler,LiuKeHua/vrjuggler,vrjuggler/vrjuggler,vancegroup-mirrors/vrjuggler,vancegroup-mirrors/vrjuggler,godbyk/vrjuggler-upstream-old,vrjuggler/vrjuggler,MichaelMcDonnell/vrjuggler,MichaelMcDonnell/vrjuggler,LiuKeHua/vrjuggler,MichaelMcDonnell/vrjuggler,vrjuggler/vrjuggler,MichaelMcDonnell/vrjuggler,vancegroup-mirrors/vrjuggler,LiuKeHua/vrjuggler,vrjuggler/vrjuggler,vancegroup-mirrors/vrjuggler,MichaelMcDonnell/vrjuggler
|
d2a25d8bc751702c6a0392a3fd66506f2e02f672
|
src/cxxconfig.hpp
|
src/cxxconfig.hpp
|
#ifndef TOML_CXX_CONFIG
#define TOML_CXX_CONFIG
#ifndef __cplusplus
#error "__cplusplus macro is not defined."
#endif
#if __cplusplus >= 201103L
# define TOML_ENABLE_CXX11 1
# define TOML_CONSTEXPR constexpr
# define TOML_NOEXCEPT noexcept
# define TOML_OVERRIDE override
# define TOML_NULLPTR nullptr
#else
# define TOML_CONSTEXPR
# define TOML_NOEXCEPT throw()
# define TOML_OVERRIDE
# define TOML_NULLPTR NULL
#endif
#ifdef TOML_ENABLE_CXX11
# include <memory>
# include <chrono>
# include <cstdint>
namespace toml
{
using std::shared_ptr;
using std::make_shared;
using std::dynamic_pointer_cast;
namespace chrono
{
using std::chrono::system_clock;
using std::chrono::hours;
using std::chrono::minutes;
using std::chrono::microseconds;
}
using std::int_least64_t;
}
#else // c++98 only
# include <boost/shared_ptr.hpp>
# include <boost/make_shared.hpp>
# ifndef BOOST_ERROR_CODE_HEADER_ONLY
# define BOOST_ERROR_CODE_HEADER_ONLY
# endif
# ifndef BOOST_CHRONO_INLINED
# define BOOST_CHRONO_INLINED
# endif
# include <boost/chrono.hpp>
namespace toml
{
using boost::shared_ptr;
using boost::make_shared;
using boost::dynamic_pointer_cast;
namespace chrono
{
using boost::chrono::system_clock;
using boost::chrono::hours;
using boost::chrono::minutes;
using boost::chrono::microseconds;
}
}
#ifdef TOML_HAVE_STDINT_H
# include <stdint.h>
namespace toml
{
using ::int_least64_t;
}
#else
# include <boost/cstdint.hpp>
namespace toml
{
using boost::int_least64_t;
}
#endif
#endif // c++11
#endif /* TOML_CXX_CONFIG */
|
#ifndef TOML_CXX_CONFIG
#define TOML_CXX_CONFIG
#ifndef __cplusplus
#error "__cplusplus macro is not defined."
#endif
#if __cplusplus >= 201103L
# define TOML_ENABLE_CXX11 1
# define TOML_CONSTEXPR constexpr
# define TOML_NOEXCEPT noexcept
# define TOML_OVERRIDE override
# define TOML_NULLPTR nullptr
#else
# define TOML_CONSTEXPR
# define TOML_NOEXCEPT throw()
# define TOML_OVERRIDE
# define TOML_NULLPTR NULL
#endif
#ifdef TOML_ENABLE_CXX11
# include <memory>
# include <chrono>
# include <cstdint>
namespace toml
{
using std::shared_ptr;
using std::make_shared;
using std::dynamic_pointer_cast;
namespace chrono
{
using std::chrono::system_clock;
using std::chrono::hours;
using std::chrono::minutes;
using std::chrono::microseconds;
}
using std::int_least64_t;
}
#else // c++98 only
# include <boost/shared_ptr.hpp>
# include <boost/make_shared.hpp>
# ifndef BOOST_ERROR_CODE_HEADER_ONLY
# define BOOST_ERROR_CODE_HEADER_ONLY
# endif
# ifndef BOOST_SYSTEM_NO_LIB
# define BOOST_SYSTEM_NO_LIB
# endif
# ifndef BOOST_CHRONO_HEADER_ONLY
# define BOOST_CHRONO_HEADER_ONLY
# endif
# ifndef BOOST_CHRONO_INLINE
# define BOOST_CHRONO_INLINE inline
# endif
# include <boost/chrono.hpp>
namespace toml
{
using boost::shared_ptr;
using boost::make_shared;
using boost::dynamic_pointer_cast;
namespace chrono
{
using boost::chrono::system_clock;
using boost::chrono::hours;
using boost::chrono::minutes;
using boost::chrono::microseconds;
}
}
# ifdef TOML_HAVE_STDINT_H
# include <stdint.h>
namespace toml
{
using ::int_least64_t;
}
# else
# include <boost/cstdint.hpp>
namespace toml
{
using boost::int_least64_t;
}
# endif
#endif // c++11
#endif /* TOML_CXX_CONFIG */
|
update cxxconfig
|
update cxxconfig
|
C++
|
mit
|
ToruNiina/TOMLParser
|
39c7eaa949ec55117bda567bb216e27ecf8b8c17
|
tools/cutehmi.daemon.1/tests/test_cutehmi_daemon.cpp
|
tools/cutehmi.daemon.1/tests/test_cutehmi_daemon.cpp
|
#include <QtTest/QtTest>
#include <QProcess>
namespace cutehmi {
namespace daemon {
class test_cutehmi_daemon:
public QObject
{
Q_OBJECT
private slots:
void initTestCase();
void helpOption();
void versionOption();
void countDaemonExample();
private:
QString m_installDir;
QString m_programPath;
};
void test_cutehmi_daemon::initTestCase()
{
QString m_installDir = qEnvironmentVariable("CUTEHMI_INSTALL_DIR");
QVERIFY(!m_installDir.isEmpty());
QString toolInstallSubdir = qEnvironmentVariable("CUTEHMI_TOOL_INSTALL_SUBDIR");
if (!toolInstallSubdir.isEmpty())
m_installDir += "/" + toolInstallSubdir;
m_programPath = m_installDir + "/cutehmi_daemon";
#ifndef CUTEHMI_NDEBUG
m_programPath += "_debug";
#endif
}
void test_cutehmi_daemon::helpOption()
{
QList<QStringList> argumentsList;
argumentsList << QStringList({"--help"})
<< QStringList({"--h"});
for (auto arguments : argumentsList) {
QProcess process;
process.start(m_programPath, arguments);
process.waitForFinished(1000);
QCOMPARE(process.error(), QProcess::UnknownError);
QVERIFY(!process.readAllStandardError().contains("Unknown option"));
QVERIFY(!process.readAllStandardOutput().isEmpty());
QCOMPARE(process.exitStatus(), QProcess::NormalExit);
QCOMPARE(process.exitCode(), EXIT_SUCCESS);
}
}
void test_cutehmi_daemon::versionOption()
{
QList<QStringList> argumentsList;
argumentsList << QStringList({"--version"})
<< QStringList({"--v"});
for (auto arguments : argumentsList) {
QProcess process;
process.start(m_programPath, arguments);
process.waitForFinished(1000);
QCOMPARE(process.error(), QProcess::UnknownError);
QVERIFY(!process.readAllStandardError().contains("Unknown option"));
QVERIFY(!process.readAllStandardOutput().isEmpty());
QCOMPARE(process.exitStatus(), QProcess::NormalExit);
QCOMPARE(process.exitCode(), EXIT_SUCCESS);
}
}
void test_cutehmi_daemon::countDaemonExample()
{
QProcess process;
QStringList arguments { {"--app"}, {"--project=examples/cutehmi_daemon/CountDaemon/Main.qml"} };
process.start(m_programPath, arguments);
QVERIFY(process.waitForFinished());
QString stdOut = QString::fromLocal8Bit(process.readAllStandardOutput());
QString stdErr = QString::fromLocal8Bit(process.readAllStandardError());
QVERIFY(!stdErr.contains("Unknown option"));
{
QRegExp rx(".*(Project file .* does not exist).*");
QVERIFY2(!rx.exactMatch(stdErr), rx.cap(1).toLocal8Bit().constData());
}
QVERIFY(stdErr.contains("I can count"));
QCOMPARE(process.error(), QProcess::UnknownError);
QCOMPARE(process.exitStatus(), QProcess::NormalExit);
QCOMPARE(process.exitCode(), EXIT_SUCCESS);
}
}
}
QTEST_MAIN(cutehmi::daemon::test_cutehmi_daemon)
#include "test_cutehmi_daemon.moc"
//(c)C: Copyright © 2019, Michał Policht <[email protected]>, Wojtek Zygmuntowicz <[email protected]>. All rights reserved.
//(c)C: This file is a part of CuteHMI.
//(c)C: CuteHMI is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
//(c)C: CuteHMI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
//(c)C: You should have received a copy of the GNU Lesser General Public License along with CuteHMI. If not, see <https://www.gnu.org/licenses/>.
|
#include <QtTest/QtTest>
#include <QProcess>
namespace cutehmi {
namespace daemon {
class test_cutehmi_daemon:
public QObject
{
Q_OBJECT
private slots:
void initTestCase();
void helpOption();
void versionOption();
void countDaemonExample();
private:
QString m_installDir;
QString m_programPath;
};
void test_cutehmi_daemon::initTestCase()
{
QString m_installDir = qEnvironmentVariable("CUTEHMI_INSTALL_DIR");
QVERIFY(!m_installDir.isEmpty());
QString toolInstallSubdir = qEnvironmentVariable("CUTEHMI_TOOL_INSTALL_SUBDIR");
if (!toolInstallSubdir.isEmpty())
m_installDir += "/" + toolInstallSubdir;
m_programPath = m_installDir + "/cutehmi.daemon.1";
#ifndef CUTEHMI_NDEBUG
m_programPath += ".debug";
#endif
}
void test_cutehmi_daemon::helpOption()
{
QList<QStringList> argumentsList;
argumentsList << QStringList({"--help"})
<< QStringList({"--h"});
for (auto arguments : argumentsList) {
QProcess process;
process.start(m_programPath, arguments);
process.waitForFinished(1000);
QCOMPARE(process.error(), QProcess::UnknownError);
QVERIFY(!process.readAllStandardError().contains("Unknown option"));
QVERIFY(!process.readAllStandardOutput().isEmpty());
QCOMPARE(process.exitStatus(), QProcess::NormalExit);
QCOMPARE(process.exitCode(), EXIT_SUCCESS);
}
}
void test_cutehmi_daemon::versionOption()
{
QList<QStringList> argumentsList;
argumentsList << QStringList({"--version"})
<< QStringList({"--v"});
for (auto arguments : argumentsList) {
QProcess process;
process.start(m_programPath, arguments);
process.waitForFinished(1000);
QCOMPARE(process.error(), QProcess::UnknownError);
QVERIFY(!process.readAllStandardError().contains("Unknown option"));
QVERIFY(!process.readAllStandardOutput().isEmpty());
QCOMPARE(process.exitStatus(), QProcess::NormalExit);
QCOMPARE(process.exitCode(), EXIT_SUCCESS);
}
}
void test_cutehmi_daemon::countDaemonExample()
{
QProcess process;
QStringList arguments { {"--app"}, {"--project=examples/cutehmi.daemon.1/CountDaemon/Main.qml"} };
process.start(m_programPath, arguments);
QVERIFY(process.waitForFinished());
QString stdOut = QString::fromLocal8Bit(process.readAllStandardOutput());
QString stdErr = QString::fromLocal8Bit(process.readAllStandardError());
QVERIFY(!stdErr.contains("Unknown option"));
{
QRegExp rx(".*(Project file .* does not exist).*");
QVERIFY2(!rx.exactMatch(stdErr), rx.cap(1).toLocal8Bit().constData());
}
QVERIFY(stdErr.contains("I can count"));
QCOMPARE(process.error(), QProcess::UnknownError);
QCOMPARE(process.exitStatus(), QProcess::NormalExit);
QCOMPARE(process.exitCode(), EXIT_SUCCESS);
}
}
}
QTEST_MAIN(cutehmi::daemon::test_cutehmi_daemon)
#include "test_cutehmi_daemon.moc"
//(c)C: Copyright © 2019, Michał Policht <[email protected]>, Wojtek Zygmuntowicz <[email protected]>. All rights reserved.
//(c)C: This file is a part of CuteHMI.
//(c)C: CuteHMI is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
//(c)C: CuteHMI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
//(c)C: You should have received a copy of the GNU Lesser General Public License along with CuteHMI. If not, see <https://www.gnu.org/licenses/>.
|
Fix daemon test.
|
Fix daemon test.
|
C++
|
mit
|
michpolicht/CuteHMI,michpolicht/CuteHMI,michpolicht/CuteHMI,michpolicht/CuteHMI,michpolicht/CuteHMI
|
5f8c6f8b053d0db311be2aeff2d7331e1db47f20
|
src/cpm.cpp
|
src/cpm.cpp
|
//=======================================================================
// Copyright (c) 2015 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <stdio.h>
#include <dirent.h>
#include "cxxopts.hpp"
#include "rapidjson/document.h"
#include "rapidjson/filereadstream.h"
#include "cpm/io.hpp"
//Allow range-based for loop on rapidjson objects
namespace rapidjson {
inline auto begin(rapidjson::Value& value){
return value.Begin();
}
inline auto end(rapidjson::Value& value){
return value.End();
}
} //end of namespace rapidjson
namespace {
std::string dark_unica_theme =
#include "dark_unica.inc"
;
rapidjson::Document read_document(const std::string& folder, const std::string& file){
FILE* pFile = fopen((folder + "/" + file).c_str(), "rb");
char buffer[65536];
rapidjson::FileReadStream is(pFile, buffer, sizeof(buffer));
rapidjson::Document doc;
doc.ParseStream<0>(is);
return doc;
}
void header(std::ostream& stream){
stream << "<html>" << std::endl;
stream << "<head>" << std::endl;
stream << "<script src=\"http://code.jquery.com/jquery-1.11.3.min.js\"></script>" << std::endl;
stream << "<script src=\"http://code.jquery.com/jquery-migrate-1.2.1.min.js\"></script>" << std::endl;
stream << "<script src=\"http://code.highcharts.com/highcharts.js\"></script>" << std::endl;
stream << "<script src=\"http://code.highcharts.com/modules/exporting.js\"></script>" << std::endl;
stream << "</head>" << std::endl;
stream << "<body>" << std::endl;
}
void footer(std::ostream& stream){
stream << "</body>" << std::endl;
stream << "</html>" << std::endl;
}
void information(std::ostream& stream, rapidjson::Document& doc){
stream << "<h1>" << doc["name"].GetString() << "</h1>" << std::endl;
stream << "<ul>" << std::endl;
stream << "<li>Compiler: " << doc["compiler"].GetString() << "</li>" << std::endl;
stream << "<li>Operating System: " << doc["os"].GetString() << "</li>" << std::endl;
stream << "<li>Time: " << doc["time"].GetString() << "</li>" << std::endl;
stream << "</ul>" << std::endl;
}
std::vector<rapidjson::Document> read(const std::string& source_folder){
std::vector<rapidjson::Document> documents;
struct dirent* entry;
DIR* dp = opendir(source_folder.c_str());
if(!dp){
return documents;
}
while((entry = readdir(dp))){
if(std::string(entry->d_name) == "." || std::string(entry->d_name) == ".."){
continue;
}
documents.push_back(read_document(source_folder, entry->d_name));
}
std::sort(documents.begin(), documents.end(),
[](rapidjson::Document& lhs, rapidjson::Document& rhs){ return lhs["timestamp"].GetInt() < rhs["timestamp"].GetInt(); });
return documents;
}
} //end of anonymous namespace
int main(int argc, char* argv[]){
cxxopts::Options options(argv[0], " results_folder");
try {
options.add_options()
("s,time-sizes", "Display multiple sizes in the time graphs")
("t,theme", "Theme name [std,dark_unica]", cxxopts::value<std::string>()->default_value("dark_unica"), "theme_name")
("o,output", "Output folder", cxxopts::value<std::string>()->default_value("reports"), "output_folder")
("input", "Input results", cxxopts::value<std::string>())
("d,disable-time", "Disable time graphs")
("h,help", "Print help")
;
options.parse_positional("input");
options.parse(argc, argv);
if (options.count("help")){
std::cout << options.help({""}) << std::endl;
return 0;
}
if (!options.count("input")){
std::cout << "cpm: No input provided, exiting" << std::endl;
return 0;
}
} catch (const cxxopts::OptionException& e){
std::cout << "cpm: error parsing options: " << e.what() << std::endl;
return -1;
}
//Get the entered folders
auto source_folder = options["input"].as<std::string>();
auto target_folder = options["output"].as<std::string>();
if(!cpm::folder_exists(source_folder)){
std::cout << "cpm: The input folder does not exists, exiting" << std::endl;
return -1;
}
if(!cpm::folder_exists(target_folder)){
std::cout << "cpm: The target folder does not exists, exiting" << std::endl;
return -1;
}
bool time_graphs = !options.count("disable-time");
std::string target_file = target_folder + "/index.html";
auto documents = read(source_folder);
if(documents.empty()){
std::cout << "Unable to read any files" << std::endl;
return -1;
}
auto& doc = documents.front();
std::ofstream stream(target_file);
header(stream);
information(stream, doc);
//Configure the theme
if(options["theme"].as<std::string>() == "dark_unica"){
stream << "<script>" << std::endl;
stream << dark_unica_theme << std::endl;
stream << "</script>" << std::endl;
}
std::size_t id = 1;
for(auto& result : doc["results"]){
stream << "<h2 style=\"clear:both\">" << result["title"].GetString() << "</h2>" << std::endl;
//1. Generate the last run graph
stream << "<div id=\"chart_" << id << "\" style=\"float:left; width:600px; height: 400px; margin: 5 auto; padding-right: 10px; \"></div>" << std::endl;
stream << "<script>" << std::endl;
stream << "$(function () {" << std::endl;
stream << "$('#chart_" << id << "').highcharts({" << std::endl;
stream << "title: { text: 'Last run: " << result["title"].GetString() << "', x: -20 }," << std::endl;
stream << "xAxis: { categories: [" << std::endl;
std::string comma = "";
for(auto& r : result["results"]){
stream << comma << "'" << r["size"].GetInt() << "'";
comma = ",";
}
stream << "]}," << std::endl;
stream << "yAxis: {" << std::endl;
stream << "title: { text: 'Time [us]' }," << std::endl;
stream << "plotLines: [{ value: 0, width: 1, color: '#808080'}]" << std::endl;
stream << "}," << std::endl;
stream << "tooltip: { valueSuffix: 'us' }," << std::endl;
stream << "legend: { enabled: false }," << std::endl;
stream << "series: [" << std::endl;
stream << "{" << std::endl;
stream << "name: ''," << std::endl;
stream << "data: [";
comma = "";
for(auto& r : result["results"]){
stream << comma << r["duration"].GetInt();
comma = ",";
}
stream << "]" << std::endl;
stream << "}" << std::endl;
stream << "]" << std::endl;
stream << "});" << std::endl;
stream << "});" << std::endl;
stream << "</script>" << std::endl;
++id;
if(time_graphs){
//2. Generate the time series graph
stream << "<div id=\"chart_" << id << "\" style=\"float:left; width:600px; height: 400px; margin: 5 auto\"></div>" << std::endl;
stream << "<script>" << std::endl;
stream << "$(function () {" << std::endl;
stream << "$('#chart_" << id << "').highcharts({" << std::endl;
stream << "title: { text: 'Time: " << result["title"].GetString() << "', x: -20 }," << std::endl;
stream << "xAxis: { type: 'datetime', title: { text: 'Date' } }," << std::endl;
stream << "yAxis: {" << std::endl;
stream << "title: { text: 'Time [us]' }," << std::endl;
stream << "plotLines: [{ value: 0, width: 1, color: '#808080'}]" << std::endl;
stream << "}," << std::endl;
stream << "tooltip: { valueSuffix: 'us' }," << std::endl;
if(!options.count("time-sizes")){
stream << "legend: { enabled: false }," << std::endl;
}
stream << "series: [" << std::endl;
if(options.count("time-sizes")){
comma = "";
for(auto& r : result["results"]){
stream << comma << "{" << std::endl;
stream << "name: '" << r["size"].GetInt() << "'," << std::endl;
stream << "data: [";
std::string inner_comma = "";
for(auto& document : documents){
for(auto& o_result : document["results"]){
if(std::string(o_result["title"].GetString()) == std::string(result["title"].GetString())){
for(auto& o_rr : o_result["results"]){
if(o_rr["size"].GetInt() == r["size"].GetInt()){
stream << inner_comma << "[" << document["timestamp"].GetInt() * 1000 << ",";
stream << o_rr["duration"].GetInt() << "]";
inner_comma = ",";
}
}
}
}
}
stream << "]" << std::endl;
stream << "}" << std::endl;
comma =",";
}
} else {
stream << "{" << std::endl;
stream << "name: ''," << std::endl;
stream << "data: [";
std::string inner_comma = "";
for(auto& document : documents){
for(auto& o_result : document["results"]){
if(std::string(o_result["title"].GetString()) == std::string(result["title"].GetString())){
stream << inner_comma << "[" << document["timestamp"].GetInt() * 1000 << ",";
auto& o_r_results = o_result["results"];
stream << o_r_results[o_r_results.Size() - 1]["duration"].GetInt() << "]";
inner_comma = ",";
}
}
}
stream << "]" << std::endl;
stream << "}" << std::endl;
}
stream << "]" << std::endl;
stream << "});" << std::endl;
stream << "});" << std::endl;
stream << "</script>" << std::endl;
++id;
}
}
for(auto& section : doc["sections"]){
stream << "<h2 style=\"clear:both\">" << section["name"].GetString() << "</h2>" << std::endl;
//1. Generate the last run graph
stream << "<div id=\"chart_" << id << "\" style=\"float:left; width:600px; height:400px; margin: 5 auto; padding-right: 10px; \"></div>" << std::endl;
stream << "<script>" << std::endl;
stream << "$(function () {" << std::endl;
stream << "$('#chart_" << id << "').highcharts({" << std::endl;
stream << "title: { text: 'Last run:" << section["name"].GetString() << "', x: -20 }," << std::endl;
stream << "xAxis: { categories: [" << std::endl;
//TODO Use all the sizes
std::string comma = "";
for(auto& r : section["results"][static_cast<rapidjson::SizeType>(0)]["results"]){
stream << comma << "'" << r["size"].GetInt() << "'";
comma = ",";
}
stream << "]}," << std::endl;
stream << "yAxis: {" << std::endl;
stream << "title: { text: 'Time [us]' }," << std::endl;
stream << "plotLines: [{ value: 0, width: 1, color: '#808080'}]" << std::endl;
stream << "}," << std::endl;
stream << "tooltip: { valueSuffix: 'us' }," << std::endl;
stream << "legend: { align: 'left', verticalAlign: 'top', floating: false, borderWidth: 0, y: 20 }," << std::endl;
stream << "series: [" << std::endl;
comma = "";
for(auto& r : section["results"]){
stream << comma << "{" << std::endl;
stream << "name: '" << r["name"].GetString() << "'," << std::endl;
stream << "data: [";
std::string comma_inner = "";
for(auto& rr : r["results"]){
stream << comma_inner << rr["duration"].GetInt();
comma_inner = ",";
}
stream << "]" << std::endl;
stream << "}" << std::endl;
comma = ",";
}
stream << "]" << std::endl;
stream << "});" << std::endl;
stream << "});" << std::endl;
stream << "</script>" << std::endl;
++id;
if(time_graphs){
//2. Generate the time graph
stream << "<div id=\"chart_" << id << "\" style=\"float:left; width:600px; height:400px; margin: 5 auto; padding-right: 10px; \"></div>" << std::endl;
stream << "<script>" << std::endl;
stream << "$(function () {" << std::endl;
stream << "$('#chart_" << id << "').highcharts({" << std::endl;
stream << "title: { text: 'Time:" << section["name"].GetString() << "', x: -20 }," << std::endl;
stream << "xAxis: { type: 'datetime', title: { text: 'Date' } }," << std::endl;
stream << "yAxis: {" << std::endl;
stream << "title: { text: 'Time [us]' }," << std::endl;
stream << "plotLines: [{ value: 0, width: 1, color: '#808080'}]" << std::endl;
stream << "}," << std::endl;
stream << "tooltip: { valueSuffix: 'us' }," << std::endl;
stream << "legend: { align: 'left', verticalAlign: 'top', floating: false, borderWidth: 0, y: 20 }," << std::endl;
stream << "series: [" << std::endl;
comma = "";
for(auto& r : section["results"]){
stream << comma << "{" << std::endl;
stream << "name: '" << r["name"].GetString() << "'," << std::endl;
stream << "data: [";
std::string comma_inner = "";
for(auto& r_doc : documents){
for(auto& r_section : r_doc["sections"]){
if(std::string(r_section["name"].GetString()) == std::string(section["name"].GetString())){
for(auto& r_r : r_section["results"]){
if(std::string(r_r["name"].GetString()) == std::string(r["name"].GetString())){
stream << comma_inner << "[" << r_doc["timestamp"].GetInt() * 1000 << ",";
auto& r_r_results = r_r["results"];
stream << r_r_results[r_r_results.Size() - 1]["duration"].GetInt() << "]";
comma_inner = ",";
}
}
}
}
}
stream << "]" << std::endl;
stream << "}" << std::endl;
comma = ",";
}
stream << "]" << std::endl;
stream << "});" << std::endl;
stream << "});" << std::endl;
stream << "</script>" << std::endl;
++id;
}
}
footer(stream);
return 0;
}
|
//=======================================================================
// Copyright (c) 2015 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <stdio.h>
#include <dirent.h>
#include "cxxopts.hpp"
#include "rapidjson/document.h"
#include "rapidjson/filereadstream.h"
#include "cpm/io.hpp"
//Allow range-based for loop on rapidjson objects
namespace rapidjson {
inline auto begin(rapidjson::Value& value){
return value.Begin();
}
inline auto end(rapidjson::Value& value){
return value.End();
}
} //end of namespace rapidjson
namespace {
std::string dark_unica_theme =
#include "dark_unica.inc"
;
rapidjson::Document read_document(const std::string& folder, const std::string& file){
FILE* pFile = fopen((folder + "/" + file).c_str(), "rb");
char buffer[65536];
rapidjson::FileReadStream is(pFile, buffer, sizeof(buffer));
rapidjson::Document doc;
doc.ParseStream<0>(is);
return doc;
}
void header(std::ostream& stream){
stream << "<html>" << std::endl;
stream << "<head>" << std::endl;
stream << "<script src=\"http://code.jquery.com/jquery-1.11.3.min.js\"></script>" << std::endl;
stream << "<script src=\"http://code.jquery.com/jquery-migrate-1.2.1.min.js\"></script>" << std::endl;
stream << "<script src=\"http://code.highcharts.com/highcharts.js\"></script>" << std::endl;
stream << "<script src=\"http://code.highcharts.com/modules/exporting.js\"></script>" << std::endl;
stream << "</head>" << std::endl;
stream << "<body>" << std::endl;
}
void footer(std::ostream& stream){
stream << "</body>" << std::endl;
stream << "</html>" << std::endl;
}
void information(std::ostream& stream, rapidjson::Document& doc){
stream << "<h1>" << doc["name"].GetString() << "</h1>" << std::endl;
stream << "<ul>" << std::endl;
stream << "<li>Compiler: " << doc["compiler"].GetString() << "</li>" << std::endl;
stream << "<li>Operating System: " << doc["os"].GetString() << "</li>" << std::endl;
stream << "<li>Time: " << doc["time"].GetString() << "</li>" << std::endl;
stream << "</ul>" << std::endl;
}
std::vector<rapidjson::Document> read(const std::string& source_folder){
std::vector<rapidjson::Document> documents;
struct dirent* entry;
DIR* dp = opendir(source_folder.c_str());
if(!dp){
return documents;
}
while((entry = readdir(dp))){
if(std::string(entry->d_name) == "." || std::string(entry->d_name) == ".."){
continue;
}
documents.push_back(read_document(source_folder, entry->d_name));
}
std::sort(documents.begin(), documents.end(),
[](rapidjson::Document& lhs, rapidjson::Document& rhs){ return lhs["timestamp"].GetInt() < rhs["timestamp"].GetInt(); });
return documents;
}
} //end of anonymous namespace
int main(int argc, char* argv[]){
cxxopts::Options options(argv[0], " results_folder");
try {
options.add_options()
("s,time-sizes", "Display multiple sizes in the time graphs")
("t,theme", "Theme name [std,dark_unica]", cxxopts::value<std::string>()->default_value("dark_unica"), "theme_name")
("o,output", "Output folder", cxxopts::value<std::string>()->default_value("reports"), "output_folder")
("input", "Input results", cxxopts::value<std::string>())
("d,disable-time", "Disable time graphs")
("h,help", "Print help")
;
options.parse_positional("input");
options.parse(argc, argv);
if (options.count("help")){
std::cout << options.help({""}) << std::endl;
return 0;
}
if (!options.count("input")){
std::cout << "cpm: No input provided, exiting" << std::endl;
return 0;
}
} catch (const cxxopts::OptionException& e){
std::cout << "cpm: error parsing options: " << e.what() << std::endl;
return -1;
}
//Get the entered folders
auto source_folder = options["input"].as<std::string>();
auto target_folder = options["output"].as<std::string>();
if(!cpm::folder_exists(source_folder)){
std::cout << "cpm: The input folder does not exists, exiting" << std::endl;
return -1;
}
if(!cpm::folder_exists(target_folder)){
std::cout << "cpm: The target folder does not exists, exiting" << std::endl;
return -1;
}
bool time_graphs = !options.count("disable-time");
std::string target_file = target_folder + "/index.html";
auto documents = read(source_folder);
if(documents.empty()){
std::cout << "Unable to read any files" << std::endl;
return -1;
}
auto& doc = documents.front();
std::ofstream stream(target_file);
header(stream);
information(stream, doc);
//Configure the theme
if(options["theme"].as<std::string>() == "dark_unica"){
stream << "<script>" << std::endl;
stream << dark_unica_theme << std::endl;
stream << "</script>" << std::endl;
}
std::size_t id = 1;
for(auto& result : doc["results"]){
stream << "<h2 style=\"clear:both\">" << result["title"].GetString() << "</h2>" << std::endl;
//1. Generate the last run graph
stream << "<div id=\"chart_" << id << "\" style=\"float:left; width:600px; height: 400px; margin: 5 auto; padding-right: 10px; \"></div>" << std::endl;
stream << "<script>" << std::endl;
stream << "$(function () {" << std::endl;
stream << "$('#chart_" << id << "').highcharts({" << std::endl;
stream << "title: { text: 'Last run: " << result["title"].GetString() << "', x: -20 }," << std::endl;
stream << "xAxis: { categories: [" << std::endl;
std::string comma = "";
for(auto& r : result["results"]){
stream << comma << "'" << r["size"].GetString() << "'";
comma = ",";
}
stream << "]}," << std::endl;
stream << "yAxis: {" << std::endl;
stream << "title: { text: 'Time [us]' }," << std::endl;
stream << "plotLines: [{ value: 0, width: 1, color: '#808080'}]" << std::endl;
stream << "}," << std::endl;
stream << "tooltip: { valueSuffix: 'us' }," << std::endl;
stream << "legend: { enabled: false }," << std::endl;
stream << "series: [" << std::endl;
stream << "{" << std::endl;
stream << "name: ''," << std::endl;
stream << "data: [";
comma = "";
for(auto& r : result["results"]){
stream << comma << r["duration"].GetInt();
comma = ",";
}
stream << "]" << std::endl;
stream << "}" << std::endl;
stream << "]" << std::endl;
stream << "});" << std::endl;
stream << "});" << std::endl;
stream << "</script>" << std::endl;
++id;
if(time_graphs){
//2. Generate the time series graph
stream << "<div id=\"chart_" << id << "\" style=\"float:left; width:600px; height: 400px; margin: 5 auto\"></div>" << std::endl;
stream << "<script>" << std::endl;
stream << "$(function () {" << std::endl;
stream << "$('#chart_" << id << "').highcharts({" << std::endl;
stream << "title: { text: 'Time: " << result["title"].GetString() << "', x: -20 }," << std::endl;
stream << "xAxis: { type: 'datetime', title: { text: 'Date' } }," << std::endl;
stream << "yAxis: {" << std::endl;
stream << "title: { text: 'Time [us]' }," << std::endl;
stream << "plotLines: [{ value: 0, width: 1, color: '#808080'}]" << std::endl;
stream << "}," << std::endl;
stream << "tooltip: { valueSuffix: 'us' }," << std::endl;
if(!options.count("time-sizes")){
stream << "legend: { enabled: false }," << std::endl;
}
stream << "series: [" << std::endl;
if(options.count("time-sizes")){
comma = "";
for(auto& r : result["results"]){
stream << comma << "{" << std::endl;
stream << "name: '" << r["size"].GetString() << "'," << std::endl;
stream << "data: [";
std::string inner_comma = "";
for(auto& document : documents){
for(auto& o_result : document["results"]){
if(std::string(o_result["title"].GetString()) == std::string(result["title"].GetString())){
for(auto& o_rr : o_result["results"]){
if(o_rr["size"].GetString() == r["size"].GetString()){
stream << inner_comma << "[" << document["timestamp"].GetInt() * 1000 << ",";
stream << o_rr["duration"].GetInt() << "]";
inner_comma = ",";
}
}
}
}
}
stream << "]" << std::endl;
stream << "}" << std::endl;
comma =",";
}
} else {
stream << "{" << std::endl;
stream << "name: ''," << std::endl;
stream << "data: [";
std::string inner_comma = "";
for(auto& document : documents){
for(auto& o_result : document["results"]){
if(std::string(o_result["title"].GetString()) == std::string(result["title"].GetString())){
stream << inner_comma << "[" << document["timestamp"].GetInt() * 1000 << ",";
auto& o_r_results = o_result["results"];
stream << o_r_results[o_r_results.Size() - 1]["duration"].GetInt() << "]";
inner_comma = ",";
}
}
}
stream << "]" << std::endl;
stream << "}" << std::endl;
}
stream << "]" << std::endl;
stream << "});" << std::endl;
stream << "});" << std::endl;
stream << "</script>" << std::endl;
++id;
}
}
for(auto& section : doc["sections"]){
stream << "<h2 style=\"clear:both\">" << section["name"].GetString() << "</h2>" << std::endl;
//1. Generate the last run graph
stream << "<div id=\"chart_" << id << "\" style=\"float:left; width:600px; height:400px; margin: 5 auto; padding-right: 10px; \"></div>" << std::endl;
stream << "<script>" << std::endl;
stream << "$(function () {" << std::endl;
stream << "$('#chart_" << id << "').highcharts({" << std::endl;
stream << "title: { text: 'Last run:" << section["name"].GetString() << "', x: -20 }," << std::endl;
stream << "xAxis: { categories: [" << std::endl;
//TODO Use all the sizes
std::string comma = "";
for(auto& r : section["results"][static_cast<rapidjson::SizeType>(0)]["results"]){
stream << comma << "'" << r["size"].GetString() << "'";
comma = ",";
}
stream << "]}," << std::endl;
stream << "yAxis: {" << std::endl;
stream << "title: { text: 'Time [us]' }," << std::endl;
stream << "plotLines: [{ value: 0, width: 1, color: '#808080'}]" << std::endl;
stream << "}," << std::endl;
stream << "tooltip: { valueSuffix: 'us' }," << std::endl;
stream << "legend: { align: 'left', verticalAlign: 'top', floating: false, borderWidth: 0, y: 20 }," << std::endl;
stream << "series: [" << std::endl;
comma = "";
for(auto& r : section["results"]){
stream << comma << "{" << std::endl;
stream << "name: '" << r["name"].GetString() << "'," << std::endl;
stream << "data: [";
std::string comma_inner = "";
for(auto& rr : r["results"]){
stream << comma_inner << rr["duration"].GetInt();
comma_inner = ",";
}
stream << "]" << std::endl;
stream << "}" << std::endl;
comma = ",";
}
stream << "]" << std::endl;
stream << "});" << std::endl;
stream << "});" << std::endl;
stream << "</script>" << std::endl;
++id;
if(time_graphs){
//2. Generate the time graph
stream << "<div id=\"chart_" << id << "\" style=\"float:left; width:600px; height:400px; margin: 5 auto; padding-right: 10px; \"></div>" << std::endl;
stream << "<script>" << std::endl;
stream << "$(function () {" << std::endl;
stream << "$('#chart_" << id << "').highcharts({" << std::endl;
stream << "title: { text: 'Time:" << section["name"].GetString() << "', x: -20 }," << std::endl;
stream << "xAxis: { type: 'datetime', title: { text: 'Date' } }," << std::endl;
stream << "yAxis: {" << std::endl;
stream << "title: { text: 'Time [us]' }," << std::endl;
stream << "plotLines: [{ value: 0, width: 1, color: '#808080'}]" << std::endl;
stream << "}," << std::endl;
stream << "tooltip: { valueSuffix: 'us' }," << std::endl;
stream << "legend: { align: 'left', verticalAlign: 'top', floating: false, borderWidth: 0, y: 20 }," << std::endl;
stream << "series: [" << std::endl;
comma = "";
for(auto& r : section["results"]){
stream << comma << "{" << std::endl;
stream << "name: '" << r["name"].GetString() << "'," << std::endl;
stream << "data: [";
std::string comma_inner = "";
for(auto& r_doc : documents){
for(auto& r_section : r_doc["sections"]){
if(std::string(r_section["name"].GetString()) == std::string(section["name"].GetString())){
for(auto& r_r : r_section["results"]){
if(std::string(r_r["name"].GetString()) == std::string(r["name"].GetString())){
stream << comma_inner << "[" << r_doc["timestamp"].GetInt() * 1000 << ",";
auto& r_r_results = r_r["results"];
stream << r_r_results[r_r_results.Size() - 1]["duration"].GetInt() << "]";
comma_inner = ",";
}
}
}
}
}
stream << "]" << std::endl;
stream << "}" << std::endl;
comma = ",";
}
stream << "]" << std::endl;
stream << "});" << std::endl;
stream << "});" << std::endl;
stream << "</script>" << std::endl;
++id;
}
}
footer(stream);
return 0;
}
|
Fix handling of sizes
|
Fix handling of sizes
|
C++
|
mit
|
wichtounet/cpm,wichtounet/cpm,wichtounet/cpm
|
77f74d5c8f9f6c198193a0d1e19eebe8b72b917f
|
test/optimisationAlgorithm/trajectoryBasedAlgorithm/testHillClimbing.cpp
|
test/optimisationAlgorithm/trajectoryBasedAlgorithm/testHillClimbing.cpp
|
// Catch
#include <catch.hpp>
// C++ Standard Library
#include <memory>
#include <iostream>
// Armadillo
#include <armadillo>
// HOP
#include <hop>
class TestHillClimbing : public hop::HillClimbing {
public:
TestHillClimbing(
const std::shared_ptr<hop::OptimisationProblem> optimisationProblem)
: HillClimbing(optimisationProblem),
velocityIndex_(0){
velocities_.load("/Users/SRA/Documents/workspace/OnlineOptimisation/test/data/testVel.mat");
}
arma::Col<double> getVelocity() {
return velocities_.col(velocityIndex_++);
}
protected:
unsigned int velocityIndex_;
arma::mat velocities_;
};
class TestHillClimbingProblem : public hop::OptimisationProblem {
public:
TestHillClimbingProblem(
const unsigned int numberOfDimensions)
: OptimisationProblem(numberOfDimensions),
objectiveValueIndex_(0) {
objectiveValues_.load("/Users/SRA/Documents/workspace/OnlineOptimisation/test/data/testObj.mat");
}
arma::Mat<double> getParameterHistory() const noexcept {
return parameterHistory_;
}
protected:
unsigned int objectiveValueIndex_;
arma::Col<double> objectiveValues_;
int n;
arma::Mat<double> parameterHistory_;
double getObjectiveValueImplementation(
const arma::Col<double>& parameter) const override {
//parameterHistory_.insert_cols(n, parameter);
return objectiveValues_.at(objectiveValueIndex_);
}
std::string to_string() const noexcept {
return "HillClimbing";
}
};
TEST_CASE("Hill climbing", "") {
std::shared_ptr<TestHillClimbingProblem> testHillClimbingProblem(new TestHillClimbingProblem(4));
TestHillClimbing testHillClimbing(testHillClimbingProblem);
testHillClimbing.setInitialParameter(arma::zeros<arma::Col<double>>(testHillClimbingProblem->getNumberOfDimensions()));
testHillClimbing.setMaximalNumberOfIterations(4);
testHillClimbing.optimise();
arma::Mat<double> actualParameterHistory = testHillClimbingProblem->getParameterHistory();
actualParameterHistory.load("/Users/SRA/Documents/workspace/OnlineOptimisation/test/data/testExp.mat");
arma::Mat<double> expectedParameterHistory;
expectedParameterHistory.load("/Users/SRA/Documents/workspace/OnlineOptimisation/test/data/testExp.mat");
for(std::size_t n = 0; n < expectedParameterHistory.n_cols; ++n) {
arma::Col<double> expectedParameter = expectedParameterHistory.col(n);
arma::Col<double> actualParameter = actualParameterHistory.col(n);
for (std::size_t k = 0; k < expectedParameter.n_elem; ++k) {
CHECK(actualParameter.at(k) == Approx(expectedParameter.at(k)));
}
}
}
|
// Catch
#include <catch.hpp>
// C++ Standard Library
#include <memory>
#include <iostream>
// Armadillo
#include <armadillo>
// HOP
#include <hop>
class TestHillClimbing : public hop::HillClimbing {
public:
TestHillClimbing(
const std::shared_ptr<hop::OptimisationProblem> optimisationProblem)
: HillClimbing(optimisationProblem),
velocityIndex_(0){
velocities_.load("/Users/SRA/Documents/workspace/OnlineOptimisation/test/data/testVel.mat");
}
arma::Col<double> getVelocity() {
return velocities_.col(velocityIndex_++);
}
protected:
unsigned int velocityIndex_;
arma::mat velocities_;
};
class TestHillClimbingProblem : public hop::OptimisationProblem {
public:
TestHillClimbingProblem(
const unsigned int numberOfDimensions)
: OptimisationProblem(numberOfDimensions),
objectiveValueIndex_(0) {
objectiveValues_.load("/Users/SRA/Documents/workspace/OnlineOptimisation/test/data/testObj.mat");
}
std::vector<arma::Col<double>> getParameterHistory() const noexcept {
return parameterHistory_;
}
protected:
unsigned int objectiveValueIndex_;
arma::Col<double> objectiveValues_;
static std::vector<arma::Col<double>> parameterHistory_;
double getObjectiveValueImplementation(
const arma::Col<double>& parameter) const override {
parameterHistory_.push_back(parameter);
return objectiveValues_.at(objectiveValueIndex_);
}
std::string to_string() const noexcept {
return "TestHillClimbing";
}
};
decltype(TestHillClimbingProblem::parameterHistory_) TestHillClimbingProblem::parameterHistory_;
TEST_CASE("Hill climbing", "") {
std::shared_ptr<TestHillClimbingProblem> testHillClimbingProblem(new TestHillClimbingProblem(4));
TestHillClimbing testHillClimbing(testHillClimbingProblem);
testHillClimbing.setInitialParameter(arma::zeros<arma::Col<double>>(testHillClimbingProblem->getNumberOfDimensions()));
testHillClimbing.setMaximalNumberOfIterations(4);
testHillClimbing.optimise();
std::vector<arma::Col<double>> actualParameterHistory = testHillClimbingProblem->getParameterHistory();
arma::Mat<double> expectedParameterHistory;
expectedParameterHistory.load("/Users/SRA/Documents/workspace/OnlineOptimisation/test/data/testExp.mat");
for(std::size_t n = 0; n < expectedParameterHistory.n_cols; ++n) {
arma::Col<double> expectedParameter = expectedParameterHistory.col(n);
arma::Col<double> actualParameter = actualParameterHistory.at(n);
for (std::size_t k = 0; k < expectedParameter.n_elem; ++k) {
CHECK(actualParameter.at(k) == Approx(expectedParameter.at(k)));
}
}
}
|
Use std::vector<arma::Col<double>> for dynamic amounts of Columns
|
devel: Use std::vector<arma::Col<double>> for dynamic amounts of Columns
|
C++
|
mit
|
SebastianNiemann/Mantella,Mantella/Mantella,SebastianNiemann/Mantella,Mantella/Mantella,Mantella/Mantella,SebastianNiemann/Mantella
|
034b75b0a036a1821d7e921eb1d42794123368e5
|
src/cry.cpp
|
src/cry.cpp
|
#include <cstdio>
#include <fcntl.h>
#include <iostream>
#include <vector>
#include <string>
#include <termios.h>
#include <unistd.h>
#ifndef OFILL
#define OFILL 0000100
#endif
#ifndef OFDEL
#define OFDEL 0000200
#endif
#ifndef NLDLY
#define NLDLY 0000400
#endif
#ifndef CRDLY
#define CRDLY 0003000
#endif
#ifndef BSDLY
#define BSDLY 0020000
#endif
#ifndef VTDLY
#define VTDLY 0040000
#endif
#ifndef FFDLY
#define FFDLY 0100000
#endif
#include "Crc16.h"
struct Command {
uint8_t type;
uint8_t length;
uint8_t data[22];
uint16_t crc;
};
class Display {
public:
Display(std::string devName, speed_t baud = B115200) {
_devName = devName;
_baud = baud;
std::cout << "Init device: " << _devName.c_str() << std::endl;
_fd = open(_devName.c_str(), O_NOCTTY | O_NONBLOCK | O_RDWR );
if (_fd == -1) {
std::perror("Display():open");
}
struct termios term;
tcgetattr(_fd, &term);
term.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|INPCK|ISTRIP|INLCR|IGNCR|ICRNL
|IXON|IXOFF);
term.c_iflag |= IGNPAR;
//output modes
term.c_oflag &= ~(OPOST|ONLCR|OCRNL|ONOCR|ONLRET|OFILL
|OFDEL|NLDLY|CRDLY|TABDLY|BSDLY|VTDLY|FFDLY);
//control modes
term.c_cflag &= ~(CSIZE|PARENB|PARODD|HUPCL|CRTSCTS);
term.c_cflag |= CREAD|CS8|CSTOPB|CLOCAL;
//local modes
term.c_lflag &= ~(ISIG|ICANON|IEXTEN|ECHO);
term.c_lflag |= NOFLSH;
cfsetospeed(&term, baud);
cfsetispeed(&term, baud);
//set new device settings
if(tcsetattr(_fd, TCSANOW, &term) == -1) {
std::perror("Display():tcsetattr");
}
}
~Display() {
close(_fd);
_fd = -1;
}
void clear() {
uint8_t data[4] = { 0 };
data[0] = 0x06;
data[1] = 0;
uint16_t crc = Crc16::compute(data, 2);
data[3] = (0xFF00 & crc) >> 8;
data[2] = 0x00FF & crc;
write(_fd, data, 4);
}
void text() {
std::string text("hello world!");
uint8_t data[1 + 1 + 22 + 2] = { 0 };
data[0] = 0x1F;
data[1] = text.length() + 2;
data[2] = 0;
data[3] = 1;
std::copy(text.begin(), text.end(), &data[4]);
uint16_t crc = Crc16::compute(data, data[1] + 2);
printf("crc: %x\n", crc);
data[16] = 0xFF & crc;
data[17] = (0xFF00 & crc) >> 8;
write(_fd, data, 18);
}
void setLedState() {
Command cmd;
cmd.type = 0x22;
cmd.length = 2;
cmd.data[0] = 5;
cmd.data[1] = 100;
cmd.crc = Crc16::compute((uint8_t *) &cmd, cmd.length + 2);
//write(_fd, (uint8_t *) &cmd, cmd.length + 2 + 2);
send(cmd);
}
void send(Command &cmd) {
write(_fd, &cmd.type, 2);
write(_fd, &cmd.data, cmd.length);
uint16_t crc = Crc16::compute((uint8_t *) &cmd, cmd.length + 2);
printf("CRC: %x\n", crc);
write(_fd, &crc, 2);
}
private:
int _fd;
std::string _devName;
speed_t _baud;
};
int main (int argc, char *argv[]) {
Display d("/dev/ttyU0");
d.clear();
d.text();
d.setLedState();
Command cmd;
cmd.type = 0x1F;
cmd.length = 14;
cmd.data[0] = 0;
cmd.data[1] = 1;
std::string msg("hello world!");
std::copy(msg.begin(), msg.end(), &cmd.data[2]);
d.send(cmd);
}
|
#include <cstdio>
#include <fcntl.h>
#include <iostream>
#include <vector>
#include <string>
#include <termios.h>
#include <unistd.h>
#ifndef OFILL
#define OFILL 0000100
#endif
#ifndef OFDEL
#define OFDEL 0000200
#endif
#ifndef NLDLY
#define NLDLY 0000400
#endif
#ifndef CRDLY
#define CRDLY 0003000
#endif
#ifndef BSDLY
#define BSDLY 0020000
#endif
#ifndef VTDLY
#define VTDLY 0040000
#endif
#ifndef FFDLY
#define FFDLY 0100000
#endif
#include "Crc16.h"
#include "Command.h"
class Display {
public:
Display(std::string devName, speed_t baud = B115200) {
_devName = devName;
_baud = baud;
std::cout << "Init device: " << _devName.c_str() << std::endl;
_fd = open(_devName.c_str(), O_NOCTTY | O_NONBLOCK | O_RDWR );
if (_fd == -1) {
std::perror("Display():open");
}
struct termios term;
tcgetattr(_fd, &term);
term.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|INPCK|ISTRIP|INLCR|IGNCR|ICRNL
|IXON|IXOFF);
term.c_iflag |= IGNPAR;
//output modes
term.c_oflag &= ~(OPOST|ONLCR|OCRNL|ONOCR|ONLRET|OFILL
|OFDEL|NLDLY|CRDLY|TABDLY|BSDLY|VTDLY|FFDLY);
//control modes
term.c_cflag &= ~(CSIZE|PARENB|PARODD|HUPCL|CRTSCTS);
term.c_cflag |= CREAD|CS8|CSTOPB|CLOCAL;
//local modes
term.c_lflag &= ~(ISIG|ICANON|IEXTEN|ECHO);
term.c_lflag |= NOFLSH;
cfsetospeed(&term, baud);
cfsetispeed(&term, baud);
//set new device settings
if(tcsetattr(_fd, TCSANOW, &term) == -1) {
std::perror("Display():tcsetattr");
}
}
~Display() {
close(_fd);
_fd = -1;
}
void clear() {
uint8_t data[4] = { 0 };
data[0] = 0x06;
data[1] = 0;
uint16_t crc = Crc16::compute(data, 2);
data[3] = (0xFF00 & crc) >> 8;
data[2] = 0x00FF & crc;
write(_fd, data, 4);
}
void text() {
std::string text("hello world!");
uint8_t data[1 + 1 + 22 + 2] = { 0 };
data[0] = 0x1F;
data[1] = text.length() + 2;
data[2] = 0;
data[3] = 1;
std::copy(text.begin(), text.end(), &data[4]);
uint16_t crc = Crc16::compute(data, data[1] + 2);
printf("crc: %x\n", crc);
data[16] = 0xFF & crc;
data[17] = (0xFF00 & crc) >> 8;
write(_fd, data, 18);
}
void setLedState() {
Command cmd;
cmd.type = 0x22;
cmd.length = 2;
cmd.data[0] = 5;
cmd.data[1] = 100;
cmd.crc = Crc16::compute((uint8_t *) &cmd, cmd.length + 2);
//write(_fd, (uint8_t *) &cmd, cmd.length + 2 + 2);
send(cmd);
}
void send(Command &cmd) {
write(_fd, &cmd.type, 2);
write(_fd, &cmd.data, cmd.length);
uint16_t crc = Crc16::compute((uint8_t *) &cmd, cmd.length + 2);
printf("CRC: %x\n", crc);
write(_fd, &crc, 2);
}
private:
int _fd;
std::string _devName;
speed_t _baud;
};
int main (int argc, char *argv[]) {
Display d("/dev/ttyU0");
d.clear();
d.text();
d.setLedState();
Command cmd;
cmd.type = 0x1F;
cmd.length = 14;
cmd.data[0] = 0;
cmd.data[1] = 1;
std::string msg("hello world!");
std::copy(msg.begin(), msg.end(), &cmd.data[2]);
d.send(cmd);
}
|
Remove Command struct, import new file
|
Remove Command struct, import new file
|
C++
|
mit
|
malensek/cryctl,malensek/cryctl
|
cf39dd5d82a565f1ec5fd45453208adf4ee01407
|
webrtc/modules/utility/source/process_thread_impl.cc
|
webrtc/modules/utility/source/process_thread_impl.cc
|
/*
* Copyright (c) 2012 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 "webrtc/modules/utility/source/process_thread_impl.h"
#include "webrtc/modules/include/module.h"
#include "webrtc/rtc_base/checks.h"
#include "webrtc/rtc_base/task_queue.h"
#include "webrtc/rtc_base/timeutils.h"
#include "webrtc/rtc_base/trace_event.h"
namespace webrtc {
namespace {
// We use this constant internally to signal that a module has requested
// a callback right away. When this is set, no call to TimeUntilNextProcess
// should be made, but Process() should be called directly.
const int64_t kCallProcessImmediately = -1;
int64_t GetNextCallbackTime(Module* module, int64_t time_now) {
int64_t interval = module->TimeUntilNextProcess();
if (interval < 0) {
// Falling behind, we should call the callback now.
return time_now;
}
return time_now + interval;
}
}
ProcessThread::~ProcessThread() {}
// static
std::unique_ptr<ProcessThread> ProcessThread::Create(
const char* thread_name) {
return std::unique_ptr<ProcessThread>(new ProcessThreadImpl(thread_name));
}
ProcessThreadImpl::ProcessThreadImpl(const char* thread_name)
: wake_up_(EventWrapper::Create()),
stop_(false),
thread_name_(thread_name) {}
ProcessThreadImpl::~ProcessThreadImpl() {
RTC_DCHECK(thread_checker_.CalledOnValidThread());
RTC_DCHECK(!thread_.get());
RTC_DCHECK(!stop_);
while (!queue_.empty()) {
delete queue_.front();
queue_.pop();
}
}
void ProcessThreadImpl::Start() {
RTC_DCHECK(thread_checker_.CalledOnValidThread());
RTC_DCHECK(!thread_.get());
if (thread_.get())
return;
RTC_DCHECK(!stop_);
for (ModuleCallback& m : modules_)
m.module->ProcessThreadAttached(this);
thread_.reset(
new rtc::PlatformThread(&ProcessThreadImpl::Run, this, thread_name_));
thread_->Start();
}
void ProcessThreadImpl::Stop() {
RTC_DCHECK(thread_checker_.CalledOnValidThread());
if(!thread_.get())
return;
{
rtc::CritScope lock(&lock_);
stop_ = true;
}
wake_up_->Set();
thread_->Stop();
stop_ = false;
thread_.reset();
for (ModuleCallback& m : modules_)
m.module->ProcessThreadAttached(nullptr);
}
void ProcessThreadImpl::WakeUp(Module* module) {
// Allowed to be called on any thread.
{
rtc::CritScope lock(&lock_);
for (ModuleCallback& m : modules_) {
if (m.module == module)
m.next_callback = kCallProcessImmediately;
}
}
wake_up_->Set();
}
void ProcessThreadImpl::PostTask(std::unique_ptr<rtc::QueuedTask> task) {
// Allowed to be called on any thread.
{
rtc::CritScope lock(&lock_);
queue_.push(task.release());
}
wake_up_->Set();
}
void ProcessThreadImpl::RegisterModule(Module* module,
const rtc::Location& from) {
RTC_DCHECK(thread_checker_.CalledOnValidThread());
RTC_DCHECK(module);
#if RTC_DCHECK_IS_ON
{
// Catch programmer error.
rtc::CritScope lock(&lock_);
for (const ModuleCallback& mc : modules_)
RTC_DCHECK(mc.module != module);
}
#endif
// Now that we know the module isn't in the list, we'll call out to notify
// the module that it's attached to the worker thread. We don't hold
// the lock while we make this call.
if (thread_.get())
module->ProcessThreadAttached(this);
{
rtc::CritScope lock(&lock_);
modules_.push_back(ModuleCallback(module, from));
}
// Wake the thread calling ProcessThreadImpl::Process() to update the
// waiting time. The waiting time for the just registered module may be
// shorter than all other registered modules.
wake_up_->Set();
}
void ProcessThreadImpl::DeRegisterModule(Module* module) {
RTC_DCHECK(thread_checker_.CalledOnValidThread());
RTC_DCHECK(module);
{
rtc::CritScope lock(&lock_);
modules_.remove_if([&module](const ModuleCallback& m) {
return m.module == module;
});
}
// Notify the module that it's been detached.
module->ProcessThreadAttached(nullptr);
}
// static
bool ProcessThreadImpl::Run(void* obj) {
return static_cast<ProcessThreadImpl*>(obj)->Process();
}
bool ProcessThreadImpl::Process() {
TRACE_EVENT1("webrtc", "ProcessThreadImpl", "name", thread_name_);
int64_t now = rtc::TimeMillis();
int64_t next_checkpoint = now + (1000 * 60);
{
rtc::CritScope lock(&lock_);
if (stop_)
return false;
for (ModuleCallback& m : modules_) {
// TODO(tommi): Would be good to measure the time TimeUntilNextProcess
// takes and dcheck if it takes too long (e.g. >=10ms). Ideally this
// operation should not require taking a lock, so querying all modules
// should run in a matter of nanoseconds.
if (m.next_callback == 0)
m.next_callback = GetNextCallbackTime(m.module, now);
if (m.next_callback <= now ||
m.next_callback == kCallProcessImmediately) {
{
TRACE_EVENT2("webrtc", "ModuleProcess", "function",
m.location.function_name(), "file",
m.location.file_and_line());
m.module->Process();
}
// Use a new 'now' reference to calculate when the next callback
// should occur. We'll continue to use 'now' above for the baseline
// of calculating how long we should wait, to reduce variance.
int64_t new_now = rtc::TimeMillis();
m.next_callback = GetNextCallbackTime(m.module, new_now);
}
if (m.next_callback < next_checkpoint)
next_checkpoint = m.next_callback;
}
while (!queue_.empty()) {
rtc::QueuedTask* task = queue_.front();
queue_.pop();
lock_.Leave();
task->Run();
delete task;
lock_.Enter();
}
}
int64_t time_to_wait = next_checkpoint - rtc::TimeMillis();
if (time_to_wait > 0)
wake_up_->Wait(static_cast<unsigned long>(time_to_wait));
return true;
}
} // namespace webrtc
|
/*
* Copyright (c) 2012 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 "webrtc/modules/utility/source/process_thread_impl.h"
#include "webrtc/modules/include/module.h"
#include "webrtc/rtc_base/checks.h"
#include "webrtc/rtc_base/task_queue.h"
#include "webrtc/rtc_base/timeutils.h"
#include "webrtc/rtc_base/trace_event.h"
namespace webrtc {
namespace {
// We use this constant internally to signal that a module has requested
// a callback right away. When this is set, no call to TimeUntilNextProcess
// should be made, but Process() should be called directly.
const int64_t kCallProcessImmediately = -1;
int64_t GetNextCallbackTime(Module* module, int64_t time_now) {
int64_t interval = module->TimeUntilNextProcess();
if (interval < 0) {
// Falling behind, we should call the callback now.
return time_now;
}
return time_now + interval;
}
}
ProcessThread::~ProcessThread() {}
// static
std::unique_ptr<ProcessThread> ProcessThread::Create(
const char* thread_name) {
return std::unique_ptr<ProcessThread>(new ProcessThreadImpl(thread_name));
}
ProcessThreadImpl::ProcessThreadImpl(const char* thread_name)
: wake_up_(EventWrapper::Create()),
stop_(false),
thread_name_(thread_name) {}
ProcessThreadImpl::~ProcessThreadImpl() {
RTC_DCHECK(thread_checker_.CalledOnValidThread());
RTC_DCHECK(!thread_.get());
RTC_DCHECK(!stop_);
while (!queue_.empty()) {
delete queue_.front();
queue_.pop();
}
}
void ProcessThreadImpl::Start() {
RTC_DCHECK(thread_checker_.CalledOnValidThread());
RTC_DCHECK(!thread_.get());
if (thread_.get())
return;
RTC_DCHECK(!stop_);
for (ModuleCallback& m : modules_)
m.module->ProcessThreadAttached(this);
thread_.reset(
new rtc::PlatformThread(&ProcessThreadImpl::Run, this, thread_name_));
thread_->Start();
}
void ProcessThreadImpl::Stop() {
RTC_DCHECK(thread_checker_.CalledOnValidThread());
if(!thread_.get())
return;
{
rtc::CritScope lock(&lock_);
stop_ = true;
}
wake_up_->Set();
thread_->Stop();
stop_ = false;
thread_.reset();
for (ModuleCallback& m : modules_)
m.module->ProcessThreadAttached(nullptr);
}
void ProcessThreadImpl::WakeUp(Module* module) {
// Allowed to be called on any thread.
{
rtc::CritScope lock(&lock_);
for (ModuleCallback& m : modules_) {
if (m.module == module)
m.next_callback = kCallProcessImmediately;
}
}
wake_up_->Set();
}
void ProcessThreadImpl::PostTask(std::unique_ptr<rtc::QueuedTask> task) {
// Allowed to be called on any thread.
{
rtc::CritScope lock(&lock_);
queue_.push(task.release());
}
wake_up_->Set();
}
void ProcessThreadImpl::RegisterModule(Module* module,
const rtc::Location& from) {
RTC_DCHECK(thread_checker_.CalledOnValidThread());
RTC_DCHECK(module) << from.ToString();
#if RTC_DCHECK_IS_ON
{
// Catch programmer error.
rtc::CritScope lock(&lock_);
for (const ModuleCallback& mc : modules_) {
RTC_DCHECK(mc.module != module)
<< "Already registered here: " << mc.location.ToString() << "\n"
<< "Now attempting from here: " << from.ToString();
}
}
#endif
// Now that we know the module isn't in the list, we'll call out to notify
// the module that it's attached to the worker thread. We don't hold
// the lock while we make this call.
if (thread_.get())
module->ProcessThreadAttached(this);
{
rtc::CritScope lock(&lock_);
modules_.push_back(ModuleCallback(module, from));
}
// Wake the thread calling ProcessThreadImpl::Process() to update the
// waiting time. The waiting time for the just registered module may be
// shorter than all other registered modules.
wake_up_->Set();
}
void ProcessThreadImpl::DeRegisterModule(Module* module) {
RTC_DCHECK(thread_checker_.CalledOnValidThread());
RTC_DCHECK(module);
{
rtc::CritScope lock(&lock_);
modules_.remove_if([&module](const ModuleCallback& m) {
return m.module == module;
});
}
// Notify the module that it's been detached.
module->ProcessThreadAttached(nullptr);
}
// static
bool ProcessThreadImpl::Run(void* obj) {
return static_cast<ProcessThreadImpl*>(obj)->Process();
}
bool ProcessThreadImpl::Process() {
TRACE_EVENT1("webrtc", "ProcessThreadImpl", "name", thread_name_);
int64_t now = rtc::TimeMillis();
int64_t next_checkpoint = now + (1000 * 60);
{
rtc::CritScope lock(&lock_);
if (stop_)
return false;
for (ModuleCallback& m : modules_) {
// TODO(tommi): Would be good to measure the time TimeUntilNextProcess
// takes and dcheck if it takes too long (e.g. >=10ms). Ideally this
// operation should not require taking a lock, so querying all modules
// should run in a matter of nanoseconds.
if (m.next_callback == 0)
m.next_callback = GetNextCallbackTime(m.module, now);
if (m.next_callback <= now ||
m.next_callback == kCallProcessImmediately) {
{
TRACE_EVENT2("webrtc", "ModuleProcess", "function",
m.location.function_name(), "file",
m.location.file_and_line());
m.module->Process();
}
// Use a new 'now' reference to calculate when the next callback
// should occur. We'll continue to use 'now' above for the baseline
// of calculating how long we should wait, to reduce variance.
int64_t new_now = rtc::TimeMillis();
m.next_callback = GetNextCallbackTime(m.module, new_now);
}
if (m.next_callback < next_checkpoint)
next_checkpoint = m.next_callback;
}
while (!queue_.empty()) {
rtc::QueuedTask* task = queue_.front();
queue_.pop();
lock_.Leave();
task->Run();
delete task;
lock_.Enter();
}
}
int64_t time_to_wait = next_checkpoint - rtc::TimeMillis();
if (time_to_wait > 0)
wake_up_->Wait(static_cast<unsigned long>(time_to_wait));
return true;
}
} // namespace webrtc
|
Add RTC_FROM_HERE location information to two DCHECKs in ProcessThread.
|
Add RTC_FROM_HERE location information to two DCHECKs in ProcessThread.
BUG=none
[email protected]
Review-Url: https://codereview.webrtc.org/2967693002
Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#18937}
|
C++
|
bsd-3-clause
|
ShiftMediaProject/libilbc,ShiftMediaProject/libilbc,ShiftMediaProject/libilbc,ShiftMediaProject/libilbc,TimothyGu/libilbc,TimothyGu/libilbc,TimothyGu/libilbc,ShiftMediaProject/libilbc,TimothyGu/libilbc,TimothyGu/libilbc
|
fdf44122356296b577c6816d9ff4d934153b401a
|
src/game.cc
|
src/game.cc
|
#include <string>
#include <iostream>
using namespace std;
#include "os.h"
#include "potions.h"
#include "scrolls.h"
#include "io.h"
#include "armor.h"
#include "pack.h"
#include "daemons.h"
#include "colors.h"
#include "level.h"
#include "rings.h"
#include "misc.h"
#include "player.h"
#include "weapons.h"
#include "wand.h"
#include "things.h"
#include "options.h"
#include "rogue.h"
#include "Game.h"
IO* Game::io = nullptr;
Level* Game::level = nullptr;
int Game::current_level = 1;
int Game::levels_without_food = 0;
int Game::max_level_visited = 1;
void
Game::new_level(int dungeon_level) {
/* Set max level we've been to */
Game::current_level = dungeon_level;
if (Game::current_level > Game::max_level_visited) {
Game::max_level_visited = Game::current_level;
}
if (Game::level != nullptr) {
delete Game::level;
}
Game::level = new Level();
// Drop player in the new dungeon level
if (player == nullptr) {
player = new Player();
}
Coordinate new_player_pos = player->get_position();
Game::level->get_random_room_coord(nullptr, &new_player_pos, 0, true);
player->set_position(new_player_pos);
room_enter(new_player_pos);
Game::io->print_color(new_player_pos.x, new_player_pos.y, player->get_type());
// Unhold player just in case
player->set_not_held();
// Reapply hallucination, just in case
if (player->is_hallucinating()) {
daemon_change_visuals();
}
}
int Game::init_graphics()
{
initscr(); /* Start up cursor package */
/* Ncurses colors */
if (use_colors) {
if (start_color() == ERR) {
endwin();
cerr
<< "Error: Failed to start colors. "
<< "Try restarting without colors enabled\n";
return 1;
}
/* Because ncurses has defined COLOR_BLACK to 0 and COLOR_WHITE to 7,
* and then decided that init_pair cannot change number 0 (COLOR_BLACK)
* I use COLOR_WHITE for black text and COLOR_BLACK for white text */
assume_default_colors(0, -1); /* Default is white text and any background */
init_pair(COLOR_RED, COLOR_RED, -1);
init_pair(COLOR_GREEN, COLOR_GREEN, -1);
init_pair(COLOR_YELLOW, COLOR_YELLOW, -1);
init_pair(COLOR_BLUE, COLOR_BLUE, -1);
init_pair(COLOR_MAGENTA, COLOR_MAGENTA, -1);
init_pair(COLOR_CYAN, COLOR_CYAN, -1);
init_pair(COLOR_WHITE, COLOR_BLACK, -1);
}
if (LINES < NUMLINES || COLS < NUMCOLS) {
endwin();
cerr << "\nSorry, the screen must be at least "
<< NUMLINES << "x" << NUMCOLS << "\n";
return 1;
}
raw(); /* Raw mode */
noecho(); /* Echo off */
hw = newwin(LINES, COLS, 0, 0);
Game::io = new IO();
return 0;
}
Game::Game() {
/* Parse environment opts */
whoami = os_whoami();
cout << "Hello " << whoami << ", just a moment while I dig the dungeon..." << flush;
/* Init Graphics */
if (init_graphics() != 0)
exit(1);
/* Init stuff */
Scroll::init_scrolls(); // Set up names of scrolls
Potion::init_potions(); // Set up colors of potions
Ring::init_rings(); // Set up stone settings of rings
Wand::init_wands(); // Set up materials of wands
Game::new_level(Game::current_level); // Set up level (and player)
/* Start up daemons and fuses */
daemon_start(runners_move, AFTER);
daemon_start(doctor, AFTER);
daemon_start(ring_abilities, AFTER);
}
Game::~Game() {
delete Game::io;
Game::io = nullptr;
}
|
#include <string>
#include <iostream>
using namespace std;
#include "os.h"
#include "potions.h"
#include "scrolls.h"
#include "io.h"
#include "armor.h"
#include "pack.h"
#include "daemons.h"
#include "colors.h"
#include "level.h"
#include "rings.h"
#include "misc.h"
#include "player.h"
#include "weapons.h"
#include "wand.h"
#include "things.h"
#include "options.h"
#include "rogue.h"
#include "Game.h"
IO* Game::io = nullptr;
Level* Game::level = nullptr;
int Game::current_level = 1;
int Game::levels_without_food = 0;
int Game::max_level_visited = 1;
void
Game::new_level(int dungeon_level) {
/* Set max level we've been to */
Game::current_level = dungeon_level;
if (Game::current_level > Game::max_level_visited) {
Game::max_level_visited = Game::current_level;
}
if (Game::level != nullptr) {
delete Game::level;
}
Game::level = new Level();
// Drop player in the new dungeon level
if (player == nullptr) {
player = new Player();
}
Coordinate new_player_pos = player->get_position();
Game::level->get_random_room_coord(nullptr, &new_player_pos, 0, true);
player->set_position(new_player_pos);
room_enter(new_player_pos);
Game::io->print_color(new_player_pos.x, new_player_pos.y, player->get_type());
// Unhold player just in case
player->set_not_held();
// Reapply hallucination, just in case
if (player->is_hallucinating()) {
daemon_change_visuals();
}
}
int Game::init_graphics()
{
initscr(); /* Start up cursor package */
/* Ncurses colors */
if (use_colors) {
if (start_color() == ERR) {
endwin();
cerr
<< "Error: Failed to start colors. "
<< "Try restarting without colors enabled\n";
return 1;
}
/* Because ncurses has defined COLOR_BLACK to 0 and COLOR_WHITE to 7,
* and then decided that init_pair cannot change number 0 (COLOR_BLACK)
* I use COLOR_WHITE for black text and COLOR_BLACK for white text */
assume_default_colors(0, -1); /* Default is white text and any background */
init_pair(COLOR_RED, COLOR_RED, -1);
init_pair(COLOR_GREEN, COLOR_GREEN, -1);
init_pair(COLOR_YELLOW, COLOR_YELLOW, -1);
init_pair(COLOR_BLUE, COLOR_BLUE, -1);
init_pair(COLOR_MAGENTA, COLOR_MAGENTA, -1);
init_pair(COLOR_CYAN, COLOR_CYAN, -1);
init_pair(COLOR_WHITE, COLOR_BLACK, -1);
}
if (LINES < NUMLINES || COLS < NUMCOLS) {
endwin();
cerr << "\nSorry, the screen must be at least "
<< NUMLINES << "x" << NUMCOLS << "\n";
return 1;
}
raw(); /* Raw mode */
noecho(); /* Echo off */
hw = newwin(LINES, COLS, 0, 0);
Game::io = new IO();
return 0;
}
Game::Game() {
/* Parse environment opts */
if (whoami.empty()) {
whoami = os_whoami();
}
cout << "Hello " << whoami << ", just a moment while I dig the dungeon..." << flush;
/* Init Graphics */
if (init_graphics() != 0)
exit(1);
/* Init stuff */
Scroll::init_scrolls(); // Set up names of scrolls
Potion::init_potions(); // Set up colors of potions
Ring::init_rings(); // Set up stone settings of rings
Wand::init_wands(); // Set up materials of wands
Game::new_level(Game::current_level); // Set up level (and player)
/* Start up daemons and fuses */
daemon_start(runners_move, AFTER);
daemon_start(doctor, AFTER);
daemon_start(ring_abilities, AFTER);
}
Game::~Game() {
delete Game::io;
Game::io = nullptr;
}
|
make -n parameter work again
|
make -n parameter work again
|
C++
|
bsd-3-clause
|
lollek/Misty-Mountains,lollek/Rogue14,lollek/Rogue14,lollek/Misty-Mountains,lollek/Rogue14,lollek/Misty-Mountains
|
fa0d0d8a5969cd481e185a4906764aed74b6b403
|
src/imf.cpp
|
src/imf.cpp
|
/*
* Adplug - Replayer for many OPL2/OPL3 audio file formats.
* Copyright (C) 1999 - 2008 Simon Peter <[email protected]>, et al.
*
* 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
*
* imf.cpp - IMF Player by Simon Peter <[email protected]>
*
* FILE FORMAT:
* There seem to be 2 different flavors of IMF formats out there. One version
* contains just the raw IMF music data. In this case, the first word of the
* file is always 0 (because the music data starts this way). This is already
* the music data! So read in the entire file and play it.
*
* If this word is greater than 0, it specifies the size of the following
* song data in bytes. In this case, the file has a footer that contains
* arbitrary infos about it. Mostly, this is plain ASCII text with some words
* of the author. Read and play the specified amount of song data and display
* the remaining data as ASCII text.
*
* NOTES:
* This player handles the two above mentioned formats, as well as a third
* type, invented by Martin Fernandez <[email protected]>, that's got a
* proper header to add title/game name information. After the header starts
* the normal IMF file in one of the two above mentioned formats.
*
* This player also handles a special footer format by Adam Nielsen,
* which has defined fields of information about the song, the author
* and more.
*/
#include <cstring>
#include "imf.h"
#include "database.h"
/*** public methods *************************************/
CPlayer *CimfPlayer::factory(Copl *newopl)
{
return new CimfPlayer(newopl);
}
bool CimfPlayer::load(const std::string &filename, const CFileProvider &fp)
{
binistream *f = fp.open(filename);
if (!f) return false;
// file validation section
size_t hdr_size = 0;
{
char header[5];
int version;
f->readString(header, 5);
version = f->readInt(1);
if (memcmp(header, "ADLIB", 5) || version != 1) {
if (!fp.extension(filename, ".imf") && !fp.extension(filename, ".wlf")) {
// It's no IMF file at all
fp.close(f);
return false;
} else
f->seek(0); // It's a normal IMF file
} else {
// It's a IMF file with header
track_name = f->readString('\0');
game_name = f->readString('\0');
f->ignore(1);
hdr_size = f->pos();
}
}
// determine data size
unsigned long file_size = fp.filesize(f);
int len_size = hdr_size ? 4 : 2;
size_t song_size = f->readInt(len_size);
if (!song_size) { // raw music data (no length field, no footer)
f->seek(-len_size, binio::Add);
len_size = 0;
song_size = file_size - hdr_size;
// some IMF files end *before* the last time value (either format)
if (song_size & 2) song_size += 2;
}
hdr_size += len_size;
// validity check
if (hdr_size + 4 > file_size || song_size & 3 // too short || invalid length
|| (song_size > file_size - hdr_size && // truncated song data
song_size != file_size + 2 - hdr_size)) { // allow trunc. final time
fp.close(f);
return false;
}
// read song data
size = song_size / 4;
data = new Sdata[size];
for (size_t i = 0; i < size; i++) {
data[i].reg = f->readInt(1);
data[i].val = f->readInt(1);
data[i].time = f->readInt(2);
}
// read footer, if any
if (song_size < file_size - hdr_size) {
if (f->readInt(1) == 0x1a) {
// Adam Nielsen's footer format
track_name = f->readString();
author_name = f->readString();
remarks = f->readString();
} else {
// Generic footer
size_t footerlen = file_size - hdr_size - song_size;
footer = new char[footerlen + 1];
f->readString(footer, footerlen);
footer[footerlen] = '\0'; // Make ASCIIZ string
}
}
rate = getrate(filename, fp, f);
fp.close(f);
rewind(0);
return true;
}
bool CimfPlayer::update()
{
do {
opl->write(data[pos].reg,data[pos].val);
del = data[pos].time;
pos++;
} while(!del && pos < size);
if(pos >= size) {
pos = 0;
songend = true;
}
else timer = rate / (float)del;
return !songend;
}
void CimfPlayer::rewind(int subsong)
{
pos = 0; del = 0; timer = rate; songend = false;
opl->init(); opl->write(1,32); // go to OPL2 mode
}
std::string CimfPlayer::gettitle()
{
std::string title;
title = track_name;
if(!track_name.empty() && !game_name.empty())
title += " - ";
title += game_name;
return title;
}
std::string CimfPlayer::getdesc()
{
if (footer)
return std::string(footer);
return remarks;
}
/*** private methods *************************************/
float CimfPlayer::getrate(const std::string &filename, const CFileProvider &fp, binistream *f)
{
if(db) { // Database available
f->seek(0, binio::Set);
CClockRecord *record = (CClockRecord *)db->search(CAdPlugDatabase::CKey(*f));
if (record && record->type == CAdPlugDatabase::CRecord::ClockSpeed)
return record->clock;
}
// Otherwise the database is either unavailable, or there's no entry for this file
if (fp.extension(filename, ".imf")) return 560.0f;
if (fp.extension(filename, ".wlf")) return 700.0f;
return 700.0f; // default speed for unknown files that aren't .IMF or .WLF
}
|
/*
* Adplug - Replayer for many OPL2/OPL3 audio file formats.
* Copyright (C) 1999 - 2008 Simon Peter <[email protected]>, et al.
*
* 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
*
* imf.cpp - IMF Player by Simon Peter <[email protected]>
*
* FILE FORMAT:
* There seem to be 2 different flavors of IMF formats out there. One version
* contains just the raw IMF music data. In this case, the first word of the
* file is always 0 (because the music data starts this way). This is already
* the music data! So read in the entire file and play it.
*
* If this word is greater than 0, it specifies the size of the following
* song data in bytes. In this case, the file has a footer that contains
* arbitrary infos about it. Mostly, this is plain ASCII text with some words
* of the author. Read and play the specified amount of song data and display
* the remaining data as ASCII text.
*
* NOTES:
* This player handles the two above mentioned formats, as well as a third
* type, invented by Martin Fernandez <[email protected]>, that's got a
* proper header to add title/game name information. After the header starts
* the normal IMF file in one of the two above mentioned formats.
*
* This player also handles a special footer format by Adam Nielsen,
* which has defined fields of information about the song, the author
* and more.
*/
#include <cstring>
#include "imf.h"
#include "database.h"
/*** public methods *************************************/
CPlayer *CimfPlayer::factory(Copl *newopl)
{
return new CimfPlayer(newopl);
}
bool CimfPlayer::load(const std::string &filename, const CFileProvider &fp)
{
binistream *f = fp.open(filename);
if (!f) return false;
// file validation section
size_t hdr_size = 0;
{
char header[5];
int version;
f->readString(header, 5);
version = f->readInt(1);
if (memcmp(header, "ADLIB", 5) || version != 1) {
if (!fp.extension(filename, ".imf") && !fp.extension(filename, ".wlf")) {
// It's no IMF file at all
fp.close(f);
return false;
} else
f->seek(0); // It's a normal IMF file
} else {
// It's a IMF file with header
track_name = f->readString('\0');
game_name = f->readString('\0');
f->ignore(1);
hdr_size = f->pos();
}
}
// determine data size
unsigned long file_size = fp.filesize(f);
int len_size = hdr_size ? 4 : 2;
size_t song_size = f->readInt(len_size);
if (!song_size) { // raw music data (no length field, no footer)
f->seek(-len_size, binio::Add);
len_size = 0;
song_size = file_size - hdr_size;
// some IMF files end *before* the last time value (either format)
if (song_size & 2) song_size += 2;
}
hdr_size += len_size;
// validity check
if (hdr_size + 4 > file_size || song_size & 3 // too short || invalid length
|| (song_size > file_size - hdr_size && // truncated song data
song_size != file_size + 2 - hdr_size)) { // allow trunc. final time
fp.close(f);
return false;
}
// read song data
size = song_size / 4;
data = new Sdata[size];
for (size_t i = 0; i < size; i++) {
data[i].reg = f->readInt(1);
data[i].val = f->readInt(1);
data[i].time = f->readInt(2);
}
// read footer, if any
if (song_size < file_size - hdr_size) {
size_t footerlen = file_size - hdr_size - song_size;
char signature = f->readInt(1);
if (signature == 0x1a && footerlen <= 1 + 3 * 256 + 9) {
// Adam Nielsen's footer format
track_name = f->readString();
author_name = f->readString();
remarks = f->readString();
// f->ignore(9); // tagging program
} else {
// Generic footer
footer = new char[footerlen + 1];
footer[0] = signature;
f->readString(&footer[1], footerlen);
footer[footerlen] = '\0'; // Make ASCIIZ string
if (footerlen == 88 && // maybe Muse tag data
!footer[17] && !footer[81] && track_name.empty()) {
// For the lack of a better test assume it's Muse data if the size
// is correct and both string fields end with NUL. Format is:
// 2 Bytes: unknown
// 16 Bytes: title
// 64 Bytes: remarks (usually source file)
// 6 Bytes: unknown data
track_name = std::string(&footer[2]);
remarks = std::string(&footer[18]);
delete footer;
footer = 0;
}
}
}
rate = getrate(filename, fp, f);
fp.close(f);
rewind(0);
return true;
}
bool CimfPlayer::update()
{
do {
opl->write(data[pos].reg,data[pos].val);
del = data[pos].time;
pos++;
} while(!del && pos < size);
if(pos >= size) {
pos = 0;
songend = true;
}
else timer = rate / (float)del;
return !songend;
}
void CimfPlayer::rewind(int subsong)
{
pos = 0; del = 0; timer = rate; songend = false;
opl->init(); opl->write(1,32); // go to OPL2 mode
}
std::string CimfPlayer::gettitle()
{
std::string title;
title = track_name;
if(!track_name.empty() && !game_name.empty())
title += " - ";
title += game_name;
return title;
}
std::string CimfPlayer::getdesc()
{
if (footer)
return std::string(footer);
return remarks;
}
/*** private methods *************************************/
float CimfPlayer::getrate(const std::string &filename, const CFileProvider &fp, binistream *f)
{
if(db) { // Database available
f->seek(0, binio::Set);
CClockRecord *record = (CClockRecord *)db->search(CAdPlugDatabase::CKey(*f));
if (record && record->type == CAdPlugDatabase::CRecord::ClockSpeed)
return record->clock;
}
// Otherwise the database is either unavailable, or there's no entry for this file
if (fp.extension(filename, ".imf")) return 560.0f;
if (fp.extension(filename, ".wlf")) return 700.0f;
return 700.0f; // default speed for unknown files that aren't .IMF or .WLF
}
|
Improve footer handling
|
imf: Improve footer handling
Don't swallow first byte of a generic footer. Assume it's in
Muse tag format when it passes some crude plausibility check.
|
C++
|
lgpl-2.1
|
adplug/adplug,adplug/adplug
|
1e53445e85fe7d9597a274e4ddc1b1af190d0a64
|
src/io/config.cpp
|
src/io/config.cpp
|
#include <LightGBM/config.h>
#include <LightGBM/utils/common.h>
#include <LightGBM/utils/random.h>
#include <LightGBM/utils/log.h>
#include <vector>
#include <string>
#include <unordered_set>
#include <algorithm>
#include <limits>
namespace LightGBM {
void Config::KV2Map(std::unordered_map<std::string, std::string>& params, const char* kv) {
std::vector<std::string> tmp_strs = Common::Split(kv, '=');
if (tmp_strs.size() == 2) {
std::string key = Common::RemoveQuotationSymbol(Common::Trim(tmp_strs[0]));
std::string value = Common::RemoveQuotationSymbol(Common::Trim(tmp_strs[1]));
if (key.size() > 0) {
auto value_search = params.find(key);
if (value_search == params.end()) { // not set
params.emplace(key, value);
} else {
Log::Warning("%s is set=%s, %s=%s will be ignored. Current value: %s=%s",
key.c_str(), value_search->second.c_str(), key.c_str(), value.c_str(),
key.c_str(), value_search->second.c_str());
}
}
} else {
Log::Warning("Unknown parameter %s", kv);
}
}
std::unordered_map<std::string, std::string> Config::Str2Map(const char* parameters) {
std::unordered_map<std::string, std::string> params;
auto args = Common::Split(parameters, " \t\n\r");
for (auto arg : args) {
KV2Map(params, Common::Trim(arg).c_str());
}
ParameterAlias::KeyAliasTransform(¶ms);
return params;
}
void GetBoostingType(const std::unordered_map<std::string, std::string>& params, std::string* boosting) {
std::string value;
if (Config::GetString(params, "boosting", &value)) {
std::transform(value.begin(), value.end(), value.begin(), Common::tolower);
if (value == std::string("gbdt") || value == std::string("gbrt")) {
*boosting = "gbdt";
} else if (value == std::string("dart")) {
*boosting = "dart";
} else if (value == std::string("goss")) {
*boosting = "goss";
} else if (value == std::string("rf") || value == std::string("random_forest")) {
*boosting = "rf";
} else {
Log::Fatal("Unknown boosting type %s", value.c_str());
}
}
}
void GetObjectiveType(const std::unordered_map<std::string, std::string>& params, std::string* objective) {
std::string value;
if (Config::GetString(params, "objective", &value)) {
std::transform(value.begin(), value.end(), value.begin(), Common::tolower);
*objective = value;
}
}
void GetMetricType(const std::unordered_map<std::string, std::string>& params, std::vector<std::string>* metric) {
std::string value;
if (Config::GetString(params, "metric", &value)) {
// clear old metrics
metric->clear();
// to lower
std::transform(value.begin(), value.end(), value.begin(), Common::tolower);
// split
std::vector<std::string> metrics = Common::Split(value.c_str(), ',');
// remove duplicate
std::unordered_set<std::string> metric_sets;
for (auto& met : metrics) {
std::transform(met.begin(), met.end(), met.begin(), Common::tolower);
if (metric_sets.count(met) <= 0) {
metric_sets.insert(met);
}
}
for (auto& met : metric_sets) {
metric->push_back(met);
}
metric->shrink_to_fit();
}
// add names of objective function if not providing metric
if (metric->empty() && value.size() == 0) {
if (Config::GetString(params, "objective", &value)) {
std::transform(value.begin(), value.end(), value.begin(), Common::tolower);
metric->push_back(value);
}
}
}
void GetTaskType(const std::unordered_map<std::string, std::string>& params, TaskType* task) {
std::string value;
if (Config::GetString(params, "task", &value)) {
std::transform(value.begin(), value.end(), value.begin(), Common::tolower);
if (value == std::string("train") || value == std::string("training")) {
*task = TaskType::kTrain;
} else if (value == std::string("predict") || value == std::string("prediction")
|| value == std::string("test")) {
*task = TaskType::kPredict;
} else if (value == std::string("convert_model")) {
*task = TaskType::kConvertModel;
} else if (value == std::string("refit") || value == std::string("refit_tree")) {
*task = TaskType::KRefitTree;
} else {
Log::Fatal("Unknown task type %s", value.c_str());
}
}
}
void GetDeviceType(const std::unordered_map<std::string, std::string>& params, std::string* device_type) {
std::string value;
if (Config::GetString(params, "device_type", &value)) {
std::transform(value.begin(), value.end(), value.begin(), Common::tolower);
if (value == std::string("cpu")) {
*device_type = "cpu";
} else if (value == std::string("gpu")) {
*device_type = "gpu";
} else {
Log::Fatal("Unknown device type %s", value.c_str());
}
}
}
void GetTreeLearnerType(const std::unordered_map<std::string, std::string>& params, std::string* tree_learner) {
std::string value;
if (Config::GetString(params, "tree_learner", &value)) {
std::transform(value.begin(), value.end(), value.begin(), Common::tolower);
if (value == std::string("serial")) {
*tree_learner = "serial";
} else if (value == std::string("feature") || value == std::string("feature_parallel")) {
*tree_learner = "feature";
} else if (value == std::string("data") || value == std::string("data_parallel")) {
*tree_learner = "data";
} else if (value == std::string("voting") || value == std::string("voting_parallel")) {
*tree_learner = "voting";
} else {
Log::Fatal("Unknown tree learner type %s", value.c_str());
}
}
}
void Config::Set(const std::unordered_map<std::string, std::string>& params) {
// generate seeds by seed.
if (GetInt(params, "seed", &seed)) {
Random rand(seed);
int int_max = std::numeric_limits<short>::max();
data_random_seed = static_cast<int>(rand.NextShort(0, int_max));
bagging_seed = static_cast<int>(rand.NextShort(0, int_max));
drop_seed = static_cast<int>(rand.NextShort(0, int_max));
feature_fraction_seed = static_cast<int>(rand.NextShort(0, int_max));
}
GetTaskType(params, &task);
GetBoostingType(params, &boosting);
GetMetricType(params, &metric);
GetObjectiveType(params, &objective);
GetDeviceType(params, &device_type);
GetTreeLearnerType(params, &tree_learner);
GetMembersFromString(params);
if (valid_data_initscores.size() == 0 && valid.size() > 0) {
valid_data_initscores = std::vector<std::string>(valid.size(), "");
}
CHECK(valid.size() == valid_data_initscores.size());
// check for conflicts
CheckParamConflict();
if (verbosity == 1) {
LightGBM::Log::ResetLogLevel(LightGBM::LogLevel::Info);
} else if (verbosity == 0) {
LightGBM::Log::ResetLogLevel(LightGBM::LogLevel::Warning);
} else if (verbosity >= 2) {
LightGBM::Log::ResetLogLevel(LightGBM::LogLevel::Debug);
} else {
LightGBM::Log::ResetLogLevel(LightGBM::LogLevel::Fatal);
}
}
bool CheckMultiClassObjective(const std::string& objective) {
return (objective == std::string("multiclass")
|| objective == std::string("multiclassova")
|| objective == std::string("softmax")
|| objective == std::string("multiclass_ova")
|| objective == std::string("ova")
|| objective == std::string("ovr"));
}
void Config::CheckParamConflict() {
// check if objective, metric, and num_class match
int num_class_check = num_class;
bool objective_custom = objective == std::string("none") || objective == std::string("null") || objective == std::string("custom");
bool objective_type_multiclass = CheckMultiClassObjective(objective) || (objective_custom && num_class_check > 1);
if (objective_type_multiclass) {
if (num_class_check <= 1) {
Log::Fatal("Number of classes should be specified and greater than 1 for multiclass training");
}
} else {
if (task == TaskType::kTrain && num_class_check != 1) {
Log::Fatal("Number of classes must be 1 for non-multiclass training");
}
}
if (is_provide_training_metric || !valid.empty()) {
for (std::string metric_type : metric) {
bool metric_type_multiclass = (CheckMultiClassObjective(metric_type)
|| metric_type == std::string("multi_logloss")
|| metric_type == std::string("multi_error"));
if ((objective_type_multiclass && !metric_type_multiclass)
|| (!objective_type_multiclass && metric_type_multiclass)) {
Log::Fatal("Objective and metrics don't match");
}
}
}
if (num_machines > 1) {
is_parallel = true;
} else {
is_parallel = false;
tree_learner = "serial";
}
bool is_single_tree_learner = tree_learner == std::string("serial");
if (is_single_tree_learner) {
is_parallel = false;
num_machines = 1;
}
if (is_single_tree_learner || tree_learner == std::string("feature")) {
is_parallel_find_bin = false;
} else if (tree_learner == std::string("data")
|| tree_learner == std::string("voting")) {
is_parallel_find_bin = true;
if (histogram_pool_size >= 0
&& tree_learner == std::string("data")) {
Log::Warning("Histogram LRU queue was enabled (histogram_pool_size=%f).\n"
"Will disable this to reduce communication costs",
histogram_pool_size);
// Change pool size to -1 (no limit) when using data parallel to reduce communication costs
histogram_pool_size = -1;
}
}
// Check max_depth and num_leaves
if (max_depth > 0) {
int full_num_leaves = static_cast<int>(std::pow(2, max_depth));
if (full_num_leaves > num_leaves
&& num_leaves == kDefaultNumLeaves) {
Log::Warning("Accuracy may be bad since you didn't set num_leaves and 2^max_depth > num_leaves");
}
}
}
std::string Config::ToString() const {
std::stringstream str_buf;
str_buf << "[boosting: " << boosting << "]\n";
str_buf << "[objective: " << objective << "]\n";
str_buf << "[metric: " << Common::Join(metric, ",") << "]\n";
str_buf << "[tree_learner: " << tree_learner << "]\n";
str_buf << "[device_type: " << device_type << "]\n";
str_buf << SaveMembersToString();
return str_buf.str();
}
} // namespace LightGBM
|
#include <LightGBM/config.h>
#include <LightGBM/utils/common.h>
#include <LightGBM/utils/random.h>
#include <LightGBM/utils/log.h>
#include <vector>
#include <string>
#include <unordered_set>
#include <algorithm>
#include <limits>
namespace LightGBM {
void Config::KV2Map(std::unordered_map<std::string, std::string>& params, const char* kv) {
std::vector<std::string> tmp_strs = Common::Split(kv, '=');
if (tmp_strs.size() == 2) {
std::string key = Common::RemoveQuotationSymbol(Common::Trim(tmp_strs[0]));
std::string value = Common::RemoveQuotationSymbol(Common::Trim(tmp_strs[1]));
if (key.size() > 0) {
auto value_search = params.find(key);
if (value_search == params.end()) { // not set
params.emplace(key, value);
} else {
Log::Warning("%s is set=%s, %s=%s will be ignored. Current value: %s=%s",
key.c_str(), value_search->second.c_str(), key.c_str(), value.c_str(),
key.c_str(), value_search->second.c_str());
}
}
} else {
Log::Warning("Unknown parameter %s", kv);
}
}
std::unordered_map<std::string, std::string> Config::Str2Map(const char* parameters) {
std::unordered_map<std::string, std::string> params;
auto args = Common::Split(parameters, " \t\n\r");
for (auto arg : args) {
KV2Map(params, Common::Trim(arg).c_str());
}
ParameterAlias::KeyAliasTransform(¶ms);
return params;
}
void GetBoostingType(const std::unordered_map<std::string, std::string>& params, std::string* boosting) {
std::string value;
if (Config::GetString(params, "boosting", &value)) {
std::transform(value.begin(), value.end(), value.begin(), Common::tolower);
if (value == std::string("gbdt") || value == std::string("gbrt")) {
*boosting = "gbdt";
} else if (value == std::string("dart")) {
*boosting = "dart";
} else if (value == std::string("goss")) {
*boosting = "goss";
} else if (value == std::string("rf") || value == std::string("random_forest")) {
*boosting = "rf";
} else {
Log::Fatal("Unknown boosting type %s", value.c_str());
}
}
}
void GetObjectiveType(const std::unordered_map<std::string, std::string>& params, std::string* objective) {
std::string value;
if (Config::GetString(params, "objective", &value)) {
std::transform(value.begin(), value.end(), value.begin(), Common::tolower);
*objective = value;
}
}
void GetMetricType(const std::unordered_map<std::string, std::string>& params, std::vector<std::string>* metric) {
std::string value;
if (Config::GetString(params, "metric", &value)) {
// clear old metrics
metric->clear();
// to lower
std::transform(value.begin(), value.end(), value.begin(), Common::tolower);
// split
std::vector<std::string> metrics = Common::Split(value.c_str(), ',');
// remove duplicate
std::unordered_set<std::string> metric_sets;
for (auto& met : metrics) {
std::transform(met.begin(), met.end(), met.begin(), Common::tolower);
if (metric_sets.count(met) <= 0) {
metric_sets.insert(met);
}
}
for (auto& met : metric_sets) {
metric->push_back(met);
}
metric->shrink_to_fit();
}
// add names of objective function if not providing metric
if (metric->empty() && value.size() == 0) {
if (Config::GetString(params, "objective", &value)) {
std::transform(value.begin(), value.end(), value.begin(), Common::tolower);
metric->push_back(value);
}
}
}
void GetTaskType(const std::unordered_map<std::string, std::string>& params, TaskType* task) {
std::string value;
if (Config::GetString(params, "task", &value)) {
std::transform(value.begin(), value.end(), value.begin(), Common::tolower);
if (value == std::string("train") || value == std::string("training")) {
*task = TaskType::kTrain;
} else if (value == std::string("predict") || value == std::string("prediction")
|| value == std::string("test")) {
*task = TaskType::kPredict;
} else if (value == std::string("convert_model")) {
*task = TaskType::kConvertModel;
} else if (value == std::string("refit") || value == std::string("refit_tree")) {
*task = TaskType::KRefitTree;
} else {
Log::Fatal("Unknown task type %s", value.c_str());
}
}
}
void GetDeviceType(const std::unordered_map<std::string, std::string>& params, std::string* device_type) {
std::string value;
if (Config::GetString(params, "device_type", &value)) {
std::transform(value.begin(), value.end(), value.begin(), Common::tolower);
if (value == std::string("cpu")) {
*device_type = "cpu";
} else if (value == std::string("gpu")) {
*device_type = "gpu";
} else {
Log::Fatal("Unknown device type %s", value.c_str());
}
}
}
void GetTreeLearnerType(const std::unordered_map<std::string, std::string>& params, std::string* tree_learner) {
std::string value;
if (Config::GetString(params, "tree_learner", &value)) {
std::transform(value.begin(), value.end(), value.begin(), Common::tolower);
if (value == std::string("serial")) {
*tree_learner = "serial";
} else if (value == std::string("feature") || value == std::string("feature_parallel")) {
*tree_learner = "feature";
} else if (value == std::string("data") || value == std::string("data_parallel")) {
*tree_learner = "data";
} else if (value == std::string("voting") || value == std::string("voting_parallel")) {
*tree_learner = "voting";
} else {
Log::Fatal("Unknown tree learner type %s", value.c_str());
}
}
}
void Config::Set(const std::unordered_map<std::string, std::string>& params) {
// generate seeds by seed.
if (GetInt(params, "seed", &seed)) {
Random rand(seed);
int int_max = std::numeric_limits<short>::max();
data_random_seed = static_cast<int>(rand.NextShort(0, int_max));
bagging_seed = static_cast<int>(rand.NextShort(0, int_max));
drop_seed = static_cast<int>(rand.NextShort(0, int_max));
feature_fraction_seed = static_cast<int>(rand.NextShort(0, int_max));
}
GetTaskType(params, &task);
GetBoostingType(params, &boosting);
GetMetricType(params, &metric);
GetObjectiveType(params, &objective);
GetDeviceType(params, &device_type);
GetTreeLearnerType(params, &tree_learner);
GetMembersFromString(params);
if (valid_data_initscores.size() == 0 && valid.size() > 0) {
valid_data_initscores = std::vector<std::string>(valid.size(), "");
}
CHECK(valid.size() == valid_data_initscores.size());
// check for conflicts
CheckParamConflict();
if (verbosity == 1) {
LightGBM::Log::ResetLogLevel(LightGBM::LogLevel::Info);
} else if (verbosity == 0) {
LightGBM::Log::ResetLogLevel(LightGBM::LogLevel::Warning);
} else if (verbosity >= 2) {
LightGBM::Log::ResetLogLevel(LightGBM::LogLevel::Debug);
} else {
LightGBM::Log::ResetLogLevel(LightGBM::LogLevel::Fatal);
}
}
bool CheckMultiClassObjective(const std::string& objective) {
return (objective == std::string("multiclass")
|| objective == std::string("multiclassova")
|| objective == std::string("softmax")
|| objective == std::string("multiclass_ova")
|| objective == std::string("ova")
|| objective == std::string("ovr"));
}
void Config::CheckParamConflict() {
// check if objective, metric, and num_class match
int num_class_check = num_class;
bool objective_custom = objective == std::string("none") || objective == std::string("null") || objective == std::string("custom");
bool objective_type_multiclass = CheckMultiClassObjective(objective) || (objective_custom && num_class_check > 1);
if (objective_type_multiclass) {
if (num_class_check <= 1) {
Log::Fatal("Number of classes should be specified and greater than 1 for multiclass training");
}
} else {
if (task == TaskType::kTrain && num_class_check != 1) {
Log::Fatal("Number of classes must be 1 for non-multiclass training");
}
}
for (std::string metric_type : metric) {
bool metric_type_multiclass = (CheckMultiClassObjective(metric_type)
|| metric_type == std::string("multi_logloss")
|| metric_type == std::string("multi_error"));
if ((objective_type_multiclass && !metric_type_multiclass)
|| (!objective_type_multiclass && metric_type_multiclass)) {
Log::Fatal("Multiclass qbjective and metrics don't match");
}
}
if (num_machines > 1) {
is_parallel = true;
} else {
is_parallel = false;
tree_learner = "serial";
}
bool is_single_tree_learner = tree_learner == std::string("serial");
if (is_single_tree_learner) {
is_parallel = false;
num_machines = 1;
}
if (is_single_tree_learner || tree_learner == std::string("feature")) {
is_parallel_find_bin = false;
} else if (tree_learner == std::string("data")
|| tree_learner == std::string("voting")) {
is_parallel_find_bin = true;
if (histogram_pool_size >= 0
&& tree_learner == std::string("data")) {
Log::Warning("Histogram LRU queue was enabled (histogram_pool_size=%f).\n"
"Will disable this to reduce communication costs",
histogram_pool_size);
// Change pool size to -1 (no limit) when using data parallel to reduce communication costs
histogram_pool_size = -1;
}
}
// Check max_depth and num_leaves
if (max_depth > 0) {
int full_num_leaves = static_cast<int>(std::pow(2, max_depth));
if (full_num_leaves > num_leaves
&& num_leaves == kDefaultNumLeaves) {
Log::Warning("Accuracy may be bad since you didn't set num_leaves and 2^max_depth > num_leaves");
}
}
}
std::string Config::ToString() const {
std::stringstream str_buf;
str_buf << "[boosting: " << boosting << "]\n";
str_buf << "[objective: " << objective << "]\n";
str_buf << "[metric: " << Common::Join(metric, ",") << "]\n";
str_buf << "[tree_learner: " << tree_learner << "]\n";
str_buf << "[device_type: " << device_type << "]\n";
str_buf << SaveMembersToString();
return str_buf.str();
}
} // namespace LightGBM
|
fix #1504
|
fix #1504
|
C++
|
mit
|
microsoft/LightGBM,henry0312/LightGBM,microsoft/LightGBM,henry0312/LightGBM,microsoft/LightGBM,microsoft/LightGBM,henry0312/LightGBM,henry0312/LightGBM,henry0312/LightGBM,microsoft/LightGBM
|
64a3b141b37ee6420db527752717624be7ed9f6b
|
src/math.hh
|
src/math.hh
|
#include <cassert>
static int clamp(int number, int low, int high) {
assert(low<=high);
if(number < low) return low;
if(number > high) return high;
return number;
}
template <class Container, class Key>
bool
has_key(Container &container, const Key &key) {
return container.find(key) != container.end();
}
#define min(a, b) (((a)<(b))?(a):(b))
#define max(a, b) (((b)<(a))?(a):(b))
|
#include <cassert>
static int clamp(int number, int low, int high) {
assert(low<=high);
if(number < low) return low;
if(number > high) return high;
return number;
}
template <class Container, typename Key>
bool
has_key(Container &container, Key &&key) {
return container.find(std::forward<Key>(key)) != container.end();
}
using std::min;
using std::max;
|
Use perfect forwarding to fix has_key()
|
Use perfect forwarding to fix has_key()
|
C++
|
agpl-3.0
|
mmtorni/HamLTE,mmtorni/HamLTE,mmtorni/HamLTE
|
3c650054ce9e684a574ca529407c876f541a2553
|
src/kernel/os.cpp
|
src/kernel/os.cpp
|
// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2017 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//#define DEBUG
#define MYINFO(X,...) INFO("Kernel", X, ##__VA_ARGS__)
#include <cstdio>
#include <boot/multiboot.h>
#include <hw/cmos.hpp>
#include <kernel/os.hpp>
#include <kernel/irq_manager.hpp>
#include <kernel/rtc.hpp>
#include <kernel/rdrand.hpp>
#include <kernel/rng.hpp>
#include <kernel/cpuid.hpp>
#include <util/fixedvec.hpp>
#include <kprint>
#include <service>
#include <statman>
#include <cinttypes>
//#define ENABLE_PROFILERS
#ifdef ENABLE_PROFILERS
#include <profile>
#define PROFILE(name) ScopedProfiler __CONCAT(sp, __COUNTER__){name};
#else
#define PROFILE(name) /* name */
#endif
extern "C" void* get_cpu_esp();
extern "C" void kernel_sanity_checks();
extern uintptr_t heap_begin;
extern uintptr_t heap_end;
extern uintptr_t _start;
extern uintptr_t _end;
extern uintptr_t _ELF_START_;
extern uintptr_t _TEXT_START_;
extern uintptr_t _LOAD_START_;
extern uintptr_t _ELF_END_;
// Initialize static OS data members
bool OS::power_ = true;
bool OS::boot_sequence_passed_ = false;
MHz OS::cpu_mhz_ {-1};
uintptr_t OS::low_memory_size_ {0};
uintptr_t OS::high_memory_size_ {0};
uintptr_t OS::memory_end_ {0};
uintptr_t OS::heap_max_ {0xfffffff};
const uintptr_t OS::elf_binary_size_ {(uintptr_t)&_ELF_END_ - (uintptr_t)&_ELF_START_};
multiboot_info_t* OS::bootinfo_ = nullptr;
std::string OS::cmdline{Service::binary_name()};
// stdout redirection
using Print_vec = fixedvector<OS::print_func, 8>;
static Print_vec os_print_handlers(Fixedvector_Init::UNINIT);
extern void default_stdout_handlers();
// Plugins
OS::Plugin_vec OS::plugins_(Fixedvector_Init::UNINIT);
// OS version
#ifndef OS_VERSION
#define OS_VERSION "v?.?.?"
#endif
std::string OS::version_str_ = OS_VERSION;
std::string OS::arch_str_ = ARCH;
// sleep statistics
static uint64_t* os_cycles_hlt = nullptr;
static uint64_t* os_cycles_total = nullptr;
const std::string& OS::cmdline_args() noexcept
{
return cmdline;
}
void OS::start(uint32_t boot_magic, uint32_t boot_addr)
{
PROFILE("");
// Print a fancy header
CAPTION("#include<os> // Literally");
void* esp = get_cpu_esp();
MYINFO("Stack: %p", esp);
MYINFO("Boot magic: 0x%x, addr: 0x%x",
boot_magic, boot_addr);
/// STATMAN ///
/// initialize on page 7, 2 pages in size
Statman::get().init(0x6000, 0x2000);
PROFILE("Multiboot / legacy");
// Detect memory limits etc. depending on boot type
if (boot_magic == MULTIBOOT_BOOTLOADER_MAGIC) {
OS::multiboot(boot_addr);
} else {
if (is_softreset_magic(boot_magic) && boot_addr != 0)
OS::resume_softreset(boot_addr);
OS::legacy_boot();
}
Expects(high_memory_size_);
PROFILE("Memory map");
// Assign memory ranges used by the kernel
auto& memmap = memory_map();
OS::memory_end_ = high_memory_size_ + 0x100000;
MYINFO("Assigning fixed memory ranges (Memory map)");
memmap.assign_range({0x6000, 0x7fff, "Statman", "Statistics"});
memmap.assign_range({0xA000, 0x9fbff, "Kernel / service main stack"});
memmap.assign_range({(uintptr_t)&_LOAD_START_, (uintptr_t)&_end,
"ELF", "Your service binary including OS"});
Expects(::heap_begin and heap_max_);
// @note for security we don't want to expose this
memmap.assign_range({(uintptr_t)&_end + 1, ::heap_begin - 1,
"Pre-heap", "Heap randomization area"});
// Give the rest of physical memory to heap
heap_max_ = ((0x100000 + high_memory_size_) & 0xffff0000) - 1;
uintptr_t span_max = std::numeric_limits<std::ptrdiff_t>::max();
uintptr_t heap_range_max_ = std::min(span_max, heap_max_);
MYINFO("Assigning heap");
memmap.assign_range({::heap_begin, heap_range_max_,
"Heap", "Dynamic memory", heap_usage });
MYINFO("Printing memory map");
for (const auto &i : memmap)
INFO2("* %s",i.second.to_string().c_str());
// sleep statistics
// NOTE: needs to be positioned before anything that calls OS::halt
os_cycles_hlt = &Statman::get().create(
Stat::UINT64, std::string("cpu0.cycles_hlt")).get_uint64();
os_cycles_total = &Statman::get().create(
Stat::UINT64, std::string("cpu0.cycles_total")).get_uint64();
PROFILE("Arch init");
extern void __arch_init();
__arch_init();
kernel_sanity_checks();
PROFILE("RTC init");
// Realtime/monotonic clock
RTC::init();
kernel_sanity_checks();
MYINFO("Initializing RNG");
PROFILE("RNG init");
// initialize random seed based on cycles since start
if (CPUID::has_feature(CPUID::Feature::RDRAND)) {
uint32_t rdrand_output[32];
for (size_t i = 0; i != 32; ++i) {
while (!rdrand32(&rdrand_output[i])) {}
}
rng_absorb(rdrand_output, sizeof(rdrand_output));
}
else {
// this is horrible, better solution needed here
for (size_t i = 0; i != 32; ++i) {
uint64_t clock = cycles_since_boot();
// maybe additionally call something which will take
// variable time depending in some way on the processor
// state (clflush?) or a HAVEGE-like approach.
rng_absorb(&clock, sizeof(clock));
}
}
// Seed rand with 32 bits from RNG
srand(rng_extract_uint32());
// Custom initialization functions
MYINFO("Initializing plugins");
// the boot sequence is over when we get to plugins/Service::start
OS::boot_sequence_passed_ = true;
PROFILE("Plugins init");
for (auto plugin : plugins_) {
INFO2("* Initializing %s", plugin.name_);
try{
plugin.func_();
} catch(std::exception& e){
MYINFO("Exception thrown when initializing plugin: %s", e.what());
} catch(...){
MYINFO("Unknown exception when initializing plugin");
}
}
PROFILE("Service::start");
// begin service start
FILLINE('=');
printf(" IncludeOS %s (%s / %i-bit)\n",
version().c_str(), arch().c_str(),
static_cast<int>(sizeof(uintptr_t)) * 8);
printf(" +--> Running [ %s ]\n", Service::name().c_str());
FILLINE('~');
Service::start();
}
void OS::register_plugin(Plugin delg, const char* name){
MYINFO("Registering plugin %s", name);
plugins_.emplace(delg, name);
}
int64_t OS::micros_since_boot() noexcept {
return cycles_since_boot() / cpu_freq().count();
}
uint64_t OS::get_cycles_halt() noexcept {
return *os_cycles_hlt;
}
uint64_t OS::get_cycles_total() noexcept {
return *os_cycles_total;
}
__attribute__((noinline))
void OS::halt() {
*os_cycles_total = cycles_since_boot();
#if defined(ARCH_x86)
asm volatile("hlt");
// add a global symbol here so we can quickly discard
// event loop from stack sampling
asm volatile(
".global _irq_cb_return_location;\n"
"_irq_cb_return_location:" );
#else
#warning "OS::halt() not implemented for selected arch"
#endif
// Count sleep cycles
*os_cycles_hlt += cycles_since_boot() - *os_cycles_total;
}
void OS::event_loop()
{
IRQ_manager::get().process_interrupts();
do {
OS::halt();
IRQ_manager::get().process_interrupts();
} while (power_);
MYINFO("Stopping service");
Service::stop();
MYINFO("Powering off");
extern void __arch_poweroff();
__arch_poweroff();
}
void OS::reboot()
{
extern void __arch_reboot();
__arch_reboot();
}
void OS::shutdown()
{
MYINFO("Soft shutdown signalled");
power_ = false;
}
void OS::on_panic(on_panic_func func)
{
extern on_panic_func panic_handler;
panic_handler = func;
}
void OS::add_stdout(OS::print_func func)
{
os_print_handlers.add(func);
}
void OS::add_stdout_default_serial()
{
add_stdout(
[] (const char* str, const size_t len) {
kprintf("%.*s", static_cast<int>(len), str);
});
}
__attribute__ ((weak))
void default_stdout_handlers()
{
OS::add_stdout_default_serial();
}
size_t OS::print(const char* str, const size_t len)
{
for (auto& func : os_print_handlers)
func(str, len);
return len;
}
void OS::legacy_boot() {
// Fetch CMOS memory info (unfortunately this is maximally 10^16 kb)
auto mem = hw::CMOS::meminfo();
low_memory_size_ = mem.base.total * 1024;
INFO2("* Low memory: %i Kib", mem.base.total);
high_memory_size_ = mem.extended.total * 1024;
// Use memsize provided by Make / linker unless CMOS knows this is wrong
INFO2("* High memory (from cmos): %i Kib", mem.extended.total);
auto& memmap = memory_map();
// No guarantees without multiboot, but we assume standard memory layout
memmap.assign_range({0x0009FC00, 0x0009FFFF,
"EBDA", "Extended BIOS data area"});
memmap.assign_range({0x000A0000, 0x000FFFFF,
"VGA/ROM", "Memory mapped video memory"});
// @note : since the maximum size of a span is unsigned (ptrdiff_t) we may need more than one
uintptr_t addr_max = std::numeric_limits<std::size_t>::max();
uintptr_t span_max = std::numeric_limits<std::ptrdiff_t>::max();
uintptr_t unavail_start = 0x100000 + high_memory_size_;
size_t interval = std::min(span_max, addr_max - unavail_start) - 1;
uintptr_t unavail_end = unavail_start + interval;
while (unavail_end < addr_max){
INFO2("* Unavailable memory: 0x%" PRIxPTR" - 0x%" PRIxPTR, unavail_start, unavail_end);
memmap.assign_range({unavail_start, unavail_end,
"N/A", "Reserved / outside physical range" });
unavail_start = unavail_end + 1;
interval = std::min(span_max, addr_max - unavail_start);
// Increment might wrapped around
if (unavail_start > unavail_end + interval or unavail_start + interval == addr_max){
INFO2("* Last chunk of memory: 0x%" PRIxPTR" - 0x%" PRIxPTR, unavail_start, addr_max);
memmap.assign_range({unavail_start, addr_max,
"N/A", "Reserved / outside physical range" });
break;
}
unavail_end += interval;
}
}
|
// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2017 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//#define DEBUG
#define MYINFO(X,...) INFO("Kernel", X, ##__VA_ARGS__)
#include <cstdio>
#include <boot/multiboot.h>
#include <hw/cmos.hpp>
#include <kernel/os.hpp>
#include <kernel/irq_manager.hpp>
#include <kernel/rtc.hpp>
#include <kernel/rdrand.hpp>
#include <kernel/rng.hpp>
#include <kernel/cpuid.hpp>
#include <util/fixedvec.hpp>
#include <kprint>
#include <service>
#include <statman>
#include <cinttypes>
//#define ENABLE_PROFILERS
#ifdef ENABLE_PROFILERS
#include <profile>
#define PROFILE(name) ScopedProfiler __CONCAT(sp, __COUNTER__){name};
#else
#define PROFILE(name) /* name */
#endif
extern "C" void* get_cpu_esp();
extern "C" void kernel_sanity_checks();
extern uintptr_t heap_begin;
extern uintptr_t heap_end;
extern uintptr_t _start;
extern uintptr_t _end;
extern uintptr_t _ELF_START_;
extern uintptr_t _TEXT_START_;
extern uintptr_t _LOAD_START_;
extern uintptr_t _ELF_END_;
// Initialize static OS data members
bool OS::power_ = true;
bool OS::boot_sequence_passed_ = false;
MHz OS::cpu_mhz_ {-1};
uintptr_t OS::low_memory_size_ {0};
uintptr_t OS::high_memory_size_ {0};
uintptr_t OS::memory_end_ {0};
uintptr_t OS::heap_max_ {0xfffffff};
const uintptr_t OS::elf_binary_size_ {(uintptr_t)&_ELF_END_ - (uintptr_t)&_ELF_START_};
multiboot_info_t* OS::bootinfo_ = nullptr;
std::string OS::cmdline{Service::binary_name()};
// stdout redirection
using Print_vec = fixedvector<OS::print_func, 8>;
static Print_vec os_print_handlers(Fixedvector_Init::UNINIT);
extern void default_stdout_handlers();
// Plugins
OS::Plugin_vec OS::plugins_(Fixedvector_Init::UNINIT);
// OS version
#ifndef OS_VERSION
#define OS_VERSION "v?.?.?"
#endif
std::string OS::version_str_ = OS_VERSION;
std::string OS::arch_str_ = ARCH;
// sleep statistics
static uint64_t* os_cycles_hlt = nullptr;
static uint64_t* os_cycles_total = nullptr;
const std::string& OS::cmdline_args() noexcept
{
return cmdline;
}
void OS::start(uint32_t boot_magic, uint32_t boot_addr)
{
PROFILE("");
// Print a fancy header
CAPTION("#include<os> // Literally");
void* esp = get_cpu_esp();
MYINFO("Stack: %p", esp);
MYINFO("Boot magic: 0x%x, addr: 0x%x",
boot_magic, boot_addr);
/// STATMAN ///
/// initialize on page 7, 2 pages in size
Statman::get().init(0x6000, 0x2000);
PROFILE("Multiboot / legacy");
// Detect memory limits etc. depending on boot type
if (boot_magic == MULTIBOOT_BOOTLOADER_MAGIC) {
OS::multiboot(boot_addr);
} else {
if (is_softreset_magic(boot_magic) && boot_addr != 0)
OS::resume_softreset(boot_addr);
OS::legacy_boot();
}
Expects(high_memory_size_);
PROFILE("Memory map");
// Assign memory ranges used by the kernel
auto& memmap = memory_map();
OS::memory_end_ = high_memory_size_ + 0x100000;
MYINFO("Assigning fixed memory ranges (Memory map)");
memmap.assign_range({0x6000, 0x7fff, "Statman", "Statistics"});
memmap.assign_range({0xA000, 0x9fbff, "Stack", "Kernel / service main stack"});
memmap.assign_range({(uintptr_t)&_LOAD_START_, (uintptr_t)&_end,
"ELF", "Your service binary including OS"});
Expects(::heap_begin and heap_max_);
// @note for security we don't want to expose this
memmap.assign_range({(uintptr_t)&_end + 1, ::heap_begin - 1,
"Pre-heap", "Heap randomization area"});
// Give the rest of physical memory to heap
heap_max_ = ((0x100000 + high_memory_size_) & 0xffff0000) - 1;
uintptr_t span_max = std::numeric_limits<std::ptrdiff_t>::max();
uintptr_t heap_range_max_ = std::min(span_max, heap_max_);
MYINFO("Assigning heap");
memmap.assign_range({::heap_begin, heap_range_max_,
"Heap", "Dynamic memory", heap_usage });
MYINFO("Printing memory map");
for (const auto &i : memmap)
INFO2("* %s",i.second.to_string().c_str());
// sleep statistics
// NOTE: needs to be positioned before anything that calls OS::halt
os_cycles_hlt = &Statman::get().create(
Stat::UINT64, std::string("cpu0.cycles_hlt")).get_uint64();
os_cycles_total = &Statman::get().create(
Stat::UINT64, std::string("cpu0.cycles_total")).get_uint64();
PROFILE("Arch init");
extern void __arch_init();
__arch_init();
kernel_sanity_checks();
PROFILE("RTC init");
// Realtime/monotonic clock
RTC::init();
kernel_sanity_checks();
MYINFO("Initializing RNG");
PROFILE("RNG init");
// initialize random seed based on cycles since start
if (CPUID::has_feature(CPUID::Feature::RDRAND)) {
uint32_t rdrand_output[32];
for (size_t i = 0; i != 32; ++i) {
while (!rdrand32(&rdrand_output[i])) {}
}
rng_absorb(rdrand_output, sizeof(rdrand_output));
}
else {
// this is horrible, better solution needed here
for (size_t i = 0; i != 32; ++i) {
uint64_t clock = cycles_since_boot();
// maybe additionally call something which will take
// variable time depending in some way on the processor
// state (clflush?) or a HAVEGE-like approach.
rng_absorb(&clock, sizeof(clock));
}
}
// Seed rand with 32 bits from RNG
srand(rng_extract_uint32());
// Custom initialization functions
MYINFO("Initializing plugins");
// the boot sequence is over when we get to plugins/Service::start
OS::boot_sequence_passed_ = true;
PROFILE("Plugins init");
for (auto plugin : plugins_) {
INFO2("* Initializing %s", plugin.name_);
try{
plugin.func_();
} catch(std::exception& e){
MYINFO("Exception thrown when initializing plugin: %s", e.what());
} catch(...){
MYINFO("Unknown exception when initializing plugin");
}
}
PROFILE("Service::start");
// begin service start
FILLINE('=');
printf(" IncludeOS %s (%s / %i-bit)\n",
version().c_str(), arch().c_str(),
static_cast<int>(sizeof(uintptr_t)) * 8);
printf(" +--> Running [ %s ]\n", Service::name().c_str());
FILLINE('~');
Service::start();
}
void OS::register_plugin(Plugin delg, const char* name){
MYINFO("Registering plugin %s", name);
plugins_.emplace(delg, name);
}
int64_t OS::micros_since_boot() noexcept {
return cycles_since_boot() / cpu_freq().count();
}
uint64_t OS::get_cycles_halt() noexcept {
return *os_cycles_hlt;
}
uint64_t OS::get_cycles_total() noexcept {
return *os_cycles_total;
}
__attribute__((noinline))
void OS::halt() {
*os_cycles_total = cycles_since_boot();
#if defined(ARCH_x86)
asm volatile("hlt");
// add a global symbol here so we can quickly discard
// event loop from stack sampling
asm volatile(
".global _irq_cb_return_location;\n"
"_irq_cb_return_location:" );
#else
#warning "OS::halt() not implemented for selected arch"
#endif
// Count sleep cycles
*os_cycles_hlt += cycles_since_boot() - *os_cycles_total;
}
void OS::event_loop()
{
IRQ_manager::get().process_interrupts();
do {
OS::halt();
IRQ_manager::get().process_interrupts();
} while (power_);
MYINFO("Stopping service");
Service::stop();
MYINFO("Powering off");
extern void __arch_poweroff();
__arch_poweroff();
}
void OS::reboot()
{
extern void __arch_reboot();
__arch_reboot();
}
void OS::shutdown()
{
MYINFO("Soft shutdown signalled");
power_ = false;
}
void OS::on_panic(on_panic_func func)
{
extern on_panic_func panic_handler;
panic_handler = func;
}
void OS::add_stdout(OS::print_func func)
{
os_print_handlers.add(func);
}
void OS::add_stdout_default_serial()
{
add_stdout(
[] (const char* str, const size_t len) {
kprintf("%.*s", static_cast<int>(len), str);
});
}
__attribute__ ((weak))
void default_stdout_handlers()
{
OS::add_stdout_default_serial();
}
size_t OS::print(const char* str, const size_t len)
{
for (auto& func : os_print_handlers)
func(str, len);
return len;
}
void OS::legacy_boot() {
// Fetch CMOS memory info (unfortunately this is maximally 10^16 kb)
auto mem = hw::CMOS::meminfo();
low_memory_size_ = mem.base.total * 1024;
INFO2("* Low memory: %i Kib", mem.base.total);
high_memory_size_ = mem.extended.total * 1024;
// Use memsize provided by Make / linker unless CMOS knows this is wrong
INFO2("* High memory (from cmos): %i Kib", mem.extended.total);
auto& memmap = memory_map();
// No guarantees without multiboot, but we assume standard memory layout
memmap.assign_range({0x0009FC00, 0x0009FFFF,
"EBDA", "Extended BIOS data area"});
memmap.assign_range({0x000A0000, 0x000FFFFF,
"VGA/ROM", "Memory mapped video memory"});
// @note : since the maximum size of a span is unsigned (ptrdiff_t) we may need more than one
uintptr_t addr_max = std::numeric_limits<std::size_t>::max();
uintptr_t span_max = std::numeric_limits<std::ptrdiff_t>::max();
uintptr_t unavail_start = 0x100000 + high_memory_size_;
size_t interval = std::min(span_max, addr_max - unavail_start) - 1;
uintptr_t unavail_end = unavail_start + interval;
while (unavail_end < addr_max){
INFO2("* Unavailable memory: 0x%" PRIxPTR" - 0x%" PRIxPTR, unavail_start, unavail_end);
memmap.assign_range({unavail_start, unavail_end,
"N/A", "Reserved / outside physical range" });
unavail_start = unavail_end + 1;
interval = std::min(span_max, addr_max - unavail_start);
// Increment might wrapped around
if (unavail_start > unavail_end + interval or unavail_start + interval == addr_max){
INFO2("* Last chunk of memory: 0x%" PRIxPTR" - 0x%" PRIxPTR, unavail_start, addr_max);
memmap.assign_range({unavail_start, addr_max,
"N/A", "Reserved / outside physical range" });
break;
}
unavail_end += interval;
}
}
|
add shortname for stack memmap entry
|
kernel: add shortname for stack memmap entry
|
C++
|
apache-2.0
|
ingve/IncludeOS,AnnikaH/IncludeOS,ingve/IncludeOS,AndreasAakesson/IncludeOS,alfred-bratterud/IncludeOS,mnordsletten/IncludeOS,AndreasAakesson/IncludeOS,ingve/IncludeOS,hioa-cs/IncludeOS,ingve/IncludeOS,mnordsletten/IncludeOS,mnordsletten/IncludeOS,hioa-cs/IncludeOS,hioa-cs/IncludeOS,AnnikaH/IncludeOS,hioa-cs/IncludeOS,hioa-cs/IncludeOS,AnnikaH/IncludeOS,AndreasAakesson/IncludeOS,mnordsletten/IncludeOS,alfred-bratterud/IncludeOS,ingve/IncludeOS,AndreasAakesson/IncludeOS,alfred-bratterud/IncludeOS,AnnikaH/IncludeOS,AndreasAakesson/IncludeOS,mnordsletten/IncludeOS,AnnikaH/IncludeOS,mnordsletten/IncludeOS,alfred-bratterud/IncludeOS,AndreasAakesson/IncludeOS,alfred-bratterud/IncludeOS
|
95426bf133a8ed6e225e746978f7101ffb7fbd36
|
src/pow.cpp
|
src/pow.cpp
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "pow.h"
#include "chain.h"
#include "chainparams.h"
#include "primitives/block.h"
#include "uint256.h"
#include "util.h"
unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock)
{
unsigned int nProofOfWorkLimit = Params().ProofOfWorkLimit().GetCompact();
// Genesis block
if (pindexLast == NULL)
return nProofOfWorkLimit;
// Only change once per interval
if ((pindexLast->nHeight+1) % Params().Interval() != 0)
{
if (Params().AllowMinDifficultyBlocks())
{
// Special difficulty rule for testnet:
// If the new block's timestamp is more than 2* 10 minutes
// then allow mining of a min-difficulty block.
if (pblock->GetBlockTime() > pindexLast->GetBlockTime() + Params().TargetSpacing()*2)
return nProofOfWorkLimit;
else
{
// Return the last non-special-min-difficulty-rules-block
const CBlockIndex* pindex = pindexLast;
while (pindex->pprev && pindex->nHeight % Params().Interval() != 0 && pindex->nBits == nProofOfWorkLimit)
pindex = pindex->pprev;
return pindex->nBits;
}
}
return pindexLast->nBits;
}
// Go back by what we want to be 14 days worth of blocks
const CBlockIndex* pindexFirst = pindexLast;
for (int i = 0; pindexFirst && i < Params().Interval()-1; i++)
pindexFirst = pindexFirst->pprev;
assert(pindexFirst);
// Limit adjustment step
int64_t nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();
LogPrintf(" nActualTimespan = %d before bounds\n", nActualTimespan);
if (nActualTimespan < Params().TargetTimespan()/4)
nActualTimespan = Params().TargetTimespan()/4;
if (nActualTimespan > Params().TargetTimespan()*4)
nActualTimespan = Params().TargetTimespan()*4;
// Retarget
uint256 bnNew;
uint256 bnOld;
bnNew.SetCompact(pindexLast->nBits);
bnOld = bnNew;
bnNew *= nActualTimespan;
bnNew /= Params().TargetTimespan();
if (bnNew > Params().ProofOfWorkLimit())
bnNew = Params().ProofOfWorkLimit();
/// debug print
LogPrintf("GetNextWorkRequired RETARGET\n");
LogPrintf("Params().TargetTimespan() = %d nActualTimespan = %d\n", Params().TargetTimespan(), nActualTimespan);
LogPrintf("Before: %08x %s\n", pindexLast->nBits, bnOld.ToString());
LogPrintf("After: %08x %s\n", bnNew.GetCompact(), bnNew.ToString());
return bnNew.GetCompact();
}
bool CheckProofOfWork(uint256 hash, unsigned int nBits)
{
bool fNegative;
bool fOverflow;
uint256 bnTarget;
if (Params().SkipProofOfWorkCheck())
return true;
bnTarget.SetCompact(nBits, &fNegative, &fOverflow);
// Check range
if (fNegative || bnTarget == 0 || fOverflow || bnTarget > Params().ProofOfWorkLimit())
return error("CheckProofOfWork() : nBits below minimum work");
// Check proof of work matches claimed amount
if (hash > bnTarget)
return error("CheckProofOfWork() : hash doesn't match nBits");
return true;
}
uint256 GetBlockProof(const CBlockIndex& block)
{
uint256 bnTarget;
bool fNegative;
bool fOverflow;
bnTarget.SetCompact(block.nBits, &fNegative, &fOverflow);
if (fNegative || fOverflow || bnTarget == 0)
return 0;
// We need to compute 2**256 / (bnTarget+1), but we can't represent 2**256
// as it's too large for a uint256. However, as 2**256 is at least as large
// as bnTarget+1, it is equal to ((2**256 - bnTarget - 1) / (bnTarget+1)) + 1,
// or ~bnTarget / (nTarget+1) + 1.
return (~bnTarget / (bnTarget + 1)) + 1;
}
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "pow.h"
#include "chain.h"
#include "chainparams.h"
#include "primitives/block.h"
#include "uint256.h"
#include "util.h"
unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock)
{
unsigned int nProofOfWorkLimit = Params().ProofOfWorkLimit().GetCompact();
// Genesis block
if (pindexLast == NULL)
return nProofOfWorkLimit;
// Only change once per interval
if ((pindexLast->nHeight+1) % Params().Interval() != 0)
{
if (Params().AllowMinDifficultyBlocks())
{
// Special difficulty rule for testnet:
// If the new block's timestamp is more than 2* 10 minutes
// then allow mining of a min-difficulty block.
if (pblock->GetBlockTime() > pindexLast->GetBlockTime() + Params().TargetSpacing()*2)
return nProofOfWorkLimit;
else
{
// Return the last non-special-min-difficulty-rules-block
const CBlockIndex* pindex = pindexLast;
while (pindex->pprev && pindex->nHeight % Params().Interval() != 0 && pindex->nBits == nProofOfWorkLimit)
pindex = pindex->pprev;
return pindex->nBits;
}
}
return pindexLast->nBits;
}
/* Adapt the retargeting interval after merge-mining start
according to the changed Namecoin rules. */
int nBlocksBack = Params().Interval() - 1;
if (pindexLast->nHeight >= Params().AuxpowStartHeight()
&& (pindexLast->nHeight + 1 > Params().Interval()))
nBlocksBack = Params().Interval();
// Go back by what we want to be 14 days worth of blocks
const CBlockIndex* pindexFirst = pindexLast;
for (int i = 0; pindexFirst && i < nBlocksBack; i++)
pindexFirst = pindexFirst->pprev;
assert(pindexFirst);
// Limit adjustment step
int64_t nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();
LogPrintf(" nActualTimespan = %d before bounds\n", nActualTimespan);
if (nActualTimespan < Params().TargetTimespan()/4)
nActualTimespan = Params().TargetTimespan()/4;
if (nActualTimespan > Params().TargetTimespan()*4)
nActualTimespan = Params().TargetTimespan()*4;
// Retarget
uint256 bnNew;
uint256 bnOld;
bnNew.SetCompact(pindexLast->nBits);
bnOld = bnNew;
bnNew *= nActualTimespan;
bnNew /= Params().TargetTimespan();
if (bnNew > Params().ProofOfWorkLimit())
bnNew = Params().ProofOfWorkLimit();
/// debug print
LogPrintf("GetNextWorkRequired RETARGET\n");
LogPrintf("Params().TargetTimespan() = %d nActualTimespan = %d\n", Params().TargetTimespan(), nActualTimespan);
LogPrintf("Before: %08x %s\n", pindexLast->nBits, bnOld.ToString());
LogPrintf("After: %08x %s\n", bnNew.GetCompact(), bnNew.ToString());
return bnNew.GetCompact();
}
bool CheckProofOfWork(uint256 hash, unsigned int nBits)
{
bool fNegative;
bool fOverflow;
uint256 bnTarget;
if (Params().SkipProofOfWorkCheck())
return true;
bnTarget.SetCompact(nBits, &fNegative, &fOverflow);
// Check range
if (fNegative || bnTarget == 0 || fOverflow || bnTarget > Params().ProofOfWorkLimit())
return error("CheckProofOfWork() : nBits below minimum work");
// Check proof of work matches claimed amount
if (hash > bnTarget)
return error("CheckProofOfWork() : hash doesn't match nBits");
return true;
}
uint256 GetBlockProof(const CBlockIndex& block)
{
uint256 bnTarget;
bool fNegative;
bool fOverflow;
bnTarget.SetCompact(block.nBits, &fNegative, &fOverflow);
if (fNegative || fOverflow || bnTarget == 0)
return 0;
// We need to compute 2**256 / (bnTarget+1), but we can't represent 2**256
// as it's too large for a uint256. However, as 2**256 is at least as large
// as bnTarget+1, it is equal to ((2**256 - bnTarget - 1) / (bnTarget+1)) + 1,
// or ~bnTarget / (nTarget+1) + 1.
return (~bnTarget / (bnTarget + 1)) + 1;
}
|
Use Namecoin's modified difficulty retargeting.
|
Use Namecoin's modified difficulty retargeting.
Add the code that fixes the retargeting period off-by-one error.
|
C++
|
mit
|
FinalHashLLC/namecore,FinalHashLLC/namecore,FinalHashLLC/namecore,FinalHashLLC/namecore,FinalHashLLC/namecore
|
545632ed04c312cdca5e08eb353b3df96891e9ab
|
src/load_image.cc
|
src/load_image.cc
|
/*
* Copyright (c) 2017 Eddie Antonio Santos <[email protected]>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <cassert>
#include <cstdlib>
#include <cstdbool>
#include <cstdint>
#include <cstring>
#include <iostream>
#include <algorithm>
#include "cimg_config.h"
#include "CImg.hpp"
#include "load_image.h"
/**
* red/L*, blue/a*, green/b*, and alpha.
*/
const int COLOUR_DEPTH = 4;
namespace {
void maybe_resize(cimg_library::CImg<unsigned char>&, const LoadOpts&);
}
// TODO: Take "max width", "pixel ratio", "colour space".
// TODO: colour space transformation?
bool load_image(const char *filename, Image *image, struct LoadOpts* options) {
/* Zero-out the struct. */
bzero(image, sizeof(struct Image));
cimg_library::CImg<unsigned char> img;
try {
img.assign(filename);
} catch (cimg_library::CImgIOException& ex) {
// Could not load the image for some reason.
return false;
}
assert(img.data() != nullptr);
/* The image may be resized smaller. */
maybe_resize(img, *options);
/* Determine the number of bytes of the image. */
int size = img.width() * img.height() * COLOUR_DEPTH;
if (size < COLOUR_DEPTH) {
/* The image is too small! */
return false;
}
static_assert(1 == sizeof (uint8_t),
"somehow an octet is not the size of one byte");
uint8_t* buffer = (uint8_t*) malloc(size);
if (buffer == nullptr) {
/* Memory allocation error. */
return false;
}
/* Creates a 32bpp flat buffer copy of the image.
* The data layout is optimized for linear access to entire pixels,
* from top-to-bottom, left-to-right per each row.
* The channels are **interleaved** such that the memory for each
* individual pixel is cache-local (processor caches don't like it
* when you hop around memory for each datum).
*/
uint8_t *pos = buffer;
const auto greyscale = img.spectrum() < 3;
for (int y = 0; y < img.height(); y++) {
for (int x = 0; x < img.width(); x++) {
if (greyscale) {
/* Copy the grey channel three times. */
*pos++ = img(x, y);
*pos++ = img(x, y);
*pos++ = img(x, y);
} else {
/* Copy each channel independently. */
*pos++ = img(x, y, 0, 0);
*pos++ = img(x, y, 0, 1);
*pos++ = img(x, y, 0, 2);
}
/* The alpha channel is currently ignored,
* so let every pixel be opaque. */
/* TODO: handle transparency? */
*pos++ = 0xFF;
}
}
/* Assert we've processed the entire image. */
assert(pos == buffer + size);
image->width = img.width();
image->height = img.height();
image->buffer = buffer;
image->depth = COLOUR_DEPTH;
return true;
}
void unload_image(Image *image) {
assert(image->buffer != nullptr);
free(image->buffer);
image->buffer = nullptr;
image->width = 0;
image->height = 0;
}
namespace {
void maybe_resize(cimg_library::CImg<unsigned char>& img, const LoadOpts& options) {
bool resize_width = options.max_width > 0;
bool resize_height = options.desired_height > 0;
if (resize_width && resize_height) {
fprintf(stderr, "Not implemented!\n");
abort();
} else if (resize_width) {
/* Only resize if the image is strictly greater than the source width. */
if (img.width() <= options.max_width) {
return;
}
int new_width = options.max_width;
double ratio = ((double) img.height()) / img.width();
int new_height = ratio * (double) new_width;
img.resize(new_width, new_height);
} else if (resize_height) {
/* Resize without affecting aspect ratio. */
int new_height = options.desired_height;
double ratio = ((double) img.width()) / img.height();
/* Scale width, ensuring it's at least 1px. */
int new_width = std::max((int) (ratio * (double) new_height), 1);
fprintf(stderr, "width: %d, height: %d, ratio: %g\n",
new_width, new_height, ratio);
img.resize(new_width, new_height);
}
}
}
|
/*
* Copyright (c) 2017 Eddie Antonio Santos <[email protected]>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <cassert>
#include <cstdlib>
#include <cstdbool>
#include <cstdint>
#include <cstring>
#include <iostream>
#include <algorithm>
#include "cimg_config.h"
#include "CImg.hpp"
#include "load_image.h"
/**
* red/L*, blue/a*, green/b*, and alpha.
*/
const int COLOUR_DEPTH = 4;
namespace {
void maybe_resize(cimg_library::CImg<unsigned char>&, const LoadOpts&);
}
// TODO: Take "max width", "pixel ratio", "colour space".
// TODO: colour space transformation?
bool load_image(const char *filename, Image *image, struct LoadOpts* options) {
/* Zero-out the struct. */
bzero(image, sizeof(struct Image));
cimg_library::CImg<unsigned char> img;
try {
img.assign(filename);
} catch (cimg_library::CImgIOException& ex) {
// Could not load the image for some reason.
return false;
}
assert(img.data() != nullptr);
/* The image may be resized smaller. */
maybe_resize(img, *options);
/* Determine the number of bytes of the image. */
int size = img.width() * img.height() * COLOUR_DEPTH;
if (size < COLOUR_DEPTH) {
/* The image is too small! */
return false;
}
static_assert(1 == sizeof (uint8_t),
"somehow an octet is not the size of one byte");
uint8_t* buffer = (uint8_t*) malloc(size);
if (buffer == nullptr) {
/* Memory allocation error. */
return false;
}
/* Creates a 32bpp flat buffer copy of the image.
* The data layout is optimized for linear access to entire pixels,
* from top-to-bottom, left-to-right per each row.
* The channels are **interleaved** such that the memory for each
* individual pixel is cache-local (processor caches don't like it
* when you hop around memory for each datum).
*/
uint8_t *pos = buffer;
const auto greyscale = img.spectrum() < 3;
for (int y = 0; y < img.height(); y++) {
for (int x = 0; x < img.width(); x++) {
if (greyscale) {
/* Copy the grey channel three times. */
*pos++ = img(x, y);
*pos++ = img(x, y);
*pos++ = img(x, y);
} else {
/* Copy each channel independently. */
*pos++ = img(x, y, 0, 0);
*pos++ = img(x, y, 0, 1);
*pos++ = img(x, y, 0, 2);
}
/* The alpha channel is currently ignored,
* so let every pixel be opaque. */
/* TODO: handle transparency? */
*pos++ = 0xFF;
}
}
/* Assert we've processed the entire image. */
assert(pos == buffer + size);
image->width = img.width();
image->height = img.height();
image->buffer = buffer;
image->depth = COLOUR_DEPTH;
return true;
}
void unload_image(Image *image) {
assert(image->buffer != nullptr);
free(image->buffer);
image->buffer = nullptr;
image->width = 0;
image->height = 0;
}
namespace {
void maybe_resize(cimg_library::CImg<unsigned char>& img, const LoadOpts& options) {
bool resize_width = options.max_width > 0;
bool resize_height = options.desired_height > 0;
if (resize_width && resize_height) {
/* Make sure the image is never smaller than 1x1 pixels. */
int new_width = std::max(options.max_width, 1);
int new_height = std::max(options.desired_height, 1);
img.resize(new_width, new_height);
} else if (resize_width) {
/* Only resize if the image is strictly greater than the source width. */
if (img.width() <= options.max_width) {
return;
}
int new_width = options.max_width;
double ratio = ((double) img.height()) / img.width();
int new_height = ratio * (double) new_width;
img.resize(new_width, new_height);
} else if (resize_height) {
/* Resize without affecting aspect ratio. */
int new_height = options.desired_height;
double ratio = ((double) img.width()) / img.height();
/* Scale width, ensuring it's at least 1px. */
int new_width = std::max((int) (ratio * (double) new_height), 1);
img.resize(new_width, new_height);
}
}
}
|
Scale both height and width.
|
Scale both height and width.
|
C++
|
isc
|
eddieantonio/imgcat,eddieantonio/imgcat,eddieantonio/imgcat,eddieantonio/imgcat
|
15847a736393081affb51dda76b72f0257441168
|
src/main-menu.cpp
|
src/main-menu.cpp
|
#include <sstream>
#include "factory/collector.h"
// #include "network/network.h"
#include "util/token_exception.h"
#include "mugen/exception.h"
#include "mugen/menu.h"
#include "music.h"
#include "menu/menu.h"
#include "menu/menu_global.h"
#include "input/input-manager.h"
#include "game/mod.h"
#include "shutdown_exception.h"
#include "util/timedifference.h"
#include "util/funcs.h"
#include "util/file-system.h"
#include "util/tokenreader.h"
#include "util/token.h"
#include "globals.h"
// #include "network/server.h"
#include "configuration.h"
#include "init.h"
#include <string.h>
#include <vector>
using namespace std;
static int gfx = Global::WINDOWED;
#define NUM_ARGS(d) (sizeof(d)/sizeof(char*))
static const char * WINDOWED_ARG[] = {"-w", "fullscreen", "nowindowed", "no-windowed"};
static const char * DATAPATH_ARG[] = {"-d", "data", "datapath", "data-path", "path"};
static const char * DEBUG_ARG[] = {"-l", "debug"};
static const char * MUSIC_ARG[] = {"-m", "music", "nomusic", "no-music"};
static const char * NETWORK_SERVER_ARG[] = {"server", "network-server"};
static const char * MUGEN_ARG[] = {"mugen"};
static const char * closestMatch(const char * s1, vector<const char *> args){
const char * good = NULL;
int minimum = -1;
for (vector<const char *>::iterator it = args.begin(); it != args.end(); it++){
const char * compare = *it;
if (strlen(compare) > 2){
int distance = Util::levenshtein(s1, compare);
if (distance != -1 && (minimum == -1 || distance < minimum)){
minimum = distance;
good = compare;
}
}
}
return good;
}
static bool isArg( const char * s1, const char * s2[], int num){
for (int i = 0; i < num; i++){
if (strcasecmp(s1, s2[i]) == 0){
return true;
}
}
return false;
}
/* {"a", "b", "c"}, 3, ',' => "a, b, c"
*/
static const char * all(const char * args[], const int num, const char separate = ','){
static char buffer[1<<10];
strcpy(buffer, "");
for (int i = 0; i < num; i++){
char fuz[10];
sprintf(fuz, "%c ", separate);
strcat(buffer, args[i]);
if (i != num - 1){
strcat(buffer, fuz);
}
}
return buffer;
}
static void showOptions(){
Global::debug(0) << "Paintown by Jon Rafkind" << endl;
Global::debug(0) << all(WINDOWED_ARG, NUM_ARGS(WINDOWED_ARG), ',') << " : Fullscreen mode" << endl;
Global::debug(0) << all(DATAPATH_ARG, NUM_ARGS(DATAPATH_ARG)) << " <path> : Use data path of <path>. Default is " << Util::getDataPath2() << endl;
Global::debug(0) << all(DEBUG_ARG, NUM_ARGS(DEBUG_ARG)) << " # : Enable debug statements. Higher numbers gives more debugging. Default is 0. Negative numbers are allowed. Example: -l 3" << endl;
Global::debug(0) << all(MUSIC_ARG, NUM_ARGS(MUSIC_ARG)) << " : Turn off music" << endl;
Global::debug(0) << all(MUGEN_ARG, NUM_ARGS(MUGEN_ARG)) << " : Go directly to the mugen menu" << endl;
// Global::debug(0) << all(NETWORK_SERVER_ARG, NUM_ARGS(NETWORK_SERVER_ARG)) << " : Go straight to the network server" << endl;
Global::debug(0) << endl;
}
static void addArgs(vector<const char *> & args, const char * strings[], int num){
for (int i = 0; i < num; i++){
args.push_back(strings[i]);
}
}
static string mainMenuPath() throw (TokenException, LoadException, Filesystem::NotFound){
string menu = Paintown::Mod::getCurrentMod()->getMenu();
return Filesystem::find(menu);
/*
string file = Filesystem::find(currentMod());
TokenReader tr(file);
Token * head = tr.readToken();
Token * menu = head->findToken("game/menu");
if (menu == NULL){
throw LoadException(file + " does not contain a game/menu token");
}
string path;
*menu >> path;
// string path = "/menu/main.txt"
return Filesystem::find(path);
*/
}
int paintown_main( int argc, char ** argv ){
bool music_on = true;
bool mugen = false;
// bool just_network_server = false;
Collector janitor;
Global::setDebug( 0 );
vector<const char *> all_args;
#define ADD_ARGS(args) addArgs(all_args, args, NUM_ARGS(args))
ADD_ARGS(WINDOWED_ARG);
ADD_ARGS(DATAPATH_ARG);
ADD_ARGS(DEBUG_ARG);
ADD_ARGS(MUSIC_ARG);
ADD_ARGS(MUGEN_ARG);
// ADD_ARGS(NETWORK_SERVER_ARG);
#undef ADD_ARGS
for ( int q = 1; q < argc; q++ ){
if ( isArg( argv[ q ], WINDOWED_ARG, NUM_ARGS(WINDOWED_ARG) ) ){
gfx = Global::FULLSCREEN;
} else if ( isArg( argv[ q ], DATAPATH_ARG, NUM_ARGS(DATAPATH_ARG) ) ){
q += 1;
if ( q < argc ){
Util::setDataPath( argv[ q ] );
}
} else if ( isArg( argv[ q ], MUSIC_ARG, NUM_ARGS(MUSIC_ARG) ) ){
music_on = false;
} else if (isArg(argv[q], MUGEN_ARG, NUM_ARGS(MUGEN_ARG))){
mugen = true;
} else if ( isArg( argv[ q ], DEBUG_ARG, NUM_ARGS(DEBUG_ARG) ) ){
q += 1;
if ( q < argc ){
istringstream i( argv[ q ] );
int f;
i >> f;
Global::setDebug( f );
}
/*
} else if (isArg(argv[q], NETWORK_SERVER_ARG, NUM_ARGS(NETWORK_SERVER_ARG))){
just_network_server = true;
*/
} else {
const char * arg = argv[q];
const char * closest = closestMatch(arg, all_args);
if (closest == NULL){
Global::debug(0) << "I don't recognize option '" << arg << "'" << endl;
} else {
Global::debug(0) << "You gave option '" << arg << "'. Did you mean '" << closest << "'?" << endl;
}
}
}
#undef NUM_ARGS
showOptions();
Global::debug(0) << "Debug level: " << Global::getDebug() << endl;
/* time how long init takes */
TimeDifference diff;
diff.startTime();
/* init initializes practically everything including
* graphics
* sound
* input
* network
* configuration
* ...
*/
if (! Global::init(gfx)){
Global::debug( 0 ) << "Could not initialize system" << endl;
return -1;
} else {
MenuGlobals::setFullscreen((gfx == Global::FULLSCREEN ? true : false));
}
diff.endTime();
Global::debug(0) << diff.printTime("Init took") << endl;
Paintown::Mod::loadMod(Configuration::getCurrentGame());
InputManager input;
Music music(music_on);
try{
if (mugen){
Mugen::run();
} else {
Menu game;
game.load(mainMenuPath());
game.run();
}
} catch (const Filesystem::NotFound & ex){
Global::debug(0) << "There was a problem loading the main menu. Error was:\n " << ex.getReason() << endl;
} catch (const TokenException & ex){
Global::debug(0) << "There was a problem with the token. Error was:\n " << ex.getReason() << endl;
return -1;
} catch (const LoadException & ex){
Global::debug(0) << "There was a problem loading the main menu. Error was:\n " << ex.getReason() << endl;
return -1;
} catch (const ReturnException & ex){
} catch (const ShutdownException & shutdown){
Global::debug(1) << "Forced a shutdown. Cya!" << endl;
} catch (const MugenException & m){
Global::debug(0) << "Mugen exception: " << m.getReason() << endl;
} catch (...){
Global::debug(0) << "Uncaught exception!" << endl;
}
Configuration::saveConfiguration();
return 0;
}
|
#include <sstream>
#include "factory/collector.h"
// #include "network/network.h"
#include "util/token_exception.h"
#include "mugen/exception.h"
#include "mugen/menu.h"
#include "music.h"
#include "menu/menu.h"
#include "menu/menu_global.h"
#include "input/input-manager.h"
#include "game/mod.h"
#include "shutdown_exception.h"
#include "util/timedifference.h"
#include "util/funcs.h"
#include "util/file-system.h"
#include "util/tokenreader.h"
#include "util/token.h"
#include "globals.h"
// #include "network/server.h"
#include "configuration.h"
#include "init.h"
#include <string.h>
#include <vector>
using namespace std;
static int gfx = Global::WINDOWED;
#define NUM_ARGS(d) (sizeof(d)/sizeof(char*))
static const char * WINDOWED_ARG[] = {"-w", "fullscreen", "nowindowed", "no-windowed"};
static const char * DATAPATH_ARG[] = {"-d", "data", "datapath", "data-path", "path"};
static const char * DEBUG_ARG[] = {"-l", "debug"};
static const char * MUSIC_ARG[] = {"-m", "music", "nomusic", "no-music"};
static const char * NETWORK_SERVER_ARG[] = {"server", "network-server"};
static const char * MUGEN_ARG[] = {"mugen"};
static const char * closestMatch(const char * s1, vector<const char *> args){
const char * good = NULL;
int minimum = -1;
for (vector<const char *>::iterator it = args.begin(); it != args.end(); it++){
const char * compare = *it;
if (strlen(compare) > 2){
int distance = Util::levenshtein(s1, compare);
if (distance != -1 && (minimum == -1 || distance < minimum)){
minimum = distance;
good = compare;
}
}
}
return good;
}
static bool isArg( const char * s1, const char * s2[], int num){
for (int i = 0; i < num; i++){
if (strcasecmp(s1, s2[i]) == 0){
return true;
}
}
return false;
}
/* {"a", "b", "c"}, 3, ',' => "a, b, c"
*/
static const char * all(const char * args[], const int num, const char separate = ','){
static char buffer[1<<10];
strcpy(buffer, "");
for (int i = 0; i < num; i++){
char fuz[10];
sprintf(fuz, "%c ", separate);
strcat(buffer, args[i]);
if (i != num - 1){
strcat(buffer, fuz);
}
}
return buffer;
}
static void showOptions(){
Global::debug(0) << "Paintown by Jon Rafkind" << endl;
Global::debug(0) << all(WINDOWED_ARG, NUM_ARGS(WINDOWED_ARG), ',') << " : Fullscreen mode" << endl;
Global::debug(0) << all(DATAPATH_ARG, NUM_ARGS(DATAPATH_ARG)) << " <path> : Use data path of <path>. Default is " << Util::getDataPath2() << endl;
Global::debug(0) << all(DEBUG_ARG, NUM_ARGS(DEBUG_ARG)) << " # : Enable debug statements. Higher numbers gives more debugging. Default is 0. Negative numbers are allowed. Example: -l 3" << endl;
Global::debug(0) << all(MUSIC_ARG, NUM_ARGS(MUSIC_ARG)) << " : Turn off music" << endl;
Global::debug(0) << all(MUGEN_ARG, NUM_ARGS(MUGEN_ARG)) << " : Go directly to the mugen menu" << endl;
// Global::debug(0) << all(NETWORK_SERVER_ARG, NUM_ARGS(NETWORK_SERVER_ARG)) << " : Go straight to the network server" << endl;
Global::debug(0) << endl;
}
static void addArgs(vector<const char *> & args, const char * strings[], int num){
for (int i = 0; i < num; i++){
args.push_back(strings[i]);
}
}
static string mainMenuPath() throw (TokenException, LoadException, Filesystem::NotFound){
string menu = Paintown::Mod::getCurrentMod()->getMenu();
return Filesystem::find(menu);
/*
string file = Filesystem::find(currentMod());
TokenReader tr(file);
Token * head = tr.readToken();
Token * menu = head->findToken("game/menu");
if (menu == NULL){
throw LoadException(file + " does not contain a game/menu token");
}
string path;
*menu >> path;
// string path = "/menu/main.txt"
return Filesystem::find(path);
*/
}
int paintown_main( int argc, char ** argv ){
bool music_on = true;
bool mugen = false;
// bool just_network_server = false;
Collector janitor;
Global::setDebug( 0 );
vector<const char *> all_args;
#define ADD_ARGS(args) addArgs(all_args, args, NUM_ARGS(args))
ADD_ARGS(WINDOWED_ARG);
ADD_ARGS(DATAPATH_ARG);
ADD_ARGS(DEBUG_ARG);
ADD_ARGS(MUSIC_ARG);
ADD_ARGS(MUGEN_ARG);
// ADD_ARGS(NETWORK_SERVER_ARG);
#undef ADD_ARGS
for ( int q = 1; q < argc; q++ ){
if ( isArg( argv[ q ], WINDOWED_ARG, NUM_ARGS(WINDOWED_ARG) ) ){
gfx = Global::FULLSCREEN;
} else if ( isArg( argv[ q ], DATAPATH_ARG, NUM_ARGS(DATAPATH_ARG) ) ){
q += 1;
if ( q < argc ){
Util::setDataPath( argv[ q ] );
}
} else if ( isArg( argv[ q ], MUSIC_ARG, NUM_ARGS(MUSIC_ARG) ) ){
music_on = false;
} else if (isArg(argv[q], MUGEN_ARG, NUM_ARGS(MUGEN_ARG))){
mugen = true;
} else if ( isArg( argv[ q ], DEBUG_ARG, NUM_ARGS(DEBUG_ARG) ) ){
q += 1;
if ( q < argc ){
istringstream i( argv[ q ] );
int f;
i >> f;
Global::setDebug( f );
}
/*
} else if (isArg(argv[q], NETWORK_SERVER_ARG, NUM_ARGS(NETWORK_SERVER_ARG))){
just_network_server = true;
*/
} else {
const char * arg = argv[q];
const char * closest = closestMatch(arg, all_args);
if (closest == NULL){
Global::debug(0) << "I don't recognize option '" << arg << "'" << endl;
} else {
Global::debug(0) << "You gave option '" << arg << "'. Did you mean '" << closest << "'?" << endl;
}
}
}
#undef NUM_ARGS
showOptions();
Global::debug(0) << "Debug level: " << Global::getDebug() << endl;
/* time how long init takes */
TimeDifference diff;
diff.startTime();
/* init initializes practically everything including
* graphics
* sound
* input
* network
* configuration
* ...
*/
if (! Global::init(gfx)){
Global::debug( 0 ) << "Could not initialize system" << endl;
return -1;
} else {
MenuGlobals::setFullscreen((gfx == Global::FULLSCREEN ? true : false));
}
diff.endTime();
Global::debug(0) << diff.printTime("Init took") << endl;
Paintown::Mod::loadMod(Configuration::getCurrentGame());
InputManager input;
Music music(music_on);
try{
Menu game;
game.load(mainMenuPath());
if (mugen){
Mugen::run();
} else {
game.run();
}
} catch (const Filesystem::NotFound & ex){
Global::debug(0) << "There was a problem loading the main menu. Error was:\n " << ex.getReason() << endl;
} catch (const TokenException & ex){
Global::debug(0) << "There was a problem with the token. Error was:\n " << ex.getReason() << endl;
return -1;
} catch (const LoadException & ex){
Global::debug(0) << "There was a problem loading the main menu. Error was:\n " << ex.getReason() << endl;
return -1;
} catch (const ReturnException & ex){
} catch (const ShutdownException & shutdown){
Global::debug(1) << "Forced a shutdown. Cya!" << endl;
} catch (const MugenException & m){
Global::debug(0) << "Mugen exception: " << m.getReason() << endl;
} catch (...){
Global::debug(0) << "Uncaught exception!" << endl;
}
Configuration::saveConfiguration();
return 0;
}
|
load the main menu no matter what
|
load the main menu no matter what
|
C++
|
bsd-3-clause
|
scristopher/paintown,scristopher/paintown,scristopher/paintown,scristopher/paintown,scristopher/paintown,scristopher/paintown,scristopher/paintown,scristopher/paintown
|
7b74d0a2a8a3c479d31a377a211430d0bbb7010f
|
src/tag.cpp
|
src/tag.cpp
|
#include <tag.hpp>
#include <string.hpp>
#include <map>
namespace rack {
namespace tag {
const std::vector<std::vector<std::string>> tagAliases = {
{"Arpeggiator"},
// With a level knob and not much else.
{"Attenuator"},
// No parameters or ports. Serves no purpose except visual.
{"Blank"},
{"Chorus"},
{"Clock generator", "Clock"},
// Clock dividers, multipliers, etc.
{"Clock modulator"},
// With threshold, ratio, knee, etc parameters.
{"Compressor"},
// Use only if the artist "performs" with this module. Simply having knobs is not enough. Examples: on-screen keyboard, XY pad.
{"Controller"},
{"Delay"},
{"Digital"},
{"Distortion"},
{"Drum", "Drums", "Percussion"},
// The core functionality times two. If multiple channels are a requirement for the module to exist (ring modulator, mixer, etc), it is not a Dual module.
{"Dual"},
{"Dynamics"},
{"Effect"},
{"Envelope follower"},
{"Envelope generator"},
{"Equalizer", "EQ"},
// Expands the functionality of a "mother" module when placed next to it. Expanders should inherit the tags of its mother module.
{"Expander"},
{"External"},
{"Filter", "VCF", "Voltage controlled filter"},
{"Flanger"},
{"Function generator"},
{"Granular"},
{"Limiter"},
{"Logic"},
{"Low-frequency oscillator", "LFO", "Low frequency oscillator"},
{"Low-pass gate", "Low pass gate", "Lowpass gate"},
{"MIDI"},
{"Mixer"},
{"Multiple"},
{"Noise"},
{"Oscillator", "VCO", "Voltage controlled oscillator"},
{"Panning", "Pan"},
{"Phaser"},
{"Physical modeling"},
{"Polyphonic", "Poly"},
// The core functionality times four. If multiple channels are a requirement for the module to exist (ring modulator, mixer, etc), it is not a Quad module.
{"Quad"},
{"Quantizer"},
{"Random"},
{"Recording"},
{"Reverb"},
{"Ring modulator"},
{"Sample and hold", "S&H", "Sample & hold"},
{"Sampler"},
{"Sequencer"},
{"Slew limiter"},
{"Switch"},
// A synth voice must have, at the minimum, a built-in oscillator and envelope.
{"Synth voice"},
{"Tuner"},
// Serves only extremely basic functions, like inverting, max, min, multiplying by 2, etc.
{"Utility"},
{"Visual"},
{"Vocoder"},
{"Voltage-controlled amplifier", "Amplifier", "VCA", "Voltage controlled amplifier"},
{"Waveshaper"},
};
int findId(const std::string& tag) {
std::string lowercaseTag = string::lowercase(tag);
for (int tagId = 0; tagId < (int) tagAliases.size(); tagId++) {
for (const std::string& alias : tagAliases[tagId]) {
if (string::lowercase(alias) == lowercaseTag)
return tagId;
}
}
return -1;
}
} // namespace tag
} // namespace rack
|
#include <tag.hpp>
#include <string.hpp>
#include <map>
namespace rack {
namespace tag {
const std::vector<std::vector<std::string>> tagAliases = {
{"Arpeggiator"}, // With a level knob and not much else.
{"Attenuator"}, // No parameters or ports. Serves no purpose except visual.
{"Blank"},
{"Chorus"},
{"Clock generator", "Clock"}, // Clock dividers, multipliers, etc.
{"Clock modulator"}, // With threshold, ratio, knee, etc parameters.
{"Compressor"}, // Use only if the artist "performs" with this module. Simply having knobs is not enough. Examples: on-screen keyboard, XY pad.
{"Controller"},
{"Delay"},
{"Digital"},
{"Distortion"},
{"Drum", "Drums", "Percussion"}, // The core functionality times two. If multiple channels are a requirement for the module to exist (ring modulator, mixer, etc), it is not a Dual module.
{"Dual"},
{"Dynamics"},
{"Effect"},
{"Envelope follower"},
{"Envelope generator"},
{"Equalizer", "EQ"}, // Expands the functionality of a "mother" module when placed next to it. Expanders should inherit the tags of its mother module.
{"Expander"},
{"External"},
{"Filter", "VCF", "Voltage controlled filter"},
{"Flanger"},
{"Function generator"},
{"Granular"},
{"Hardware clone", "Hardware"}, // Clones the functionality *and* appearance of a real-world hardware module.
{"Limiter"},
{"Logic"},
{"Low-frequency oscillator", "LFO", "Low frequency oscillator"},
{"Low-pass gate", "Low pass gate", "Lowpass gate"},
{"MIDI"},
{"Mixer"},
{"Multiple"},
{"Noise"},
{"Oscillator", "VCO", "Voltage controlled oscillator"},
{"Panning", "Pan"},
{"Phaser"},
{"Physical modeling"},
{"Polyphonic", "Poly"}, // The core functionality times four. If multiple channels are a requirement for the module to exist (ring modulator, mixer, etc), it is not a Quad module.
{"Quad"},
{"Quantizer"},
{"Random"},
{"Recording"},
{"Reverb"},
{"Ring modulator"},
{"Sample and hold", "S&H", "Sample & hold"},
{"Sampler"},
{"Sequencer"},
{"Slew limiter"},
{"Switch"}, // A synth voice must have, at the minimum, a built-in oscillator and envelope.
{"Synth voice"},
{"Tuner"}, // Serves only extremely basic functions, like inverting, max, min, multiplying by 2, etc.
{"Utility"},
{"Visual"},
{"Vocoder"},
{"Voltage-controlled amplifier", "Amplifier", "VCA", "Voltage controlled amplifier"},
{"Waveshaper"},
};
int findId(const std::string& tag) {
std::string lowercaseTag = string::lowercase(tag);
for (int tagId = 0; tagId < (int) tagAliases.size(); tagId++) {
for (const std::string& alias : tagAliases[tagId]) {
if (string::lowercase(alias) == lowercaseTag)
return tagId;
}
}
return -1;
}
} // namespace tag
} // namespace rack
|
Add Hardware tag.
|
Add Hardware tag.
|
C++
|
mit
|
AndrewBelt/Rack
|
b2de5528752eee7a12497fb9241b519daf6c7c62
|
src/runner/main.cpp
|
src/runner/main.cpp
|
#include <iostream>
#include <string>
#include <cstdint>
#include "linenoise.h"
#include <db.h>
#include <humblelogging/api.h>
#include <boost/algorithm/string.hpp>
using namespace std;
HUMBLE_LOGGER(logger, "default");
void completion(const char *bufRaw, linenoiseCompletions *lc)
{
std::string buf(bufRaw);
if(boost::starts_with(buf, "q"))
{
linenoiseAddCompletion(lc,"quit");
}
else if(boost::starts_with(buf, "e"))
{
linenoiseAddCompletion(lc,"exit");
}
else if(boost::starts_with(buf, "i"))
{
linenoiseAddCompletion(lc,"import");
}
else if(boost::starts_with(buf, "s"))
{
linenoiseAddCompletion(lc, "save");
}
else if(boost::starts_with(buf, "l"))
{
linenoiseAddCompletion(lc, "load");
}
}
int main(int argc, char** argv)
{
char* lineBuffer = NULL;
humble::logging::Factory &fac = humble::logging::Factory::getInstance();
fac.setDefaultLogLevel(humble::logging::LogLevel::All);
fac.setDefaultFormatter(new humble::logging::PatternFormatter("[%date] %m\n"));
fac.registerAppender(new humble::logging::ConsoleAppender());
linenoiseHistoryLoad("annis4_history.txt");
linenoiseSetCompletionCallback(completion);
// our main database
annis::DB db;
bool exit = false;
while(!exit && (lineBuffer = linenoise("annis4> ")) != NULL)
{
std::string line(lineBuffer);
linenoiseHistoryAdd(lineBuffer);
linenoiseHistorySave("annis4_history.txt");
// split the line into it's components
vector<string> args;
boost::split(args,line, boost::is_any_of(" "));
std::string cmd = "";
if(args.size() > 0)
{
cmd = args[0];
args.erase(args.begin());
}
try
{
if (cmd == "import")
{
if(args.size() > 0)
{
std::cout << "Import relANNIS from " << args[0] << std::endl;
db.loadRelANNIS(args[0]);
}
else
{
std::cout << "You have to give a path as argument" << std::endl;
}
}
else if(cmd == "save")
{
if(args.size() > 0)
{
std::cout << "Save to " << args[0] << std::endl;
db.save(args[0]);
}
else
{
std::cout << "You have to give a path as argument" << std::endl;
}
}
else if(cmd == "load")
{
if(args.size() > 0)
{
std::cout << "Loading from " << args[0] << std::endl;
db.load(args[0]);
}
else
{
std::cout << "You have to give a path as argument" << std::endl;
}
}
else if(cmd == "info")
{
std::cout << db.info() << std::endl;
}
else if (cmd == "quit" || cmd == "exit")
{
exit = true;
}
else
{
std::cout << "Unknown command \"" << cmd << "\"" << std::endl;
}
}
catch(std::string ex)
{
std::cerr << "Exception: " << ex << std::endl;
}
free(lineBuffer);
}
std::cout << "Exiting" << std::endl;
return 0;
}
|
#include <iostream>
#include <string>
#include <cstdint>
#include "linenoise.h"
#include <db.h>
#include <humblelogging/api.h>
#include <boost/algorithm/string.hpp>
using namespace std;
HUMBLE_LOGGER(logger, "default");
void completion(const char *bufRaw, linenoiseCompletions *lc)
{
std::string buf(bufRaw);
if(boost::starts_with(buf, "q"))
{
linenoiseAddCompletion(lc,"quit");
}
else if(boost::starts_with(buf, "e"))
{
linenoiseAddCompletion(lc,"exit");
}
else if(boost::starts_with(buf, "i"))
{
linenoiseAddCompletion(lc,"import");
}
else if(boost::starts_with(buf, "s"))
{
linenoiseAddCompletion(lc, "save");
}
else if(boost::starts_with(buf, "l"))
{
linenoiseAddCompletion(lc, "load");
}
else if(boost::starts_with(buf, "o"))
{
linenoiseAddCompletion(lc, "optimize");
}
}
int main(int argc, char** argv)
{
char* lineBuffer = NULL;
humble::logging::Factory &fac = humble::logging::Factory::getInstance();
fac.setDefaultLogLevel(humble::logging::LogLevel::All);
fac.setDefaultFormatter(new humble::logging::PatternFormatter("[%date] %m\n"));
fac.registerAppender(new humble::logging::ConsoleAppender());
linenoiseHistoryLoad("annis4_history.txt");
linenoiseSetCompletionCallback(completion);
// our main database
annis::DB db;
bool exit = false;
while(!exit && (lineBuffer = linenoise("annis4> ")) != NULL)
{
std::string line(lineBuffer);
linenoiseHistoryAdd(lineBuffer);
linenoiseHistorySave("annis4_history.txt");
// split the line into it's components
vector<string> args;
boost::split(args,line, boost::is_any_of(" "));
std::string cmd = "";
if(args.size() > 0)
{
cmd = args[0];
args.erase(args.begin());
}
try
{
if (cmd == "import")
{
if(args.size() > 0)
{
std::cout << "Import relANNIS from " << args[0] << std::endl;
db.loadRelANNIS(args[0]);
}
else
{
std::cout << "You have to give a path as argument" << std::endl;
}
}
else if(cmd == "save")
{
if(args.size() > 0)
{
std::cout << "Save to " << args[0] << std::endl;
db.save(args[0]);
}
else
{
std::cout << "You have to give a path as argument" << std::endl;
}
}
else if(cmd == "load")
{
if(args.size() > 0)
{
std::cout << "Loading from " << args[0] << std::endl;
db.load(args[0]);
}
else
{
std::cout << "You have to give a path as argument" << std::endl;
}
}
else if(cmd == "info")
{
std::cout << db.info() << std::endl;
}
else if(cmd == "optimize")
{
std::cout << "Optimizing..." << std::endl;
db.optimizeAll();
std::cout << "Finished." << std::endl;
}
else if (cmd == "quit" || cmd == "exit")
{
exit = true;
}
else
{
std::cout << "Unknown command \"" << cmd << "\"" << std::endl;
}
}
catch(std::string ex)
{
std::cerr << "Exception: " << ex << std::endl;
}
free(lineBuffer);
}
std::cout << "Exiting" << std::endl;
return 0;
}
|
allow to optimize all components from the command line (e.g. to update a DB after loading a version which used another heuristic)
|
allow to optimize all components from the command line (e.g. to update a DB after loading a version which used another heuristic)
|
C++
|
apache-2.0
|
thomaskrause/graphANNIS,thomaskrause/graphANNIS,thomaskrause/graphANNIS,thomaskrause/graphANNIS,thomaskrause/graphANNIS,thomaskrause/graphANNIS,thomaskrause/graphANNIS
|
cf1274dd69ba2168d2c1bb5a9428691e0e0d4670
|
libs/graphslam/src/CRosTopicMP.cpp
|
libs/graphslam/src/CRosTopicMP.cpp
|
/* +---------------------------------------------------------------------------+
| Mobile Robot Programming Toolkit (MRPT) |
| http://www.mrpt.org/ |
| |
| Copyright (c) 2005-2016, Individual contributors, see AUTHORS file |
| See: http://www.mrpt.org/Authors - All rights reserved. |
| Released under BSD License. See details in http://www.mrpt.org/License |
+---------------------------------------------------------------------------+ */
#include "graphslam-precomp.h" // Precompiled headers
#include <mrpt/graphslam/CRosTopicMP.h>
namespace mrpt { namespace graphslam { namespace measurement_providers {
CRosTopicMP::CRosTopicMP():
client_params(*this) {
this->init();
}
CRosTopicMP::~CRosTopicMP() {
MRPT_LOG_DEBUG_STREAM << "In class Destructor";
MRPT_LOG_DEBUG_STREAM << "Deleting client socket instance.";
delete m_client;
}
void CRosTopicMP::init() {
MRPT_START;
// configure the current provider
m_class_name = "CRosTopicMP";
m_ini_section_name = "CMeasurementProviderParameters";
this->setLoggerName(m_class_name);
run_online = true;
provider_ready = false;
m_client = NULL;
MRPT_END;
}
bool CRosTopicMP::getActionObservationPairOrObservation(
mrpt::obs::CActionCollectionPtr& action,
mrpt::obs::CSensoryFramePtr& observations,
mrpt::obs::CObservationPtr& observation,
size_t& rawlog_entry ) {
MRPT_START;
using namespace std;
using namespace mrpt::obs;
using namespace mrpt::utils;
ASSERTMSG_(provider_ready,
"getActionObservationPairOrObservation was called even though provider is not ready yet.");
//is there any data available - if so return it, otherwise block and wait
// TODO - maybe inform of the user if it takes too long to return from this
// --> requires multithreading
// Ask the server of data
CMessage msg;
bool did_receive = m_client->receiveMessage(msg,
/*timeoutStart_ms =*/ 40000,
/*timeoutBetween_ms =*/ 2000 );
if (!did_receive) { // communication failed. What exception should I raise?
if (client_params.has_transmitted_valid_data) {
// Overall, I have managed to transmit some data.
// Assume that the data transmission is over.
msg.type = client_params.msg_types["EXIT"];
}
else {
THROW_EXCEPTION("\nMessage transmission stopped abruptly.\n");
}
}
stringstream ss("");
ss << "Received message: Type: " << msg.type
<< " | Length: " << msg.content.size();
MRPT_LOG_DEBUG_STREAM << ss.str();
// discard anything that might be in the rawlog
action.clear_unique();
observations.clear_unique();
observation.clear_unique();
bool success;
if (msg.type == client_params.msg_types["FORMAT_1"]) {
// in case of format #1 I need two objects:
// - CActionCollection
// - CSensoryFrame
// TODO
THROW_EXCEPTION("FORMAT 1 (action-observations) is not implemented yet.");
}
else if (msg.type == client_params.msg_types["FORMAT_2"]) {
observation = mrpt::obs::CObservation2DRangeScan::Create();
msg.deserializeIntoExistingObject(observation.pointer());
success=true;
}
else if (msg.type == client_params.msg_types["EXIT"]) {
success = false;
}
else {
THROW_EXCEPTION(
mrpt::format("%s: Received measurement was not understood.",
m_class_name.c_str()));
}
if (success) {
client_params.has_transmitted_valid_data = true;
}
return success;
MRPT_END;
}
bool CRosTopicMP::providerIsReady() {
return provider_ready;
}
bool CRosTopicMP::providerRunsOnline() {
return run_online;
}
void CRosTopicMP::printParams() const {
MRPT_START;
// TODO - implement this.
client_params.dumpToConsole();
MRPT_END;
}
void CRosTopicMP::loadParams(const std::string& source_fname) {
MRPT_START;
using namespace mrpt::utils;
client_params.loadFromConfigFileName(source_fname, m_ini_section_name);
// set the logging level if given by the user
CConfigFile source(source_fname);
// Minimum verbosity level of the logger
int min_verbosity_level = source.read_int(
m_ini_section_name,
"class_verbosity",
1, false);
this->setMinLoggingLevel(VerbosityLevel(min_verbosity_level));
this->logStr(LVL_DEBUG, "Successfully loaded parameters.");
// initialize the client - connect to remote part...
this->initClient(m_client);
provider_ready = true;
MRPT_END;
}
void CRosTopicMP::initClient(mrpt::utils::CClientTCPSocket* cl) {
MRPT_START;
using namespace std;
stringstream msg_ss;
msg_ss << "Connecting to server side...\n";
msg_ss << client_params.getAsString();
MRPT_LOG_INFO_STREAM << msg_ss;
// Connect to the server side. Server counterpart may not be up when the
// connection attempt is made Make multiple attempts.
bool did_connect = false;
int tries_thresh = 10;
int curr_try = 1;
m_client = new mrpt::utils::CClientTCPSocket();
std::string error_msg = "Connection with remote server could not be established.";
while (tries_thresh >= curr_try) {
try {
m_client->connect(
client_params.server_addr,
client_params.server_port_no,
client_params.client_timeout_ms);
did_connect = true;
break;
}
catch(std::logic_error& e) {
MRPT_LOG_WARN_STREAM << error_msg << "Retrying... "
<< curr_try++ << "/" << tries_thresh << endl;
mrpt::system::sleep(1000);
}
}
error_msg = error_msg +
"\nMake sure that the TCP server on the ROS side is up, otherwise contact the maintainer.";
ASSERTMSG_(did_connect, mrpt::format("\n%s\n", error_msg.c_str()));
MRPT_LOG_INFO_STREAM << "Connection with server was successfully established." << endl;
MRPT_END;
}
// TClientParams
////////////////////////////////////////////////////////////////////////////////
CRosTopicMP::TClientParams::TClientParams(provider_t& p):
provider(p) {
MRPT_START;
has_transmitted_valid_data = false;
MRPT_END;
}
CRosTopicMP::TClientParams::~TClientParams() { }
void CRosTopicMP::TClientParams::dumpToTextStream(
mrpt::utils::CStream &out) const {
MRPT_START;
out.printf("%s", this->getAsString().c_str());
MRPT_END;
}
void CRosTopicMP::TClientParams::loadFromConfigFile(
const mrpt::utils::CConfigFileBase &source,
const std::string §ion) {
MRPT_START;
using namespace mrpt::utils;
server_addr = source.read_string(section , "tcp_server_addr" , "127.0.0.1" , false);
server_port_no = source.read_int(section , "tcp_server_port_no" , 6800 , false);
client_timeout_ms = source.read_int(section , "tcp_client_timeout_ms" , 10000 , false);
// reading the possilble formats that an incoming message may have
msg_types["FORMAT_1"] = source.read_int(section , "MSG_TYPE_FORMAT_1" , 1 , false);
msg_types["FORMAT_2"] = source.read_int(section , "MSG_TYPE_FORMAT_2" , 2 , false);
msg_types["EXIT"] = source.read_int(section , "MSG_TYPE_EXIT" , 99 , false);
MRPT_END;
}
void CRosTopicMP::TClientParams::getAsString(std::string* params_out) const {
MRPT_START;
using namespace std;
stringstream ss("");
ss << "------------------[ CRosTopicMP ]------------------\n";
ss << "Port No. : " << server_port_no << endl;
ss << "Server IP Address : " << server_addr.c_str() << endl;
ss << "Client Time to wait for connection : " << client_timeout_ms << endl;
ss << "Available message codes: " << endl;
ss << "\tMessage code for FORMAT #1: " << msg_types.find("FORMAT_1")->second << endl;
ss << "\tMessage code for FORMAT #2: " << msg_types.find("FORMAT_2")->second << endl;
ss << "\tMessage code for end of data transmission " << msg_types.find("EXIT")->second << endl;
*params_out = ss.str();
MRPT_END;
}
std::string CRosTopicMP::TClientParams::getAsString() const {
MRPT_START;
std::string str;
this->getAsString(&str);
return str;
MRPT_END;
}
} } } // end of namespaces
|
/* +---------------------------------------------------------------------------+
| Mobile Robot Programming Toolkit (MRPT) |
| http://www.mrpt.org/ |
| |
| Copyright (c) 2005-2016, Individual contributors, see AUTHORS file |
| See: http://www.mrpt.org/Authors - All rights reserved. |
| Released under BSD License. See details in http://www.mrpt.org/License |
+---------------------------------------------------------------------------+ */
#include "graphslam-precomp.h" // Precompiled headers
#include <mrpt/graphslam/CRosTopicMP.h>
namespace mrpt { namespace graphslam { namespace measurement_providers {
CRosTopicMP::CRosTopicMP():
client_params(*this) {
this->init();
}
CRosTopicMP::~CRosTopicMP() {
MRPT_LOG_DEBUG_STREAM << "In class Destructor";
MRPT_LOG_DEBUG_STREAM << "Deleting client socket instance.";
delete m_client;
}
void CRosTopicMP::init() {
MRPT_START;
// configure the current provider
m_class_name = "CRosTopicMP";
m_ini_section_name = "CMeasurementProviderParameters";
this->setLoggerName(m_class_name);
run_online = true;
provider_ready = false;
m_client = NULL;
MRPT_END;
}
bool CRosTopicMP::getActionObservationPairOrObservation(
mrpt::obs::CActionCollectionPtr& action,
mrpt::obs::CSensoryFramePtr& observations,
mrpt::obs::CObservationPtr& observation,
size_t& rawlog_entry ) {
MRPT_START;
using namespace std;
using namespace mrpt::obs;
using namespace mrpt::utils;
ASSERTMSG_(provider_ready,
"getActionObservationPairOrObservation was called even though provider is not ready yet.");
//is there any data available - if so return it, otherwise block and wait
// TODO - maybe inform of the user if it takes too long to return from this
// --> requires multithreading
// Ask the server of data
CMessage msg;
bool did_receive = m_client->receiveMessage(msg,
/*timeoutStart_ms =*/ 40000,
/*timeoutBetween_ms =*/ 2000 );
if (!did_receive) { // communication failed. What exception should I raise?
if (client_params.has_transmitted_valid_data) {
// Overall, I have managed to transmit some data.
// Assume that the data transmission is over.
msg.type = client_params.msg_types["EXIT"];
}
else {
THROW_EXCEPTION("\nMessage transmission stopped abruptly.\n");
}
}
stringstream ss("");
ss << "Received message: Type: " << msg.type
<< " | Length: " << msg.content.size();
MRPT_LOG_DEBUG_STREAM << ss.str();
// discard anything that might be in the rawlog
action.clear_unique();
observations.clear_unique();
observation.clear_unique();
bool success;
if (msg.type == client_params.msg_types["FORMAT_1"]) {
// in case of format #1 I need two objects:
// - CActionCollection
// - CSensoryFrame
// TODO
THROW_EXCEPTION("FORMAT 1 (action-observations) is not implemented yet.");
}
else if (msg.type == client_params.msg_types["FORMAT_2"]) {
msg.deserializeIntoNewObject(observation);
success=true;
}
else if (msg.type == client_params.msg_types["EXIT"]) {
success = false;
}
else {
THROW_EXCEPTION(
mrpt::format("%s: Received measurement was not understood.",
m_class_name.c_str()));
}
if (success) {
client_params.has_transmitted_valid_data = true;
}
return success;
MRPT_END;
}
bool CRosTopicMP::providerIsReady() {
return provider_ready;
}
bool CRosTopicMP::providerRunsOnline() {
return run_online;
}
void CRosTopicMP::printParams() const {
MRPT_START;
// TODO - implement this.
client_params.dumpToConsole();
MRPT_END;
}
void CRosTopicMP::loadParams(const std::string& source_fname) {
MRPT_START;
using namespace mrpt::utils;
client_params.loadFromConfigFileName(source_fname, m_ini_section_name);
// set the logging level if given by the user
CConfigFile source(source_fname);
// Minimum verbosity level of the logger
int min_verbosity_level = source.read_int(
m_ini_section_name,
"class_verbosity",
1, false);
this->setMinLoggingLevel(VerbosityLevel(min_verbosity_level));
this->logStr(LVL_DEBUG, "Successfully loaded parameters.");
// initialize the client - connect to remote part...
this->initClient(m_client);
provider_ready = true;
MRPT_END;
}
void CRosTopicMP::initClient(mrpt::utils::CClientTCPSocket* cl) {
MRPT_START;
using namespace std;
stringstream msg_ss;
msg_ss << "Connecting to server side...\n";
msg_ss << client_params.getAsString();
MRPT_LOG_INFO_STREAM << msg_ss;
// Connect to the server side. Server counterpart may not be up when the
// connection attempt is made Make multiple attempts.
bool did_connect = false;
int tries_thresh = 10;
int curr_try = 1;
m_client = new mrpt::utils::CClientTCPSocket();
std::string error_msg = "Connection with remote server could not be established.";
while (tries_thresh >= curr_try) {
try {
m_client->connect(
client_params.server_addr,
client_params.server_port_no,
client_params.client_timeout_ms);
did_connect = true;
break;
}
catch(std::logic_error& e) {
MRPT_LOG_WARN_STREAM << error_msg << "Retrying... "
<< curr_try++ << "/" << tries_thresh << endl;
mrpt::system::sleep(1000);
}
}
error_msg = error_msg +
"\nMake sure that the TCP server on the ROS side is up, otherwise contact the maintainer.";
ASSERTMSG_(did_connect, mrpt::format("\n%s\n", error_msg.c_str()));
MRPT_LOG_INFO_STREAM << "Connection with server was successfully established." << endl;
MRPT_END;
}
// TClientParams
////////////////////////////////////////////////////////////////////////////////
CRosTopicMP::TClientParams::TClientParams(provider_t& p):
provider(p) {
MRPT_START;
has_transmitted_valid_data = false;
MRPT_END;
}
CRosTopicMP::TClientParams::~TClientParams() { }
void CRosTopicMP::TClientParams::dumpToTextStream(
mrpt::utils::CStream &out) const {
MRPT_START;
out.printf("%s", this->getAsString().c_str());
MRPT_END;
}
void CRosTopicMP::TClientParams::loadFromConfigFile(
const mrpt::utils::CConfigFileBase &source,
const std::string §ion) {
MRPT_START;
using namespace mrpt::utils;
server_addr = source.read_string(section , "tcp_server_addr" , "127.0.0.1" , false);
server_port_no = source.read_int(section , "tcp_server_port_no" , 6800 , false);
client_timeout_ms = source.read_int(section , "tcp_client_timeout_ms" , 10000 , false);
// reading the possilble formats that an incoming message may have
msg_types["FORMAT_1"] = source.read_int(section , "MSG_TYPE_FORMAT_1" , 1 , false);
msg_types["FORMAT_2"] = source.read_int(section , "MSG_TYPE_FORMAT_2" , 2 , false);
msg_types["EXIT"] = source.read_int(section , "MSG_TYPE_EXIT" , 99 , false);
MRPT_END;
}
void CRosTopicMP::TClientParams::getAsString(std::string* params_out) const {
MRPT_START;
using namespace std;
stringstream ss("");
ss << "------------------[ CRosTopicMP ]------------------\n";
ss << "Port No. : " << server_port_no << endl;
ss << "Server IP Address : " << server_addr.c_str() << endl;
ss << "Client Time to wait for connection : " << client_timeout_ms << endl;
ss << "Available message codes: " << endl;
ss << "\tMessage code for FORMAT #1: " << msg_types.find("FORMAT_1")->second << endl;
ss << "\tMessage code for FORMAT #2: " << msg_types.find("FORMAT_2")->second << endl;
ss << "\tMessage code for end of data transmission " << msg_types.find("EXIT")->second << endl;
*params_out = ss.str();
MRPT_END;
}
std::string CRosTopicMP::TClientParams::getAsString() const {
MRPT_START;
std::string str;
this->getAsString(&str);
return str;
MRPT_END;
}
} } } // end of namespaces
|
Handle odometry in CRosTopicMP
|
graphslam-engine: Handle odometry in CRosTopicMP
|
C++
|
bsd-3-clause
|
MRPT/mrpt,MRPT/mrpt,MRPT/mrpt,MRPT/mrpt,MRPT/mrpt
|
49a7d39c57d24e71b2b8ba781c131cf988a3a8e6
|
libvcf2multialign/sample_sorter.cc
|
libvcf2multialign/sample_sorter.cc
|
/*
* Copyright (c) 2019 Tuukka Norri
* This code is licensed under MIT license (see LICENSE for details).
*/
#include <libbio/assert.hh>
#include <range/v3/all.hpp>
#include <vcf2multialign/preprocess/sample_sorter.hh>
#include <vcf2multialign/utility/can_handle_variant_alts.hh>
#include <vcf2multialign/variant_format.hh>
namespace lb = libbio;
namespace v2m = vcf2multialign;
namespace vcf2multialign {
bool sample_sorter::check_variant_for_sample_and_update_state(std::size_t const sample_idx, lb::variant const &var, std::uint8_t const alt_idx)
{
// Check the output position of the given sample. REF can always be handled.
// If the current sample has zero, do not change its end position.
libbio_assert_neq(0, alt_idx);
auto const &alt(var.alts()[alt_idx - 1]);
if (can_handle_variant_alt(alt))
{
auto const pos(var.zero_based_pos());
if (m_end_positions_by_sample[sample_idx] <= pos)
{
auto const end_pos(variant_end_pos(var));
libbio_assert_lt(sample_idx, m_end_positions_by_sample.size());
m_end_positions_by_sample[sample_idx] = end_pos;
return true;
}
else
{
m_delegate->sample_sorter_found_overlapping_variant(var, sample_idx, m_end_positions_by_sample[sample_idx]);
}
}
else
{
// FIXME: logging should be elsewhere.
std::cerr << "Line " << var.lineno() << ": Unable to handle ALT " << alt_idx << " (type " << lb::to_string(alt.alt_sv_type) << ").\n";
}
return false;
}
// Called before processing the next subgraph.
void sample_sorter::prepare_for_next_subgraph()
{
m_path_counter = 1;
std::fill(m_src_paths.begin(), m_src_paths.end(), 0);
std::fill(m_end_positions_by_sample.begin(), m_end_positions_by_sample.end(), 0);
}
void sample_sorter::sort_by_variant_and_alt(lb::variant const &var, std::uint8_t const expected_alt_idx)
{
libbio_assert_neq(0, expected_alt_idx);
// FIXME: currently the variable naming is slightly confusing as alt_idx and expected_alt_idx are 1-based but var.alts() expects a zero-based index.
auto const *gt_field(get_variant_format(var).gt);
// Reset variant-specific state.
for (auto &word : m_branches_by_path_index.word_range() | ranges::view::take(1 + m_path_counter / branch_vector::ELEMENT_COUNT))
word.store(0, std::memory_order_release);
// Check which paths branch by setting a bit mask in m_branches_by_path_index.
// The branching ones will have 0x3 in the end.
{
std::size_t sample_idx(0);
for (auto const path_idx : m_src_paths)
{
// Convert to donor and chr indices.
// If the ALT cannot be handled, use REF in alt_idx_.
auto const [donor_idx, chr_idx] = m_sample_indexer->donor_and_chr_idx(sample_idx);
auto const &var_samples(var.samples());
libbio_assert_lt(donor_idx, var_samples.size());
auto const &sample(var_samples[donor_idx]);
auto const >((*gt_field)(sample));
libbio_assert_lt(chr_idx, gt.size());
auto const alt_idx(gt[chr_idx].alt);
if (expected_alt_idx == alt_idx)
{
auto const alt_idx_(check_variant_for_sample_and_update_state(sample_idx, var, alt_idx) ? alt_idx : 0);
auto const val((expected_alt_idx == alt_idx_) ? 0x2 : 0x1);
//std::cerr << "1 donor_idx: " << donor_idx << " chr_idx: " << +chr_idx << " expected_alt_idx: " << +expected_alt_idx << " alt_idx: " << alt_idx << " alt_idx_: " << alt_idx_ << " path_idx: " << path_idx << " val: " << val << std::endl;
m_branches_by_path_index.fetch_or(path_idx, val, std::memory_order_release);
}
else
{
m_branches_by_path_index.fetch_or(path_idx, 0x1, std::memory_order_release);
}
++sample_idx;
}
}
// Assign numbers to the branching paths.
for (auto const &tup : ranges::view::enumerate(m_branches_by_path_index) | ranges::view::take(m_path_counter))
{
auto const [path_idx, val] = tup;
auto const mask(val.load(std::memory_order_acquire));
//std::cerr << "2 path_idx: " << path_idx << " mask: " << mask << std::endl;
if (0x3 == mask)
{
libbio_assert_lt(path_idx, m_branching_paths.size());
m_branching_paths[path_idx] = m_path_counter++;
libbio_assert_lt(m_path_counter, std::numeric_limits <path_number_type>::max());
}
}
// Assign path numbers to samples.
{
std::size_t sample_idx(0);
for (auto const src_path_idx : m_src_paths)
{
auto const [donor_idx, chr_idx] = m_sample_indexer->donor_and_chr_idx(sample_idx);
auto const &sample(var.samples()[donor_idx]);
auto const >((*gt_field)(sample));
auto const alt_idx(gt[chr_idx].alt);
libbio_assert_lt(src_path_idx, m_branching_paths.size());
auto const dst_path_idx(
(m_branches_by_path_index.load(src_path_idx, std::memory_order_acquire) == 0x3 && expected_alt_idx == alt_idx)
? m_branching_paths[src_path_idx]
: src_path_idx
);
libbio_assert_lt(sample_idx, m_dst_paths.size());
//std::cerr << "3 lineno: " << var.lineno() << " sample_idx: " << sample_idx << " dst_path_idx: " << dst_path_idx << std::endl;
m_dst_paths[sample_idx] = dst_path_idx;
++sample_idx;
}
}
using std::swap;
swap(m_src_paths, m_dst_paths);
}
}
|
/*
* Copyright (c) 2019 Tuukka Norri
* This code is licensed under MIT license (see LICENSE for details).
*/
#include <libbio/assert.hh>
#include <range/v3/all.hpp>
#include <vcf2multialign/preprocess/sample_sorter.hh>
#include <vcf2multialign/utility/can_handle_variant_alts.hh>
#include <vcf2multialign/variant_format.hh>
namespace lb = libbio;
namespace v2m = vcf2multialign;
namespace vcf2multialign {
bool sample_sorter::check_variant_for_sample_and_update_state(std::size_t const sample_idx, lb::variant const &var, std::uint8_t const alt_idx)
{
// Check the output position of the given sample. REF can always be handled.
// If the current sample has zero, do not change its end position.
libbio_assert_neq(0, alt_idx);
auto const &alt(var.alts()[alt_idx - 1]);
if (can_handle_variant_alt(alt))
{
auto const pos(var.zero_based_pos());
libbio_assert_lt(sample_idx, m_end_positions_by_sample.size());
if (m_end_positions_by_sample[sample_idx] <= pos)
{
auto const end_pos(variant_end_pos(var));
m_end_positions_by_sample[sample_idx] = end_pos;
return true;
}
else
{
libbio_assert_neq(nullptr, m_delegate);
m_delegate->sample_sorter_found_overlapping_variant(var, sample_idx, m_end_positions_by_sample[sample_idx]);
}
}
else
{
// FIXME: logging should be elsewhere.
std::cerr << "Line " << var.lineno() << ": Unable to handle ALT " << alt_idx << " (type " << lb::to_string(alt.alt_sv_type) << ").\n";
}
return false;
}
// Called before processing the next subgraph.
void sample_sorter::prepare_for_next_subgraph()
{
m_path_counter = 1;
std::fill(m_src_paths.begin(), m_src_paths.end(), 0);
std::fill(m_end_positions_by_sample.begin(), m_end_positions_by_sample.end(), 0);
}
void sample_sorter::sort_by_variant_and_alt(lb::variant const &var, std::uint8_t const expected_alt_idx)
{
libbio_assert_neq(0, expected_alt_idx);
// FIXME: currently the variable naming is slightly confusing as alt_idx and expected_alt_idx are 1-based but var.alts() expects a zero-based index.
auto const *gt_field(get_variant_format(var).gt);
// Reset variant-specific state.
for (auto &word : m_branches_by_path_index.word_range() | ranges::view::take(1 + m_path_counter / branch_vector::ELEMENT_COUNT))
word.store(0, std::memory_order_release);
// Check which paths branch by setting a bit mask in m_branches_by_path_index.
// The branching ones will have 0x3 in the end.
{
std::size_t sample_idx(0);
for (auto const path_idx : m_src_paths)
{
// Convert to donor and chr indices.
// If the ALT cannot be handled, use REF in alt_idx_.
auto const [donor_idx, chr_idx] = m_sample_indexer->donor_and_chr_idx(sample_idx);
auto const &var_samples(var.samples());
libbio_assert_lt(donor_idx, var_samples.size());
auto const &sample(var_samples[donor_idx]);
auto const >((*gt_field)(sample));
libbio_assert_lt(chr_idx, gt.size());
auto const alt_idx(gt[chr_idx].alt);
if (expected_alt_idx == alt_idx)
{
auto const alt_idx_(check_variant_for_sample_and_update_state(sample_idx, var, alt_idx) ? alt_idx : 0);
auto const val((expected_alt_idx == alt_idx_) ? 0x2 : 0x1);
//std::cerr << "1 donor_idx: " << donor_idx << " chr_idx: " << +chr_idx << " expected_alt_idx: " << +expected_alt_idx << " alt_idx: " << alt_idx << " alt_idx_: " << alt_idx_ << " path_idx: " << path_idx << " val: " << val << std::endl;
m_branches_by_path_index.fetch_or(path_idx, val, std::memory_order_release);
}
else
{
m_branches_by_path_index.fetch_or(path_idx, 0x1, std::memory_order_release);
}
++sample_idx;
}
}
// Assign numbers to the branching paths.
for (auto const &tup : ranges::view::enumerate(m_branches_by_path_index) | ranges::view::take(m_path_counter))
{
auto const [path_idx, val] = tup;
auto const mask(val.load(std::memory_order_acquire));
//std::cerr << "2 path_idx: " << path_idx << " mask: " << mask << std::endl;
if (0x3 == mask)
{
libbio_assert_lt(path_idx, m_branching_paths.size());
m_branching_paths[path_idx] = m_path_counter++;
libbio_assert_lt(m_path_counter, std::numeric_limits <path_number_type>::max());
}
}
// Assign path numbers to samples.
{
std::size_t sample_idx(0);
for (auto const src_path_idx : m_src_paths)
{
auto const [donor_idx, chr_idx] = m_sample_indexer->donor_and_chr_idx(sample_idx);
auto const &sample(var.samples()[donor_idx]);
auto const >((*gt_field)(sample));
auto const alt_idx(gt[chr_idx].alt);
libbio_assert_lt(src_path_idx, m_branching_paths.size());
auto const dst_path_idx(
(m_branches_by_path_index.load(src_path_idx, std::memory_order_acquire) == 0x3 && expected_alt_idx == alt_idx)
? m_branching_paths[src_path_idx]
: src_path_idx
);
libbio_assert_lt(sample_idx, m_dst_paths.size());
//std::cerr << "3 lineno: " << var.lineno() << " sample_idx: " << sample_idx << " dst_path_idx: " << dst_path_idx << std::endl;
m_dst_paths[sample_idx] = dst_path_idx;
++sample_idx;
}
}
using std::swap;
swap(m_src_paths, m_dst_paths);
}
}
|
Add assertions
|
Add assertions
|
C++
|
mit
|
tsnorri/vcf2multialign,tsnorri/vcf2multialign,tsnorri/vcf2multialign,tsnorri/vcf2multialign
|
81e769c9ff7850bef038c251fc3b61de45adbd80
|
src/sim/byteswap.hh
|
src/sim/byteswap.hh
|
/*
* Copyright (c) 2004 The Regents of The University of Michigan
* 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 the copyright holders 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.
*
* Authors: Gabe Black
* Ali Saidi
* Nathan Binkert
*/
//The purpose of this file is to provide endainness conversion utility
//functions. Depending on the endianness of the guest system, either
//the LittleEndianGuest or BigEndianGuest namespace is used.
#ifndef __SIM_BYTE_SWAP_HH__
#define __SIM_BYTE_SWAP_HH__
#include "base/bigint.hh"
#include "base/misc.hh"
#include "base/types.hh"
// This lets us figure out what the byte order of the host system is
#if defined(__linux__)
#include <endian.h>
// If this is a linux system, lets used the optimized definitions if they exist.
// If one doesn't exist, we pretty much get what is listed below, so it all
// works out
#include <byteswap.h>
#elif defined (__sun)
#include <sys/isa_defs.h>
#else
#include <machine/endian.h>
#endif
#if defined(__APPLE__)
#include <libkern/OSByteOrder.h>
#endif
enum ByteOrder {BigEndianByteOrder, LittleEndianByteOrder};
//These functions actually perform the swapping for parameters
//of various bit lengths
inline uint64_t
swap_byte64(uint64_t x)
{
#if defined(__linux__)
return bswap_64(x);
#elif defined(__APPLE__)
return OSSwapInt64(x);
#else
return (uint64_t)((((uint64_t)(x) & 0xff) << 56) |
((uint64_t)(x) & 0xff00ULL) << 40 |
((uint64_t)(x) & 0xff0000ULL) << 24 |
((uint64_t)(x) & 0xff000000ULL) << 8 |
((uint64_t)(x) & 0xff00000000ULL) >> 8 |
((uint64_t)(x) & 0xff0000000000ULL) >> 24 |
((uint64_t)(x) & 0xff000000000000ULL) >> 40 |
((uint64_t)(x) & 0xff00000000000000ULL) >> 56) ;
#endif
}
inline uint32_t
swap_byte32(uint32_t x)
{
#if defined(__linux__)
return bswap_32(x);
#elif defined(__APPLE__)
return OSSwapInt32(x);
#else
return (uint32_t)(((uint32_t)(x) & 0xff) << 24 |
((uint32_t)(x) & 0xff00) << 8 | ((uint32_t)(x) & 0xff0000) >> 8 |
((uint32_t)(x) & 0xff000000) >> 24);
#endif
}
inline uint16_t
swap_byte16(uint16_t x)
{
#if defined(__linux__)
return bswap_16(x);
#elif defined(__APPLE__)
return OSSwapInt16(x);
#else
return (uint16_t)(((uint16_t)(x) & 0xff) << 8 |
((uint16_t)(x) & 0xff00) >> 8);
#endif
}
// This function lets the compiler figure out how to call the
// swap_byte functions above for different data types. Since the
// sizeof() values are known at compile time, it should inline to a
// direct call to the right swap_byteNN() function.
template <typename T>
inline T swap_byte(T x) {
if (sizeof(T) == 8)
return swap_byte64((uint64_t)x);
else if (sizeof(T) == 4)
return swap_byte32((uint32_t)x);
else if (sizeof(T) == 2)
return swap_byte16((uint16_t)x);
else if (sizeof(T) == 1)
return x;
else
panic("Can't byte-swap values larger than 64 bits");
}
template<>
inline Twin64_t swap_byte<Twin64_t>(Twin64_t x)
{
x.a = swap_byte(x.a);
x.b = swap_byte(x.b);
return x;
}
template<>
inline Twin32_t swap_byte<Twin32_t>(Twin32_t x)
{
x.a = swap_byte(x.a);
x.b = swap_byte(x.b);
return x;
}
//The conversion functions with fixed endianness on both ends don't need to
//be in a namespace
template <typename T> inline T betole(T value) {return swap_byte(value);}
template <typename T> inline T letobe(T value) {return swap_byte(value);}
//For conversions not involving the guest system, we can define the functions
//conditionally based on the BYTE_ORDER macro and outside of the namespaces
#if defined(_BIG_ENDIAN) || !defined(_LITTLE_ENDIAN) && BYTE_ORDER == BIG_ENDIAN
const ByteOrder HostByteOrder = BigEndianByteOrder;
template <typename T> inline T htole(T value) {return swap_byte(value);}
template <typename T> inline T letoh(T value) {return swap_byte(value);}
template <typename T> inline T htobe(T value) {return value;}
template <typename T> inline T betoh(T value) {return value;}
#elif defined(_LITTLE_ENDIAN) || BYTE_ORDER == LITTLE_ENDIAN
const ByteOrder HostByteOrder = LittleEndianByteOrder;
template <typename T> inline T htole(T value) {return value;}
template <typename T> inline T letoh(T value) {return value;}
template <typename T> inline T htobe(T value) {return swap_byte(value);}
template <typename T> inline T betoh(T value) {return swap_byte(value);}
#else
#error Invalid Endianess
#endif
namespace BigEndianGuest
{
const ByteOrder GuestByteOrder = BigEndianByteOrder;
template <typename T>
inline T gtole(T value) {return betole(value);}
template <typename T>
inline T letog(T value) {return letobe(value);}
template <typename T>
inline T gtobe(T value) {return value;}
template <typename T>
inline T betog(T value) {return value;}
template <typename T>
inline T htog(T value) {return htobe(value);}
template <typename T>
inline T gtoh(T value) {return betoh(value);}
}
namespace LittleEndianGuest
{
const ByteOrder GuestByteOrder = LittleEndianByteOrder;
template <typename T>
inline T gtole(T value) {return value;}
template <typename T>
inline T letog(T value) {return value;}
template <typename T>
inline T gtobe(T value) {return letobe(value);}
template <typename T>
inline T betog(T value) {return betole(value);}
template <typename T>
inline T htog(T value) {return htole(value);}
template <typename T>
inline T gtoh(T value) {return letoh(value);}
}
#endif // __SIM_BYTE_SWAP_HH__
|
/*
* Copyright (c) 2004 The Regents of The University of Michigan
* 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 the copyright holders 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.
*
* Authors: Gabe Black
* Ali Saidi
* Nathan Binkert
*/
//The purpose of this file is to provide endainness conversion utility
//functions. Depending on the endianness of the guest system, either
//the LittleEndianGuest or BigEndianGuest namespace is used.
#ifndef __SIM_BYTE_SWAP_HH__
#define __SIM_BYTE_SWAP_HH__
#include "base/bigint.hh"
#include "base/misc.hh"
#include "base/types.hh"
// This lets us figure out what the byte order of the host system is
#if defined(__linux__)
#include <endian.h>
// If this is a linux system, lets used the optimized definitions if they exist.
// If one doesn't exist, we pretty much get what is listed below, so it all
// works out
#include <byteswap.h>
#elif defined (__sun)
#include <sys/isa_defs.h>
#else
#include <machine/endian.h>
#endif
#if defined(__APPLE__)
#include <libkern/OSByteOrder.h>
#endif
enum ByteOrder {BigEndianByteOrder, LittleEndianByteOrder};
//These functions actually perform the swapping for parameters
//of various bit lengths
inline uint64_t
swap_byte64(uint64_t x)
{
#if defined(__linux__)
return bswap_64(x);
#elif defined(__APPLE__)
return OSSwapInt64(x);
#else
return (uint64_t)((((uint64_t)(x) & 0xff) << 56) |
((uint64_t)(x) & 0xff00ULL) << 40 |
((uint64_t)(x) & 0xff0000ULL) << 24 |
((uint64_t)(x) & 0xff000000ULL) << 8 |
((uint64_t)(x) & 0xff00000000ULL) >> 8 |
((uint64_t)(x) & 0xff0000000000ULL) >> 24 |
((uint64_t)(x) & 0xff000000000000ULL) >> 40 |
((uint64_t)(x) & 0xff00000000000000ULL) >> 56) ;
#endif
}
inline uint32_t
swap_byte32(uint32_t x)
{
#if defined(__linux__)
return bswap_32(x);
#elif defined(__APPLE__)
return OSSwapInt32(x);
#else
return (uint32_t)(((uint32_t)(x) & 0xff) << 24 |
((uint32_t)(x) & 0xff00) << 8 | ((uint32_t)(x) & 0xff0000) >> 8 |
((uint32_t)(x) & 0xff000000) >> 24);
#endif
}
inline uint16_t
swap_byte16(uint16_t x)
{
#if defined(__linux__)
return bswap_16(x);
#elif defined(__APPLE__)
return OSSwapInt16(x);
#else
return (uint16_t)(((uint16_t)(x) & 0xff) << 8 |
((uint16_t)(x) & 0xff00) >> 8);
#endif
}
// This function lets the compiler figure out how to call the
// swap_byte functions above for different data types. Since the
// sizeof() values are known at compile time, it should inline to a
// direct call to the right swap_byteNN() function.
template <typename T>
inline T swap_byte(T x) {
if (sizeof(T) == 8)
return swap_byte64((uint64_t)x);
else if (sizeof(T) == 4)
return swap_byte32((uint32_t)x);
else if (sizeof(T) == 2)
return swap_byte16((uint16_t)x);
else if (sizeof(T) == 1)
return x;
else
panic("Can't byte-swap values larger than 64 bits");
}
template<>
inline Twin64_t swap_byte<Twin64_t>(Twin64_t x)
{
x.a = swap_byte(x.a);
x.b = swap_byte(x.b);
return x;
}
template<>
inline Twin32_t swap_byte<Twin32_t>(Twin32_t x)
{
x.a = swap_byte(x.a);
x.b = swap_byte(x.b);
return x;
}
//The conversion functions with fixed endianness on both ends don't need to
//be in a namespace
template <typename T> inline T betole(T value) {return swap_byte(value);}
template <typename T> inline T letobe(T value) {return swap_byte(value);}
//For conversions not involving the guest system, we can define the functions
//conditionally based on the BYTE_ORDER macro and outside of the namespaces
#if (defined(_BIG_ENDIAN) || !defined(_LITTLE_ENDIAN)) && BYTE_ORDER == BIG_ENDIAN
const ByteOrder HostByteOrder = BigEndianByteOrder;
template <typename T> inline T htole(T value) {return swap_byte(value);}
template <typename T> inline T letoh(T value) {return swap_byte(value);}
template <typename T> inline T htobe(T value) {return value;}
template <typename T> inline T betoh(T value) {return value;}
#elif defined(_LITTLE_ENDIAN) || BYTE_ORDER == LITTLE_ENDIAN
const ByteOrder HostByteOrder = LittleEndianByteOrder;
template <typename T> inline T htole(T value) {return value;}
template <typename T> inline T letoh(T value) {return value;}
template <typename T> inline T htobe(T value) {return swap_byte(value);}
template <typename T> inline T betoh(T value) {return swap_byte(value);}
#else
#error Invalid Endianess
#endif
namespace BigEndianGuest
{
const ByteOrder GuestByteOrder = BigEndianByteOrder;
template <typename T>
inline T gtole(T value) {return betole(value);}
template <typename T>
inline T letog(T value) {return letobe(value);}
template <typename T>
inline T gtobe(T value) {return value;}
template <typename T>
inline T betog(T value) {return value;}
template <typename T>
inline T htog(T value) {return htobe(value);}
template <typename T>
inline T gtoh(T value) {return betoh(value);}
}
namespace LittleEndianGuest
{
const ByteOrder GuestByteOrder = LittleEndianByteOrder;
template <typename T>
inline T gtole(T value) {return value;}
template <typename T>
inline T letog(T value) {return value;}
template <typename T>
inline T gtobe(T value) {return letobe(value);}
template <typename T>
inline T betog(T value) {return betole(value);}
template <typename T>
inline T htog(T value) {return htole(value);}
template <typename T>
inline T gtoh(T value) {return letoh(value);}
}
#endif // __SIM_BYTE_SWAP_HH__
|
correct check for endianess
|
sim: correct check for endianess
Committed by: Nilay Vaish <[email protected]>
|
C++
|
bsd-3-clause
|
vovojh/gem5,vovojh/gem5,pombredanne/http-repo.gem5.org-gem5-,pombredanne/http-repo.gem5.org-gem5-,vovojh/gem5,vovojh/gem5,pombredanne/http-repo.gem5.org-gem5-,pombredanne/http-repo.gem5.org-gem5-,vovojh/gem5,pombredanne/http-repo.gem5.org-gem5-,vovojh/gem5,pombredanne/http-repo.gem5.org-gem5-,pombredanne/http-repo.gem5.org-gem5-,vovojh/gem5
|
cb89d0059515e40f421eef6002641a37efe6201f
|
src/testlibrbdpp.cc
|
src/testlibrbdpp.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2011 New Dream Network
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License version 2, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#include "include/assert.h"
#include "include/rbd/librbd.hpp"
#include "include/rados/librados.hpp"
#include "include/buffer.h"
#include <algorithm>
#include <cstdarg>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <errno.h>
#include <memory>
#include <sys/types.h>
#include <string>
#include <vector>
using namespace std;
#define TEST_IMAGE "testimg"
#define TEST_IMAGE2 "testimg2"
#define TEST_POOL "librbdtest"
#define TEST_SNAP "testsnap"
#define TEST_IO_SIZE 513
#define MB_BYTES(mb) (mb << 20)
librbd::RBD *rbd;
void test_create_and_stat(librados::IoCtx& io_ctx, const char *name, size_t size)
{
librbd::image_info_t info;
librbd::Image image;
int order = 0;
assert(rbd->create(io_ctx, name, size, &order) == 0);
assert(rbd->open(io_ctx, image, name, NULL) == 0);
assert(image.stat(info, sizeof(info)) == 0);
cout << "image has size " << info.size << " and order " << info.order << endl;
assert(info.size == size);
assert(info.order == order);
}
void test_resize_and_stat(librbd::Image& image, size_t size)
{
librbd::image_info_t info;
assert(image.resize(size) == 0);
assert(image.stat(info, sizeof(info)) == 0);
cout << "image has size " << info.size << " and order " << info.order << endl;
assert(info.size == size);
}
void test_ls(librados::IoCtx& io_ctx, size_t num_expected, ...)
{
int r;
size_t i;
char *expected;
va_list ap;
vector<string> names;
r = rbd->list(io_ctx, names);
if (r == -ENOENT)
r = 0;
assert(r >= 0);
cout << "num images is: " << names.size() << endl
<< "expected: " << num_expected << endl;
assert(names.size() == num_expected);
for (i = 0; i < names.size(); i++) {
cout << "image: " << names[i] << endl;
}
va_start(ap, num_expected);
for (i = num_expected; i > 0; i--) {
expected = va_arg(ap, char *);
cout << "expected = " << expected << endl;
vector<string>::iterator listed_name = find(names.begin(), names.end(), string(expected));
assert(listed_name != names.end());
names.erase(listed_name);
}
assert(names.empty());
}
void test_delete(librados::IoCtx& io_ctx, const char *name)
{
assert(rbd->remove(io_ctx, name) == 0);
}
void test_create_snap(librbd::Image& image, const char *name)
{
assert(image.snap_create(name) == 0);
}
void test_ls_snaps(librbd::Image& image, size_t num_expected, ...)
{
int r;
size_t i, j, expected_size;
char *expected;
va_list ap;
vector<librbd::snap_info_t> snaps;
r = image.snap_list(snaps);
assert(r >= 0);
cout << "num snaps is: " << snaps.size() << endl
<< "expected: " << num_expected << endl;
assert(snaps.size() == num_expected);
for (i = 0; i < snaps.size(); i++) {
cout << "snap: " << snaps[i].name << endl;
}
va_start(ap, num_expected);
for (i = num_expected; i > 0; i--) {
expected = va_arg(ap, char *);
expected_size = va_arg(ap, int);
int found = 0;
for (j = 0; j < snaps.size(); j++) {
if (snaps[j].name == "")
continue;
if (strcmp(snaps[j].name.c_str(), expected) == 0) {
cout << "found " << snaps[j].name << " with size " << snaps[j].size << endl;
assert(snaps[j].size == (size_t) expected_size);
snaps[j].name = "";
found = 1;
break;
}
}
assert(found);
}
for (i = 0; i < snaps.size(); i++) {
assert(snaps[i].name == "");
}
}
void test_delete_snap(librbd::Image& image, const char *name)
{
assert(image.snap_remove(name) == 0);
}
void simple_write_cb(librbd::completion_t cb, void *arg)
{
cout << "write completion cb called!" << endl;
}
void simple_read_cb(librbd::completion_t cb, void *arg)
{
cout << "read completion cb called!" << endl;
}
void aio_write_test_data(librbd::Image& image, const char *test_data, off_t off)
{
ceph::bufferlist bl;
bl.append(test_data, strlen(test_data));
librbd::RBD::AioCompletion *comp = new librbd::RBD::AioCompletion(NULL, (librbd::callback_t) simple_write_cb);
printf("created completion\n");
image.aio_write(off, strlen(test_data), bl, comp);
printf("started write\n");
comp->wait_for_complete();
int r = comp->get_return_value();
printf("return value is: %d\n", r);
assert(r == 0);
printf("finished write\n");
comp->release();
}
void write_test_data(librbd::Image& image, const char *test_data, off_t off)
{
int written;
size_t len = strlen(test_data);
ceph::bufferlist bl;
bl.append(test_data, len);
written = image.write(off, len, bl);
assert(written >= 0);
printf("wrote: %u\n", (unsigned int) written);
}
void aio_read_test_data(librbd::Image& image, const char *expected, off_t off)
{
librbd::RBD::AioCompletion *comp = new librbd::RBD::AioCompletion(NULL, (librbd::callback_t) simple_read_cb);
ceph::bufferlist bl;
printf("created completion\n");
image.aio_read(off, strlen(expected), bl, comp);
printf("started read\n");
comp->wait_for_complete();
int r = comp->get_return_value();
printf("return value is: %d\n", r);
assert(r == TEST_IO_SIZE - 1);
assert(strncmp(expected, bl.c_str(), TEST_IO_SIZE - 1) == 0);
printf("finished read\n");
comp->release();
}
void read_test_data(librbd::Image& image, const char *expected, off_t off)
{
int read, total_read = 0;
size_t expected_len = strlen(expected);
size_t len = expected_len;
ceph::bufferlist bl;
read = image.read(off + total_read, len, bl);
assert(read >= 0);
printf("read: %u\n", (unsigned int) read);
printf("read: %s\nexpected: %s\n", bl.c_str(), expected);
assert(strncmp(bl.c_str(), expected, expected_len) == 0);
}
void test_io(librados::IoCtx& io_ctx, librbd::Image& image)
{
char test_data[TEST_IO_SIZE];
int i;
srand(time(0));
for (i = 0; i < TEST_IO_SIZE - 1; ++i) {
test_data[i] = (char) (rand() % (126 - 33) + 33);
}
test_data[TEST_IO_SIZE - 1] = '\0';
for (i = 0; i < 5; ++i)
write_test_data(image, test_data, strlen(test_data) * i);
for (i = 5; i < 10; ++i)
aio_write_test_data(image, test_data, strlen(test_data) * i);
for (i = 0; i < 5; ++i)
read_test_data(image, test_data, strlen(test_data) * i);
for (i = 5; i < 10; ++i)
aio_read_test_data(image, test_data, strlen(test_data) * i);
}
void test_rbd_copy(librados::IoCtx& io_ctx, librbd::Image& image)
{
int ret;
ret = image.copy(io_ctx, TEST_IMAGE2);
if (ret < 0) {
fprintf(stderr, "image.copy returned %d!\n", ret);
abort();
}
}
int main(int argc, const char **argv)
{
librados::Rados rados;
librados::IoCtx io_ctx;
librbd::Image image;
rbd = new librbd::RBD();
assert(rados.init(NULL) == 0);
assert(rados.conf_parse_argv(argc, argv) == 0);
assert(rados.conf_read_file(NULL) == 0);
assert(rados.connect() == 0);
if (rados.pool_lookup(TEST_POOL) != -ENOENT) {
int r = rados.pool_delete(TEST_POOL);
printf("rados.pool_delete returned %d\n", r);
}
int r = rados.pool_create(TEST_POOL);
printf("rados.pool_create returned %d\n", r);
assert(rados.ioctx_create(TEST_POOL, io_ctx) == 0);
test_ls(io_ctx, 0);
test_create_and_stat(io_ctx, TEST_IMAGE, MB_BYTES(1));
assert(rbd->open(io_ctx, image, TEST_IMAGE, NULL) == 0);
test_ls(io_ctx, 1, TEST_IMAGE);
test_ls_snaps(image, 0);
test_create_snap(image, TEST_SNAP);
test_ls_snaps(image, 1, TEST_SNAP, MB_BYTES(1));
test_resize_and_stat(image, MB_BYTES(2));
test_io(io_ctx, image);
test_create_snap(image, TEST_SNAP "1");
test_ls_snaps(image, 2, TEST_SNAP, MB_BYTES(1), TEST_SNAP "1", MB_BYTES(2));
test_delete_snap(image, TEST_SNAP);
test_ls_snaps(image, 1, TEST_SNAP "1", MB_BYTES(2));
test_delete_snap(image, TEST_SNAP "1");
test_ls_snaps(image, 0);
test_create_and_stat(io_ctx, TEST_IMAGE "1", MB_BYTES(2));
test_ls(io_ctx, 2, TEST_IMAGE, TEST_IMAGE "1");
test_delete(io_ctx, TEST_IMAGE);
test_ls(io_ctx, 1, TEST_IMAGE "1");
test_delete(io_ctx, TEST_IMAGE "1");
test_ls(io_ctx, 0);
test_rbd_copy(io_ctx, image);
delete rbd;
return 0;
}
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2011 New Dream Network
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License version 2, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#include "include/assert.h"
#include "include/rbd/librbd.hpp"
#include "include/rados/librados.hpp"
#include "include/buffer.h"
#include <algorithm>
#include <cstdarg>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <errno.h>
#include <memory>
#include <sys/types.h>
#include <string>
#include <vector>
using namespace std;
#define TEST_IMAGE "testimg"
#define TEST_IMAGE2 "testimg2"
#define TEST_POOL "librbdtest"
#define TEST_SNAP "testsnap"
#define TEST_IO_SIZE 513
#define MB_BYTES(mb) (mb << 20)
librbd::RBD *rbd;
void test_create_and_stat(librados::IoCtx& io_ctx, const char *name, size_t size)
{
librbd::image_info_t info;
librbd::Image image;
int order = 0;
assert(rbd->create(io_ctx, name, size, &order) == 0);
assert(rbd->open(io_ctx, image, name, NULL) == 0);
assert(image.stat(info, sizeof(info)) == 0);
cout << "image has size " << info.size << " and order " << info.order << endl;
assert(info.size == size);
assert(info.order == order);
}
void test_resize_and_stat(librbd::Image& image, size_t size)
{
librbd::image_info_t info;
assert(image.resize(size) == 0);
assert(image.stat(info, sizeof(info)) == 0);
cout << "image has size " << info.size << " and order " << info.order << endl;
assert(info.size == size);
}
void test_ls(librados::IoCtx& io_ctx, size_t num_expected, ...)
{
int r;
size_t i;
char *expected;
va_list ap;
vector<string> names;
r = rbd->list(io_ctx, names);
if (r == -ENOENT)
r = 0;
assert(r >= 0);
cout << "num images is: " << names.size() << endl
<< "expected: " << num_expected << endl;
assert(names.size() == num_expected);
for (i = 0; i < names.size(); i++) {
cout << "image: " << names[i] << endl;
}
va_start(ap, num_expected);
for (i = num_expected; i > 0; i--) {
expected = va_arg(ap, char *);
cout << "expected = " << expected << endl;
vector<string>::iterator listed_name = find(names.begin(), names.end(), string(expected));
assert(listed_name != names.end());
names.erase(listed_name);
}
assert(names.empty());
}
void test_delete(librados::IoCtx& io_ctx, const char *name)
{
assert(rbd->remove(io_ctx, name) == 0);
}
void test_create_snap(librbd::Image& image, const char *name)
{
assert(image.snap_create(name) == 0);
}
void test_ls_snaps(librbd::Image& image, size_t num_expected, ...)
{
int r;
size_t i, j, expected_size;
char *expected;
va_list ap;
vector<librbd::snap_info_t> snaps;
r = image.snap_list(snaps);
assert(r >= 0);
cout << "num snaps is: " << snaps.size() << endl
<< "expected: " << num_expected << endl;
assert(snaps.size() == num_expected);
for (i = 0; i < snaps.size(); i++) {
cout << "snap: " << snaps[i].name << endl;
}
va_start(ap, num_expected);
for (i = num_expected; i > 0; i--) {
expected = va_arg(ap, char *);
expected_size = va_arg(ap, int);
int found = 0;
for (j = 0; j < snaps.size(); j++) {
if (snaps[j].name == "")
continue;
if (strcmp(snaps[j].name.c_str(), expected) == 0) {
cout << "found " << snaps[j].name << " with size " << snaps[j].size << endl;
assert(snaps[j].size == (size_t) expected_size);
snaps[j].name = "";
found = 1;
break;
}
}
assert(found);
}
for (i = 0; i < snaps.size(); i++) {
assert(snaps[i].name == "");
}
}
void test_delete_snap(librbd::Image& image, const char *name)
{
assert(image.snap_remove(name) == 0);
}
void simple_write_cb(librbd::completion_t cb, void *arg)
{
cout << "write completion cb called!" << endl;
}
void simple_read_cb(librbd::completion_t cb, void *arg)
{
cout << "read completion cb called!" << endl;
}
void aio_write_test_data(librbd::Image& image, const char *test_data, off_t off)
{
ceph::bufferlist bl;
bl.append(test_data, strlen(test_data));
librbd::RBD::AioCompletion *comp = new librbd::RBD::AioCompletion(NULL, (librbd::callback_t) simple_write_cb);
printf("created completion\n");
image.aio_write(off, strlen(test_data), bl, comp);
printf("started write\n");
comp->wait_for_complete();
int r = comp->get_return_value();
printf("return value is: %d\n", r);
assert(r == 0);
printf("finished write\n");
comp->release();
}
void write_test_data(librbd::Image& image, const char *test_data, off_t off)
{
int written;
size_t len = strlen(test_data);
ceph::bufferlist bl;
bl.append(test_data, len);
written = image.write(off, len, bl);
assert(written >= 0);
printf("wrote: %u\n", (unsigned int) written);
}
void aio_read_test_data(librbd::Image& image, const char *expected, off_t off)
{
librbd::RBD::AioCompletion *comp = new librbd::RBD::AioCompletion(NULL, (librbd::callback_t) simple_read_cb);
ceph::bufferlist bl;
printf("created completion\n");
image.aio_read(off, strlen(expected), bl, comp);
printf("started read\n");
comp->wait_for_complete();
int r = comp->get_return_value();
printf("return value is: %d\n", r);
assert(r == TEST_IO_SIZE - 1);
assert(strncmp(expected, bl.c_str(), TEST_IO_SIZE - 1) == 0);
printf("finished read\n");
comp->release();
}
void read_test_data(librbd::Image& image, const char *expected, off_t off)
{
int read, total_read = 0;
size_t expected_len = strlen(expected);
size_t len = expected_len;
ceph::bufferlist bl;
read = image.read(off + total_read, len, bl);
assert(read >= 0);
printf("read: %u\n", (unsigned int) read);
printf("read: %s\nexpected: %s\n", bl.c_str(), expected);
assert(strncmp(bl.c_str(), expected, expected_len) == 0);
}
void test_io(librados::IoCtx& io_ctx, librbd::Image& image)
{
char test_data[TEST_IO_SIZE];
int i;
srand(time(0));
for (i = 0; i < TEST_IO_SIZE - 1; ++i) {
test_data[i] = (char) (rand() % (126 - 33) + 33);
}
test_data[TEST_IO_SIZE - 1] = '\0';
for (i = 0; i < 5; ++i)
write_test_data(image, test_data, strlen(test_data) * i);
for (i = 5; i < 10; ++i)
aio_write_test_data(image, test_data, strlen(test_data) * i);
for (i = 0; i < 5; ++i)
read_test_data(image, test_data, strlen(test_data) * i);
for (i = 5; i < 10; ++i)
aio_read_test_data(image, test_data, strlen(test_data) * i);
}
void test_rbd_copy(librados::IoCtx& io_ctx, librbd::Image& image)
{
int ret;
ret = image.copy(io_ctx, TEST_IMAGE2);
if (ret < 0) {
fprintf(stderr, "image.copy returned %d!\n", ret);
abort();
}
}
static void print_progress_percent(uint64_t offset, uint64_t src_size,
void *data)
{
float percent = ((float)offset * 100) / src_size;
printf("%3.2f%% done\n", percent);
}
void test_rbd_copy_with_progress(librados::IoCtx& io_ctx, librbd::Image& image)
{
int ret;
ret = image.copy_with_progress(io_ctx, TEST_IMAGE2,
print_progress_percent, NULL);
if (ret < 0) {
fprintf(stderr, "image.copy returned %d!\n", ret);
abort();
}
}
int main(int argc, const char **argv)
{
librados::Rados rados;
librados::IoCtx io_ctx;
librbd::Image image;
rbd = new librbd::RBD();
assert(rados.init(NULL) == 0);
assert(rados.conf_parse_argv(argc, argv) == 0);
assert(rados.conf_read_file(NULL) == 0);
assert(rados.connect() == 0);
if (rados.pool_lookup(TEST_POOL) != -ENOENT) {
int r = rados.pool_delete(TEST_POOL);
printf("rados.pool_delete returned %d\n", r);
}
int r = rados.pool_create(TEST_POOL);
printf("rados.pool_create returned %d\n", r);
assert(rados.ioctx_create(TEST_POOL, io_ctx) == 0);
test_ls(io_ctx, 0);
test_create_and_stat(io_ctx, TEST_IMAGE, MB_BYTES(1));
assert(rbd->open(io_ctx, image, TEST_IMAGE, NULL) == 0);
test_ls(io_ctx, 1, TEST_IMAGE);
test_ls_snaps(image, 0);
test_create_snap(image, TEST_SNAP);
test_ls_snaps(image, 1, TEST_SNAP, MB_BYTES(1));
test_resize_and_stat(image, MB_BYTES(2));
test_io(io_ctx, image);
test_create_snap(image, TEST_SNAP "1");
test_ls_snaps(image, 2, TEST_SNAP, MB_BYTES(1), TEST_SNAP "1", MB_BYTES(2));
test_delete_snap(image, TEST_SNAP);
test_ls_snaps(image, 1, TEST_SNAP "1", MB_BYTES(2));
test_delete_snap(image, TEST_SNAP "1");
test_ls_snaps(image, 0);
test_create_and_stat(io_ctx, TEST_IMAGE "1", MB_BYTES(2));
test_ls(io_ctx, 2, TEST_IMAGE, TEST_IMAGE "1");
test_delete(io_ctx, TEST_IMAGE);
test_ls(io_ctx, 1, TEST_IMAGE "1");
test_delete(io_ctx, TEST_IMAGE "1");
test_ls(io_ctx, 0);
test_rbd_copy(io_ctx, image);
test_delete(io_ctx, TEST_IMAGE2);
test_rbd_copy_with_progress(io_ctx, image);
delete rbd;
return 0;
}
|
test copy_with_progress
|
testlibrbdpp: test copy_with_progress
Signed-off-by: Colin McCabe <[email protected]>
|
C++
|
lgpl-2.1
|
ajnelson/ceph,ajnelson/ceph,ajnelson/ceph,ajnelson/ceph,ajnelson/ceph,ajnelson/ceph
|
2a5ac5c8497cd4868e90514cc6736ec5b484d135
|
src/tgl_message.cpp
|
src/tgl_message.cpp
|
#include "tgl/tgl_message.h"
#include "tgl/tgl_secret_chat.h"
#include "structures.h"
#include "tgl/tgl_log.h"
#include "tgl_secret_chat_private.h"
#include "tgl_secret_chat_private.h"
tgl_message::tgl_message()
: server_id(0)
, random_id(0)
, fwd_date(0)
, date(0)
, permanent_id(0)
, reply_id(0)
, seq_no(0)
, fwd_from_id()
, from_id()
, to_id()
, action(std::make_shared<tgl_message_action_none>())
, media(std::make_shared<tgl_message_media_none>())
, m_flags()
{ }
tgl_message::tgl_message(int64_t message_id,
const tgl_peer_id_t& from_id,
const tgl_input_peer_t& to_id,
const tgl_peer_id_t* fwd_from_id,
const int64_t* fwd_date,
const int64_t* date,
const std::string& message,
const tl_ds_message_media* media,
const tl_ds_message_action* action,
int32_t reply_id,
const tl_ds_reply_markup* reply_markup)
: tgl_message()
{
this->permanent_id = message_id;
this->seq_no = message_id;
this->from_id = from_id;
this->to_id = to_id;
assert(to_id.peer_type != tgl_peer_type::enc_chat);
if (date) {
this->date = *date;
}
if (fwd_from_id) {
this->fwd_from_id = *fwd_from_id;
this->fwd_date = *fwd_date;
}
if (action) {
this->action = tglf_fetch_message_action(action);
this->set_service(true);
}
this->message = message;
if (media) {
this->media = tglf_fetch_message_media(media);
assert(!this->is_service());
}
this->reply_id = reply_id;
if (reply_markup) {
this->reply_markup = tglf_fetch_alloc_reply_markup(reply_markup);
}
}
tgl_message::tgl_message(
const std::shared_ptr<tgl_secret_chat>& secret_chat,
int64_t message_id,
const tgl_peer_id_t& from_id,
const int64_t* date,
const std::string& message,
const tl_ds_decrypted_message_media* media,
const tl_ds_decrypted_message_action* action,
const tl_ds_encrypted_file* file)
: tgl_message()
{
this->permanent_id = message_id;
this->from_id = from_id;
this->to_id = secret_chat->id();
if (date) {
this->date = *date;
}
assert(secret_chat);
if (action) {
this->action = tglf_fetch_message_action_encrypted(action);
this->set_service(true);
}
this->message = message;
if (media) {
this->media = tglf_fetch_message_media_encrypted(media);
assert(!this->is_service());
}
if (file) {
tglf_fetch_encrypted_message_file(this->media, file);
}
this->set_outgoing(from_id.peer_id == tgl_state::instance()->our_id().peer_id);
if (action && !this->is_outgoing() && this->action && this->action->type() == tgl_message_action_type::notify_layer) {
// FIXME is following right?
secret_chat->private_facet()->update_layer(std::static_pointer_cast<tgl_message_action_notify_layer>(this->action)->layer);
}
if (this->is_outgoing()) {
//secret_chat->out_seq_no++;
secret_chat->private_facet()->message_sent(message_id);
TGL_DEBUG("out seq number " << secret_chat->out_seq_no());
}
}
|
#include "tgl/tgl_message.h"
#include "tgl/tgl_secret_chat.h"
#include "structures.h"
#include "tgl/tgl_log.h"
#include "tgl_secret_chat_private.h"
tgl_message::tgl_message()
: server_id(0)
, random_id(0)
, fwd_date(0)
, date(0)
, permanent_id(0)
, reply_id(0)
, seq_no(0)
, fwd_from_id()
, from_id()
, to_id()
, action(std::make_shared<tgl_message_action_none>())
, media(std::make_shared<tgl_message_media_none>())
, m_flags()
{ }
tgl_message::tgl_message(int64_t message_id,
const tgl_peer_id_t& from_id,
const tgl_input_peer_t& to_id,
const tgl_peer_id_t* fwd_from_id,
const int64_t* fwd_date,
const int64_t* date,
const std::string& message,
const tl_ds_message_media* media,
const tl_ds_message_action* action,
int32_t reply_id,
const tl_ds_reply_markup* reply_markup)
: tgl_message()
{
this->permanent_id = message_id;
this->seq_no = message_id;
this->from_id = from_id;
this->to_id = to_id;
assert(to_id.peer_type != tgl_peer_type::enc_chat);
if (date) {
this->date = *date;
}
if (fwd_from_id) {
this->fwd_from_id = *fwd_from_id;
this->fwd_date = *fwd_date;
}
if (action) {
this->action = tglf_fetch_message_action(action);
this->set_service(true);
}
this->message = message;
if (media) {
this->media = tglf_fetch_message_media(media);
assert(!this->is_service());
}
this->reply_id = reply_id;
if (reply_markup) {
this->reply_markup = tglf_fetch_alloc_reply_markup(reply_markup);
}
}
tgl_message::tgl_message(
const std::shared_ptr<tgl_secret_chat>& secret_chat,
int64_t message_id,
const tgl_peer_id_t& from_id,
const int64_t* date,
const std::string& message,
const tl_ds_decrypted_message_media* media,
const tl_ds_decrypted_message_action* action,
const tl_ds_encrypted_file* file)
: tgl_message()
{
this->permanent_id = message_id;
this->from_id = from_id;
this->to_id = secret_chat->id();
if (date) {
this->date = *date;
}
assert(secret_chat);
if (action) {
this->action = tglf_fetch_message_action_encrypted(action);
this->set_service(true);
}
this->message = message;
if (media) {
this->media = tglf_fetch_message_media_encrypted(media);
assert(!this->is_service());
}
if (file) {
tglf_fetch_encrypted_message_file(this->media, file);
}
this->set_outgoing(from_id.peer_id == tgl_state::instance()->our_id().peer_id);
if (action && !this->is_outgoing() && this->action && this->action->type() == tgl_message_action_type::notify_layer) {
// FIXME is following right?
secret_chat->private_facet()->update_layer(std::static_pointer_cast<tgl_message_action_notify_layer>(this->action)->layer);
}
if (this->is_outgoing()) {
//secret_chat->out_seq_no++;
secret_chat->private_facet()->message_sent(message_id);
TGL_DEBUG("out seq number " << secret_chat->out_seq_no());
}
}
|
Remove a unnecessary extra #include
|
Remove a unnecessary extra #include
|
C++
|
lgpl-2.1
|
tplgy/tgl,tplgy/tgl,tplgy/tgl,tplgy/tgl
|
32e4b122a49000cc36241895312c4df90ad874d7
|
src/transaction.cpp
|
src/transaction.cpp
|
/*
* Copyright (c) 2011-2013 libbitcoin developers (see AUTHORS)
*
* This file is part of libbitcoin.
*
* libbitcoin is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see LICENSE.
*
* 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 <bitcoin/constants.hpp>
#include <bitcoin/format.hpp>
#include <bitcoin/satoshi_serialize.hpp>
#include <bitcoin/transaction.hpp>
#include <bitcoin/types.hpp>
#include <bitcoin/utility/hash.hpp>
#include <bitcoin/utility/logger.hpp>
#include <bitcoin/utility/serializer.hpp>
namespace libbitcoin {
typedef std::vector<hash_digest> hash_list;
hash_digest hash_transaction_impl(const transaction_type& tx,
uint32_t* hash_type_code)
{
data_chunk serialized_tx(satoshi_raw_size(tx));
satoshi_save(tx, serialized_tx.begin());
if (hash_type_code != nullptr)
extend_data(serialized_tx, to_little_endian(*hash_type_code));
return bitcoin_hash(serialized_tx);
}
hash_digest hash_transaction(const transaction_type& tx)
{
return hash_transaction_impl(tx, nullptr);
}
hash_digest hash_transaction(const transaction_type& tx,
uint32_t hash_type_code)
{
return hash_transaction_impl(tx, &hash_type_code);
}
hash_digest build_merkle_tree(hash_list& merkle)
{
if (merkle.empty())
return null_hash;
else if (merkle.size() == 1)
return merkle[0];
while (merkle.size() > 1)
{
if (merkle.size() % 2 != 0)
merkle.push_back(merkle.back());
hash_list new_merkle;
for (auto it = merkle.begin(); it != merkle.end(); it += 2)
{
data_chunk concat_data(hash_size * 2);
auto concat = make_serializer(concat_data.begin());
concat.write_hash(*it);
concat.write_hash(*(it + 1));
BITCOIN_ASSERT(
std::distance(concat_data.begin(), concat.iterator()) ==
hash_size * 2);
hash_digest new_root = bitcoin_hash(concat_data);
new_merkle.push_back(new_root);
}
merkle = new_merkle;
}
return merkle[0];
}
hash_digest generate_merkle_root(const transaction_list& transactions)
{
hash_list tx_hashes;
for (transaction_type tx: transactions)
tx_hashes.push_back(hash_transaction(tx));
return build_merkle_tree(tx_hashes);
}
std::string pretty(const transaction_input_type& input)
{
std::ostringstream ss;
ss << "\thash = " << input.previous_output.hash << "\n"
<< "\tindex = " << input.previous_output.index << "\n"
<< "\t" << input.script << "\n"
<< "\tsequence = " << input.sequence << "\n";
return ss.str();
}
std::string pretty(const transaction_output_type& output)
{
std::ostringstream ss;
ss << "\tvalue = " << output.value << "\n"
<< "\t" << output.script << "\n";
return ss.str();
}
std::string pretty(const transaction_type& tx)
{
std::ostringstream ss;
ss << "Transaction:\n"
<< "\tversion = " << tx.version << "\n"
<< "\tlocktime = " << tx.locktime << "\n"
<< "Inputs:\n";
for (transaction_input_type input: tx.inputs)
ss << pretty(input);
ss << "Outputs:\n";
for (transaction_output_type output: tx.outputs)
ss << pretty(output);
ss << "\n";
return ss.str();
}
bool previous_output_is_null(const output_point& previous_output)
{
return previous_output.index == std::numeric_limits<uint32_t>::max() &&
previous_output.hash == null_hash;
}
bool is_coinbase(const transaction_type& tx)
{
return tx.inputs.size() == 1 &&
previous_output_is_null(tx.inputs[0].previous_output);
}
uint64_t total_output_value(const transaction_type& tx)
{
uint64_t total = 0;
for (const transaction_output_type& output: tx.outputs)
total += output.value;
return total;
}
bool operator==(const output_point& output_a, const output_point& output_b)
{
return output_a.hash == output_b.hash && output_a.index == output_b.index;
}
bool operator!=(const output_point& output_a, const output_point& output_b)
{
return !(output_a == output_b);
}
bool is_final(const transaction_input_type& tx_input)
{
return tx_input.sequence == std::numeric_limits<uint32_t>::max();
}
bool is_final(const transaction_type& tx,
size_t block_height, uint32_t block_time)
{
if (tx.locktime == 0)
return true;
uint32_t max_locktime = block_time;
if (tx.locktime < locktime_threshold)
max_locktime = block_height;
if (tx.locktime < max_locktime)
return true;
for (const transaction_input_type& tx_input: tx.inputs)
if (!is_final(tx_input))
return false;
return true;
}
} // namespace libbitcoin
|
/*
* Copyright (c) 2011-2013 libbitcoin developers (see AUTHORS)
*
* This file is part of libbitcoin.
*
* libbitcoin is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see LICENSE.
*
* 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 <bitcoin/constants.hpp>
#include <bitcoin/format.hpp>
#include <bitcoin/satoshi_serialize.hpp>
#include <bitcoin/transaction.hpp>
#include <bitcoin/types.hpp>
#include <bitcoin/utility/hash.hpp>
#include <bitcoin/utility/logger.hpp>
#include <bitcoin/utility/serializer.hpp>
namespace libbitcoin {
hash_digest hash_transaction_impl(const transaction_type& tx,
uint32_t* hash_type_code)
{
data_chunk serialized_tx(satoshi_raw_size(tx));
satoshi_save(tx, serialized_tx.begin());
if (hash_type_code != nullptr)
extend_data(serialized_tx, to_little_endian(*hash_type_code));
return bitcoin_hash(serialized_tx);
}
hash_digest hash_transaction(const transaction_type& tx)
{
return hash_transaction_impl(tx, nullptr);
}
hash_digest hash_transaction(const transaction_type& tx,
uint32_t hash_type_code)
{
return hash_transaction_impl(tx, &hash_type_code);
}
hash_digest build_merkle_tree(hash_digest_list& merkle)
{
if (merkle.empty())
return null_hash;
else if (merkle.size() == 1)
return merkle[0];
while (merkle.size() > 1)
{
if (merkle.size() % 2 != 0)
merkle.push_back(merkle.back());
hash_digest_list new_merkle;
for (auto it = merkle.begin(); it != merkle.end(); it += 2)
{
data_chunk concat_data(hash_size * 2);
auto concat = make_serializer(concat_data.begin());
concat.write_hash(*it);
concat.write_hash(*(it + 1));
BITCOIN_ASSERT(concat.iterator() == concat_data.end());
hash_digest new_root = bitcoin_hash(concat_data);
new_merkle.push_back(new_root);
}
merkle = new_merkle;
}
return merkle[0];
}
hash_digest generate_merkle_root(const transaction_list& transactions)
{
hash_digest_list tx_hashes;
for (transaction_type tx: transactions)
tx_hashes.push_back(hash_transaction(tx));
return build_merkle_tree(tx_hashes);
}
std::string pretty(const transaction_input_type& input)
{
std::ostringstream ss;
ss << "\thash = " << input.previous_output.hash << "\n"
<< "\tindex = " << input.previous_output.index << "\n"
<< "\t" << input.script << "\n"
<< "\tsequence = " << input.sequence << "\n";
return ss.str();
}
std::string pretty(const transaction_output_type& output)
{
std::ostringstream ss;
ss << "\tvalue = " << output.value << "\n"
<< "\t" << output.script << "\n";
return ss.str();
}
std::string pretty(const transaction_type& tx)
{
std::ostringstream ss;
ss << "Transaction:\n"
<< "\tversion = " << tx.version << "\n"
<< "\tlocktime = " << tx.locktime << "\n"
<< "Inputs:\n";
for (transaction_input_type input: tx.inputs)
ss << pretty(input);
ss << "Outputs:\n";
for (transaction_output_type output: tx.outputs)
ss << pretty(output);
ss << "\n";
return ss.str();
}
bool previous_output_is_null(const output_point& previous_output)
{
return previous_output.index == std::numeric_limits<uint32_t>::max() &&
previous_output.hash == null_hash;
}
bool is_coinbase(const transaction_type& tx)
{
return tx.inputs.size() == 1 &&
previous_output_is_null(tx.inputs[0].previous_output);
}
uint64_t total_output_value(const transaction_type& tx)
{
uint64_t total = 0;
for (const transaction_output_type& output: tx.outputs)
total += output.value;
return total;
}
bool operator==(const output_point& output_a, const output_point& output_b)
{
return output_a.hash == output_b.hash && output_a.index == output_b.index;
}
bool operator!=(const output_point& output_a, const output_point& output_b)
{
return !(output_a == output_b);
}
bool is_final(const transaction_input_type& tx_input)
{
return tx_input.sequence == std::numeric_limits<uint32_t>::max();
}
bool is_final(const transaction_type& tx,
size_t block_height, uint32_t block_time)
{
if (tx.locktime == 0)
return true;
uint32_t max_locktime = block_time;
if (tx.locktime < locktime_threshold)
max_locktime = block_height;
if (tx.locktime < max_locktime)
return true;
for (const transaction_input_type& tx_input: tx.inputs)
if (!is_final(tx_input))
return false;
return true;
}
} // namespace libbitcoin
|
use global hash_digest_list type instead of redefining duplicate.
|
use global hash_digest_list type instead of redefining duplicate.
|
C++
|
agpl-3.0
|
GroestlCoin/libgroestlcoin,Airbitz/libbitcoin,libmetrocoin/libmetrocoin-consensus,GroestlCoin/libgroestlcoin,Airbitz/libbitcoin,libtetcoin/libtetcoin-consensus,swansontec/libbitcoin,libtetcoin/libtetcoin-consensus,libmetrocoin/libmetrocoin-consensus,libmetrocoin/libmetrocoin-consensus,swansontec/libbitcoin,swansontec/libbitcoin,GroestlCoin/libgroestlcoin,GroestlCoin/libgroestlcoin,libmetrocoin/libmetrocoin-consensus,libtetcoin/libtetcoin-consensus,libmetrocoin/libmetrocoin-consensus,libtetcoin/libtetcoin-consensus,swansontec/libbitcoin,Airbitz/libbitcoin,Airbitz/libbitcoin,libtetcoin/libtetcoin-consensus
|
c2d62d8818c6b22530f4708c12c42ba8e30c6aaa
|
src/unix_stream.cpp
|
src/unix_stream.cpp
|
// -D_GNU_SOURCE makes SOCK_NONBLOCK etc. available on linux
#undef _GNU_SOURCE
#define _GNU_SOURCE
#include "uv.h"
#include "node.h"
#include "pipe_wrap.h"
#include <sys/socket.h>
#include <sys/un.h>
#include <errno.h>
using namespace v8;
using namespace node;
namespace {
Persistent<String> errno_symbol;
void SetErrno(int errorno) {
// set errno in the global context, this is the technique
// that node uses to propagate system level errors to JS land
Context::GetCurrent()->Global()->Set(errno_symbol, Integer::New(errorno));
}
Handle<Value> Socket(const Arguments& args) {
HandleScope scope;
int protocol;
int domain;
int type;
int fd;
assert(args.Length() == 3);
domain = args[0]->Int32Value();
type = args[1]->Int32Value();
protocol = args[2]->Int32Value();
#if defined(SOCK_NONBLOCK)
type |= SOCK_NONBLOCK;
#endif
#if defined(SOCK_CLOEXEC)
type |= SOCK_CLOEXEC;
#endif
if ((fd = socket(domain, type, protocol)) == -1) {
SetErrno(errno);
goto out;
}
#if !defined(SOCK_NONBLOCK)
SetNonBlock(fd);
#endif
#if !defined(SOCK_CLOEXEC)
SetCloExec(fd);
#endif
out:
return scope.Close(Integer::New(fd));
}
Handle<Value> Bind(const Arguments& args) {
HandleScope scope;
sockaddr_un sun;
int fd;
int ret;
assert(args.Length() == 2);
fd = args[0]->Int32Value();
String::Utf8Value path(args[1]);
strncpy(sun.sun_path, *path, sizeof(sun.sun_path) - 1);
sun.sun_path[sizeof(sun.sun_path) - 1] = '\0';
sun.sun_family = AF_UNIX;
if ((ret = bind(fd, reinterpret_cast<sockaddr*>(&sun), sizeof(sun))) == -1) {
SetErrno(errno);
}
return scope.Close(Integer::New(ret));
}
Handle<Value> GetPeerName(const Arguments& args) {
HandleScope scope;
assert(args.Length() == 1);
Local<Object> obj = args[0]->ToObject();
assert(obj->InternalFieldCount() > 0);
int ret;
sockaddr_un sun;
socklen_t addrlen = sizeof(sun);
memset(&sun, '\0', addrlen);
PipeWrap* wrap = static_cast<PipeWrap*>(obj->GetPointerFromInternalField(0));
int fd = wrap->UVHandle()->fd;
if ((ret = getpeername(fd, reinterpret_cast<sockaddr*>(&sun), &addrlen)) == -1) {
SetErrno(errno);
return Null();
}
/* If addrlen == 2 --> no path */
return addrlen == 2 ? Null() : scope.Close(String::New(sun.sun_path));
}
Handle<Value> GetSockName(const Arguments& args) {
HandleScope scope;
assert(args.Length() == 1);
Local<Object> obj = args[0]->ToObject();
assert(obj->InternalFieldCount() > 0);
int ret;
sockaddr_un sun;
socklen_t addrlen = sizeof(sun);
memset(&sun, '\0', addrlen);
PipeWrap* wrap = static_cast<PipeWrap*>(obj->GetPointerFromInternalField(0));
int fd = wrap->UVHandle()->fd;
if ((ret = getsockname(fd, reinterpret_cast<sockaddr*>(&sun), &addrlen)) == -1) {
SetErrno(errno);
return Null();
}
/* If addrlen == 2 --> no path */
return addrlen == 2 ? Null() : scope.Close(String::New(sun.sun_path));
}
void Initialize(Handle<Object> target) {
errno_symbol = Persistent<String>::New(String::NewSymbol("errno"));
target->Set(String::NewSymbol("AF_UNIX"), Integer::New(AF_UNIX));
target->Set(String::NewSymbol("SOCK_STREAM"), Integer::New(SOCK_STREAM));
target->Set(String::NewSymbol("socket"), FunctionTemplate::New(Socket)->GetFunction());
target->Set(String::NewSymbol("bind"), FunctionTemplate::New(Bind)->GetFunction());
target->Set(String::NewSymbol("getpeername"), FunctionTemplate::New(GetPeerName)->GetFunction());
target->Set(String::NewSymbol("getsockname"), FunctionTemplate::New(GetSockName)->GetFunction());
}
}
NODE_MODULE(unix_stream, Initialize)
|
// -D_GNU_SOURCE makes SOCK_NONBLOCK etc. available on linux
#undef _GNU_SOURCE
#define _GNU_SOURCE
#include "uv.h"
#include "node.h"
#include "pipe_wrap.h"
#include <sys/socket.h>
#include <sys/un.h>
#include <errno.h>
using namespace v8;
using namespace node;
namespace {
Persistent<String> errno_symbol;
void SetErrno(int errorno) {
// set errno in the global context, this is the technique
// that node uses to propagate system level errors to JS land
Context::GetCurrent()->Global()->Set(errno_symbol, Integer::New(errorno));
}
void SetNonBlock(int fd) {
int flags;
int r;
flags = fcntl(fd, F_GETFL);
assert(flags != -1);
r = fcntl(fd, F_SETFL, flags | O_NONBLOCK);
assert(r != -1);
}
void SetCloExec(int fd) {
int flags;
int r;
flags = fcntl(fd, F_GETFD);
assert(flags != -1);
r = fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
assert(r != -1);
}
Handle<Value> Socket(const Arguments& args) {
HandleScope scope;
int protocol;
int domain;
int type;
int fd;
assert(args.Length() == 3);
domain = args[0]->Int32Value();
type = args[1]->Int32Value();
protocol = args[2]->Int32Value();
#if defined(SOCK_NONBLOCK)
type |= SOCK_NONBLOCK;
#endif
#if defined(SOCK_CLOEXEC)
type |= SOCK_CLOEXEC;
#endif
if ((fd = socket(domain, type, protocol)) == -1) {
SetErrno(errno);
goto out;
}
#if !defined(SOCK_NONBLOCK)
SetNonBlock(fd);
#endif
#if !defined(SOCK_CLOEXEC)
SetCloExec(fd);
#endif
out:
return scope.Close(Integer::New(fd));
}
Handle<Value> Bind(const Arguments& args) {
HandleScope scope;
sockaddr_un sun;
int fd;
int ret;
assert(args.Length() == 2);
fd = args[0]->Int32Value();
String::Utf8Value path(args[1]);
strncpy(sun.sun_path, *path, sizeof(sun.sun_path) - 1);
sun.sun_path[sizeof(sun.sun_path) - 1] = '\0';
sun.sun_family = AF_UNIX;
if ((ret = bind(fd, reinterpret_cast<sockaddr*>(&sun), sizeof(sun))) == -1) {
SetErrno(errno);
}
return scope.Close(Integer::New(ret));
}
Handle<Value> GetPeerName(const Arguments& args) {
HandleScope scope;
assert(args.Length() == 1);
Local<Object> obj = args[0]->ToObject();
assert(obj->InternalFieldCount() > 0);
int ret;
sockaddr_un sun;
socklen_t addrlen = sizeof(sun);
memset(&sun, '\0', addrlen);
PipeWrap* wrap = static_cast<PipeWrap*>(obj->GetPointerFromInternalField(0));
int fd = wrap->UVHandle()->fd;
if ((ret = getpeername(fd, reinterpret_cast<sockaddr*>(&sun), &addrlen)) == -1) {
SetErrno(errno);
return Null();
}
/* If addrlen == 2 --> no path */
return addrlen == 2 ? Null() : scope.Close(String::New(sun.sun_path));
}
Handle<Value> GetSockName(const Arguments& args) {
HandleScope scope;
assert(args.Length() == 1);
Local<Object> obj = args[0]->ToObject();
assert(obj->InternalFieldCount() > 0);
int ret;
sockaddr_un sun;
socklen_t addrlen = sizeof(sun);
memset(&sun, '\0', addrlen);
PipeWrap* wrap = static_cast<PipeWrap*>(obj->GetPointerFromInternalField(0));
int fd = wrap->UVHandle()->fd;
if ((ret = getsockname(fd, reinterpret_cast<sockaddr*>(&sun), &addrlen)) == -1) {
SetErrno(errno);
return Null();
}
/* If addrlen == 2 --> no path */
return addrlen == 2 ? Null() : scope.Close(String::New(sun.sun_path));
}
void Initialize(Handle<Object> target) {
errno_symbol = Persistent<String>::New(String::NewSymbol("errno"));
target->Set(String::NewSymbol("AF_UNIX"), Integer::New(AF_UNIX));
target->Set(String::NewSymbol("SOCK_STREAM"), Integer::New(SOCK_STREAM));
target->Set(String::NewSymbol("socket"), FunctionTemplate::New(Socket)->GetFunction());
target->Set(String::NewSymbol("bind"), FunctionTemplate::New(Bind)->GetFunction());
target->Set(String::NewSymbol("getpeername"), FunctionTemplate::New(GetPeerName)->GetFunction());
target->Set(String::NewSymbol("getsockname"), FunctionTemplate::New(GetSockName)->GetFunction());
}
}
NODE_MODULE(unix_stream, Initialize)
|
Implement SetNonBlock and SetCloExec
|
Implement SetNonBlock and SetCloExec
|
C++
|
isc
|
santigimeno/node-unix-stream,santigimeno/node-unix-stream,santigimeno/node-unix-stream
|
b32654daf2b49daa52bcb604840d49d9d4a08e39
|
src/utils/Timer.hpp
|
src/utils/Timer.hpp
|
/*
* Timer.hpp
*
* Created by Craig Rasmussen on 11/15/09.
* Copyright 2009 Los Alamos National Laboratory. All rights reserved.
*
*/
#ifndef TIMER_HPP_
#define TIMER_HPP_
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <assert.h>
#include <string.h>
////////////////////////////////////////////////////////////////////////////////
namespace PV {
class Timer {
public:
Timer(double init_time=0.0);
Timer(const char * timermessage, double init_time=0.0);
Timer(const char * objname, const char * objtype, const char * timertype, double init_time=0.0);
virtual ~Timer();
void reset(double init_time=0.0);
virtual double start();
virtual double stop();
inline double elapsed_time();
int fprint_time(FILE * stream);
protected:
int rank;
char * message;
uint64_t time_start, time_end;
uint64_t time_elapsed;
};
} // namespace PV
#endif /* TIMER_HPP_ */
|
/*
* Timer.hpp
*
* Created by Craig Rasmussen on 11/15/09.
* Copyright 2009 Los Alamos National Laboratory. All rights reserved.
*
*/
#ifndef TIMER_HPP_
#define TIMER_HPP_
#include <stdlib.h>
#include <stdio.h>
#include <stddef.h>
#include <stdint.h>
#include <assert.h>
#include <string.h>
////////////////////////////////////////////////////////////////////////////////
namespace PV {
class Timer {
public:
Timer(double init_time=0.0);
Timer(const char * timermessage, double init_time=0.0);
Timer(const char * objname, const char * objtype, const char * timertype, double init_time=0.0);
virtual ~Timer();
void reset(double init_time=0.0);
virtual double start();
virtual double stop();
inline double elapsed_time();
int fprint_time(FILE * stream);
protected:
int rank;
char * message;
uint64_t time_start, time_end;
uint64_t time_elapsed;
};
} // namespace PV
#endif /* TIMER_HPP_ */
|
Add stddef.h to eliminate eclipse indexing problem
|
Add stddef.h to eliminate eclipse indexing problem
git-svn-id: 602a26e73ae9f2a14e2bb95676f2e137fcc39919@8553 7c0444ca-5550-0410-9008-faecdbe78eb5
|
C++
|
epl-1.0
|
PetaVision/OpenPV,dpaiton/OpenPV,PetaVision/OpenPV,dpaiton/OpenPV,dpaiton/OpenPV,PetaVision/OpenPV,dpaiton/OpenPV,PetaVision/OpenPV,PetaVision/OpenPV,dpaiton/OpenPV,dpaiton/OpenPV,dpaiton/OpenPV,dpaiton/OpenPV
|
0e754f618419f586d8e56bd7632328390eff4b55
|
src/utils/cpuid.cpp
|
src/utils/cpuid.cpp
|
/**
* Runtime CPU detection
* (C) 2009 Jack Lloyd
*
* Distributed under the terms of the Botan license
*/
#include <botan/cpuid.h>
#include <botan/types.h>
#include <botan/loadstor.h>
#include <botan/mem_ops.h>
#include <stdio.h>
#if defined(_MSC_VER)
#include <intrin.h>
#endif
namespace Botan {
namespace {
void x86_cpuid(u32bit type, u32bit out[4])
{
out[0] = out[1] = out[2] = out[3] = 0;
#if defined(BOTAN_BUILD_COMPILER_IS_GCC)
#if defined(BOTAN_TARGET_ARCH_IS_X86)
asm("pushq %%ebx; cpuid; mov %%ebx, %%edi; popq %%ebx"
: "=a" (out[0]), "=D" (out[1]), "=c" (out[2]), "=d" (out[3])
: "0" (type));
#elif defined(BOTAN_TARGET_ARCH_IS_AMD64)
asm("pushq %%rbx; cpuid; mov %%ebx, %%edi; popq %%rbx"
: "=a" (out[0]), "=D" (out[1]), "=c" (out[2]), "=d" (out[3])
: "0" (type));
#endif
#elif defined(BOTAN_BUILD_COMPILER_IS_MSVC)
__cpuid(out, type);
#endif
}
u32bit get_x86_cache_line_size()
{
const u32bit INTEL_CPUID[3] = { 0x756E6547, 0x6C65746E, 0x49656E69 };
const u32bit AMD_CPUID[3] = { 0x68747541, 0x444D4163, 0x69746E65 };
u32bit cpuid[4] = { 0 };
x86_cpuid(0, cpuid);
if(same_mem(cpuid + 1, INTEL_CPUID, 3) && cpuid[0] > 2)
{
x86_cpuid(1, cpuid);
return 8 * get_byte(2, cpuid[1]);
}
if(same_mem(cpuid + 1, AMD_CPUID, 3))
{
x86_cpuid(0x80000005, cpuid);
return get_byte(3, cpuid[2]);
}
return 32; // default cache line guess
}
}
/*
* Call the x86 CPUID instruction and return the contents of ecx and
* edx, which contain the feature masks.
*/
u64bit CPUID::x86_processor_flags()
{
static u64bit proc_flags = 0;
if(proc_flags)
return proc_flags;
u32bit cpuid[4] = { 0 };
x86_cpuid(1, cpuid);
// Set the FPU bit on to force caching in proc_flags
proc_flags = ((u64bit)cpuid[2] << 32) | cpuid[3] | 1;
return proc_flags;
}
u32bit CPUID::cache_line_size()
{
static u32bit cl_size = 0;
if(cl_size)
return cl_size;
cl_size = get_x86_cache_line_size();
return cl_size;
}
}
|
/**
* Runtime CPU detection
* (C) 2009 Jack Lloyd
*
* Distributed under the terms of the Botan license
*/
#include <botan/cpuid.h>
#include <botan/types.h>
#include <botan/loadstor.h>
#include <botan/mem_ops.h>
#if defined(BOTAN_TARGET_ARCH_IS_X86) || defined(BOTAN_TARGET_ARCH_IS_AMD64)
#if defined(BOTAN_BUILD_COMPILER_IS_MSVC)
#include <intrin.h>
#define CALL_CPUID(type, out) do { __cpuid(out, type) } while(0)
#elif defined(BOTAN_BUILD_COMPILER_IS_ICC)
#include <ia32intrin.h>
#define CALL_CPUID(type, out) do { __cpuid(out, type) } while(0);
#elif defined(BOTAN_BUILD_COMPILER_IS_GCC)
#include <cpuid.h>
#define CALL_CPUID(type, out) \
do { __get_cpuid(type, out, out+1, out+2, out+3); } while(0);
#endif
#else
// In all other cases, just zeroize the supposed cpuid output
#define CALL_CPUID(type, out) out[0] = out[1] = out[2] = out[3] = 0;
#endif
namespace Botan {
namespace {
u32bit get_x86_cache_line_size()
{
const u32bit INTEL_CPUID[3] = { 0x756E6547, 0x6C65746E, 0x49656E69 };
const u32bit AMD_CPUID[3] = { 0x68747541, 0x444D4163, 0x69746E65 };
u32bit cpuid[4] = { 0 };
CALL_CPUID(0, cpuid);
if(same_mem(cpuid + 1, INTEL_CPUID, 3))
{
CALL_CPUID(1, cpuid);
return 8 * get_byte(2, cpuid[1]);
}
else if(same_mem(cpuid + 1, AMD_CPUID, 3))
{
CALL_CPUID(0x80000005, cpuid);
return get_byte(3, cpuid[2]);
}
else
return 32; // default cache line guess
}
}
/*
* Call the x86 CPUID instruction and return the contents of ecx and
* edx, which contain the feature masks.
*/
u64bit CPUID::x86_processor_flags()
{
static u64bit proc_flags = 0;
if(proc_flags)
return proc_flags;
u32bit cpuid[4] = { 0 };
CALL_CPUID(1, cpuid);
// Set the FPU bit on to force caching in proc_flags
proc_flags = ((u64bit)cpuid[2] << 32) | cpuid[3] | 1;
return proc_flags;
}
u32bit CPUID::cache_line_size()
{
static u32bit cl_size = 0;
if(cl_size)
return cl_size;
cl_size = get_x86_cache_line_size();
return cl_size;
}
}
|
Clean up cpuid calling
|
Clean up cpuid calling
|
C++
|
bsd-2-clause
|
Rohde-Schwarz-Cybersecurity/botan,webmaster128/botan,Rohde-Schwarz-Cybersecurity/botan,randombit/botan,webmaster128/botan,Rohde-Schwarz-Cybersecurity/botan,randombit/botan,randombit/botan,webmaster128/botan,Rohde-Schwarz-Cybersecurity/botan,randombit/botan,webmaster128/botan,webmaster128/botan,Rohde-Schwarz-Cybersecurity/botan,randombit/botan,Rohde-Schwarz-Cybersecurity/botan
|
411eccd192d7a379248b0f04742da13819fbbc78
|
strings/strings.cpp
|
strings/strings.cpp
|
#include "strings.h"
BOOST_AUTO_TEST_CASE(std_string_variants)
{
BOOST_REQUIRE((std::is_same_v<std::string, std::basic_string<XXX>>));
BOOST_REQUIRE((std::is_same_v<std::wstring, std::basic_string<XXX>>));
BOOST_REQUIRE((std::is_same_v<std::u16string, std::basic_string<XXX>>));
BOOST_REQUIRE((std::is_same_v<std::u32string, std::basic_string<XXX>>));
}
BOOST_AUTO_TEST_CASE(std_string_related_types)
{
BOOST_REQUIRE((std::is_same_v<std::string::traits_type, XXX>));
BOOST_REQUIRE((std::is_same_v<std::string::value_type, XXX>));
BOOST_REQUIRE((std::is_same_v<std::string::reference, XXX>));
BOOST_REQUIRE((std::is_same_v<std::string::const_reference, XXX>));
BOOST_REQUIRE((std::is_same_v<std::string::reverse_iterator, std::reverse_iterator<XXX>>));
BOOST_REQUIRE((std::is_same_v<std::string::const_reverse_iterator, std::reverse_iterator<XXX>>));
}
BOOST_AUTO_TEST_CASE(std_string_constructors)
{
std::string const s1;
BOOST_REQUIRE_EQUAL(xxx, s1.length());
std::string const s2{5, 'E'};
BOOST_REQUIRE_EQUAL(xxx, s2.length());
std::string const s3{s2};
BOOST_REQUIRE_EQUAL(xxx, s3.length());
std::string const s4{s2, 1};
BOOST_REQUIRE_EQUAL(xxx, s4.length());
std::string const hw{"Hello, world!"};
std::string const s5{hw, 1, 4};
BOOST_REQUIRE_EQUAL(xxx, s5);
std::string const s6{"Hello, world!"};
BOOST_REQUIRE_EQUAL(xxx, s6.length());
std::string const s7{"Hello, world!", 5};
BOOST_REQUIRE_EQUAL(xxx, s7);
std::string const s8{s7.begin(), s7.begin() + 1};
BOOST_REQUIRE_EQUAL(xxx, s8);
std::string const s9{'H', 'e', 'l', 'l', 'o'};
BOOST_REQUIRE_EQUAL(xxx, s9);
}
BOOST_AUTO_TEST_CASE(std_string_literals)
{
using namespace std::literals::string_literals;
auto s1{"Hello, world!"s};
auto s2{L"Hello, world!"s};
auto s3{u"Hello, world!"s};
auto s4{U"Hello, world!"s};
BOOST_REQUIRE((std::is_same_v<decltype(s1), XXX>));
BOOST_REQUIRE((std::is_same_v<decltype(s2), XXX>));
BOOST_REQUIRE((std::is_same_v<decltype(s3), XXX>));
BOOST_REQUIRE((std::is_same_v<decltype(s4), XXX>));
}
BOOST_AUTO_TEST_CASE(std_string_accessors)
{
std::string const s{"Hello, world!"};
BOOST_REQUIRE_EQUAL(xxx, s[0]);
BOOST_REQUIRE_EQUAL('w', s.at(xxx));
BOOST_REQUIRE_THROW(s.at(1000), XXX);
BOOST_REQUIRE_EQUAL(xxx, s.front());
BOOST_REQUIRE_EQUAL(xxx, s.back());
BOOST_REQUIRE((std::is_same_v<decltype(s.data()), XXX>));
BOOST_REQUIRE((std::is_same_v<decltype(s.c_str()), XXX>));
}
BOOST_AUTO_TEST_CASE(string_iterators)
{
std::string const s{"Hello, world!"};
BOOST_REQUIRE((std::is_same_v<decltype(s.begin()), XXX>));
BOOST_REQUIRE((std::is_same_v<decltype(s.cbegin()), XXX>));
BOOST_REQUIRE_EQUAL(xxx, *s.begin());
BOOST_REQUIRE_EQUAL(xxx, *(s.end() - 1));
BOOST_REQUIRE_EQUAL(xxx, *s.rbegin());
BOOST_REQUIRE_EQUAL(xxx, *(s.rend() - 1));
}
BOOST_AUTO_TEST_CASE(std_string_capacity)
{
std::string s{"Hello, world!"};
BOOST_REQUIRE_EQUAL(xxx, s.length());
BOOST_REQUIRE_EQUAL(xxx, s.empty());
BOOST_REQUIRE_GE(static_cast<std::string::size_type>(xxx), s.capacity());
s += s;
s = "Hello, world!";
BOOST_REQUIRE_EQUAL(xxx, s.length());
BOOST_REQUIRE_GE(static_cast<std::string::size_type>(xxx), s.capacity());
s.shrink_to_fit();
BOOST_REQUIRE_EQUAL(xxx, s.length());
BOOST_REQUIRE_GE(static_cast<std::string::size_type>(xxx), s.capacity());
s.reserve(1024);
BOOST_REQUIRE_EQUAL(xxx, s.length());
BOOST_REQUIRE_EQUAL(xxx, s.capacity());
}
BOOST_AUTO_TEST_CASE(std_string_clear)
{
std::string s{"Hello, world!"};
s.clear();
BOOST_REQUIRE_EQUAL(xxx, s.length());
BOOST_REQUIRE_EQUAL(xxx, s.empty());
BOOST_REQUIRE_GE(static_cast<std::string::size_type>(xxx), s.capacity());
}
BOOST_AUTO_TEST_CASE(std_string_insert)
{
std::string s2{"Bob"};
s2.insert(1, "illy B");
BOOST_REQUIRE_EQUAL(xxx, s2);
s2.insert(0, 2, '-');
BOOST_REQUIRE_EQUAL(xxx, s2);
s2.insert(2, "Hello, world!", 7);
BOOST_REQUIRE_EQUAL(xxx, s2);
std::string s3{"Hello, world!"};
std::string s4{"big, fat"};
s3.insert(7, s4);
BOOST_REQUIRE_EQUAL(xxx, s3);
}
BOOST_AUTO_TEST_CASE(std_string_allocators)
{
BOOST_REQUIRE((std::is_same_v<std::string::allocator_type, XXX>));
BOOST_REQUIRE((std::is_same_v<std::string::size_type, XXX>));
BOOST_REQUIRE((std::is_same_v<std::string::difference_type, XXX>));
BOOST_REQUIRE((std::is_same_v<std::string::pointer, XXX>));
BOOST_REQUIRE((std::is_same_v<std::string::const_pointer, XXX>));
}
|
#include "strings.h"
BOOST_AUTO_TEST_CASE(std_string_literals)
{
using namespace std::string_literals;
auto s1{"Hello, world!"s};
auto s2{L"Hello, world!"s};
auto s3{u"Hello, world!"s};
auto s4{U"Hello, world!"s};
BOOST_REQUIRE((std::is_same_v<decltype(s1), XXX>));
BOOST_REQUIRE((std::is_same_v<decltype(s2), XXX>));
BOOST_REQUIRE((std::is_same_v<decltype(s3), XXX>));
BOOST_REQUIRE((std::is_same_v<decltype(s4), XXX>));
}
BOOST_AUTO_TEST_CASE(std_string_variants)
{
BOOST_REQUIRE((std::is_same_v<std::basic_string<char>, XXX>));
BOOST_REQUIRE((std::is_same_v<std::string, std::basic_string<XXX>>));
BOOST_REQUIRE((std::is_same_v<std::wstring, std::basic_string<XXX>>));
BOOST_REQUIRE((std::is_same_v<std::u16string, std::basic_string<XXX>>));
BOOST_REQUIRE((std::is_same_v<std::u32string, std::basic_string<XXX>>));
}
BOOST_AUTO_TEST_CASE(std_string_related_types)
{
BOOST_REQUIRE((std::is_same_v<std::string::traits_type, XXX>));
BOOST_REQUIRE((std::is_same_v<std::string::value_type, XXX>));
BOOST_REQUIRE((std::is_same_v<std::string::reference, XXX>));
BOOST_REQUIRE((std::is_same_v<std::string::const_reference, XXX>));
BOOST_REQUIRE((std::is_same_v<std::string::reverse_iterator, std::reverse_iterator<XXX>>));
BOOST_REQUIRE((std::is_same_v<std::string::const_reverse_iterator, std::reverse_iterator<XXX>>));
}
BOOST_AUTO_TEST_CASE(std_string_constructors)
{
std::string const s1;
BOOST_REQUIRE_EQUAL(xxx, s1.length());
std::string const s2{5, 'E'};
BOOST_REQUIRE_EQUAL(xxx, s2.length());
std::string const s3{s2};
BOOST_REQUIRE_EQUAL(xxx, s3.length());
std::string const s4{s2, 1};
BOOST_REQUIRE_EQUAL(xxx, s4.length());
std::string const hw{"Hello, world!"};
std::string const s5{hw, 1, 4};
BOOST_REQUIRE_EQUAL(xxx, s5);
std::string const s6{"Hello, world!"};
BOOST_REQUIRE_EQUAL(xxx, s6.length());
std::string const s7{"Hello, world!", 5};
BOOST_REQUIRE_EQUAL(xxx, s7);
std::string const s8{s7.begin(), s7.begin() + 1};
BOOST_REQUIRE_EQUAL(xxx, s8);
std::string const s9{'H', 'e', 'l', 'l', 'o'};
BOOST_REQUIRE_EQUAL(xxx, s9);
}
BOOST_AUTO_TEST_CASE(std_string_accessors)
{
std::string const s{"Hello, world!"};
BOOST_REQUIRE_EQUAL(xxx, s[0]);
BOOST_REQUIRE_EQUAL('w', s.at(xxx));
BOOST_REQUIRE_THROW(s.at(1000), XXX);
BOOST_REQUIRE_EQUAL(xxx, s.front());
BOOST_REQUIRE_EQUAL(xxx, s.back());
BOOST_REQUIRE((std::is_same_v<decltype(s.data()), XXX>));
BOOST_REQUIRE((std::is_same_v<decltype(s.c_str()), XXX>));
}
BOOST_AUTO_TEST_CASE(string_iterators)
{
std::string const s{"Hello, world!"};
BOOST_REQUIRE((std::is_same_v<decltype(s.begin()), XXX>));
BOOST_REQUIRE((std::is_same_v<decltype(s.cbegin()), XXX>));
BOOST_REQUIRE_EQUAL(xxx, *s.begin());
BOOST_REQUIRE_EQUAL(xxx, *(s.end() - 1));
BOOST_REQUIRE_EQUAL(xxx, *s.rbegin());
BOOST_REQUIRE_EQUAL(xxx, *(s.rend() - 1));
}
BOOST_AUTO_TEST_CASE(std_string_capacity)
{
std::string s{"Hello, world!"};
BOOST_REQUIRE_EQUAL(xxx, s.length());
BOOST_REQUIRE_EQUAL(xxx, s.empty());
BOOST_REQUIRE_GE(static_cast<std::string::size_type>(xxx), s.capacity());
s += s;
s = "Hello, world!";
BOOST_REQUIRE_EQUAL(xxx, s.length());
BOOST_REQUIRE_GE(static_cast<std::string::size_type>(xxx), s.capacity());
s.shrink_to_fit();
BOOST_REQUIRE_EQUAL(xxx, s.length());
BOOST_REQUIRE_GE(static_cast<std::string::size_type>(xxx), s.capacity());
s.reserve(1024);
BOOST_REQUIRE_EQUAL(xxx, s.length());
BOOST_REQUIRE_EQUAL(xxx, s.capacity());
}
BOOST_AUTO_TEST_CASE(std_string_clear)
{
std::string s{"Hello, world!"};
s.clear();
BOOST_REQUIRE_EQUAL(xxx, s.length());
BOOST_REQUIRE_EQUAL(xxx, s.empty());
BOOST_REQUIRE_GE(s.capacity(), static_cast<std::string::size_type>(xxx));
}
BOOST_AUTO_TEST_CASE(std_string_insert)
{
using namespace std::string_literals;
std::string s2{"Bob"};
s2.insert(1, "illy B");
BOOST_REQUIRE_EQUAL(xxx, s2);
s2.insert(0, 2, '-');
BOOST_REQUIRE_EQUAL(xxx, s2);
s2.insert(2, "Hello, world!", 7);
BOOST_REQUIRE_EQUAL(xxx, s2);
std::string s3{"Hello, world!"};
std::string s4{"big, fat "};
s3.insert(7, s4);
BOOST_REQUIRE_EQUAL(xxx, s3);
std::string s5{"Hello, world!"};
s5.insert(7, s4, xxx, 3);
BOOST_REQUIRE_EQUAL("Hello, fat world!"s, s5);
}
BOOST_AUTO_TEST_CASE(std_string_allocators)
{
BOOST_REQUIRE((std::is_same_v<std::string::allocator_type, XXX>));
BOOST_REQUIRE((std::is_same_v<std::string::size_type, XXX>));
BOOST_REQUIRE((std::is_same_v<std::string::difference_type, XXX>));
BOOST_REQUIRE((std::is_same_v<std::string::pointer, XXX>));
BOOST_REQUIRE((std::is_same_v<std::string::const_pointer, XXX>));
}
|
Improve std::string test cases
|
Improve std::string test cases
|
C++
|
mit
|
LegalizeAdulthood/cpp-koans
|
00429b13d5c577d43fe7c601eb1d015e602022cd
|
worker/src/handles/UdpSocket.cpp
|
worker/src/handles/UdpSocket.cpp
|
#define MS_CLASS "UdpSocket"
// #define MS_LOG_DEV_LEVEL 3
#include "handles/UdpSocket.hpp"
#include "Logger.hpp"
#include "MediaSoupErrors.hpp"
#include "Utils.hpp"
#include <cstring> // std::memcpy()
/* Static. */
static constexpr size_t ReadBufferSize{ 65536 };
static uint8_t ReadBuffer[ReadBufferSize];
/* Static methods for UV callbacks. */
inline static void onAlloc(uv_handle_t* handle, size_t suggestedSize, uv_buf_t* buf)
{
auto* socket = static_cast<UdpSocket*>(handle->data);
if (socket)
socket->OnUvRecvAlloc(suggestedSize, buf);
}
inline static void onRecv(
uv_udp_t* handle, ssize_t nread, const uv_buf_t* buf, const struct sockaddr* addr, unsigned int flags)
{
auto* socket = static_cast<UdpSocket*>(handle->data);
if (socket)
socket->OnUvRecv(nread, buf, addr, flags);
}
inline static void onSend(uv_udp_send_t* req, int status)
{
auto* sendData = static_cast<UdpSocket::UvSendData*>(req->data);
auto* handle = req->handle;
auto* socket = static_cast<UdpSocket*>(handle->data);
auto* cb = sendData->cb;
if (socket)
socket->OnUvSend(status, cb);
// Delete the UvSendData struct (it will delete the store and cb too).
delete sendData;
}
inline static void onClose(uv_handle_t* handle)
{
delete handle;
}
/* Instance methods. */
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init)
UdpSocket::UdpSocket(uv_udp_t* uvHandle) : uvHandle(uvHandle)
{
MS_TRACE();
int err;
this->uvHandle->data = static_cast<void*>(this);
err = uv_udp_recv_start(
this->uvHandle, static_cast<uv_alloc_cb>(onAlloc), static_cast<uv_udp_recv_cb>(onRecv));
if (err != 0)
{
uv_close(reinterpret_cast<uv_handle_t*>(this->uvHandle), static_cast<uv_close_cb>(onClose));
MS_THROW_ERROR("uv_udp_recv_start() failed: %s", uv_strerror(err));
}
// Set local address.
if (!SetLocalAddress())
{
uv_close(reinterpret_cast<uv_handle_t*>(this->uvHandle), static_cast<uv_close_cb>(onClose));
MS_THROW_ERROR("error setting local IP and port");
}
}
UdpSocket::~UdpSocket()
{
MS_TRACE();
if (!this->closed)
Close();
}
void UdpSocket::Close()
{
MS_TRACE();
if (this->closed)
return;
this->closed = true;
// Tell the UV handle that the UdpSocket has been closed.
this->uvHandle->data = nullptr;
// Don't read more.
int err = uv_udp_recv_stop(this->uvHandle);
if (err != 0)
MS_ABORT("uv_udp_recv_stop() failed: %s", uv_strerror(err));
uv_close(reinterpret_cast<uv_handle_t*>(this->uvHandle), static_cast<uv_close_cb>(onClose));
}
void UdpSocket::Dump() const
{
MS_DUMP("<UdpSocket>");
MS_DUMP(" localIp : %s", this->localIp.c_str());
MS_DUMP(" localPort : %" PRIu16, static_cast<uint16_t>(this->localPort));
MS_DUMP(" closed : %s", !this->closed ? "open" : "closed");
MS_DUMP("</UdpSocket>");
}
void UdpSocket::Send(
const uint8_t* data, size_t len, const struct sockaddr* addr, UdpSocket::onSendCallback* cb)
{
MS_TRACE();
if (this->closed)
{
if (cb)
(*cb)(false);
return;
}
if (len == 0)
{
if (cb)
(*cb)(false);
return;
}
// First try uv_udp_try_send(). In case it can not directly send the datagram
// then build a uv_req_t and use uv_udp_send().
uv_buf_t buffer = uv_buf_init(reinterpret_cast<char*>(const_cast<uint8_t*>(data)), len);
int sent = uv_udp_try_send(this->uvHandle, &buffer, 1, addr);
// Entire datagram was sent. Done.
if (sent == static_cast<int>(len))
{
// Update sent bytes.
this->sentBytes += sent;
if (cb)
{
(*cb)(true);
delete cb;
}
return;
}
else if (sent >= 0)
{
MS_WARN_DEV("datagram truncated (just %d of %zu bytes were sent)", sent, len);
// Update sent bytes.
this->sentBytes += sent;
if (cb)
{
(*cb)(false);
delete cb;
}
return;
}
// Any error but legit EAGAIN. Use uv_udp_send().
else if (sent != UV_EAGAIN)
{
MS_WARN_DEV("uv_udp_try_send() failed, trying uv_udp_send(): %s", uv_strerror(sent));
}
auto* sendData = new UvSendData(len);
sendData->req.data = static_cast<void*>(sendData);
std::memcpy(sendData->store, data, len);
sendData->cb = cb;
buffer = uv_buf_init(reinterpret_cast<char*>(sendData->store), len);
int err = uv_udp_send(
&sendData->req, this->uvHandle, &buffer, 1, addr, static_cast<uv_udp_send_cb>(onSend));
if (err != 0)
{
// NOTE: uv_udp_send() returns error if a wrong INET family is given
// (IPv6 destination on a IPv4 binded socket), so be ready.
MS_WARN_DEV("uv_udp_send() failed: %s", uv_strerror(err));
if (cb)
(*cb)(false);
// Delete the UvSendData struct (it will delete the store and cb too).
delete sendData;
}
else
{
// Update sent bytes.
this->sentBytes += len;
}
}
bool UdpSocket::SetLocalAddress()
{
MS_TRACE();
int err;
int len = sizeof(this->localAddr);
err =
uv_udp_getsockname(this->uvHandle, reinterpret_cast<struct sockaddr*>(&this->localAddr), &len);
if (err != 0)
{
MS_ERROR("uv_udp_getsockname() failed: %s", uv_strerror(err));
return false;
}
int family;
Utils::IP::GetAddressInfo(
reinterpret_cast<const struct sockaddr*>(&this->localAddr), family, this->localIp, this->localPort);
return true;
}
inline void UdpSocket::OnUvRecvAlloc(size_t /*suggestedSize*/, uv_buf_t* buf)
{
MS_TRACE();
// Tell UV to write into the static buffer.
buf->base = reinterpret_cast<char*>(ReadBuffer);
// Give UV all the buffer space.
buf->len = ReadBufferSize;
}
inline void UdpSocket::OnUvRecv(
ssize_t nread, const uv_buf_t* buf, const struct sockaddr* addr, unsigned int flags)
{
MS_TRACE();
// NOTE: libuv calls twice to alloc & recv when a datagram is received, the
// second one with nread = 0 and addr = NULL. Ignore it.
if (nread == 0)
return;
// Check flags.
if ((flags & UV_UDP_PARTIAL) != 0u)
{
MS_ERROR("received datagram was truncated due to insufficient buffer, ignoring it");
return;
}
// Data received.
if (nread > 0)
{
// Update received bytes.
this->recvBytes += nread;
// Notify the subclass.
UserOnUdpDatagramReceived(reinterpret_cast<uint8_t*>(buf->base), nread, addr);
}
// Some error.
else
{
MS_DEBUG_DEV("read error: %s", uv_strerror(nread));
}
}
inline void UdpSocket::OnUvSend(int status, UdpSocket::onSendCallback* cb)
{
MS_TRACE();
if (status == 0)
{
if (cb)
(*cb)(true);
}
else
{
#if MS_LOG_DEV_LEVEL == 3
MS_DEBUG_DEV("send error: %s", uv_strerror(status));
#endif
if (cb)
(*cb)(false);
}
}
|
#define MS_CLASS "UdpSocket"
// #define MS_LOG_DEV_LEVEL 3
#include "handles/UdpSocket.hpp"
#include "Logger.hpp"
#include "MediaSoupErrors.hpp"
#include "Utils.hpp"
#include <cstring> // std::memcpy()
/* Static. */
// This value will make libuv to use uv__udp_recvmmsg() internally, which is
// more efficient.
static constexpr size_t ReadBufferSize{ 65536 * 2 };
static uint8_t ReadBuffer[ReadBufferSize];
/* Static methods for UV callbacks. */
inline static void onAlloc(uv_handle_t* handle, size_t suggestedSize, uv_buf_t* buf)
{
auto* socket = static_cast<UdpSocket*>(handle->data);
if (socket)
socket->OnUvRecvAlloc(suggestedSize, buf);
}
inline static void onRecv(
uv_udp_t* handle, ssize_t nread, const uv_buf_t* buf, const struct sockaddr* addr, unsigned int flags)
{
auto* socket = static_cast<UdpSocket*>(handle->data);
if (socket)
socket->OnUvRecv(nread, buf, addr, flags);
}
inline static void onSend(uv_udp_send_t* req, int status)
{
auto* sendData = static_cast<UdpSocket::UvSendData*>(req->data);
auto* handle = req->handle;
auto* socket = static_cast<UdpSocket*>(handle->data);
auto* cb = sendData->cb;
if (socket)
socket->OnUvSend(status, cb);
// Delete the UvSendData struct (it will delete the store and cb too).
delete sendData;
}
inline static void onClose(uv_handle_t* handle)
{
delete handle;
}
/* Instance methods. */
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init)
UdpSocket::UdpSocket(uv_udp_t* uvHandle) : uvHandle(uvHandle)
{
MS_TRACE();
int err;
this->uvHandle->data = static_cast<void*>(this);
err = uv_udp_recv_start(
this->uvHandle, static_cast<uv_alloc_cb>(onAlloc), static_cast<uv_udp_recv_cb>(onRecv));
if (err != 0)
{
uv_close(reinterpret_cast<uv_handle_t*>(this->uvHandle), static_cast<uv_close_cb>(onClose));
MS_THROW_ERROR("uv_udp_recv_start() failed: %s", uv_strerror(err));
}
// Set local address.
if (!SetLocalAddress())
{
uv_close(reinterpret_cast<uv_handle_t*>(this->uvHandle), static_cast<uv_close_cb>(onClose));
MS_THROW_ERROR("error setting local IP and port");
}
}
UdpSocket::~UdpSocket()
{
MS_TRACE();
if (!this->closed)
Close();
}
void UdpSocket::Close()
{
MS_TRACE();
if (this->closed)
return;
this->closed = true;
// Tell the UV handle that the UdpSocket has been closed.
this->uvHandle->data = nullptr;
// Don't read more.
int err = uv_udp_recv_stop(this->uvHandle);
if (err != 0)
MS_ABORT("uv_udp_recv_stop() failed: %s", uv_strerror(err));
uv_close(reinterpret_cast<uv_handle_t*>(this->uvHandle), static_cast<uv_close_cb>(onClose));
}
void UdpSocket::Dump() const
{
MS_DUMP("<UdpSocket>");
MS_DUMP(" localIp : %s", this->localIp.c_str());
MS_DUMP(" localPort : %" PRIu16, static_cast<uint16_t>(this->localPort));
MS_DUMP(" closed : %s", !this->closed ? "open" : "closed");
MS_DUMP("</UdpSocket>");
}
void UdpSocket::Send(
const uint8_t* data, size_t len, const struct sockaddr* addr, UdpSocket::onSendCallback* cb)
{
MS_TRACE();
if (this->closed)
{
if (cb)
(*cb)(false);
return;
}
if (len == 0)
{
if (cb)
(*cb)(false);
return;
}
// First try uv_udp_try_send(). In case it can not directly send the datagram
// then build a uv_req_t and use uv_udp_send().
uv_buf_t buffer = uv_buf_init(reinterpret_cast<char*>(const_cast<uint8_t*>(data)), len);
int sent = uv_udp_try_send(this->uvHandle, &buffer, 1, addr);
// Entire datagram was sent. Done.
if (sent == static_cast<int>(len))
{
// Update sent bytes.
this->sentBytes += sent;
if (cb)
{
(*cb)(true);
delete cb;
}
return;
}
else if (sent >= 0)
{
MS_WARN_DEV("datagram truncated (just %d of %zu bytes were sent)", sent, len);
// Update sent bytes.
this->sentBytes += sent;
if (cb)
{
(*cb)(false);
delete cb;
}
return;
}
// Any error but legit EAGAIN. Use uv_udp_send().
else if (sent != UV_EAGAIN)
{
MS_WARN_DEV("uv_udp_try_send() failed, trying uv_udp_send(): %s", uv_strerror(sent));
}
auto* sendData = new UvSendData(len);
sendData->req.data = static_cast<void*>(sendData);
std::memcpy(sendData->store, data, len);
sendData->cb = cb;
buffer = uv_buf_init(reinterpret_cast<char*>(sendData->store), len);
int err = uv_udp_send(
&sendData->req, this->uvHandle, &buffer, 1, addr, static_cast<uv_udp_send_cb>(onSend));
if (err != 0)
{
// NOTE: uv_udp_send() returns error if a wrong INET family is given
// (IPv6 destination on a IPv4 binded socket), so be ready.
MS_WARN_DEV("uv_udp_send() failed: %s", uv_strerror(err));
if (cb)
(*cb)(false);
// Delete the UvSendData struct (it will delete the store and cb too).
delete sendData;
}
else
{
// Update sent bytes.
this->sentBytes += len;
}
}
bool UdpSocket::SetLocalAddress()
{
MS_TRACE();
int err;
int len = sizeof(this->localAddr);
err =
uv_udp_getsockname(this->uvHandle, reinterpret_cast<struct sockaddr*>(&this->localAddr), &len);
if (err != 0)
{
MS_ERROR("uv_udp_getsockname() failed: %s", uv_strerror(err));
return false;
}
int family;
Utils::IP::GetAddressInfo(
reinterpret_cast<const struct sockaddr*>(&this->localAddr), family, this->localIp, this->localPort);
return true;
}
inline void UdpSocket::OnUvRecvAlloc(size_t /*suggestedSize*/, uv_buf_t* buf)
{
MS_TRACE();
// Tell UV to write into the static buffer.
buf->base = reinterpret_cast<char*>(ReadBuffer);
// Give UV all the buffer space.
buf->len = ReadBufferSize;
}
inline void UdpSocket::OnUvRecv(
ssize_t nread, const uv_buf_t* buf, const struct sockaddr* addr, unsigned int flags)
{
MS_TRACE();
// NOTE: libuv calls twice to alloc & recv when a datagram is received, the
// second one with nread = 0 and addr = NULL. Ignore it.
if (nread == 0)
return;
// Check flags.
if ((flags & UV_UDP_PARTIAL) != 0u)
{
MS_ERROR("received datagram was truncated due to insufficient buffer, ignoring it");
return;
}
// Data received.
if (nread > 0)
{
// Update received bytes.
this->recvBytes += nread;
// Notify the subclass.
UserOnUdpDatagramReceived(reinterpret_cast<uint8_t*>(buf->base), nread, addr);
}
// Some error.
else
{
MS_DEBUG_DEV("read error: %s", uv_strerror(nread));
}
}
inline void UdpSocket::OnUvSend(int status, UdpSocket::onSendCallback* cb)
{
MS_TRACE();
if (status == 0)
{
if (cb)
(*cb)(true);
}
else
{
#if MS_LOG_DEV_LEVEL == 3
MS_DEBUG_DEV("send error: %s", uv_strerror(status));
#endif
if (cb)
(*cb)(false);
}
}
|
use uv__udp_recvmmsg() internally
|
worker/src/handles/UdpSocket.cpp: use uv__udp_recvmmsg() internally
|
C++
|
isc
|
ibc/MediaSoup,versatica/mediasoup,versatica/mediasoup,versatica/mediasoup,versatica/mediasoup,versatica/mediasoup,ibc/MediaSoup,versatica/mediasoup,versatica/mediasoup,ibc/MediaSoup,versatica/mediasoup,versatica/mediasoup
|
8ed98bf908b6f3d9feb0ef71e00b48c2c9bae94f
|
src/main/cpp/signal_handler.cpp
|
src/main/cpp/signal_handler.cpp
|
#include "signal_handler.h"
namespace {
// Helper class to store and reset errno when in a signal handler.
class ErrnoRaii {
public:
ErrnoRaii() {
stored_errno_ = errno;
}
~ErrnoRaii() {
errno = stored_errno_;
}
private:
int stored_errno_;
DISALLOW_COPY_AND_ASSIGN(ErrnoRaii);
};
} // namespace
bool SignalHandler::updateSigprofInterval() {
bool res = updateSigprofInterval(timingIntervals[intervalIndex]);
intervalIndex = (intervalIndex + 1) % NUMBER_OF_INTERVALS;
return res;
}
bool SignalHandler::updateSigprofInterval(const int timingInterval) {
if (timingInterval == currentInterval)
return true;
static struct itimerval timer;
// timingInterval is in milliseconds, not seconds.
timer.it_interval.tv_sec = (timingInterval / 1000000) / 1000;
timer.it_interval.tv_usec = timingInterval % 1000;
timer.it_value = timer.it_interval;
if (setitimer(ITIMER_PROF, &timer, 0) == -1) {
logError("Scheduling profiler interval failed with error %d\n", errno);
return false;
}
currentInterval = timingInterval;
return true;
}
struct sigaction SignalHandler::SetAction(void (*action)(int, siginfo_t *, void *)) {
struct sigaction sa;
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
#endif
sa.sa_handler = NULL;
sa.sa_sigaction = action;
sa.sa_flags = SA_RESTART | SA_SIGINFO;
#ifdef __clang__
#pragma clang diagnostic pop
#endif
sigemptyset(&sa.sa_mask);
struct sigaction old_handler;
if (sigaction(SIGPROF, &sa, &old_handler) != 0) {
logError("Scheduling profiler action failed with error %d\n", errno);
return old_handler;
}
return old_handler;
}
|
#include "signal_handler.h"
namespace {
// Helper class to store and reset errno when in a signal handler.
class ErrnoRaii {
public:
ErrnoRaii() {
stored_errno_ = errno;
}
~ErrnoRaii() {
errno = stored_errno_;
}
private:
int stored_errno_;
DISALLOW_COPY_AND_ASSIGN(ErrnoRaii);
};
} // namespace
bool SignalHandler::updateSigprofInterval() {
bool res = updateSigprofInterval(timingIntervals[intervalIndex]);
intervalIndex = (intervalIndex + 1) % NUMBER_OF_INTERVALS;
return res;
}
bool SignalHandler::updateSigprofInterval(const int timingInterval) {
if (timingInterval == currentInterval)
return true;
static struct itimerval timer;
// timingInterval is in milliseconds, not seconds.
timer.it_interval.tv_sec = timingInterval / 1000;
timer.it_interval.tv_usec = (timingInterval * 1000) % 1000000;
timer.it_value = timer.it_interval;
if (setitimer(ITIMER_PROF, &timer, 0) == -1) {
logError("Scheduling profiler interval failed with error %d\n", errno);
return false;
}
currentInterval = timingInterval;
return true;
}
struct sigaction SignalHandler::SetAction(void (*action)(int, siginfo_t *, void *)) {
struct sigaction sa;
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
#endif
sa.sa_handler = NULL;
sa.sa_sigaction = action;
sa.sa_flags = SA_RESTART | SA_SIGINFO;
#ifdef __clang__
#pragma clang diagnostic pop
#endif
sigemptyset(&sa.sa_mask);
struct sigaction old_handler;
if (sigaction(SIGPROF, &sa, &old_handler) != 0) {
logError("Scheduling profiler action failed with error %d\n", errno);
return old_handler;
}
return old_handler;
}
|
Correct timeunit conversion in timer's registration
|
Correct timeunit conversion in timer's registration
|
C++
|
mit
|
RichardWarburton/honest-profiler,jvm-profiling-tools/honest-profiler,RichardWarburton/honest-profiler,RichardWarburton/honest-profiler,RichardWarburton/honest-profiler,jvm-profiling-tools/honest-profiler,jvm-profiling-tools/honest-profiler,RichardWarburton/honest-profiler,jvm-profiling-tools/honest-profiler,RichardWarburton/honest-profiler
|
fa90ace9cdd96aad99177886c44d6abf710ad0e6
|
cpp/common/Url.cpp
|
cpp/common/Url.cpp
|
/*
* #%L
* %%
* Copyright (C) 2011 - 2013 BMW Car IT GmbH
* %%
* 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.
* #L%
*/
#include "joynr/Url.h"
#include <sstream>
#include <boost/algorithm/string/join.hpp>
#include <cstddef>
namespace joynr
{
Url::Url()
: protocol(), user(), password(), host(), port(), path(), query(), fragment(), valid(false)
{
}
Url::Url(const std::string& text)
: protocol(), user(), password(), host(), port(), path(), query(), fragment(), valid(false)
{
parseUrl(text);
}
Url::Url(const std::string& protocol,
const std::string& host,
std::uint16_t port,
const std::string& path)
: protocol(protocol),
user(),
password(),
host(host),
port(port),
path(path),
query(),
fragment(),
valid(false)
{
// Set valid to true if member variables are valid
validate();
}
Url::Url(const std::string& protocol,
const std::string& user,
const std::string& password,
const std::string& host,
std::uint16_t port,
const std::string& path,
const std::string& query,
const std::string& fragment)
: protocol(protocol),
user(user),
password(password),
host(host),
port(port),
path(path),
query(query),
fragment(fragment),
valid(false)
{
// Set valid to true if member variables are valid
validate();
}
bool Url::operator==(const Url& other) const
{
if (!(valid && other.valid)) {
return false;
}
return (port == other.port && protocol == other.protocol && user == other.user &&
password == other.password && host == other.host && path == other.path &&
query == other.query && fragment == other.fragment);
}
const std::string& Url::getProtocol() const
{
return protocol;
}
const std::string& Url::getUser() const
{
return user;
}
const std::string& Url::getPassword() const
{
return password;
}
const std::string& Url::getHost() const
{
return host;
}
std::uint16_t Url::getPort() const
{
return port;
}
const std::string& Url::getPath() const
{
return path;
}
void Url::setPath(const std::string& path)
{
this->path = path;
validate();
}
const std::string& Url::getQuery() const
{
return query;
}
void Url::setQuery(UrlQuery query)
{
this->query = query.toString();
validate();
}
const std::string& Url::getFragment() const
{
return fragment;
}
bool Url::isValid() const
{
return valid;
}
void Url::parseUrl(const std::string& text)
{
// scheme:[//[user:password@]host[:port]][/]path[?query][#fragment]
enum class State {
SCHEME,
SCHEME_SEP,
USER,
PASSWORD,
HOST,
PORT,
PATH,
QUERY,
FRAGMENT,
TERMINATE
};
State state = State::SCHEME;
std::string portString;
std::size_t branchStart; // used for backtracking
// Loop through the text
for (std::size_t i = 0; i < text.size() && state != State::TERMINATE; i++) {
char ch = text[i];
switch (state) {
case State::SCHEME:
if (ch == ':') {
state = State::SCHEME_SEP;
} else {
protocol += ch;
}
break;
case State::SCHEME_SEP:
if (ch != '/') {
state = State::USER;
branchStart = i;
user += ch;
}
break;
case State::USER:
if (ch == ':') {
state = State::PASSWORD;
} else if (ch == '/' || i == text.size() - 1) {
// There was no auth - backtrack
state = State::HOST;
i = branchStart - 1;
user.clear();
} else {
user += ch;
}
break;
case State::PASSWORD:
if (ch == '@') {
state = State::HOST;
} else if (ch == '/' || i == text.size() - 1) {
// There was no auth - backtrack
state = State::HOST;
i = branchStart - 1;
user.clear();
password.clear();
} else {
password += ch;
}
break;
case State::HOST:
if (ch == ':') {
state = State::PORT;
} else if (ch == '/') {
state = State::PATH;
path += ch;
} else {
host += ch;
}
break;
case State::PORT:
if (ch == '/') {
state = State::PATH;
path += ch;
} else {
portString += ch;
}
break;
case State::PATH:
if (ch == '?') {
state = State::QUERY;
} else if (ch == '#') {
state = State::FRAGMENT;
} else {
path += ch;
}
break;
case State::QUERY:
if (ch == '#') {
state = State::FRAGMENT;
} else {
query += ch;
}
break;
case State::FRAGMENT:
fragment += ch;
if (i == text.size()) {
state = State::TERMINATE;
}
break;
case State::TERMINATE:
// Ignored
break;
}
}
// Post process the port
if (portString.empty()) {
port = portFromProtocol(protocol);
} else {
port = std::stoi(portString);
}
// Set valid to true if the member variables appear correct
validate();
}
std::string Url::toString()
{
std::stringstream stringBuilder;
stringBuilder << protocol << "://";
if (!user.empty()) {
stringBuilder << user;
if (!password.empty()) {
stringBuilder << ":" << password;
}
stringBuilder << "@";
}
stringBuilder << host;
if (port != 0) {
stringBuilder << ":" << port;
}
if (!path.empty()) {
stringBuilder << path;
}
if (!query.empty()) {
stringBuilder << "?" << query;
}
if (!fragment.empty()) {
stringBuilder << "#" << fragment;
}
return stringBuilder.str();
}
std::uint16_t Url::portFromProtocol(const std::string& proto)
{
if (proto == "http") {
return 80;
} else if (proto == "https") {
return 443;
} else if (proto == "ws") {
return 80;
} else if (proto == "wss") {
return 443;
} else {
return 80;
}
}
void Url::validate()
{
// Check - valid will remain false on error
if (protocol.empty() || host.empty()) {
return;
}
// Post process the path
if (path.empty()) {
path = "/";
}
// Assume success
valid = true;
}
UrlQuery::UrlQuery() : queryItems()
{
}
void UrlQuery::addQueryItem(const std::string& itemName, const std::string& itemValue)
{
std::string queryItem = itemName + "=" + itemValue;
queryItems.push_back(queryItem);
}
std::string UrlQuery::toString()
{
if (queryItems.empty())
return "";
std::string result = boost::algorithm::join(queryItems, "&");
return result;
}
} // namespace joynr
|
/*
* #%L
* %%
* Copyright (C) 2011 - 2016 BMW Car IT GmbH
* %%
* 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.
* #L%
*/
#include "joynr/Url.h"
#include <sstream>
#include <boost/algorithm/string/join.hpp>
#include <cstddef>
namespace joynr
{
Url::Url()
: protocol(), user(), password(), host(), port(), path(), query(), fragment(), valid(false)
{
}
Url::Url(const std::string& text)
: protocol(), user(), password(), host(), port(), path(), query(), fragment(), valid(false)
{
parseUrl(text);
}
Url::Url(const std::string& protocol,
const std::string& host,
std::uint16_t port,
const std::string& path)
: protocol(protocol),
user(),
password(),
host(host),
port(port),
path(path),
query(),
fragment(),
valid(false)
{
// Set valid to true if member variables are valid
validate();
}
Url::Url(const std::string& protocol,
const std::string& user,
const std::string& password,
const std::string& host,
std::uint16_t port,
const std::string& path,
const std::string& query,
const std::string& fragment)
: protocol(protocol),
user(user),
password(password),
host(host),
port(port),
path(path),
query(query),
fragment(fragment),
valid(false)
{
// Set valid to true if member variables are valid
validate();
}
bool Url::operator==(const Url& other) const
{
if (!(valid && other.valid)) {
return false;
}
return (port == other.port && protocol == other.protocol && user == other.user &&
password == other.password && host == other.host && path == other.path &&
query == other.query && fragment == other.fragment);
}
const std::string& Url::getProtocol() const
{
return protocol;
}
const std::string& Url::getUser() const
{
return user;
}
const std::string& Url::getPassword() const
{
return password;
}
const std::string& Url::getHost() const
{
return host;
}
std::uint16_t Url::getPort() const
{
return port;
}
const std::string& Url::getPath() const
{
return path;
}
void Url::setPath(const std::string& path)
{
this->path = path;
validate();
}
const std::string& Url::getQuery() const
{
return query;
}
void Url::setQuery(UrlQuery query)
{
this->query = query.toString();
validate();
}
const std::string& Url::getFragment() const
{
return fragment;
}
bool Url::isValid() const
{
return valid;
}
void Url::parseUrl(const std::string& text)
{
// scheme:[//[user:password@]host[:port]][/]path[?query][#fragment]
enum class State {
SCHEME,
SCHEME_SEP,
USER,
PASSWORD,
HOST,
PORT,
PATH,
QUERY,
FRAGMENT,
TERMINATE
};
State state = State::SCHEME;
std::string portString;
std::size_t branchStart = 0; // used for backtracking
// Loop through the text
for (std::size_t i = 0; i < text.size() && state != State::TERMINATE; i++) {
char ch = text[i];
switch (state) {
case State::SCHEME:
if (ch == ':') {
state = State::SCHEME_SEP;
} else {
protocol += ch;
}
break;
case State::SCHEME_SEP:
if (ch != '/') {
state = State::USER;
branchStart = i;
user += ch;
}
break;
case State::USER:
if (ch == ':') {
state = State::PASSWORD;
} else if (ch == '/' || i == text.size() - 1) {
// There was no auth - backtrack
state = State::HOST;
i = branchStart - 1;
user.clear();
} else {
user += ch;
}
break;
case State::PASSWORD:
if (ch == '@') {
state = State::HOST;
} else if (ch == '/' || i == text.size() - 1) {
// There was no auth - backtrack
state = State::HOST;
i = branchStart - 1;
user.clear();
password.clear();
} else {
password += ch;
}
break;
case State::HOST:
if (ch == ':') {
state = State::PORT;
} else if (ch == '/') {
state = State::PATH;
path += ch;
} else {
host += ch;
}
break;
case State::PORT:
if (ch == '/') {
state = State::PATH;
path += ch;
} else {
portString += ch;
}
break;
case State::PATH:
if (ch == '?') {
state = State::QUERY;
} else if (ch == '#') {
state = State::FRAGMENT;
} else {
path += ch;
}
break;
case State::QUERY:
if (ch == '#') {
state = State::FRAGMENT;
} else {
query += ch;
}
break;
case State::FRAGMENT:
fragment += ch;
if (i == text.size()) {
state = State::TERMINATE;
}
break;
case State::TERMINATE:
// Ignored
break;
}
}
// Post process the port
if (portString.empty()) {
port = portFromProtocol(protocol);
} else {
port = std::stoi(portString);
}
// Set valid to true if the member variables appear correct
validate();
}
std::string Url::toString()
{
std::stringstream stringBuilder;
stringBuilder << protocol << "://";
if (!user.empty()) {
stringBuilder << user;
if (!password.empty()) {
stringBuilder << ":" << password;
}
stringBuilder << "@";
}
stringBuilder << host;
if (port != 0) {
stringBuilder << ":" << port;
}
if (!path.empty()) {
stringBuilder << path;
}
if (!query.empty()) {
stringBuilder << "?" << query;
}
if (!fragment.empty()) {
stringBuilder << "#" << fragment;
}
return stringBuilder.str();
}
std::uint16_t Url::portFromProtocol(const std::string& proto)
{
if (proto == "http") {
return 80;
} else if (proto == "https") {
return 443;
} else if (proto == "ws") {
return 80;
} else if (proto == "wss") {
return 443;
} else {
return 80;
}
}
void Url::validate()
{
// Check - valid will remain false on error
if (protocol.empty() || host.empty()) {
return;
}
// Post process the path
if (path.empty()) {
path = "/";
}
// Assume success
valid = true;
}
UrlQuery::UrlQuery() : queryItems()
{
}
void UrlQuery::addQueryItem(const std::string& itemName, const std::string& itemValue)
{
std::string queryItem = itemName + "=" + itemValue;
queryItems.push_back(queryItem);
}
std::string UrlQuery::toString()
{
if (queryItems.empty())
return "";
std::string result = boost::algorithm::join(queryItems, "&");
return result;
}
} // namespace joynr
|
Fix uninitialized variable warning.
|
[C++] Fix uninitialized variable warning.
Change-Id: I32bdcadbe0df092b90229ce9d72f52adcd7edadd
|
C++
|
apache-2.0
|
clive-jevons/joynr,bmwcarit/joynr,clive-jevons/joynr,clive-jevons/joynr,bmwcarit/joynr,bmwcarit/joynr,bmwcarit/joynr,clive-jevons/joynr,bmwcarit/joynr,clive-jevons/joynr,bmwcarit/joynr,bmwcarit/joynr,bmwcarit/joynr,bmwcarit/joynr,clive-jevons/joynr
|
813106b3b516f94b2886ee73695be19fea6d8224
|
cpp/log/file_db.cc
|
cpp/log/file_db.cc
|
/* -*- indent-tabs-mode: nil -*- */
#ifndef CERT_TRANS_LOG_FILE_DB_INL_H_
#define CERT_TRANS_LOG_FILE_DB_INL_H_
#include "log/file_db.h"
#include <glog/logging.h>
#include <map>
#include <set>
#include <stdint.h>
#include <string>
#include <vector>
#include "log/file_storage.h"
#include "proto/ct.pb.h"
#include "proto/serializer.h"
#include "monitoring/monitoring.h"
#include "monitoring/latency.h"
#include "util/util.h"
namespace cert_trans {
namespace {
static Latency<std::chrono::milliseconds, std::string> latency_by_op_ms(
"filedb_latency_by_operation_ms", "operation",
"Database latency in ms broken out by operation.");
const char kMetaNodeIdKey[] = "node_id";
std::string FormatSequenceNumber(const int64_t seq) {
return std::to_string(seq);
}
int64_t ParseSequenceNumber(const std::string& seq) {
return std::stoll(seq);
}
} // namespace
const size_t FileDB::kTimestampBytesIndexed = 6;
class FileDB::Iterator : public Database<LoggedEntry>::Iterator {
public:
Iterator(const FileDB* db, int64_t start_index)
: db_(CHECK_NOTNULL(db)), next_index_(start_index) {
CHECK_GE(next_index_, 0);
}
bool GetNextEntry(LoggedEntry* entry) override {
CHECK_NOTNULL(entry);
{
std::lock_guard<std::mutex> lock(db_->lock_);
if (next_index_ >= db_->contiguous_size_) {
std::set<int64_t>::const_iterator it(
db_->sparse_entries_.lower_bound(next_index_));
if (it == db_->sparse_entries_.end()) {
return false;
}
next_index_ = *it;
}
}
CHECK_EQ(db_->LookupByIndex(next_index_, entry),
Database<LoggedEntry>::LOOKUP_OK);
++next_index_;
return true;
}
private:
const FileDB* const db_;
int64_t next_index_;
};
FileDB::FileDB(FileStorage* cert_storage, FileStorage* tree_storage,
FileStorage* meta_storage)
: cert_storage_(CHECK_NOTNULL(cert_storage)),
tree_storage_(CHECK_NOTNULL(tree_storage)),
meta_storage_(CHECK_NOTNULL(meta_storage)),
contiguous_size_(0),
latest_tree_timestamp_(0) {
ScopedLatency latency(latency_by_op_ms.GetScopedLatency("open"));
BuildIndex();
}
FileDB::~FileDB() {
}
typename Database<LoggedEntry>::WriteResult FileDB::CreateSequencedEntry_(
const LoggedEntry& logged) {
CHECK(logged.has_sequence_number());
CHECK_GE(logged.sequence_number(), 0);
ScopedLatency latency(
latency_by_op_ms.GetScopedLatency("create_sequenced_entry"));
std::string data;
CHECK(logged.SerializeToString(&data));
const std::string seq_str(FormatSequenceNumber(logged.sequence_number()));
std::unique_lock<std::mutex> lock(lock_);
// Try to create.
util::Status status(cert_storage_->CreateEntry(seq_str, data));
if (status.CanonicalCode() == util::error::ALREADY_EXISTS) {
std::string existing_data;
status = cert_storage_->LookupEntry(seq_str, &existing_data);
CHECK_EQ(status, util::Status::OK);
if (existing_data == data) {
return this->OK;
}
return this->SEQUENCE_NUMBER_ALREADY_IN_USE;
}
CHECK_EQ(status, util::Status::OK);
InsertEntryMapping(logged.sequence_number(), logged.Hash());
return this->OK;
}
typename Database<LoggedEntry>::LookupResult FileDB::LookupByHash(
const std::string& hash, LoggedEntry* result) const {
ScopedLatency latency(latency_by_op_ms.GetScopedLatency("lookup_by_hash"));
std::unique_lock<std::mutex> lock(lock_);
auto i(id_by_hash_.find(hash));
if (i == id_by_hash_.end()) {
return this->NOT_FOUND;
}
const std::string seq_str(FormatSequenceNumber(i->second));
lock.unlock();
std::string cert_data;
const util::Status status(cert_storage_->LookupEntry(seq_str, &cert_data));
// Gotta be there, or we're in trouble...
CHECK_EQ(status, util::Status::OK);
LoggedEntry logged;
CHECK(logged.ParseFromString(cert_data));
CHECK_EQ(logged.Hash(), hash);
if (result) {
logged.Swap(result);
}
return this->LOOKUP_OK;
}
typename Database<LoggedEntry>::LookupResult FileDB::LookupByIndex(
int64_t sequence_number, LoggedEntry* result) const {
CHECK_GE(sequence_number, 0);
ScopedLatency latency(latency_by_op_ms.GetScopedLatency("lookup_by_index"));
const std::string seq_str(FormatSequenceNumber(sequence_number));
std::string cert_data;
if (cert_storage_->LookupEntry(seq_str, &cert_data).CanonicalCode() ==
util::error::NOT_FOUND) {
return this->NOT_FOUND;
}
if (result) {
CHECK(result->ParseFromString(cert_data));
CHECK_EQ(result->sequence_number(), sequence_number);
}
return this->LOOKUP_OK;
}
std::unique_ptr<typename Database<LoggedEntry>::Iterator> FileDB::ScanEntries(
int64_t start_index) const {
return std::unique_ptr<Iterator>(new Iterator(this, start_index));
}
typename Database<LoggedEntry>::WriteResult FileDB::WriteTreeHead_(
const ct::SignedTreeHead& sth) {
CHECK_GE(sth.tree_size(), 0);
ScopedLatency latency(latency_by_op_ms.GetScopedLatency("write_tree_head"));
// 6 bytes are good enough for some 9000 years.
std::string timestamp_key =
Serializer::SerializeUint(sth.timestamp(),
FileDB::kTimestampBytesIndexed);
std::string data;
CHECK(sth.SerializeToString(&data));
std::unique_lock<std::mutex> lock(lock_);
util::Status status(tree_storage_->CreateEntry(timestamp_key, data));
if (status.CanonicalCode() == util::error::ALREADY_EXISTS) {
std::string existing_sth_data;
status = tree_storage_->LookupEntry(timestamp_key, &existing_sth_data);
CHECK_EQ(status, util::Status::OK);
if (existing_sth_data == data) {
LOG(WARNING) << "Attempted to store identical STH in DB.";
return this->OK;
}
return this->DUPLICATE_TREE_HEAD_TIMESTAMP;
}
CHECK_EQ(status, util::Status::OK);
if (sth.timestamp() > latest_tree_timestamp_) {
latest_tree_timestamp_ = sth.timestamp();
latest_timestamp_key_ = timestamp_key;
}
lock.unlock();
callbacks_.Call(sth);
return this->OK;
}
typename Database<LoggedEntry>::LookupResult FileDB::LatestTreeHead(
ct::SignedTreeHead* result) const {
ScopedLatency latency(latency_by_op_ms.GetScopedLatency("latest_tree_head"));
std::lock_guard<std::mutex> lock(lock_);
return LatestTreeHeadNoLock(result);
}
int64_t FileDB::TreeSize() const {
ScopedLatency latency(latency_by_op_ms.GetScopedLatency("tree_size"));
std::lock_guard<std::mutex> lock(lock_);
return contiguous_size_;
}
void FileDB::AddNotifySTHCallback(
const typename Database<LoggedEntry>::NotifySTHCallback* callback) {
std::unique_lock<std::mutex> lock(lock_);
callbacks_.Add(callback);
ct::SignedTreeHead sth;
if (LatestTreeHeadNoLock(&sth) == this->LOOKUP_OK) {
lock.unlock();
(*callback)(sth);
}
}
void FileDB::RemoveNotifySTHCallback(
const typename Database<LoggedEntry>::NotifySTHCallback* callback) {
std::lock_guard<std::mutex> lock(lock_);
callbacks_.Remove(callback);
}
void FileDB::InitializeNode(const std::string& node_id) {
CHECK(!node_id.empty());
ScopedLatency latency(latency_by_op_ms.GetScopedLatency("initialize_node"));
std::unique_lock<std::mutex> lock(lock_);
std::string existing_id;
if (NodeId(&existing_id) != this->NOT_FOUND) {
LOG(FATAL) << "Attempting to initialze DB belonging to node with node_id: "
<< existing_id;
}
CHECK(meta_storage_->CreateEntry(kMetaNodeIdKey, node_id).ok());
}
typename Database<LoggedEntry>::LookupResult FileDB::NodeId(
std::string* node_id) {
CHECK_NOTNULL(node_id);
if (!meta_storage_->LookupEntry(kMetaNodeIdKey, node_id).ok()) {
return this->NOT_FOUND;
}
return this->LOOKUP_OK;
}
void FileDB::BuildIndex() {
ScopedLatency latency(latency_by_op_ms.GetScopedLatency("build_index"));
// Technically, this should only be called from the constructor, so
// this should not be necessarily, but just to be sure...
std::lock_guard<std::mutex> lock(lock_);
const std::set<std::string> sequence_numbers(cert_storage_->Scan());
id_by_hash_.reserve(sequence_numbers.size());
for (const auto& seq_path : sequence_numbers) {
const int64_t seq(ParseSequenceNumber(seq_path));
std::string cert_data;
// Read the data; tolerate no errors.
CHECK_EQ(cert_storage_->LookupEntry(seq_path, &cert_data),
util::Status::OK)
<< "Failed to read entry with sequence number " << seq;
LoggedEntry logged;
CHECK(logged.ParseFromString(cert_data))
<< "Failed to parse entry with sequence number " << seq;
CHECK(logged.has_sequence_number())
<< "sequence_number() is unset for for entry with sequence number "
<< seq;
CHECK_EQ(logged.sequence_number(), seq)
<< "Entry has a negative sequence_number(): " << seq;
InsertEntryMapping(logged.sequence_number(), logged.Hash());
}
// Now read the STH entries.
std::set<std::string> sth_timestamps = tree_storage_->Scan();
if (!sth_timestamps.empty()) {
latest_timestamp_key_ = *sth_timestamps.rbegin();
CHECK_EQ(Deserializer::OK,
Deserializer::DeserializeUint<uint64_t>(
latest_timestamp_key_, FileDB::kTimestampBytesIndexed,
&latest_tree_timestamp_));
}
}
typename Database<LoggedEntry>::LookupResult FileDB::LatestTreeHeadNoLock(
ct::SignedTreeHead* result) const {
if (latest_tree_timestamp_ == 0) {
return this->NOT_FOUND;
}
std::string tree_data;
CHECK_EQ(tree_storage_->LookupEntry(latest_timestamp_key_, &tree_data),
util::Status::OK);
CHECK(result->ParseFromString(tree_data));
CHECK_EQ(result->timestamp(), latest_tree_timestamp_);
return this->LOOKUP_OK;
}
// This must be called with "lock_" held.
void FileDB::InsertEntryMapping(int64_t sequence_number,
const std::string& hash) {
if (!id_by_hash_.insert(std::make_pair(hash, sequence_number)).second) {
// This is a duplicate hash under a new sequence number.
// Make sure we track the entry with the lowest sequence number:
id_by_hash_[hash] = std::min(id_by_hash_[hash], sequence_number);
}
if (sequence_number == contiguous_size_) {
++contiguous_size_;
for (auto i = sparse_entries_.find(contiguous_size_);
i != sparse_entries_.end() && *i == contiguous_size_;) {
++contiguous_size_;
i = sparse_entries_.erase(i);
}
} else {
// It's not contiguous, put it with the other sparse entries.
CHECK(sparse_entries_.insert(sequence_number).second)
<< "sequence number " << sequence_number << " already assigned.";
}
}
} // namespace cert_trans
#endif // CERT_TRANS_LOG_FILE_DB_INL_H_
|
/* -*- indent-tabs-mode: nil -*- */
#ifndef CERT_TRANS_LOG_FILE_DB_INL_H_
#define CERT_TRANS_LOG_FILE_DB_INL_H_
#include "log/file_db.h"
#include <glog/logging.h>
#include <map>
#include <set>
#include <stdint.h>
#include <string>
#include <vector>
#include "log/file_storage.h"
#include "proto/ct.pb.h"
#include "proto/serializer.h"
#include "monitoring/monitoring.h"
#include "monitoring/latency.h"
#include "util/util.h"
using std::chrono::milliseconds;
using std::lock_guard;
using std::make_pair;
using std::min;
using std::mutex;
using std::set;
using std::stoll;
using std::string;
using std::to_string;
using std::unique_lock;
using std::unique_ptr;
namespace cert_trans {
namespace {
static Latency<milliseconds, string> latency_by_op_ms(
"filedb_latency_by_operation_ms", "operation",
"Database latency in ms broken out by operation.");
const char kMetaNodeIdKey[] = "node_id";
string FormatSequenceNumber(const int64_t seq) {
return to_string(seq);
}
int64_t ParseSequenceNumber(const string& seq) {
return stoll(seq);
}
} // namespace
const size_t FileDB::kTimestampBytesIndexed = 6;
class FileDB::Iterator : public Database<LoggedEntry>::Iterator {
public:
Iterator(const FileDB* db, int64_t start_index)
: db_(CHECK_NOTNULL(db)), next_index_(start_index) {
CHECK_GE(next_index_, 0);
}
bool GetNextEntry(LoggedEntry* entry) override {
CHECK_NOTNULL(entry);
{
lock_guard<mutex> lock(db_->lock_);
if (next_index_ >= db_->contiguous_size_) {
set<int64_t>::const_iterator it(
db_->sparse_entries_.lower_bound(next_index_));
if (it == db_->sparse_entries_.end()) {
return false;
}
next_index_ = *it;
}
}
CHECK_EQ(db_->LookupByIndex(next_index_, entry),
Database<LoggedEntry>::LOOKUP_OK);
++next_index_;
return true;
}
private:
const FileDB* const db_;
int64_t next_index_;
};
FileDB::FileDB(FileStorage* cert_storage, FileStorage* tree_storage,
FileStorage* meta_storage)
: cert_storage_(CHECK_NOTNULL(cert_storage)),
tree_storage_(CHECK_NOTNULL(tree_storage)),
meta_storage_(CHECK_NOTNULL(meta_storage)),
contiguous_size_(0),
latest_tree_timestamp_(0) {
ScopedLatency latency(latency_by_op_ms.GetScopedLatency("open"));
BuildIndex();
}
FileDB::~FileDB() {
}
typename Database<LoggedEntry>::WriteResult FileDB::CreateSequencedEntry_(
const LoggedEntry& logged) {
CHECK(logged.has_sequence_number());
CHECK_GE(logged.sequence_number(), 0);
ScopedLatency latency(
latency_by_op_ms.GetScopedLatency("create_sequenced_entry"));
string data;
CHECK(logged.SerializeToString(&data));
const string seq_str(FormatSequenceNumber(logged.sequence_number()));
unique_lock<mutex> lock(lock_);
// Try to create.
util::Status status(cert_storage_->CreateEntry(seq_str, data));
if (status.CanonicalCode() == util::error::ALREADY_EXISTS) {
string existing_data;
status = cert_storage_->LookupEntry(seq_str, &existing_data);
CHECK_EQ(status, util::Status::OK);
if (existing_data == data) {
return this->OK;
}
return this->SEQUENCE_NUMBER_ALREADY_IN_USE;
}
CHECK_EQ(status, util::Status::OK);
InsertEntryMapping(logged.sequence_number(), logged.Hash());
return this->OK;
}
typename Database<LoggedEntry>::LookupResult FileDB::LookupByHash(
const string& hash, LoggedEntry* result) const {
ScopedLatency latency(latency_by_op_ms.GetScopedLatency("lookup_by_hash"));
unique_lock<mutex> lock(lock_);
auto i(id_by_hash_.find(hash));
if (i == id_by_hash_.end()) {
return this->NOT_FOUND;
}
const string seq_str(FormatSequenceNumber(i->second));
lock.unlock();
string cert_data;
const util::Status status(cert_storage_->LookupEntry(seq_str, &cert_data));
// Gotta be there, or we're in trouble...
CHECK_EQ(status, util::Status::OK);
LoggedEntry logged;
CHECK(logged.ParseFromString(cert_data));
CHECK_EQ(logged.Hash(), hash);
if (result) {
logged.Swap(result);
}
return this->LOOKUP_OK;
}
typename Database<LoggedEntry>::LookupResult FileDB::LookupByIndex(
int64_t sequence_number, LoggedEntry* result) const {
CHECK_GE(sequence_number, 0);
ScopedLatency latency(latency_by_op_ms.GetScopedLatency("lookup_by_index"));
const string seq_str(FormatSequenceNumber(sequence_number));
string cert_data;
if (cert_storage_->LookupEntry(seq_str, &cert_data).CanonicalCode() ==
util::error::NOT_FOUND) {
return this->NOT_FOUND;
}
if (result) {
CHECK(result->ParseFromString(cert_data));
CHECK_EQ(result->sequence_number(), sequence_number);
}
return this->LOOKUP_OK;
}
unique_ptr<typename Database<LoggedEntry>::Iterator> FileDB::ScanEntries(
int64_t start_index) const {
return unique_ptr<Iterator>(new Iterator(this, start_index));
}
typename Database<LoggedEntry>::WriteResult FileDB::WriteTreeHead_(
const ct::SignedTreeHead& sth) {
CHECK_GE(sth.tree_size(), 0);
ScopedLatency latency(latency_by_op_ms.GetScopedLatency("write_tree_head"));
// 6 bytes are good enough for some 9000 years.
string timestamp_key =
Serializer::SerializeUint(sth.timestamp(),
FileDB::kTimestampBytesIndexed);
string data;
CHECK(sth.SerializeToString(&data));
unique_lock<mutex> lock(lock_);
util::Status status(tree_storage_->CreateEntry(timestamp_key, data));
if (status.CanonicalCode() == util::error::ALREADY_EXISTS) {
string existing_sth_data;
status = tree_storage_->LookupEntry(timestamp_key, &existing_sth_data);
CHECK_EQ(status, util::Status::OK);
if (existing_sth_data == data) {
LOG(WARNING) << "Attempted to store identical STH in DB.";
return this->OK;
}
return this->DUPLICATE_TREE_HEAD_TIMESTAMP;
}
CHECK_EQ(status, util::Status::OK);
if (sth.timestamp() > latest_tree_timestamp_) {
latest_tree_timestamp_ = sth.timestamp();
latest_timestamp_key_ = timestamp_key;
}
lock.unlock();
callbacks_.Call(sth);
return this->OK;
}
typename Database<LoggedEntry>::LookupResult FileDB::LatestTreeHead(
ct::SignedTreeHead* result) const {
ScopedLatency latency(latency_by_op_ms.GetScopedLatency("latest_tree_head"));
lock_guard<mutex> lock(lock_);
return LatestTreeHeadNoLock(result);
}
int64_t FileDB::TreeSize() const {
ScopedLatency latency(latency_by_op_ms.GetScopedLatency("tree_size"));
lock_guard<mutex> lock(lock_);
return contiguous_size_;
}
void FileDB::AddNotifySTHCallback(
const typename Database<LoggedEntry>::NotifySTHCallback* callback) {
unique_lock<mutex> lock(lock_);
callbacks_.Add(callback);
ct::SignedTreeHead sth;
if (LatestTreeHeadNoLock(&sth) == this->LOOKUP_OK) {
lock.unlock();
(*callback)(sth);
}
}
void FileDB::RemoveNotifySTHCallback(
const typename Database<LoggedEntry>::NotifySTHCallback* callback) {
lock_guard<mutex> lock(lock_);
callbacks_.Remove(callback);
}
void FileDB::InitializeNode(const string& node_id) {
CHECK(!node_id.empty());
ScopedLatency latency(latency_by_op_ms.GetScopedLatency("initialize_node"));
unique_lock<mutex> lock(lock_);
string existing_id;
if (NodeId(&existing_id) != this->NOT_FOUND) {
LOG(FATAL) << "Attempting to initialze DB belonging to node with node_id: "
<< existing_id;
}
CHECK(meta_storage_->CreateEntry(kMetaNodeIdKey, node_id).ok());
}
typename Database<LoggedEntry>::LookupResult FileDB::NodeId(string* node_id) {
CHECK_NOTNULL(node_id);
if (!meta_storage_->LookupEntry(kMetaNodeIdKey, node_id).ok()) {
return this->NOT_FOUND;
}
return this->LOOKUP_OK;
}
void FileDB::BuildIndex() {
ScopedLatency latency(latency_by_op_ms.GetScopedLatency("build_index"));
// Technically, this should only be called from the constructor, so
// this should not be necessarily, but just to be sure...
lock_guard<mutex> lock(lock_);
const set<string> sequence_numbers(cert_storage_->Scan());
id_by_hash_.reserve(sequence_numbers.size());
for (const auto& seq_path : sequence_numbers) {
const int64_t seq(ParseSequenceNumber(seq_path));
string cert_data;
// Read the data; tolerate no errors.
CHECK_EQ(cert_storage_->LookupEntry(seq_path, &cert_data),
util::Status::OK)
<< "Failed to read entry with sequence number " << seq;
LoggedEntry logged;
CHECK(logged.ParseFromString(cert_data))
<< "Failed to parse entry with sequence number " << seq;
CHECK(logged.has_sequence_number())
<< "sequence_number() is unset for for entry with sequence number "
<< seq;
CHECK_EQ(logged.sequence_number(), seq)
<< "Entry has a negative sequence_number(): " << seq;
InsertEntryMapping(logged.sequence_number(), logged.Hash());
}
// Now read the STH entries.
set<string> sth_timestamps = tree_storage_->Scan();
if (!sth_timestamps.empty()) {
latest_timestamp_key_ = *sth_timestamps.rbegin();
CHECK_EQ(Deserializer::OK,
Deserializer::DeserializeUint<uint64_t>(
latest_timestamp_key_, FileDB::kTimestampBytesIndexed,
&latest_tree_timestamp_));
}
}
typename Database<LoggedEntry>::LookupResult FileDB::LatestTreeHeadNoLock(
ct::SignedTreeHead* result) const {
if (latest_tree_timestamp_ == 0) {
return this->NOT_FOUND;
}
string tree_data;
CHECK_EQ(tree_storage_->LookupEntry(latest_timestamp_key_, &tree_data),
util::Status::OK);
CHECK(result->ParseFromString(tree_data));
CHECK_EQ(result->timestamp(), latest_tree_timestamp_);
return this->LOOKUP_OK;
}
// This must be called with "lock_" held.
void FileDB::InsertEntryMapping(int64_t sequence_number, const string& hash) {
if (!id_by_hash_.insert(make_pair(hash, sequence_number)).second) {
// This is a duplicate hash under a new sequence number.
// Make sure we track the entry with the lowest sequence number:
id_by_hash_[hash] = min(id_by_hash_[hash], sequence_number);
}
if (sequence_number == contiguous_size_) {
++contiguous_size_;
for (auto i = sparse_entries_.find(contiguous_size_);
i != sparse_entries_.end() && *i == contiguous_size_;) {
++contiguous_size_;
i = sparse_entries_.erase(i);
}
} else {
// It's not contiguous, put it with the other sparse entries.
CHECK(sparse_entries_.insert(sequence_number).second)
<< "sequence number " << sequence_number << " already assigned.";
}
}
} // namespace cert_trans
#endif // CERT_TRANS_LOG_FILE_DB_INL_H_
|
Add some "using" statements to file_db.cc.
|
Add some "using" statements to file_db.cc.
|
C++
|
apache-2.0
|
AlCutter/certificate-transparency,google/certificate-transparency,AlCutter/certificate-transparency,kyprizel/certificate-transparency,taknira/certificate-transparency,taknira/certificate-transparency,eranmes/certificate-transparency,lexibrent/certificate-transparency,AlCutter/certificate-transparency,kyprizel/certificate-transparency,benlaurie/certificate-transparency,katjoyce/certificate-transparency,eranmes/certificate-transparency,benlaurie/certificate-transparency,katjoyce/certificate-transparency,kyprizel/certificate-transparency,pphaneuf/certificate-transparency,taknira/certificate-transparency,kyprizel/certificate-transparency,grandamp/certificate-transparency,AlCutter/certificate-transparency,eranmes/certificate-transparency,taknira/certificate-transparency,google/certificate-transparency,katjoyce/certificate-transparency,AlCutter/certificate-transparency,eranmes/certificate-transparency,taknira/certificate-transparency,RJPercival/certificate-transparency,phad/certificate-transparency,katjoyce/certificate-transparency,lexibrent/certificate-transparency,RJPercival/certificate-transparency,RJPercival/certificate-transparency,pphaneuf/certificate-transparency,benlaurie/certificate-transparency,eranmes/certificate-transparency,taknira/certificate-transparency,phad/certificate-transparency,grandamp/certificate-transparency,katjoyce/certificate-transparency,google/certificate-transparency,lexibrent/certificate-transparency,pphaneuf/certificate-transparency,AlCutter/certificate-transparency,benlaurie/certificate-transparency,grandamp/certificate-transparency,taknira/certificate-transparency,katjoyce/certificate-transparency,benlaurie/certificate-transparency,lexibrent/certificate-transparency,AlCutter/certificate-transparency,eranmes/certificate-transparency,kyprizel/certificate-transparency,benlaurie/certificate-transparency,kyprizel/certificate-transparency,eranmes/certificate-transparency,phad/certificate-transparency,benlaurie/certificate-transparency,pphaneuf/certificate-transparency,grandamp/certificate-transparency,kyprizel/certificate-transparency,RJPercival/certificate-transparency,phad/certificate-transparency,katjoyce/certificate-transparency,google/certificate-transparency
|
d6a8362538e52c58a79d66839c2318843cb32cef
|
cpp/osg/fog/fog.cc
|
cpp/osg/fog/fog.cc
|
/*
* OSG Fog
*
* Copyright (c) 2015 Jérémie Decock
*
* See "OpenSceneGraph 3.0" by Rui Wang and Xuelei Qian (ed. Packt publishing 2010) p.134
*/
#include <osg/Fog>
#include <osg/Geode>
#include <osg/Group>
#include <osg/ShapeDrawable>
#include <osgViewer/Viewer>
int main(int, char **) {
// Set scenegraph
osg::ref_ptr<osg::Box> p_box = new osg::Box( osg::Vec3(0,0,0), 1.0f );
p_box->setHalfLengths(osg::Vec3(5., 100., 1.));
osg::ref_ptr<osg::ShapeDrawable> p_box_drawable = new osg::ShapeDrawable(p_box);
osg::ref_ptr<osg::Geode> p_geode = new osg::Geode;
p_geode->addDrawable(p_box_drawable);
osg::ref_ptr<osg::Group> p_root = new osg::Group;
p_root->addChild(p_geode);
// Viewer
osgViewer::Viewer viewer;
viewer.setSceneData(p_root);
// Set the fog effect
osg::ref_ptr<osg::Fog> p_fog = new osg::Fog();
p_fog->setMode(osg::Fog::LINEAR); // The fog opacity is linear from "start" to "end" (other modes available are exponential ones)
p_fog->setStart(100.0f); // The fog start at this distance to the camera
p_fog->setEnd(500.0f); // The fog is "complete" at this distance to the camera
p_fog->setColor(viewer.getCamera()->getClearColor()); // The fog color is the same than the one used for the background
//p_fog->setColor(osg::Vec4(0.0f, 0.0f, 1.0f, 1.0f));
// Enable the fog effect
osg::ref_ptr<osg::StateSet> p_state = p_root->getOrCreateStateSet();
p_state->setAttributeAndModes(p_fog.get());
// Run OSG
viewer.run();
return 0;
}
|
/*
* OSG Fog
*
* Copyright (c) 2015 Jérémie Decock
*
* See "OpenSceneGraph 3.0" by Rui Wang and Xuelei Qian (ed. Packt publishing 2010) p.134
*
* Note that this snippet doesn't work when used with shadow techniques:
* http://forum.openscenegraph.org/viewtopic.php?t=6228&view=previous
*/
#include <osg/Fog>
#include <osg/Geode>
#include <osg/Group>
#include <osg/ShapeDrawable>
#include <osgViewer/Viewer>
int main(int, char **) {
// Set scenegraph
osg::ref_ptr<osg::Box> p_box = new osg::Box( osg::Vec3(0,0,0), 1.0f );
p_box->setHalfLengths(osg::Vec3(5., 100., 1.));
osg::ref_ptr<osg::ShapeDrawable> p_box_drawable = new osg::ShapeDrawable(p_box);
osg::ref_ptr<osg::Geode> p_geode = new osg::Geode;
p_geode->addDrawable(p_box_drawable);
osg::ref_ptr<osg::Group> p_root = new osg::Group;
p_root->addChild(p_geode);
// Viewer
osgViewer::Viewer viewer;
viewer.setSceneData(p_root);
// Set the fog effect
osg::ref_ptr<osg::Fog> p_fog = new osg::Fog();
p_fog->setMode(osg::Fog::LINEAR); // The fog opacity is linear from "start" to "end" (other modes available are exponential ones)
p_fog->setStart(100.0f); // The fog start at this distance to the camera
p_fog->setEnd(500.0f); // The fog is "complete" at this distance to the camera
p_fog->setColor(viewer.getCamera()->getClearColor()); // The fog color is the same than the one used for the background
//p_fog->setColor(osg::Vec4(0.0f, 0.0f, 1.0f, 1.0f));
// Enable the fog effect
osg::ref_ptr<osg::StateSet> p_state = p_root->getOrCreateStateSet();
p_state->setAttributeAndModes(p_fog.get());
// Run OSG
viewer.run();
return 0;
}
|
Add a comment.
|
Add a comment.
|
C++
|
mit
|
jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets
|
29d5e43d862a4e7799a33892a0ae163515c37b05
|
libcaf_core/caf/typed_actor.hpp
|
libcaf_core/caf/typed_actor.hpp
|
/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright (C) 2011 - 2015 *
* Dominik Charousset <dominik.charousset (at) haw-hamburg.de> *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#ifndef CAF_TYPED_ACTOR_HPP
#define CAF_TYPED_ACTOR_HPP
#include "caf/intrusive_ptr.hpp"
#include "caf/actor_addr.hpp"
#include "caf/actor_cast.hpp"
#include "caf/replies_to.hpp"
#include "caf/abstract_actor.hpp"
#include "caf/stateful_actor.hpp"
#include "caf/typed_behavior.hpp"
#include "caf/typed_response_promise.hpp"
namespace caf {
class actor_addr;
class local_actor;
struct invalid_actor_addr_t;
template <class... Sigs>
class typed_event_based_actor;
namespace io {
namespace experimental {
template <class... Sigs>
class typed_broker;
} // namespace experimental
} // namespace io
/// Identifies a statically typed actor.
/// @tparam Sigs Signature of this actor as `replies_to<...>::with<...>`
/// parameter pack.
template <class... Sigs>
class typed_actor : detail::comparable<typed_actor<Sigs...>>,
detail::comparable<typed_actor<Sigs...>, actor_addr>,
detail::comparable<typed_actor<Sigs...>, invalid_actor_t>,
detail::comparable<typed_actor<Sigs...>,
invalid_actor_addr_t> {
public:
static_assert(sizeof...(Sigs) > 0, "Empty typed actor handle");
// grant access to private ctor
friend class local_actor;
// friend with all possible instantiations
template <class...>
friend class typed_actor;
// allow conversion via actor_cast
template <class T, typename U>
friend T actor_cast(const U&);
/// Creates a new `typed_actor` type by extending this one with `Es...`.
template <class... Es>
using extend = typed_actor<Sigs..., Es...>;
/// Creates a new `typed_actor` type by extending this one with another
/// `typed_actor`.
template <class T>
using extend_with =
typename detail::extend_with_helper<T, Sigs...>::type;
/// Identifies the behavior type actors of this kind use
/// for their behavior stack.
using behavior_type = typed_behavior<Sigs...>;
/// Identifies pointers to instances of this kind of actor.
using pointer = typed_event_based_actor<Sigs...>*;
/// Identifies the base class for this kind of actor.
using base = typed_event_based_actor<Sigs...>;
/// Identifies pointers to brokers implementing this interface.
using broker_pointer = io::experimental::typed_broker<Sigs...>*;
/// Identifies the base class of brokers implementing this interface.
using broker_base = io::experimental::typed_broker<Sigs...>;
/// Stores the template parameter pack.
using signatures = detail::type_list<Sigs...>;
/// Identifies the base class for this kind of actor with actor.
template <class State>
using stateful_base = stateful_actor<State, base>;
/// Identifies the base class for this kind of actor with actor.
template <class State>
using stateful_pointer = stateful_actor<State, base>*;
/// Identifies the broker_base class for this kind of actor with actor.
template <class State>
using stateful_broker_base =
stateful_actor<State, broker_base>;
/// Identifies the broker_base class for this kind of actor with actor.
template <class State>
using stateful_broker_pointer =
stateful_actor<State, broker_base>*;
typed_actor() = default;
typed_actor(typed_actor&&) = default;
typed_actor(const typed_actor&) = default;
typed_actor& operator=(typed_actor&&) = default;
typed_actor& operator=(const typed_actor&) = default;
template <class TypedActor,
class Enable =
typename std::enable_if<
detail::tlf_is_subset(signatures(),
typename TypedActor::signatures())
>::type>
typed_actor(const TypedActor& other) : ptr_(other.ptr_) {
// nop
}
// allow `handle_type{this}` for typed actors
template <class TypedActor,
class Enable =
typename std::enable_if<
detail::tlf_is_subset(signatures(),
typename TypedActor::signatures())
>::type>
typed_actor(TypedActor* ptr) : ptr_(ptr) {
// nop
}
template <class TypedActor,
class Enable =
typename std::enable_if<
detail::tlf_is_subset(signatures(),
typename TypedActor::signatures())
>::type>
typed_actor& operator=(const TypedActor& other) {
ptr_ = other.ptr_;
return *this;
}
template <class Impl,
class Enable =
typename std::enable_if<
detail::tlf_is_subset(signatures(),
typename Impl::signatures())
>::type>
typed_actor(intrusive_ptr<Impl> other) : ptr_(std::move(other)) {
// nop
}
/// Queries the address of the stored actor.
actor_addr address() const noexcept {
return ptr_ ? ptr_->address() : actor_addr();
}
/// Returns `*this != invalid_actor`.
explicit operator bool() const noexcept {
return static_cast<bool>(ptr_);
}
/// Returns `*this == invalid_actor`.
bool operator!() const noexcept {
return !ptr_;
}
/// Returns the origin node of this actor.
node_id node() const noexcept {
return ptr_ ? ptr_->node() : invalid_node_id;
}
/// Returns the ID of this actor.
actor_id id() const noexcept {
return ptr_ ? ptr_->id() : invalid_actor_id;
}
/// Exchange content of `*this` and `other`.
void swap(actor& other) noexcept {
ptr_.swap(other.ptr_);
}
/// @cond PRIVATE
abstract_actor* operator->() const noexcept {
return ptr_.get();
}
abstract_actor& operator*() const noexcept {
return *ptr_.get();
}
intptr_t compare(const actor_addr& rhs) const noexcept {
return address().compare(rhs);
}
intptr_t compare(const typed_actor& other) const noexcept {
return compare(other.address());
}
intptr_t compare(const invalid_actor_addr_t&) const noexcept {
return ptr_ ? 1 : 0;
}
/// @endcond
private:
abstract_actor* get() const {
return ptr_.get();
}
typed_actor(abstract_actor* ptr) : ptr_(ptr) {
// nop
}
abstract_actor_ptr ptr_;
};
template <class T, class... Ts>
typename std::enable_if<
T::is_saving::value
>::type
serialize(T& sink, typed_actor<Ts...>& hdl, const unsigned int) {
auto addr = hdl.address();
sink << addr;
}
template <class T, class... Ts>
typename std::enable_if<
T::is_loading::value
>::type
serialize(T& sink, typed_actor<Ts...>& hdl, const unsigned int) {
actor_addr addr;
sink >> addr;
hdl = actor_cast<typed_actor<Ts...>>(addr);
}
} // namespace caf
// allow typed_actor to be used in hash maps
namespace std {
template <class... Sigs>
struct hash<caf::typed_actor<Sigs...>> {
size_t operator()(const caf::typed_actor<Sigs...>& ref) const {
return ref ? static_cast<size_t>(ref->id()) : 0;
}
};
} // namespace std
#endif // CAF_TYPED_ACTOR_HPP
|
/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright (C) 2011 - 2015 *
* Dominik Charousset <dominik.charousset (at) haw-hamburg.de> *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#ifndef CAF_TYPED_ACTOR_HPP
#define CAF_TYPED_ACTOR_HPP
#include "caf/intrusive_ptr.hpp"
#include "caf/actor_addr.hpp"
#include "caf/actor_cast.hpp"
#include "caf/replies_to.hpp"
#include "caf/abstract_actor.hpp"
#include "caf/stateful_actor.hpp"
#include "caf/typed_behavior.hpp"
#include "caf/typed_response_promise.hpp"
namespace caf {
class actor_addr;
class local_actor;
struct invalid_actor_addr_t;
template <class... Sigs>
class typed_event_based_actor;
namespace io {
namespace experimental {
template <class... Sigs>
class typed_broker;
} // namespace experimental
} // namespace io
/// Identifies a statically typed actor.
/// @tparam Sigs Signature of this actor as `replies_to<...>::with<...>`
/// parameter pack.
template <class... Sigs>
class typed_actor : detail::comparable<typed_actor<Sigs...>>,
detail::comparable<typed_actor<Sigs...>, actor_addr>,
detail::comparable<typed_actor<Sigs...>, invalid_actor_t>,
detail::comparable<typed_actor<Sigs...>,
invalid_actor_addr_t> {
public:
static_assert(sizeof...(Sigs) > 0, "Empty typed actor handle");
// grant access to private ctor
friend class local_actor;
// friend with all possible instantiations
template <class...>
friend class typed_actor;
// allow conversion via actor_cast
template <class T, typename U>
friend T actor_cast(const U&);
/// Creates a new `typed_actor` type by extending this one with `Es...`.
template <class... Es>
using extend = typed_actor<Sigs..., Es...>;
/// Creates a new `typed_actor` type by extending this one with another
/// `typed_actor`.
template <class T>
using extend_with =
typename detail::extend_with_helper<T, Sigs...>::type;
/// Identifies the behavior type actors of this kind use
/// for their behavior stack.
using behavior_type = typed_behavior<Sigs...>;
/// Identifies pointers to instances of this kind of actor.
using pointer = typed_event_based_actor<Sigs...>*;
/// Identifies the base class for this kind of actor.
using base = typed_event_based_actor<Sigs...>;
/// Identifies pointers to brokers implementing this interface.
using broker_pointer = io::experimental::typed_broker<Sigs...>*;
/// Identifies the base class of brokers implementing this interface.
using broker_base = io::experimental::typed_broker<Sigs...>;
/// Stores the template parameter pack.
using signatures = detail::type_list<Sigs...>;
/// Identifies the base class for this kind of actor with actor.
template <class State>
using stateful_base = stateful_actor<State, base>;
/// Identifies the base class for this kind of actor with actor.
template <class State>
using stateful_pointer = stateful_actor<State, base>*;
/// Identifies the broker_base class for this kind of actor with actor.
template <class State>
using stateful_broker_base =
stateful_actor<State, broker_base>;
/// Identifies the broker_base class for this kind of actor with actor.
template <class State>
using stateful_broker_pointer =
stateful_actor<State, broker_base>*;
typed_actor() = default;
typed_actor(typed_actor&&) = default;
typed_actor(const typed_actor&) = default;
typed_actor& operator=(typed_actor&&) = default;
typed_actor& operator=(const typed_actor&) = default;
template <class TypedActor,
class Enable =
typename std::enable_if<
detail::tlf_is_subset(signatures(),
typename TypedActor::signatures())
>::type>
typed_actor(const TypedActor& other) : ptr_(other.ptr_) {
// nop
}
// allow `handle_type{this}` for typed actors
template <class TypedActor,
class Enable =
typename std::enable_if<
detail::tlf_is_subset(signatures(),
typename TypedActor::signatures())
>::type>
typed_actor(TypedActor* ptr) : ptr_(ptr) {
// nop
}
template <class TypedActor,
class Enable =
typename std::enable_if<
detail::tlf_is_subset(signatures(),
typename TypedActor::signatures())
>::type>
typed_actor& operator=(const TypedActor& other) {
ptr_ = other.ptr_;
return *this;
}
template <class Impl,
class Enable =
typename std::enable_if<
detail::tlf_is_subset(signatures(),
typename Impl::signatures())
>::type>
typed_actor(intrusive_ptr<Impl> other) : ptr_(std::move(other)) {
// nop
}
/// Queries the address of the stored actor.
actor_addr address() const noexcept {
return ptr_ ? ptr_->address() : actor_addr();
}
/// Returns `*this != invalid_actor`.
explicit operator bool() const noexcept {
return static_cast<bool>(ptr_);
}
/// Returns `*this == invalid_actor`.
bool operator!() const noexcept {
return !ptr_;
}
/// Returns the origin node of this actor.
node_id node() const noexcept {
return ptr_ ? ptr_->node() : invalid_node_id;
}
/// Returns the ID of this actor.
actor_id id() const noexcept {
return ptr_ ? ptr_->id() : invalid_actor_id;
}
/// Exchange content of `*this` and `other`.
void swap(actor& other) noexcept {
ptr_.swap(other.ptr_);
}
/// @cond PRIVATE
abstract_actor* operator->() const noexcept {
return ptr_.get();
}
abstract_actor& operator*() const noexcept {
return *ptr_.get();
}
intptr_t compare(const actor_addr& rhs) const noexcept {
return address().compare(rhs);
}
intptr_t compare(const typed_actor& other) const noexcept {
return compare(other.address());
}
intptr_t compare(const invalid_actor_addr_t&) const noexcept {
return ptr_ ? 1 : 0;
}
intptr_t compare(const invalid_actor_t&) const noexcept {
return ptr_ ? 1 : 0;
}
/// @endcond
private:
abstract_actor* get() const {
return ptr_.get();
}
typed_actor(abstract_actor* ptr) : ptr_(ptr) {
// nop
}
abstract_actor_ptr ptr_;
};
template <class T, class... Ts>
typename std::enable_if<
T::is_saving::value
>::type
serialize(T& sink, typed_actor<Ts...>& hdl, const unsigned int) {
auto addr = hdl.address();
sink << addr;
}
template <class T, class... Ts>
typename std::enable_if<
T::is_loading::value
>::type
serialize(T& sink, typed_actor<Ts...>& hdl, const unsigned int) {
actor_addr addr;
sink >> addr;
hdl = actor_cast<typed_actor<Ts...>>(addr);
}
} // namespace caf
// allow typed_actor to be used in hash maps
namespace std {
template <class... Sigs>
struct hash<caf::typed_actor<Sigs...>> {
size_t operator()(const caf::typed_actor<Sigs...>& ref) const {
return ref ? static_cast<size_t>(ref->id()) : 0;
}
};
} // namespace std
#endif // CAF_TYPED_ACTOR_HPP
|
Add missing compare overload to typed_actor
|
Add missing compare overload to typed_actor
|
C++
|
bsd-3-clause
|
nq-ebaratte/actor-framework,nq-ebaratte/actor-framework,1blankz7/actor-framework,DavadDi/actor-framework,actor-framework/actor-framework,actor-framework/actor-framework,nq-ebaratte/actor-framework,actor-framework/actor-framework,nq-ebaratte/actor-framework,DavadDi/actor-framework,1blankz7/actor-framework,actor-framework/actor-framework,1blankz7/actor-framework,DavadDi/actor-framework,DavadDi/actor-framework,1blankz7/actor-framework
|
77409bccbbc3d772bcf813de2ea304c58f51ef0b
|
libgibbs/include/conditions.hpp
|
libgibbs/include/conditions.hpp
|
/*=============================================================================
Copyright (c) 2012-2013 Richard Otis
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)
=============================================================================*/
// header file for thermodynamic state variable declaration
#ifndef INCLUDED_CONDITIONS
#define INCLUDED_CONDITIONS
#include <map>
#include <vector>
#include <cstdint>
#include "libgibbs/include/optimizer/phasestatus.hpp"
struct evalconditions {
std::map<char,double> statevars; // state variable values
std::vector<std::string> elements; // elements under consideration
std::map<std::string,Optimizer::PhaseStatus> phases; // phases under consideration
std::map<std::string,double> xfrac; // system mole fractions
};
//#define SI_GAS_CONSTANT 8.3144621 // J/mol-K; the 2010 CODATA recommended value for molar gas constant
#define SI_GAS_CONSTANT 8.3145 // J/mol-K; Thermo-Calc value
#endif
|
/*=============================================================================
Copyright (c) 2012-2013 Richard Otis
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)
=============================================================================*/
// header file for thermodynamic state variable declaration
#ifndef INCLUDED_CONDITIONS
#define INCLUDED_CONDITIONS
#include <map>
#include <vector>
#include <cstdint>
#include "libgibbs/include/optimizer/phasestatus.hpp"
struct evalconditions {
std::map<char,double> statevars; // state variable values
std::vector<std::string> elements; // elements under consideration
std::map<std::string,Optimizer::PhaseStatus> phases; // phases under consideration
std::map<std::string,double> xfrac; // system mole fractions
};
//#define SI_GAS_CONSTANT 8.3144621 // J/mol-K; the 2010 CODATA recommended value for molar gas constant
constexpr const double SI_GAS_CONSTANT = 8.3145; // J/mol-K; Thermo-Calc value
#endif
|
Switch from #define to constexpr for gas constant
|
Switch from #define to constexpr for gas constant
|
C++
|
mit
|
tkphd/pycalphad,tkphd/pycalphad,tkphd/pycalphad
|
79798932ce53062f050067355e71db917e1894af
|
src/iterator.cpp
|
src/iterator.cpp
|
///
/// @file iterator.cpp
///
/// Copyright (C) 2022 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primesieve/iterator.hpp>
#include <primesieve/IteratorHelper.hpp>
#include <primesieve/PrimeGenerator.hpp>
#include <stdint.h>
#include <vector>
#include <memory>
namespace {
template <typename T>
void clear(std::unique_ptr<T>& ptr)
{
ptr.reset(nullptr);
}
} // namespace
namespace primesieve {
iterator::~iterator() = default;
iterator::iterator(iterator&&) noexcept = default;
iterator& iterator::operator=(iterator&&) noexcept = default;
iterator::iterator(uint64_t start,
uint64_t stop_hint)
{
skipto(start, stop_hint);
}
void iterator::skipto(uint64_t start,
uint64_t stop_hint)
{
start_ = start;
stop_ = start;
stop_hint_ = stop_hint;
i_ = 0;
last_idx_ = 0;
dist_ = 0;
clear(primeGenerator_);
}
void iterator::generate_next_primes()
{
std::size_t size = 0;
while (!size)
{
if (!primeGenerator_)
{
IteratorHelper::next(&start_, &stop_, stop_hint_, &dist_);
auto p = new PrimeGenerator(start_, stop_);
primeGenerator_.reset(p);
}
primeGenerator_->fillNextPrimes(primes_, &size);
// There are 3 different cases here:
// 1) The primes array contains a few primes (<= 512).
// In this case we return the primes to the user.
// 2) The primes array is empty because the next
// prime > stop. In this case we reset the
// primeGenerator object, increase the start & stop
// numbers and sieve the next segment.
// 3) The next prime > 2^64. In this case the primes
// array contains an error code (UINT64_MAX) which
// is returned to the user.
if (size == 0)
clear(primeGenerator_);
}
i_ = 0;
last_idx_ = size - 1;
}
void iterator::generate_prev_primes()
{
// Special case if generate_next_primes() has
// been used before generate_prev_primes().
if (primeGenerator_)
{
assert(!primes_.empty());
start_ = primes_.front();
clear(primeGenerator_);
}
std::size_t size = 0;
while (!size)
{
IteratorHelper::prev(&start_, &stop_, stop_hint_, &dist_);
PrimeGenerator primeGenerator(start_, stop_);
primeGenerator.fillPrevPrimes(primes_, &size);
}
last_idx_ = size - 1;
i_ = last_idx_;
}
} // namespace
|
///
/// @file iterator.cpp
///
/// Copyright (C) 2022 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primesieve/iterator.hpp>
#include <primesieve/IteratorHelper.hpp>
#include <primesieve/PrimeGenerator.hpp>
#include <stdint.h>
#include <vector>
#include <memory>
namespace {
template <typename T>
void clear(std::unique_ptr<T>& ptr)
{
ptr.reset(nullptr);
}
} // namespace
namespace primesieve {
iterator::~iterator() = default;
iterator::iterator(iterator&&) noexcept = default;
iterator& iterator::operator=(iterator&&) noexcept = default;
iterator::iterator(uint64_t start,
uint64_t stop_hint)
{
start_ = start;
stop_ = start;
stop_hint_ = stop_hint;
i_ = 0;
last_idx_ = 0;
dist_ = 0;
}
void iterator::skipto(uint64_t start,
uint64_t stop_hint)
{
start_ = start;
stop_ = start;
stop_hint_ = stop_hint;
i_ = 0;
last_idx_ = 0;
dist_ = 0;
clear(primeGenerator_);
}
void iterator::generate_next_primes()
{
std::size_t size = 0;
while (!size)
{
if (!primeGenerator_)
{
IteratorHelper::next(&start_, &stop_, stop_hint_, &dist_);
auto p = new PrimeGenerator(start_, stop_);
primeGenerator_.reset(p);
}
primeGenerator_->fillNextPrimes(primes_, &size);
// There are 3 different cases here:
// 1) The primes array contains a few primes (<= 512).
// In this case we return the primes to the user.
// 2) The primes array is empty because the next
// prime > stop. In this case we reset the
// primeGenerator object, increase the start & stop
// numbers and sieve the next segment.
// 3) The next prime > 2^64. In this case the primes
// array contains an error code (UINT64_MAX) which
// is returned to the user.
if (size == 0)
clear(primeGenerator_);
}
i_ = 0;
last_idx_ = size - 1;
}
void iterator::generate_prev_primes()
{
// Special case if generate_next_primes() has
// been used before generate_prev_primes().
if (primeGenerator_)
{
assert(!primes_.empty());
start_ = primes_.front();
clear(primeGenerator_);
}
std::size_t size = 0;
while (!size)
{
IteratorHelper::prev(&start_, &stop_, stop_hint_, &dist_);
PrimeGenerator primeGenerator(start_, stop_);
primeGenerator.fillPrevPrimes(primes_, &size);
}
last_idx_ = size - 1;
i_ = last_idx_;
}
} // namespace
|
Improve constructor
|
Improve constructor
|
C++
|
bsd-2-clause
|
kimwalisch/primesieve,kimwalisch/primesieve,kimwalisch/primesieve
|
6fdfba6ff9829a1102d410437c2b9ca2e1b6c7b7
|
src/keystore.cpp
|
src/keystore.cpp
|
// Copyright (c) 2009-2011 Satoshi Nakamoto & Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file license.txt or http://www.opensource.org/licenses/mit-license.php.
#include "headers.h"
#include "db.h"
#include "crypter.h"
std::vector<unsigned char> CKeyStore::GenerateNewKey()
{
RandAddSeedPerfmon();
CKey key;
key.MakeNewKey();
if (!AddKey(key))
throw std::runtime_error("CKeyStore::GenerateNewKey() : AddKey failed");
return key.GetPubKey();
}
bool CKeyStore::GetPubKey(const CBitcoinAddress &address, std::vector<unsigned char> &vchPubKeyOut) const
{
CKey key;
if (!GetKey(address, key))
return false;
vchPubKeyOut = key.GetPubKey();
return true;
}
bool CBasicKeyStore::AddKey(const CKey& key)
{
CRITICAL_BLOCK(cs_KeyStore)
mapKeys[key.GetAddress()] = key.GetSecret();
return true;
}
std::vector<unsigned char> CCryptoKeyStore::GenerateNewKey()
{
RandAddSeedPerfmon();
CKey key;
key.MakeNewKey();
if (!AddKey(key))
throw std::runtime_error("CCryptoKeyStore::GenerateNewKey() : AddKey failed");
return key.GetPubKey();
}
bool CCryptoKeyStore::Unlock(const CKeyingMaterial& vMasterKeyIn)
{
CRITICAL_BLOCK(cs_vMasterKey)
{
if (!SetCrypted())
return false;
CryptedKeyMap::const_iterator mi = mapCryptedKeys.begin();
for (; mi != mapCryptedKeys.end(); ++mi)
{
const std::vector<unsigned char> &vchPubKey = (*mi).second.first;
const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
CSecret vchSecret;
if(!DecryptSecret(vMasterKeyIn, vchCryptedSecret, Hash(vchPubKey.begin(), vchPubKey.end()), vchSecret))
return false;
CKey key;
key.SetSecret(vchSecret);
if (key.GetPubKey() == vchPubKey)
break;
return false;
}
vMasterKey = vMasterKeyIn;
}
return true;
}
bool CCryptoKeyStore::AddKey(const CKey& key)
{
CRITICAL_BLOCK(cs_KeyStore)
CRITICAL_BLOCK(cs_vMasterKey)
{
if (!IsCrypted())
return CBasicKeyStore::AddKey(key);
if (IsLocked())
return false;
std::vector<unsigned char> vchCryptedSecret;
std::vector<unsigned char> vchPubKey = key.GetPubKey();
if (!EncryptSecret(vMasterKey, key.GetSecret(), Hash(vchPubKey.begin(), vchPubKey.end()), vchCryptedSecret))
return false;
if (!AddCryptedKey(key.GetPubKey(), vchCryptedSecret))
return false;
}
return true;
}
bool CCryptoKeyStore::AddCryptedKey(const std::vector<unsigned char> &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
{
CRITICAL_BLOCK(cs_KeyStore)
{
if (!SetCrypted())
return false;
mapCryptedKeys[CBitcoinAddress(vchPubKey)] = make_pair(vchPubKey, vchCryptedSecret);
}
return true;
}
bool CCryptoKeyStore::GetKey(const CBitcoinAddress &address, CKey& keyOut) const
{
CRITICAL_BLOCK(cs_vMasterKey)
{
if (!IsCrypted())
return CBasicKeyStore::GetKey(address, keyOut);
CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
if (mi != mapCryptedKeys.end())
{
const std::vector<unsigned char> &vchPubKey = (*mi).second.first;
const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
CSecret vchSecret;
if (!DecryptSecret(vMasterKey, vchCryptedSecret, Hash(vchPubKey.begin(), vchPubKey.end()), vchSecret))
return false;
keyOut.SetSecret(vchSecret);
return true;
}
}
return false;
}
bool CCryptoKeyStore::GetPubKey(const CBitcoinAddress &address, std::vector<unsigned char>& vchPubKeyOut) const
{
CRITICAL_BLOCK(cs_vMasterKey)
{
if (!IsCrypted())
return CKeyStore::GetPubKey(address, vchPubKeyOut);
CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
if (mi != mapCryptedKeys.end())
{
vchPubKeyOut = (*mi).second.first;
return true;
}
}
return false;
}
bool CCryptoKeyStore::EncryptKeys(CKeyingMaterial& vMasterKeyIn)
{
CRITICAL_BLOCK(cs_KeyStore)
CRITICAL_BLOCK(cs_vMasterKey)
{
if (!mapCryptedKeys.empty() || IsCrypted())
return false;
fUseCrypto = true;
CKey key;
BOOST_FOREACH(KeyMap::value_type& mKey, mapKeys)
{
if (!key.SetPrivKey(mKey.second))
return false;
const std::vector<unsigned char> vchPubKey = key.GetPubKey();
std::vector<unsigned char> vchCryptedSecret;
if (!EncryptSecret(vMasterKeyIn, key.GetSecret(), Hash(vchPubKey.begin(), vchPubKey.end()), vchCryptedSecret))
return false;
if (!AddCryptedKey(vchPubKey, vchCryptedSecret))
return false;
}
mapKeys.clear();
}
return true;
}
|
// Copyright (c) 2009-2011 Satoshi Nakamoto & Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file license.txt or http://www.opensource.org/licenses/mit-license.php.
#include "headers.h"
#include "db.h"
#include "crypter.h"
std::vector<unsigned char> CKeyStore::GenerateNewKey()
{
RandAddSeedPerfmon();
CKey key;
key.MakeNewKey();
if (!AddKey(key))
throw std::runtime_error("CKeyStore::GenerateNewKey() : AddKey failed");
return key.GetPubKey();
}
bool CKeyStore::GetPubKey(const CBitcoinAddress &address, std::vector<unsigned char> &vchPubKeyOut) const
{
CKey key;
if (!GetKey(address, key))
return false;
vchPubKeyOut = key.GetPubKey();
return true;
}
bool CBasicKeyStore::AddKey(const CKey& key)
{
CRITICAL_BLOCK(cs_KeyStore)
mapKeys[key.GetAddress()] = key.GetSecret();
return true;
}
std::vector<unsigned char> CCryptoKeyStore::GenerateNewKey()
{
RandAddSeedPerfmon();
CKey key;
key.MakeNewKey();
if (!AddKey(key))
throw std::runtime_error("CCryptoKeyStore::GenerateNewKey() : AddKey failed");
return key.GetPubKey();
}
bool CCryptoKeyStore::Unlock(const CKeyingMaterial& vMasterKeyIn)
{
CRITICAL_BLOCK(cs_vMasterKey)
{
if (!SetCrypted())
return false;
CryptedKeyMap::const_iterator mi = mapCryptedKeys.begin();
for (; mi != mapCryptedKeys.end(); ++mi)
{
const std::vector<unsigned char> &vchPubKey = (*mi).second.first;
const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
CSecret vchSecret;
if(!DecryptSecret(vMasterKeyIn, vchCryptedSecret, Hash(vchPubKey.begin(), vchPubKey.end()), vchSecret))
return false;
CKey key;
key.SetSecret(vchSecret);
if (key.GetPubKey() == vchPubKey)
break;
return false;
}
vMasterKey = vMasterKeyIn;
}
return true;
}
bool CCryptoKeyStore::AddKey(const CKey& key)
{
CRITICAL_BLOCK(cs_KeyStore)
CRITICAL_BLOCK(cs_vMasterKey)
{
if (!IsCrypted())
return CBasicKeyStore::AddKey(key);
if (IsLocked())
return false;
std::vector<unsigned char> vchCryptedSecret;
std::vector<unsigned char> vchPubKey = key.GetPubKey();
if (!EncryptSecret(vMasterKey, key.GetSecret(), Hash(vchPubKey.begin(), vchPubKey.end()), vchCryptedSecret))
return false;
if (!AddCryptedKey(key.GetPubKey(), vchCryptedSecret))
return false;
}
return true;
}
bool CCryptoKeyStore::AddCryptedKey(const std::vector<unsigned char> &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
{
CRITICAL_BLOCK(cs_KeyStore)
{
if (!SetCrypted())
return false;
mapCryptedKeys[CBitcoinAddress(vchPubKey)] = make_pair(vchPubKey, vchCryptedSecret);
}
return true;
}
bool CCryptoKeyStore::GetKey(const CBitcoinAddress &address, CKey& keyOut) const
{
CRITICAL_BLOCK(cs_vMasterKey)
{
if (!IsCrypted())
return CBasicKeyStore::GetKey(address, keyOut);
CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
if (mi != mapCryptedKeys.end())
{
const std::vector<unsigned char> &vchPubKey = (*mi).second.first;
const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
CSecret vchSecret;
if (!DecryptSecret(vMasterKey, vchCryptedSecret, Hash(vchPubKey.begin(), vchPubKey.end()), vchSecret))
return false;
keyOut.SetSecret(vchSecret);
return true;
}
}
return false;
}
bool CCryptoKeyStore::GetPubKey(const CBitcoinAddress &address, std::vector<unsigned char>& vchPubKeyOut) const
{
CRITICAL_BLOCK(cs_vMasterKey)
{
if (!IsCrypted())
return CKeyStore::GetPubKey(address, vchPubKeyOut);
CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
if (mi != mapCryptedKeys.end())
{
vchPubKeyOut = (*mi).second.first;
return true;
}
}
return false;
}
bool CCryptoKeyStore::EncryptKeys(CKeyingMaterial& vMasterKeyIn)
{
CRITICAL_BLOCK(cs_KeyStore)
CRITICAL_BLOCK(cs_vMasterKey)
{
if (!mapCryptedKeys.empty() || IsCrypted())
return false;
fUseCrypto = true;
CKey key;
BOOST_FOREACH(KeyMap::value_type& mKey, mapKeys)
{
if (!key.SetSecret(mKey.second))
return false;
const std::vector<unsigned char> vchPubKey = key.GetPubKey();
std::vector<unsigned char> vchCryptedSecret;
if (!EncryptSecret(vMasterKeyIn, key.GetSecret(), Hash(vchPubKey.begin(), vchPubKey.end()), vchCryptedSecret))
return false;
if (!AddCryptedKey(vchPubKey, vchCryptedSecret))
return false;
}
mapKeys.clear();
}
return true;
}
|
Fix EncryptKeys crash introduced by a9ba4710, identified by TD.
|
Fix EncryptKeys crash introduced by a9ba4710, identified by TD.
|
C++
|
mit
|
MidasPaymentLTD/midascoin,MidasPaymentLTD/midascoin,MidasPaymentLTD/midascoin,MidasPaymentLTD/midascoin,MidasPaymentLTD/midascoin
|
a25d5abfce1634419a90761ec49f4411f5f201ff
|
workbench/src/mnist_rnn_perf.cpp
|
workbench/src/mnist_rnn_perf.cpp
|
//=======================================================================
// Copyright (c) 2014-2020 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#define ETL_COUNTERS
#define ETL_GPU_POOL
#include "dll/neural/dense/dense_layer.hpp"
#include "dll/neural/rnn/rnn_layer.hpp"
#include "dll/neural/recurrent/recurrent_last_layer.hpp"
#include "dll/network.hpp"
#include "dll/datasets.hpp"
int main(int /*argc*/, char* /*argv*/ []) {
// Load the dataset
auto dataset = dll::make_mnist_dataset_nc(dll::batch_size<200>{}, dll::scale_pre<255>{});
constexpr size_t time_steps = 28;
constexpr size_t sequence_length = 28;
constexpr size_t hidden_units = 200;
// Build the network
using network_t = dll::network_desc<
dll::network_layers<
dll::rnn_layer<time_steps, sequence_length, hidden_units>,
dll::recurrent_last_layer<time_steps, hidden_units>,
dll::dense_layer<hidden_units, 10, dll::softmax>
>
, dll::updater<dll::updater_type::ADAM> // Adam
, dll::batch_size<200> // The mini-batch size
, dll::no_batch_display // Disable pretty print of each every batch
, dll::no_epoch_error // Disable computation of the error at each epoch
>::network_t;
auto net = std::make_unique<network_t>();
// Display the network and dataset
net->display_pretty();
dataset.display_pretty();
// Train the network for performance sake
net->train(dataset.train(), 5);
// Test the network on test set
net->evaluate(dataset.test());
// Show where the time was spent
dll::dump_timers_pretty();
// Show ETL performance counters
etl::dump_counters_pretty();
return 0;
}
|
//=======================================================================
// Copyright (c) 2014-2020 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#define ETL_COUNTERS
#define ETL_GPU_POOL
#include "dll/neural/dense/dense_layer.hpp"
#include "dll/neural/rnn/rnn_layer.hpp"
#include "dll/neural/recurrent/recurrent_last_layer.hpp"
#include "dll/network.hpp"
#include "dll/datasets.hpp"
int main(int /*argc*/, char* /*argv*/ []) {
// Load the dataset
auto dataset = dll::make_mnist_dataset_nc(dll::batch_size<200>{}, dll::scale_pre<255>{});
constexpr size_t time_steps = 28;
constexpr size_t sequence_length = 28;
constexpr size_t hidden_units = 200;
// Build the network
using network_t = dll::network_desc<
dll::network_layers<
dll::rnn_layer<time_steps, sequence_length, hidden_units, dll::last_only>,
dll::recurrent_last_layer<time_steps, hidden_units>,
dll::dense_layer<hidden_units, 10, dll::softmax>
>
, dll::updater<dll::updater_type::ADAM> // Adam
, dll::batch_size<200> // The mini-batch size
, dll::no_batch_display // Disable pretty print of each every batch
, dll::no_epoch_error // Disable computation of the error at each epoch
>::network_t;
auto net = std::make_unique<network_t>();
// Display the network and dataset
net->display_pretty();
dataset.display_pretty();
// Train the network for performance sake
net->train(dataset.train(), 5);
// Test the network on test set
net->evaluate(dataset.test());
// Show where the time was spent
dll::dump_timers_pretty();
// Show ETL performance counters
etl::dump_counters_pretty();
return 0;
}
|
Complete the rnn_perf test
|
Complete the rnn_perf test
|
C++
|
mit
|
wichtounet/dll,wichtounet/dll,wichtounet/dll
|
7d52b06cf8756d5fbf75dfba4e0a8e74bca29705
|
elang/compiler/cg/cfg_to_ssa_transformer.cc
|
elang/compiler/cg/cfg_to_ssa_transformer.cc
|
// Copyright 2014-2015 Project Vogue. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "elang/compiler/cg/cfg_to_ssa_transformer.h"
#include <unordered_set>
#include <vector>
#include "elang/base/zone_user.h"
#include "elang/base/zone_owner.h"
#include "elang/compiler/cg/variable_usages.h"
#include "elang/hir/analysis/dominator_tree_builder.h"
#include "elang/hir/editor.h"
#include "elang/hir/instructions.h"
#include "elang/hir/instruction_visitor.h"
#include "elang/hir/values.h"
namespace elang {
namespace compiler {
namespace {
//////////////////////////////////////////////////////////////////////
//
// RenameStack
//
class RenameStack final : public ZoneAllocated {
public:
explicit RenameStack(Zone* zone) : stack_(zone) {}
hir::Value* top() const { return stack_.back(); }
void Pop() { stack_.pop_back(); }
void Push(hir::Value* value) { stack_.push_back(value); }
private:
~RenameStack() = delete;
ZoneVector<hir::Value*> stack_;
DISALLOW_COPY_AND_ASSIGN(RenameStack);
};
//////////////////////////////////////////////////////////////////////
//
// RenameStackContainer
//
class RenameStackContainer final : public ZoneUser {
public:
explicit RenameStackContainer(Zone* zone);
~RenameStackContainer() = default;
RenameStack* stack_for(hir::Value* value) const;
void AssociatePhiToVariable(hir::PhiInstruction* phi, hir::Instruction* home);
void DidEnterBlock(std::vector<RenameStack*>* kill_list);
void DidExitBlock(std::vector<RenameStack*>* kill_list);
void DidPush(RenameStack* rename_stack);
void RegisterVariable(hir::Instruction* home);
private:
std::vector<RenameStack*>* kill_list_;
std::unordered_map<hir::Instruction*, RenameStack*> map_;
DISALLOW_COPY_AND_ASSIGN(RenameStackContainer);
};
RenameStackContainer::RenameStackContainer(Zone* zone)
: ZoneUser(zone), kill_list_(nullptr) {
}
RenameStack* RenameStackContainer::stack_for(hir::Value* value) const {
auto const home = value->as<hir::Instruction>();
if (!home)
return nullptr;
auto const it = map_.find(home);
return it == map_.end() ? nullptr : it->second;
}
void RenameStackContainer::AssociatePhiToVariable(hir::PhiInstruction* phi,
hir::Instruction* home) {
DCHECK(!map_.count(phi));
DCHECK(map_.count(home));
map_[phi] = map_[home];
}
void RenameStackContainer::DidEnterBlock(std::vector<RenameStack*>* kill_list) {
DCHECK(!kill_list_);
kill_list_ = kill_list;
}
void RenameStackContainer::DidExitBlock(std::vector<RenameStack*>* kill_list) {
DCHECK(kill_list_);
for (auto const rename_stack : *kill_list)
rename_stack->Pop();
kill_list_ = nullptr;
}
void RenameStackContainer::DidPush(RenameStack* rename_stack) {
kill_list_->push_back(rename_stack);
}
void RenameStackContainer::RegisterVariable(hir::Instruction* home) {
DCHECK(!map_.count(home));
map_[home] = new (zone()) RenameStack(zone());
}
} // namespace
//////////////////////////////////////////////////////////////////////
//
// CfgToSsaTransformer::Impl
//
class CfgToSsaTransformer::Impl final : public hir::InstructionVisitor,
public ZoneOwner {
public:
Impl(hir::Factory* factory,
hir::Function* function,
const VariableUsages* variable_usages);
~Impl() final {}
void Run();
private:
hir::Editor* editor() { return &editor_; }
hir::Instruction* GetHomeFor(hir::PhiInstruction* phi) const;
void InsertPhi(hir::BasicBlock* block, const VariableUsages::Data* data);
void InsertPhis(const VariableUsages::Data* data);
void RenameVariables(hir::BasicBlock* block);
// hir::InstructionVisitor
void VisitLoad(hir::LoadInstruction* instr) final;
void VisitPhi(hir::PhiInstruction* instr) final;
void VisitStore(hir::StoreInstruction* instr) final;
hir::Editor editor_;
hir::DominatorTree* const dominator_tree_;
RenameStackContainer rename_tracker_;
const VariableUsages* const variable_usages_;
std::unordered_map<const VariableUsages*, RenameStack*> rename_map_;
std::unordered_map<hir::Value*, const VariableUsages::Data*> home_map_;
DISALLOW_COPY_AND_ASSIGN(Impl);
};
CfgToSsaTransformer::Impl::Impl(hir::Factory* factory,
hir::Function* function,
const VariableUsages* variable_usages)
: editor_(factory, function),
dominator_tree_(hir::ComputeDominatorTree(zone(), function)),
rename_tracker_(zone()),
variable_usages_(variable_usages) {
}
hir::Instruction* CfgToSsaTransformer::Impl::GetHomeFor(
hir::PhiInstruction* phi) const {
auto const it = home_map_.find(phi);
return it == home_map_.end() ? nullptr : it->second->home();
}
void CfgToSsaTransformer::Impl::InsertPhi(hir::BasicBlock* block,
const VariableUsages::Data* data) {
editor()->Edit(block);
auto const phi = editor()->NewPhi(data->type());
rename_tracker_.AssociatePhiToVariable(phi, data->home());
editor()->Commit();
}
void CfgToSsaTransformer::Impl::InsertPhis(const VariableUsages::Data* data) {
if (data->is_local())
return;
auto const home = data->home();
rename_tracker_.RegisterVariable(home);
std::unordered_set<hir::BasicBlock*> work_set;
// Initialize work list
for (auto const frontier :
dominator_tree_->node_of(editor()->entry_block())->frontiers()) {
work_set.insert(frontier->value()->as<hir::BasicBlock>());
}
// Add all variable change to work list
for (auto const user : home->users()) {
if (!user->instruction()->is<hir::StoreInstruction>())
continue;
auto const using_block = user->instruction()->basic_block();
if (work_set.count(using_block))
continue;
for (auto const frontier :
dominator_tree_->node_of(using_block)->frontiers()) {
work_set.insert(frontier->value()->as<hir::BasicBlock>());
}
}
std::vector<hir::BasicBlock*> work_list(work_set.begin(), work_set.end());
while (!work_list.empty()) {
auto const block = work_list.back();
work_list.pop_back();
InsertPhi(block, data);
for (auto const frontier : dominator_tree_->node_of(block)->frontiers()) {
auto const frontier_block = frontier->value()->as<hir::BasicBlock>();
if (work_set.count(frontier_block))
continue;
work_set.insert(frontier_block);
work_list.push_back(frontier_block);
}
}
}
void CfgToSsaTransformer::Impl::RenameVariables(hir::BasicBlock* block) {
std::vector<RenameStack*> kill_list;
rename_tracker_.DidEnterBlock(&kill_list);
editor()->Edit(block);
for (auto const phi : block->phi_instructions())
VisitPhi(phi);
for (auto const instruction : block->instructions())
instruction->Accept(this);
editor()->Commit();
// Update `phi` instructions in successors
for (auto const successor : block->successors()) {
editor()->Edit(successor);
for (auto const phi : successor->phi_instructions()) {
auto const rename_stack = rename_tracker_.stack_for(phi);
if (!rename_stack)
continue;
editor()->SetPhiInput(phi, block, rename_stack->top());
}
editor()->Commit();
}
for (auto const child : dominator_tree_->node_of(block)->children())
RenameVariables(child->value()->as<hir::BasicBlock>());
rename_tracker_.DidExitBlock(&kill_list);
}
// The entry point of CFG to SSA transformer.
void CfgToSsaTransformer::Impl::Run() {
// TODO(eval1749) If |function_| have exception handlers, we should analyze
// liveness of variables.
for (auto const variable_data :
variable_usages_->local_variables_of(editor()->function())) {
InsertPhis(variable_data);
}
RenameVariables(editor()->entry_block());
}
// hir::InstructionVisitor
void CfgToSsaTransformer::Impl::VisitLoad(hir::LoadInstruction* instr) {
auto const rename_stack = rename_tracker_.stack_for(instr->input(0));
if (!rename_stack)
return;
// Replace all uses of `load` instruction |instr| by top of rename stack.
auto const value = rename_stack->top();
for (auto const user : instr->users())
user->SetValue(value);
editor()->Edit(instr->basic_block());
editor()->RemoveInstruction(instr);
editor()->Commit();
}
void CfgToSsaTransformer::Impl::VisitPhi(hir::PhiInstruction* instr) {
auto const rename_stack = rename_tracker_.stack_for(instr);
if (!rename_stack)
return;
rename_stack->Push(instr);
}
void CfgToSsaTransformer::Impl::VisitStore(hir::StoreInstruction* instr) {
auto const rename_stack = rename_tracker_.stack_for(instr->input(0));
if (!rename_stack)
return;
rename_stack->Push(instr->input(1));
editor()->Edit(instr->basic_block());
editor()->RemoveInstruction(instr);
editor()->Commit();
}
//////////////////////////////////////////////////////////////////////
//
// CfgToSsaTransformer
//
CfgToSsaTransformer::CfgToSsaTransformer(hir::Factory* factory,
hir::Function* function,
const VariableUsages* usages)
: impl_(new Impl(factory, function, usages)) {
}
CfgToSsaTransformer::~CfgToSsaTransformer() {
}
void CfgToSsaTransformer::Run() {
impl_->Run();
}
} // namespace compiler
} // namespace elang
|
// Copyright 2014-2015 Project Vogue. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "elang/compiler/cg/cfg_to_ssa_transformer.h"
#include <unordered_set>
#include <vector>
#include "elang/base/zone_user.h"
#include "elang/base/zone_owner.h"
#include "elang/compiler/cg/variable_usages.h"
#include "elang/hir/analysis/dominator_tree_builder.h"
#include "elang/hir/editor.h"
#include "elang/hir/instructions.h"
#include "elang/hir/instruction_visitor.h"
#include "elang/hir/values.h"
namespace elang {
namespace compiler {
namespace {
//////////////////////////////////////////////////////////////////////
//
// RenameStack
//
class RenameStack final : public ZoneAllocated {
public:
explicit RenameStack(Zone* zone) : stack_(zone) {}
hir::Value* top() const { return stack_.back(); }
void Pop() { stack_.pop_back(); }
void Push(hir::Value* value) { stack_.push_back(value); }
private:
~RenameStack() = delete;
ZoneVector<hir::Value*> stack_;
DISALLOW_COPY_AND_ASSIGN(RenameStack);
};
//////////////////////////////////////////////////////////////////////
//
// Renamer
//
class Renamer final : public ZoneUser, public hir::InstructionVisitor {
public:
Renamer(Zone* zone,
hir::Editor* editor,
const hir::DominatorTree* dominator_tree);
~Renamer() final = default;
void RegisterPhi(hir::PhiInstruction* phi, hir::Instruction* home);
void RegisterVariable(hir::Instruction* home);
void Run();
private:
class RenameScope {
public:
explicit RenameScope(Renamer* passlet);
~RenameScope();
private:
std::vector<RenameStack*> kill_list_;
Renamer* const pass_;
DISALLOW_COPY_AND_ASSIGN(RenameScope);
};
hir::Editor* editor() const { return editor_; }
RenameStack* stack_for(hir::Value* value) const;
void DidPush(RenameStack* rename_stack);
void RenameVariables(hir::BasicBlock* block);
// hir::InstructionVisitor
void VisitLoad(hir::LoadInstruction* instr) final;
void VisitPhi(hir::PhiInstruction* instr) final;
void VisitStore(hir::StoreInstruction* instr) final;
const hir::DominatorTree* dominator_tree_;
hir::Editor* const editor_;
std::vector<RenameStack*>* kill_list_;
std::unordered_map<hir::Instruction*, RenameStack*> map_;
DISALLOW_COPY_AND_ASSIGN(Renamer);
};
Renamer::RenameScope::RenameScope(Renamer* pass) : pass_(pass) {
pass_->kill_list_ = &kill_list_;
}
Renamer::RenameScope::~RenameScope() {
pass_->kill_list_ = nullptr;
for (auto const rename_stack : kill_list_)
rename_stack->Pop();
}
Renamer::Renamer(Zone* zone,
hir::Editor* editor,
const hir::DominatorTree* dominator_tree)
: ZoneUser(zone),
dominator_tree_(dominator_tree),
editor_(editor),
kill_list_(nullptr) {
}
RenameStack* Renamer::stack_for(hir::Value* value) const {
auto const home = value->as<hir::Instruction>();
if (!home)
return nullptr;
auto const it = map_.find(home);
return it == map_.end() ? nullptr : it->second;
}
void Renamer::DidPush(RenameStack* rename_stack) {
kill_list_->push_back(rename_stack);
}
void Renamer::RegisterPhi(hir::PhiInstruction* phi, hir::Instruction* home) {
DCHECK(!map_.count(phi));
DCHECK(map_.count(home));
map_[phi] = map_[home];
}
void Renamer::RegisterVariable(hir::Instruction* home) {
DCHECK(!map_.count(home));
map_[home] = new (zone()) RenameStack(zone());
}
void Renamer::RenameVariables(hir::BasicBlock* block) {
RenameScope rename_scope(this);
{
hir::Editor::ScopedEdit edit_scope(editor(), block);
for (auto const phi : block->phi_instructions())
VisitPhi(phi);
// Since |instruction| can be removed during visiting, we advance iterator
// before calling visiting function.
auto& instructions = block->instructions();
for (auto it = instructions.begin(); it != instructions.end();) {
auto const instruction = *it;
++it;
instruction->Accept(this);
}
}
// Update `phi` instructions in successors
for (auto const successor : block->successors()) {
hir::Editor::ScopedEdit edit_scope(editor(), successor);
for (auto const phi : successor->phi_instructions()) {
auto const rename_stack = stack_for(phi);
if (!rename_stack)
continue;
editor()->SetPhiInput(phi, block, rename_stack->top());
}
}
for (auto const child : dominator_tree_->node_of(block)->children())
RenameVariables(child->value()->as<hir::BasicBlock>());
}
// The entry point of |Renamer|.
void Renamer::Run() {
RenameVariables(editor()->entry_block());
}
// hir::InstructionVisitor
void Renamer::VisitLoad(hir::LoadInstruction* instr) {
auto const rename_stack = stack_for(instr->input(0));
if (!rename_stack)
return;
editor()->ReplaceAll(rename_stack->top(), instr);
}
void Renamer::VisitPhi(hir::PhiInstruction* instr) {
auto const rename_stack = stack_for(instr);
if (!rename_stack)
return;
rename_stack->Push(instr);
}
void Renamer::VisitStore(hir::StoreInstruction* instr) {
auto const rename_stack = stack_for(instr->input(0));
if (!rename_stack)
return;
rename_stack->Push(instr->input(1));
editor()->RemoveInstruction(instr);
}
} // namespace
//////////////////////////////////////////////////////////////////////
//
// CfgToSsaTransformer::Impl
//
class CfgToSsaTransformer::Impl final : public ZoneOwner {
public:
Impl(hir::Factory* factory,
hir::Function* function,
const VariableUsages* variable_usages);
~Impl() = default;
void Run();
private:
hir::Editor* editor() { return &editor_; }
hir::Instruction* GetHomeFor(hir::PhiInstruction* phi) const;
void InsertPhi(hir::BasicBlock* block, const VariableUsages::Data* data);
void InsertPhis(const VariableUsages::Data* data);
hir::Editor editor_;
hir::DominatorTree* const dominator_tree_;
Renamer rename_passlet_;
const VariableUsages* const variable_usages_;
std::unordered_map<const VariableUsages*, RenameStack*> rename_map_;
std::unordered_map<hir::Value*, const VariableUsages::Data*> home_map_;
DISALLOW_COPY_AND_ASSIGN(Impl);
};
CfgToSsaTransformer::Impl::Impl(hir::Factory* factory,
hir::Function* function,
const VariableUsages* variable_usages)
: editor_(factory, function),
dominator_tree_(hir::ComputeDominatorTree(zone(), function)),
rename_passlet_(zone(), &editor_, dominator_tree_),
variable_usages_(variable_usages) {
}
hir::Instruction* CfgToSsaTransformer::Impl::GetHomeFor(
hir::PhiInstruction* phi) const {
auto const it = home_map_.find(phi);
return it == home_map_.end() ? nullptr : it->second->home();
}
void CfgToSsaTransformer::Impl::InsertPhi(hir::BasicBlock* block,
const VariableUsages::Data* data) {
editor()->Edit(block);
auto const phi = editor()->NewPhi(data->type());
rename_passlet_.RegisterPhi(phi, data->home());
editor()->Commit();
}
void CfgToSsaTransformer::Impl::InsertPhis(const VariableUsages::Data* data) {
auto const home = data->home();
rename_passlet_.RegisterVariable(home);
if (data->is_local())
return;
std::unordered_set<hir::BasicBlock*> work_set;
// Initialize work list
for (auto const frontier :
dominator_tree_->node_of(editor()->entry_block())->frontiers()) {
work_set.insert(frontier->value()->as<hir::BasicBlock>());
}
// Add all variable change to work list
for (auto const user : home->users()) {
if (!user->instruction()->is<hir::StoreInstruction>())
continue;
auto const using_block = user->instruction()->basic_block();
if (work_set.count(using_block))
continue;
for (auto const frontier :
dominator_tree_->node_of(using_block)->frontiers()) {
work_set.insert(frontier->value()->as<hir::BasicBlock>());
}
}
std::vector<hir::BasicBlock*> work_list(work_set.begin(), work_set.end());
while (!work_list.empty()) {
auto const block = work_list.back();
work_list.pop_back();
InsertPhi(block, data);
for (auto const frontier : dominator_tree_->node_of(block)->frontiers()) {
auto const frontier_block = frontier->value()->as<hir::BasicBlock>();
if (work_set.count(frontier_block))
continue;
work_set.insert(frontier_block);
work_list.push_back(frontier_block);
}
}
}
// The entry point of CFG to SSA transformer.
void CfgToSsaTransformer::Impl::Run() {
// TODO(eval1749) If |function_| have exception handlers, we should analyze
// liveness of variables.
for (auto const variable_data :
variable_usages_->local_variables_of(editor()->function())) {
InsertPhis(variable_data);
}
// Rename variables
rename_passlet_.Run();
// Remove variable home maker instructions.
for (auto const variable_data :
variable_usages_->local_variables_of(editor()->function())) {
auto const home = variable_data->home();
auto const home_block = home->basic_block();
if (!editor()->basic_block()) {
editor()->Edit(home_block);
} else if (editor()->basic_block() != home_block) {
editor()->Commit();
editor()->Edit(home_block);
}
editor()->RemoveInstruction(home);
}
if (!editor()->basic_block())
return;
editor()->Commit();
}
//////////////////////////////////////////////////////////////////////
//
// CfgToSsaTransformer
//
CfgToSsaTransformer::CfgToSsaTransformer(hir::Factory* factory,
hir::Function* function,
const VariableUsages* usages)
: impl_(new Impl(factory, function, usages)) {
}
CfgToSsaTransformer::~CfgToSsaTransformer() {
}
void CfgToSsaTransformer::Run() {
impl_->Run();
}
} // namespace compiler
} // namespace elang
|
Revise |CfgToSsaTransformer|.
|
elang/compiler/cg: Revise |CfgToSsaTransformer|.
|
C++
|
apache-2.0
|
eval1749/elang,eval1749/elang,eval1749/elang,eval1749/elang,eval1749/elang
|
78f2b64f5c4a7c6ebac08fc4a9a31d9134e7d5dc
|
bindings/python/mapnik_python.cpp
|
bindings/python/mapnik_python.cpp
|
/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko, Jean-Francois Doyon
*
* 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 St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id: mapnik_python.cc 27 2005-03-30 21:45:40Z pavlenko $
#include <boost/python.hpp>
#include <boost/get_pointer.hpp>
#include <boost/python/detail/api_placeholder.hpp>
void export_color();
void export_layer();
void export_parameters();
void export_envelope();
void export_query();
void export_image();
void export_map();
void export_python();
void export_filter();
void export_rule();
void export_style();
void export_stroke();
void export_datasource_cache();
void export_point_symbolizer();
void export_line_symbolizer();
void export_line_pattern_symbolizer();
void export_polygon_symbolizer();
void export_polygon_pattern_symbolizer();
void export_raster_symbolizer();
void export_text_symbolizer();
void export_font_engine();
#include <mapnik/map.hpp>
#include <mapnik/agg_renderer.hpp>
#include <mapnik/graphics.hpp>
#include <mapnik/datasource_cache.hpp>
#include <mapnik/load_map.hpp>
#include <mapnik/save_map.hpp>
void render_to_file(const mapnik::Map& map,
const std::string& file,
const std::string& format)
{
mapnik::Image32 image(map.getWidth(),map.getHeight());
mapnik::agg_renderer<mapnik::Image32> ren(map,image);
ren.apply();
image.saveToFile(file,format);
}
void render(const mapnik::Map& map,mapnik::Image32& image)
{
mapnik::agg_renderer<mapnik::Image32> ren(map,image);
ren.apply();
}
namespace
{
//user-friendly wrapper that uses Python dictionary
using namespace boost::python;
boost::shared_ptr<mapnik::datasource> create_datasource(const dict& d)
{
mapnik::parameters params;
boost::python::list keys=d.keys();
for (int i=0; i<len(keys); ++i)
{
std::string key=extract<std::string>(keys[i]);
std::string value=extract<std::string>(d[key]);
params[key] = value;
}
return mapnik::datasource_cache::create(params);
}
}
BOOST_PYTHON_MODULE(_mapnik)
{
using namespace boost::python;
using mapnik::Featureset;
using mapnik::featureset_ptr;
using mapnik::datasource;
using mapnik::coord;
using mapnik::filter_ptr;
using mapnik::load_map;
using mapnik::save_map;
export_query();
class_<Featureset,featureset_ptr,boost::noncopyable>("FeatureSet",no_init)
;
class_<datasource,boost::shared_ptr<datasource>,
boost::noncopyable>("Datasource",no_init)
.def("envelope",&datasource::envelope,
return_value_policy<reference_existing_object>())
.def("features",&datasource::features)
.def("params",&datasource::params,return_value_policy<reference_existing_object>(),
"The configuration parameters of the data source. "
"These vary depending on the type of data source.")
;
def("CreateDatasource",&create_datasource);
export_parameters();
export_color();
export_envelope();
export_image();
export_filter();
export_rule();
export_style();
export_layer();
export_stroke();
export_datasource_cache();
export_point_symbolizer();
export_line_symbolizer();
export_line_pattern_symbolizer();
export_polygon_symbolizer();
export_polygon_pattern_symbolizer();
export_raster_symbolizer();
export_text_symbolizer();
export_font_engine();
class_<coord<double,2> >("Coord",init<double,double>())
.def_readwrite("x", &coord<double,2>::x)
.def_readwrite("y", &coord<double,2>::y)
;
export_map();
def("render_to_file",&render_to_file);
def("render",&render);
def("load_map",&load_map,"load Map object from XML");
def("save_map",&load_map,"sace Map object to XML");
register_ptr_to_python<filter_ptr>();
}
|
/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko, Jean-Francois Doyon
*
* 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 St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id: mapnik_python.cc 27 2005-03-30 21:45:40Z pavlenko $
#include <boost/python.hpp>
#include <boost/get_pointer.hpp>
#include <boost/python/detail/api_placeholder.hpp>
void export_color();
void export_layer();
void export_parameters();
void export_envelope();
void export_query();
void export_image();
void export_map();
void export_python();
void export_filter();
void export_rule();
void export_style();
void export_stroke();
void export_datasource_cache();
void export_point_symbolizer();
void export_line_symbolizer();
void export_line_pattern_symbolizer();
void export_polygon_symbolizer();
void export_polygon_pattern_symbolizer();
void export_raster_symbolizer();
void export_text_symbolizer();
void export_font_engine();
#include <mapnik/map.hpp>
#include <mapnik/agg_renderer.hpp>
#include <mapnik/graphics.hpp>
#include <mapnik/datasource_cache.hpp>
#include <mapnik/load_map.hpp>
#include <mapnik/save_map.hpp>
void render_to_file(const mapnik::Map& map,
const std::string& file,
const std::string& format)
{
mapnik::Image32 image(map.getWidth(),map.getHeight());
mapnik::agg_renderer<mapnik::Image32> ren(map,image);
ren.apply();
image.saveToFile(file,format);
}
void render(const mapnik::Map& map,mapnik::Image32& image)
{
mapnik::agg_renderer<mapnik::Image32> ren(map,image);
ren.apply();
}
namespace
{
//user-friendly wrapper that uses Python dictionary
using namespace boost::python;
boost::shared_ptr<mapnik::datasource> create_datasource(const dict& d)
{
mapnik::parameters params;
boost::python::list keys=d.keys();
for (int i=0; i<len(keys); ++i)
{
std::string key = extract<std::string>(keys[i]);
object obj = d[key];
extract<std::string> ex(obj);
if (ex.check())
{
params[key] = ex();
}
}
return mapnik::datasource_cache::create(params);
}
}
BOOST_PYTHON_MODULE(_mapnik)
{
using namespace boost::python;
using mapnik::Featureset;
using mapnik::featureset_ptr;
using mapnik::datasource;
using mapnik::coord;
using mapnik::filter_ptr;
using mapnik::load_map;
using mapnik::save_map;
export_query();
class_<Featureset,featureset_ptr,boost::noncopyable>("FeatureSet",no_init)
;
class_<datasource,boost::shared_ptr<datasource>,
boost::noncopyable>("Datasource",no_init)
.def("envelope",&datasource::envelope,
return_value_policy<reference_existing_object>())
.def("features",&datasource::features)
.def("params",&datasource::params,return_value_policy<reference_existing_object>(),
"The configuration parameters of the data source. "
"These vary depending on the type of data source.")
;
def("CreateDatasource",&create_datasource);
export_parameters();
export_color();
export_envelope();
export_image();
export_filter();
export_rule();
export_style();
export_layer();
export_stroke();
export_datasource_cache();
export_point_symbolizer();
export_line_symbolizer();
export_line_pattern_symbolizer();
export_polygon_symbolizer();
export_polygon_pattern_symbolizer();
export_raster_symbolizer();
export_text_symbolizer();
export_font_engine();
class_<coord<double,2> >("Coord",init<double,double>())
.def_readwrite("x", &coord<double,2>::x)
.def_readwrite("y", &coord<double,2>::y)
;
export_map();
def("render_to_file",&render_to_file);
def("render",&render);
def("load_map",&load_map,"load Map object from XML");
def("save_map",&load_map,"sace Map object to XML");
register_ptr_to_python<filter_ptr>();
}
|
check if can extract std::string from dict.
|
check if can extract std::string from dict.
|
C++
|
lgpl-2.1
|
pramsey/mapnik,jwomeara/mapnik,Mappy/mapnik,mbrukman/mapnik,qianwenming/mapnik,stefanklug/mapnik,garnertb/python-mapnik,mapnik/mapnik,yohanboniface/python-mapnik,yiqingj/work,yiqingj/work,cjmayo/mapnik,pnorman/mapnik,mapycz/mapnik,rouault/mapnik,manz/python-mapnik,tomhughes/mapnik,zerebubuth/mapnik,mapnik/mapnik,mapycz/python-mapnik,naturalatlas/mapnik,tomhughes/mapnik,cjmayo/mapnik,pramsey/mapnik,naturalatlas/mapnik,yohanboniface/python-mapnik,mapnik/python-mapnik,jwomeara/mapnik,Uli1/mapnik,mapycz/python-mapnik,stefanklug/mapnik,CartoDB/mapnik,Uli1/mapnik,whuaegeanse/mapnik,Airphrame/mapnik,mapnik/python-mapnik,whuaegeanse/mapnik,pnorman/mapnik,davenquinn/python-mapnik,davenquinn/python-mapnik,tomhughes/mapnik,pnorman/mapnik,yiqingj/work,sebastic/python-mapnik,Airphrame/mapnik,mapnik/python-mapnik,tomhughes/mapnik,mapycz/mapnik,pnorman/mapnik,pramsey/mapnik,rouault/mapnik,tomhughes/python-mapnik,whuaegeanse/mapnik,manz/python-mapnik,sebastic/python-mapnik,mapnik/mapnik,yohanboniface/python-mapnik,qianwenming/mapnik,garnertb/python-mapnik,cjmayo/mapnik,Airphrame/mapnik,rouault/mapnik,strk/mapnik,Airphrame/mapnik,Mappy/mapnik,mbrukman/mapnik,mapycz/mapnik,mapnik/mapnik,naturalatlas/mapnik,whuaegeanse/mapnik,Uli1/mapnik,garnertb/python-mapnik,qianwenming/mapnik,strk/mapnik,yiqingj/work,stefanklug/mapnik,naturalatlas/mapnik,jwomeara/mapnik,davenquinn/python-mapnik,zerebubuth/mapnik,lightmare/mapnik,CartoDB/mapnik,lightmare/mapnik,strk/mapnik,qianwenming/mapnik,zerebubuth/mapnik,tomhughes/python-mapnik,kapouer/mapnik,tomhughes/python-mapnik,manz/python-mapnik,rouault/mapnik,kapouer/mapnik,cjmayo/mapnik,lightmare/mapnik,kapouer/mapnik,Mappy/mapnik,Mappy/mapnik,sebastic/python-mapnik,jwomeara/mapnik,stefanklug/mapnik,mbrukman/mapnik,pramsey/mapnik,strk/mapnik,qianwenming/mapnik,mbrukman/mapnik,Uli1/mapnik,kapouer/mapnik,lightmare/mapnik,CartoDB/mapnik
|
1aa66a62e2e050eb1f07b00d8f4fa28a2df4414b
|
src/upsampling_algorithm_long_sequence.cc
|
src/upsampling_algorithm_long_sequence.cc
|
#include <iostream>
#include <fstream>
#include <vector>
#include <memory>
#include <algorithm>
#include <functional>
#include <complex>
#include <iterator>
#include <sndfile.hh>
#define kiss_fft_scalar float
#include "kiss_fft.h"
void write_complex_data(const std::vector<std::complex<kiss_fft_scalar>>& v, const std::string& filename)
{
const auto precision = []() -> std::streamsize {
// https://www.working-software.com/cpp-floats-as-decimal
if (std::is_same<kiss_fft_scalar, float>::value) return 9;
if (std::is_same<kiss_fft_scalar, double>::value) return 17;
return std::cout.precision();
}();
std::ofstream file(filename);
file.precision(precision);
std::copy(std::begin(v), std::end(v),
std::ostream_iterator<std::complex<kiss_fft_scalar>>(file, "\n"));
}
int main(int argc, char *argv[])
{
const int I = 2;
const int D = 1;
const int N = 256;
const int M = I/D*N;
const int L = N/8;
if (argc != 2) {
std::cerr << "Usage: upsampling_algorithm_long_sequence <filename>\n";
return -1;
}
// Kiss FFT configurations
auto fwd_cfg = std::unique_ptr<std::remove_pointer<kiss_fft_cfg>::type, decltype(kiss_fft_free) *> {
kiss_fft_alloc(N, 0, nullptr, nullptr),
kiss_fft_free
};
auto inv_cfg = std::unique_ptr<std::remove_pointer<kiss_fft_cfg>::type, decltype(kiss_fft_free) *> {
kiss_fft_alloc(M, 1, nullptr, nullptr),
kiss_fft_free
};
if (fwd_cfg == nullptr || inv_cfg == nullptr) {
std::cerr << "Error allocating Kiss FFT configurations.\n";
}
const std::string input_filename = argv[argc-1];
SndfileHandle input_file(input_filename);
if (input_file.channels() != 1) {
std::cerr << "Only files with one audio channel are supported.\n";
}
const std::string debug_input_filename = "upsampling_algorithm_long_sequence_debug_input.wav";
SndfileHandle debug_input_file(input_file);
const std::string output_filename = "upsampling_algorithm_long_sequence_out.wav";
SndfileHandle output_file(output_filename,
SFM_WRITE,
input_file.format(),
input_file.channels(),
input_file.samplerate() * I/D);
// Input data
std::vector<kiss_fft_scalar> buffer(N);
// FFT input/output buffers
std::vector<std::complex<kiss_fft_scalar>> fft_input_buffer(N);
std::vector<std::complex<kiss_fft_scalar>> fft_output_buffer(fft_input_buffer.size());
// IFFT input/output buffers
std::vector<std::complex<kiss_fft_scalar>> ifft_input_buffer(M);
std::vector<std::complex<kiss_fft_scalar>> ifft_output_buffer(ifft_input_buffer.size());
/* prepend 2L zeros */
for (int i=0; i < 2*L; ++i) {
buffer[i] = 0;
}
int cnt=0;
while (sf_count_t readcount = input_file.read(buffer.data() + 2*L, N - 2*L))
{
/* Store original samples */
debug_input_file.write(buffer.data() + 2*L, std::min(static_cast<int>(readcount), N - 2*L));
/* Create FFT input buffer: 1 block of N samples with 2*L overlap */
for(int i=0; i < std::min(static_cast<int>(readcount) + 2*L, N); ++i) {
fft_input_buffer[i] = std::complex<kiss_fft_scalar>(buffer[i]);
}
write_complex_data(fft_input_buffer, "fft_input_buffer_" + std::to_string(cnt) + ".asc");
/* Forward N points FFT */
kiss_fft(fwd_cfg.get(),
reinterpret_cast<kiss_fft_cpx*>(fft_input_buffer.data()),
reinterpret_cast<kiss_fft_cpx*>(fft_output_buffer.data()));
write_complex_data(fft_output_buffer, "fft_output_buffer_" + std::to_string(cnt) + ".asc");
/* Create IFFT input buffer */
for(int i=0; i < N/2; ++i) {
ifft_input_buffer[i] = static_cast<kiss_fft_scalar>(I/D) * fft_output_buffer[i];
}
for(int i=N/2; i <= M - N/2; ++i) {
ifft_input_buffer[i] = static_cast<kiss_fft_scalar>(I/D) * fft_output_buffer[N/2];
}
for(int i=M - N/2 + 1; i < M; ++i) {
ifft_input_buffer[i] = static_cast<kiss_fft_scalar>(I/D) * fft_output_buffer[i + M/2];
}
write_complex_data(ifft_input_buffer, "ifft_input_buffer_" + std::to_string(cnt) + ".asc");
/* Backward M points IFFT */
kiss_fft(inv_cfg.get(),
reinterpret_cast<kiss_fft_cpx*>(ifft_input_buffer.data()),
reinterpret_cast<kiss_fft_cpx*>(ifft_output_buffer.data()));
std::transform(std::begin(ifft_output_buffer), std::end(ifft_output_buffer),
std::begin(ifft_output_buffer),
std::bind1st(std::multiplies<std::complex<kiss_fft_scalar>>(), 1.0/M));
write_complex_data(ifft_output_buffer, "ifft_output_buffer_" + std::to_string(cnt) + ".asc");
/* Discard first and last I/D*L points and store the rest of the real vector */
std::vector<kiss_fft_scalar> res(M - 2*I/D*L);
int j = I/D*L;
for(int i=0; i < M - 2*I/D*L; ++i) {
res[i] = ifft_output_buffer[j++].real();
}
output_file.write(res.data(), res.size());
/* Shift vector to the left 2*L times */
std::rotate(buffer.begin(), buffer.begin() + N - 2*L, buffer.end());
cnt++;
};
kiss_fft_cleanup();
return 0;
}
|
#include <iostream>
#include <fstream>
#include <vector>
#include <memory>
#include <algorithm>
#include <functional>
#include <complex>
#include <iterator>
#include <sndfile.hh>
#define kiss_fft_scalar float
#include "kiss_fft.h"
void write_complex_data(const std::vector<std::complex<kiss_fft_scalar>>& v, const std::string& filename)
{
const auto precision = []() -> std::streamsize {
// https://www.working-software.com/cpp-floats-as-decimal
if (std::is_same<kiss_fft_scalar, float>::value) return 9;
if (std::is_same<kiss_fft_scalar, double>::value) return 17;
return std::cout.precision();
}();
std::ofstream file(filename);
file.precision(precision);
std::copy(std::begin(v), std::end(v),
std::ostream_iterator<std::complex<kiss_fft_scalar>>(file, "\n"));
}
int main(int argc, char *argv[])
{
const int I = 2;
const int D = 1;
const int N = 256;
const int M = I/D*N;
const int L = N/8;
if (argc != 2) {
std::cerr << "Usage: upsampling_algorithm_long_sequence <filename>\n";
return -1;
}
// Kiss FFT configurations
auto fwd_cfg = std::unique_ptr<std::remove_pointer<kiss_fft_cfg>::type, decltype(kiss_fft_free) *> {
kiss_fft_alloc(N, 0, nullptr, nullptr),
kiss_fft_free
};
auto inv_cfg = std::unique_ptr<std::remove_pointer<kiss_fft_cfg>::type, decltype(kiss_fft_free) *> {
kiss_fft_alloc(M, 1, nullptr, nullptr),
kiss_fft_free
};
if (fwd_cfg == nullptr || inv_cfg == nullptr) {
std::cerr << "Error allocating Kiss FFT configurations.\n";
}
const std::string input_filename = argv[argc-1];
SndfileHandle input_file(input_filename);
if (input_file.channels() != 1) {
std::cerr << "Only files with one audio channel are supported.\n";
}
const std::string debug_input_filename = "upsampling_algorithm_long_sequence_debug_input.wav";
SndfileHandle debug_input_file(input_file);
const std::string output_filename = "upsampling_algorithm_long_sequence_out.wav";
SndfileHandle output_file(output_filename,
SFM_WRITE,
input_file.format(),
input_file.channels(),
input_file.samplerate() * I/D);
// Input data
std::vector<kiss_fft_scalar> buffer(N);
// FFT input/output buffers
std::vector<std::complex<kiss_fft_scalar>> fft_input_buffer(N);
std::vector<std::complex<kiss_fft_scalar>> fft_output_buffer(fft_input_buffer.size());
// IFFT input/output buffers
std::vector<std::complex<kiss_fft_scalar>> ifft_input_buffer(M);
std::vector<std::complex<kiss_fft_scalar>> ifft_output_buffer(ifft_input_buffer.size());
/* prepend 2L zeros */
for (int i=0; i < 2*L; ++i) {
buffer[i] = 0;
}
int cnt=0;
while (sf_count_t readcount = input_file.read(buffer.data() + 2*L, N - 2*L))
{
/* Store original samples */
debug_input_file.write(buffer.data() + 2*L, std::min(static_cast<int>(readcount), N - 2*L));
/* Create FFT input buffer: 1 block of N samples with 2*L overlap */
for(int i=0; i < std::min(static_cast<int>(readcount) + 2*L, N); ++i) {
fft_input_buffer[i] = std::complex<kiss_fft_scalar>(buffer[i]);
}
write_complex_data(fft_input_buffer, "fft_input_buffer_" + std::to_string(cnt) + ".asc");
/* Forward N points FFT */
kiss_fft(fwd_cfg.get(),
reinterpret_cast<kiss_fft_cpx*>(fft_input_buffer.data()),
reinterpret_cast<kiss_fft_cpx*>(fft_output_buffer.data()));
write_complex_data(fft_output_buffer, "fft_output_buffer_" + std::to_string(cnt) + ".asc");
/* Create IFFT input buffer */
std::vector<std::complex<kiss_fft_scalar>> ifft_input_buffer(M, static_cast<kiss_fft_scalar>(1.0*D/I) * std::complex<kiss_fft_scalar>(fft_output_buffer[N/2]));
std::copy(std::begin(fft_output_buffer), std::begin(fft_output_buffer) + N/2, std::begin(ifft_input_buffer));
std::copy(std::begin(fft_output_buffer) + N/2, std::end(fft_output_buffer), std::end(ifft_input_buffer) - N/2);
std::transform(std::begin(ifft_input_buffer), std::end(ifft_input_buffer),
std::begin(ifft_input_buffer),
std::bind1st(std::multiplies<std::complex<kiss_fft_scalar>>(), static_cast<float>(1.0*I/D)));
write_complex_data(ifft_input_buffer, "ifft_input_buffer_" + std::to_string(cnt) + ".asc");
/* Backward M points IFFT */
kiss_fft(inv_cfg.get(),
reinterpret_cast<kiss_fft_cpx*>(ifft_input_buffer.data()),
reinterpret_cast<kiss_fft_cpx*>(ifft_output_buffer.data()));
std::transform(std::begin(ifft_output_buffer), std::end(ifft_output_buffer),
std::begin(ifft_output_buffer),
std::bind1st(std::multiplies<std::complex<kiss_fft_scalar>>(), 1.0/M));
write_complex_data(ifft_output_buffer, "ifft_output_buffer_" + std::to_string(cnt) + ".asc");
/* Discard first and last I/D*L points and store the rest of the real vector */
std::vector<kiss_fft_scalar> res(M - 2*I/D*L);
int j = I/D*L;
for(int i=0; i < M - 2*I/D*L; ++i) {
res[i] = ifft_output_buffer[j++].real();
}
output_file.write(res.data(), res.size());
/* Shift vector to the left 2*L times */
std::rotate(buffer.begin(), buffer.begin() + N - 2*L, buffer.end());
cnt++;
};
kiss_fft_cleanup();
return 0;
}
|
Rewrite method to create IFFT input vectors.
|
Rewrite method to create IFFT input vectors.
|
C++
|
mit
|
mpoullet/audio-tools,mpoullet/audio-tools,mpoullet/audio-tools,mpoullet/audio-tools,mpoullet/audio-tools
|
6fcb03cf26ca6598e23a827fa7e3224d438f6f48
|
NaoTHSoccer/Source/Tools/Debug/DebugParameterList.cpp
|
NaoTHSoccer/Source/Tools/Debug/DebugParameterList.cpp
|
/**
* @file DebugParameterList.cpp
*
* @author <a href="mailto:[email protected]">Xu, Yuan</a>
*
* @brief handle parameter list with debug
*/
#include "DebugParameterList.h"
#include <DebugCommunication/DebugCommandManager.h>
#include "PlatformInterface/Platform.h"
using namespace std;
DebugParameterList::DebugParameterList()
{
}
void DebugParameterList::executeDebugCommand(
const std::string& command, const ArgumentMap& arguments,
std::ostream &outstream)
{
if ( command == "ParameterList:list" )
{
for(ParameterMap::const_iterator itParamList = paramlists.begin();
itParamList != paramlists.end(); ++itParamList)
{
outstream << itParamList->second->getName() << "\n";
}
}
else if( command == "ParameterList:get" )
{
ArgumentMap::const_iterator iter = arguments.find("<name>");
if(iter != arguments.end())
{
const std::string& name = iter->second;
naoth::Configuration& config = naoth::Platform::getInstance().theConfiguration;
set<string> keys = config.getKeys(name);
for(set<string>::const_iterator it = keys.begin(); it != keys.end(); ++it)
{
string val = config.getRawValue(name, *it);
outstream << *it << "=" << val << std::endl;
}
}
}
else if( command == "ParameterList:set" )
{
ArgumentMap::const_iterator iter = arguments.find("<name>");
if(iter != arguments.end())
{
const std::string& name = iter->second;
naoth::Configuration& config = naoth::Platform::getInstance().theConfiguration;
for (ArgumentMap::const_iterator iter = arguments.begin(); iter != arguments.end(); ++iter)
{
// update global config
if ( config.hasKey(name, iter->first) ) {
config.setRawValue(name, iter->first, iter->second);
}
}
config.save();
ParameterMap::iterator pIter = paramlists.find(name);
if(pIter == paramlists.end() ) {
outstream << "[error] " << name << " not registered" << std::endl;
} else {
pIter->second->syncWithConfig();
outstream << "[info] set " << name << " successfully" << std::endl;
}
}
}
}
void DebugParameterList::add(ParameterList* pl)
{
paramlists[pl->getName()] = pl;
}
void DebugParameterList::remove(ParameterList* pl)
{
paramlists.erase(paramlists.find(pl->getName()));
}
|
/**
* @file DebugParameterList.cpp
*
* @author <a href="mailto:[email protected]">Xu, Yuan</a>
*
* @brief handle parameter list with debug
*/
#include "DebugParameterList.h"
#include <DebugCommunication/DebugCommandManager.h>
#include "PlatformInterface/Platform.h"
using namespace std;
DebugParameterList::DebugParameterList()
{
}
void DebugParameterList::executeDebugCommand(
const std::string& command, const ArgumentMap& arguments,
std::ostream &outstream)
{
if ( command == "ParameterList:list" )
{
for(ParameterMap::const_iterator itParamList = paramlists.begin();
itParamList != paramlists.end(); ++itParamList)
{
outstream << itParamList->second->getName() << "\n";
}
}
else if( command == "ParameterList:get" )
{
ArgumentMap::const_iterator iter = arguments.find("<name>");
if(iter != arguments.end())
{
const std::string& name = iter->second;
ParameterMap::const_iterator itParamList = paramlists.find(name);
// print only the registered parameters
itParamList->second->print(outstream);
/*
// print all values from the config
naoth::Configuration& config = naoth::Platform::getInstance().theConfiguration;
set<string> keys = config.getKeys(name);
for(set<string>::const_iterator it = keys.begin(); it != keys.end(); ++it)
{
string val = config.getRawValue(name, *it);
outstream << *it << "=" << val << std::endl;
}
*/
}
}
else if( command == "ParameterList:set" )
{
ArgumentMap::const_iterator iter = arguments.find("<name>");
if(iter != arguments.end())
{
const std::string& name = iter->second;
naoth::Configuration& config = naoth::Platform::getInstance().theConfiguration;
for (ArgumentMap::const_iterator iter = arguments.begin(); iter != arguments.end(); ++iter)
{
// update global config
if ( config.hasKey(name, iter->first) ) {
config.setRawValue(name, iter->first, iter->second);
}
}
config.save();
ParameterMap::iterator pIter = paramlists.find(name);
if(pIter == paramlists.end() ) {
outstream << "[error] " << name << " not registered" << std::endl;
} else {
pIter->second->syncWithConfig();
outstream << "[info] set " << name << " successfully" << std::endl;
}
}
}
}
void DebugParameterList::add(ParameterList* pl)
{
paramlists[pl->getName()] = pl;
}
void DebugParameterList::remove(ParameterList* pl)
{
paramlists.erase(paramlists.find(pl->getName()));
}
|
print only the registered parameter values
|
print only the registered parameter values
|
C++
|
apache-2.0
|
BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH
|
944669b5eba5f63d65a63958e417d90664bd9940
|
core/src/scene/filters.cpp
|
core/src/scene/filters.cpp
|
#include "filters.h"
#include "scene/styleContext.h"
#include "data/tileData.h"
#include "platform.h"
#include <cmath>
namespace Tangram {
void countTypes(const std::vector<Filter>& filters, int& global, int& function, int& property) {
}
void Filter::print(int _indent) const {
switch (data.get_type_index()) {
case Data::type<OperatorAny>::value: {
logMsg("%*s any\n", _indent, "");
for (const auto& filt : data.get<OperatorAny>().operands) {
filt.print(_indent + 2);
}
break;
}
case Data::type<OperatorAll>::value: {
logMsg("%*s all\n", _indent, "");
for (const auto& filt : data.get<OperatorAll>().operands) {
filt.print(_indent + 2);
}
break;
}
case Data::type<OperatorNone>::value: {
logMsg("%*s none\n", _indent, "");
for (const auto& filt : data.get<OperatorNone>().operands) {
filt.print(_indent + 2);
}
break;
}
case Data::type<Existence>::value: {
auto& f = data.get<Existence>();
logMsg("%*s existence - key:%s\n", _indent, "", f.key.c_str());
break;
}
case Data::type<Equality>::value: {
auto& f = data.get<Equality>();
if (f.values[0].is<std::string>()) {
logMsg("%*s equality - global:%d key:%s val:%s\n", _indent, "",
f.global != FilterGlobal::undefined,
f.key.c_str(),
f.values[0].get<std::string>().c_str());
}
if (f.values[0].is<double>()) {
logMsg("%*s equality - global:%d key:%s val:%f\n", _indent, "",
f.global != FilterGlobal::undefined,
f.key.c_str(),
f.values[0].get<double>());
}
break;
}
case Data::type<Range>::value: {
auto& f = data.get<Range>();
logMsg("%*s range - global:%d key:%s min:%f max:%f\n", _indent, "",
f.global != FilterGlobal::undefined,
f.key.c_str(), f.min, f.max);
return;
}
case Data::type<Function>::value: {
logMsg("%*s function\n", _indent, "");
break;
}
default:
break;
}
}
int Filter::matchCost() const {
// Add some extra penalty for set vs simple filters
int sum = -100;
switch (data.get_type_index()) {
case Data::type<OperatorAny>::value:
for (auto& f : operands()) { sum -= f.matchCost(); }
return sum;
case Data::type<OperatorAll>::value:
for (auto& f : operands()) { sum -= f.matchCost(); }
return sum;
case Data::type<OperatorNone>::value:
for (auto& f : operands()) { sum -= f.matchCost(); }
return sum;
case Data::type<Existence>::value:
// Equality and Range are more specific for increasing
// the chance to fail early check them before Existence
return 20;
case Data::type<Equality>::value:
return data.get<Equality>().global == FilterGlobal::undefined ? 10 : 1;
case Data::type<Filter::Range>::value:
return data.get<Range>().global == FilterGlobal::undefined ? 10 : 1;
case Data::type<Function>::value:
// Most expensive filter should be checked last
return 1000;
}
assert(false);
return 0;
}
const std::string& Filter::key() const {
static const std::string empty = "";
switch (data.get_type_index()) {
case Data::type<Existence>::value:
return data.get<Existence>().key;
case Data::type<Equality>::value:
return data.get<Equality>().key;
case Data::type<Filter::Range>::value:
return data.get<Range>().key;
default:
break;
}
return empty;
}
const std::vector<Filter>& Filter::operands() const {
static const std::vector<Filter> empty;
switch (data.get_type_index()) {
case Data::type<OperatorAny>::value:
return data.get<OperatorAny>().operands;
case Data::type<OperatorAll>::value:
return data.get<OperatorAll>().operands;
case Data::type<OperatorNone>::value:
return data.get<OperatorNone>().operands;
default:
break;
}
return empty;
}
int compareSetFilter(const Filter& a, const Filter& b) {
auto& oa = a.operands();
auto& ob = b.operands();
if (oa.size() != ob.size()) { return oa.size() < ob.size(); }
if (oa[0].data.is<Filter::Range>() &&
ob[0].data.is<Filter::Range>() &&
oa[0].key() == ob[0].key()) {
// take the one with more restrictive range
auto ra = oa[0].data.get<Filter::Range>();
auto rb = ob[0].data.get<Filter::Range>();
if (ra.max == std::numeric_limits<double>::infinity() &&
rb.max == std::numeric_limits<double>::infinity()) {
return rb.min - ra.min;
}
}
return 0;
}
std::vector<Filter> Filter::sort(const std::vector<Filter>& _filters) {
std::vector<Filter> filters = _filters;
std::sort(filters.begin(), filters.end(),
[](auto& a, auto& b) {
// Sort simple filters by eval cost
int ma = a.matchCost();
int mb = b.matchCost();
if (ma > 0 && mb > 0) {
int diff = ma - mb;
if (diff != 0) {
return diff < 0;
}
// just for consistent ordering
// (and using > to prefer $zoom over $geom)
return a.key() > b.key();
}
// When one is a simple Filter and the other is a set
// or both are sets prefer the one with the cheaper
// filter(s).
if (ma != mb) {
// No abs(int) in our android libstdc..
//return std::abs(ma) < std::abs(mb);
return std::fabs(ma) < std::fabs(mb);
}
return compareSetFilter(a, b) < 0;
});
return filters;
}
bool Filter::eval(const Feature& feat, StyleContext& ctx) const {
switch (data.get_type_index()) {
case Data::type<OperatorAny>::value: {
for (const auto& filt : data.get<OperatorAny>().operands) {
if (filt.eval(feat, ctx)) { return true; }
}
return false;
}
case Data::type<OperatorAll>::value: {
for (const auto& filt : data.get<OperatorAll>().operands) {
if (!filt.eval(feat, ctx)) { return false; }
}
return true;
}
case Data::type<OperatorNone>::value: {
for (const auto& filt : data.get<OperatorNone>().operands) {
if (filt.eval(feat, ctx)) { return false; }
}
return true;
}
case Data::type<Existence>::value: {
auto& f = data.get<Existence>();
return f.exists == feat.props.contains(f.key);
}
case Data::type<Equality>::value: {
auto& f = data.get<Equality>();
if (f.global == FilterGlobal::undefined) {
auto& value = feat.props.get(f.key);
for (const auto& v : f.values) {
if (v == value) {
return true;
} else if (value.is<double>() && v.is<double>()) {
auto& a = v.get<double>();
auto& b = value.get<double>();
if (std::fabs(a - b) <= std::numeric_limits<double>::epsilon()) { return true; }
}
}
} else {
auto& global = ctx.getGlobal(f.global);
if (!global.is<none_type>()) {
for (const auto& v : f.values) {
if (v == global) { return true; }
}
return false;
}
}
return false;
}
case Data::type<Range>::value: {
auto& f = data.get<Range>();
if (f.global == FilterGlobal::undefined) {
auto& value = feat.props.get(f.key);
if (value.is<double>()) {
double num = value.get<double>();
return num >= f.min && num < f.max;
}
} else {
auto& global = ctx.getGlobal(f.global);
if (!global.is<none_type>()) {
// only check range for numbers
if (global.is<double>()) {
double num = global.get<double>();
return num >= f.min && num < f.max;
}
}
}
return false;
}
case Data::type<Function>::value: {
auto& f = data.get<Function>();
return ctx.evalFilter(f.id);
}
default:
return true;
}
// Cannot be reached
//assert(false);
return false;
}
}
|
#include "filters.h"
#include "scene/styleContext.h"
#include "data/tileData.h"
#include "platform.h"
#include <cmath>
namespace Tangram {
void countTypes(const std::vector<Filter>& filters, int& global, int& function, int& property) {
}
void Filter::print(int _indent) const {
switch (data.get_type_index()) {
case Data::type<OperatorAny>::value: {
logMsg("%*s any\n", _indent, "");
for (const auto& filt : data.get<OperatorAny>().operands) {
filt.print(_indent + 2);
}
break;
}
case Data::type<OperatorAll>::value: {
logMsg("%*s all\n", _indent, "");
for (const auto& filt : data.get<OperatorAll>().operands) {
filt.print(_indent + 2);
}
break;
}
case Data::type<OperatorNone>::value: {
logMsg("%*s none\n", _indent, "");
for (const auto& filt : data.get<OperatorNone>().operands) {
filt.print(_indent + 2);
}
break;
}
case Data::type<Existence>::value: {
auto& f = data.get<Existence>();
logMsg("%*s existence - key:%s\n", _indent, "", f.key.c_str());
break;
}
case Data::type<Equality>::value: {
auto& f = data.get<Equality>();
if (f.values[0].is<std::string>()) {
logMsg("%*s equality - global:%d key:%s val:%s\n", _indent, "",
f.global != FilterGlobal::undefined,
f.key.c_str(),
f.values[0].get<std::string>().c_str());
}
if (f.values[0].is<double>()) {
logMsg("%*s equality - global:%d key:%s val:%f\n", _indent, "",
f.global != FilterGlobal::undefined,
f.key.c_str(),
f.values[0].get<double>());
}
break;
}
case Data::type<Range>::value: {
auto& f = data.get<Range>();
logMsg("%*s range - global:%d key:%s min:%f max:%f\n", _indent, "",
f.global != FilterGlobal::undefined,
f.key.c_str(), f.min, f.max);
return;
}
case Data::type<Function>::value: {
logMsg("%*s function\n", _indent, "");
break;
}
default:
break;
}
}
int Filter::matchCost() const {
// Add some extra penalty for set vs simple filters
int sum = -100;
switch (data.get_type_index()) {
case Data::type<OperatorAny>::value:
for (auto& f : operands()) { sum -= f.matchCost(); }
return sum;
case Data::type<OperatorAll>::value:
for (auto& f : operands()) { sum -= f.matchCost(); }
return sum;
case Data::type<OperatorNone>::value:
for (auto& f : operands()) { sum -= f.matchCost(); }
return sum;
case Data::type<Existence>::value:
// Equality and Range are more specific for increasing
// the chance to fail early check them before Existence
return 20;
case Data::type<Equality>::value:
return data.get<Equality>().global == FilterGlobal::undefined ? 10 : 1;
case Data::type<Filter::Range>::value:
return data.get<Range>().global == FilterGlobal::undefined ? 10 : 1;
case Data::type<Function>::value:
// Most expensive filter should be checked last
return 1000;
}
assert(false);
return 0;
}
const std::string& Filter::key() const {
static const std::string empty = "";
switch (data.get_type_index()) {
case Data::type<Existence>::value:
return data.get<Existence>().key;
case Data::type<Equality>::value:
return data.get<Equality>().key;
case Data::type<Filter::Range>::value:
return data.get<Range>().key;
default:
break;
}
return empty;
}
const std::vector<Filter>& Filter::operands() const {
static const std::vector<Filter> empty;
switch (data.get_type_index()) {
case Data::type<OperatorAny>::value:
return data.get<OperatorAny>().operands;
case Data::type<OperatorAll>::value:
return data.get<OperatorAll>().operands;
case Data::type<OperatorNone>::value:
return data.get<OperatorNone>().operands;
default:
break;
}
return empty;
}
int compareSetFilter(const Filter& a, const Filter& b) {
auto& oa = a.operands();
auto& ob = b.operands();
if (oa.size() != ob.size()) { return oa.size() < ob.size(); }
if (oa[0].data.is<Filter::Range>() &&
ob[0].data.is<Filter::Range>() &&
oa[0].key() == ob[0].key()) {
// take the one with more restrictive range
auto ra = oa[0].data.get<Filter::Range>();
auto rb = ob[0].data.get<Filter::Range>();
if (ra.max == std::numeric_limits<double>::infinity() &&
rb.max == std::numeric_limits<double>::infinity()) {
return rb.min - ra.min;
}
}
return 0;
}
std::vector<Filter> Filter::sort(const std::vector<Filter>& _filters) {
std::vector<Filter> filters = _filters;
std::sort(filters.begin(), filters.end(),
[](auto& a, auto& b) {
// Sort simple filters by eval cost
int ma = a.matchCost();
int mb = b.matchCost();
if (ma > 0 && mb > 0) {
int diff = ma - mb;
if (diff != 0) {
return diff < 0;
}
// just for consistent ordering
// (and using > to prefer $zoom over $geom)
return a.key() > b.key();
}
// When one is a simple Filter and the other is a set
// or both are sets prefer the one with the cheaper
// filter(s).
if (ma != mb) {
// No abs(int) in our android libstdc..
//return std::abs(ma) < std::abs(mb);
return std::fabs(ma) < std::fabs(mb);
}
return compareSetFilter(a, b) < 0;
});
return filters;
}
#if 0
bool Filter::eval(const Feature& feat, StyleContext& ctx) const {
switch (data.get_type_index()) {
case Data::type<OperatorAny>::value: {
for (const auto& filt : data.get<OperatorAny>().operands) {
if (filt.eval(feat, ctx)) { return true; }
}
return false;
}
case Data::type<OperatorAll>::value: {
for (const auto& filt : data.get<OperatorAll>().operands) {
if (!filt.eval(feat, ctx)) { return false; }
}
return true;
}
case Data::type<OperatorNone>::value: {
for (const auto& filt : data.get<OperatorNone>().operands) {
if (filt.eval(feat, ctx)) { return false; }
}
return true;
}
case Data::type<Existence>::value: {
auto& f = data.get<Existence>();
return f.exists == feat.props.contains(f.key);
}
case Data::type<Equality>::value: {
auto& f = data.get<Equality>();
if (f.global == FilterGlobal::undefined) {
auto& value = feat.props.get(f.key);
for (const auto& v : f.values) {
if (v == value) {
return true;
} else if (value.is<double>() && v.is<double>()) {
auto& a = v.get<double>();
auto& b = value.get<double>();
if (std::fabs(a - b) <= std::numeric_limits<double>::epsilon()) { return true; }
}
}
} else {
auto& global = ctx.getGlobal(f.global);
if (!global.is<none_type>()) {
for (const auto& v : f.values) {
if (v == global) { return true; }
}
return false;
}
}
return false;
}
case Data::type<Range>::value: {
auto& f = data.get<Range>();
if (f.global == FilterGlobal::undefined) {
auto& value = feat.props.get(f.key);
if (value.is<double>()) {
double num = value.get<double>();
return num >= f.min && num < f.max;
}
} else {
auto& global = ctx.getGlobal(f.global);
if (!global.is<none_type>()) {
// only check range for numbers
if (global.is<double>()) {
double num = global.get<double>();
return num >= f.min && num < f.max;
}
}
}
return false;
}
case Data::type<Function>::value: {
auto& f = data.get<Function>();
return ctx.evalFilter(f.id);
}
default:
return true;
}
// Cannot be reached
//assert(false);
return false;
}
#else
struct string_matcher {
using result_type = bool;
const std::string& str;
template <typename T>
bool operator()(T v) const { return false; }
bool operator()(const std::string& v) const {
return str == v;
}
};
struct number_matcher {
using result_type = bool;
double num;
template <typename T>
bool operator()(T v) const { return false; }
bool operator()(const double& v) const {
if (num == v) { return true; }
return std::fabs(num - v) <= std::numeric_limits<double>::epsilon();
}
};
struct match_equal {
using result_type = bool;
const std::vector<Value>& values;
template <typename T>
bool operator()(T) const { return false; }
bool operator()(const double& num) const {
number_matcher m{num};
for (const auto& v : values) {
if (Value::visit(v, m)) {
return true;
}
}
return false;
}
bool operator()(const std::string& str) const {
string_matcher m{str};
for (const auto& v : values) {
if (Value::visit(v, m)) {
return true;
}
}
return false;
}
};
struct match_range {
const Filter::Range& f;
bool operator() (const double& num) const {
return num >= f.min && num < f.max;
}
bool operator() (const std::string&) const { return false; }
bool operator() (const none_type&) const { return false; }
};
struct matcher {
using result_type = bool;
matcher(const Feature& feat, StyleContext& ctx) :
props(feat.props), ctx(ctx) {}
const Properties& props;
StyleContext& ctx;
bool eval(const Filter::Data& data) const {
return Filter::Data::visit(data, *this);
}
bool operator() (const Filter::OperatorAny& f) const {
for (const auto& filt : f.operands) {
if (eval(filt.data)) { return true; }
}
return false;
}
bool operator() (const Filter::OperatorAll& f) const {
for (const auto& filt : f.operands) {
if (!eval(filt.data)) { return false; }
}
return true;
}
bool operator() (const Filter::OperatorNone& f) const {
for (const auto& filt : f.operands) {
if (eval(filt.data)) { return false; }
}
return true;
}
bool operator() (const Filter::Existence& f) const {
return f.exists == props.contains(f.key);
}
bool operator() (const Filter::Equality& f) const {
auto& value = (f.global == FilterGlobal::undefined)
? props.get(f.key)
: ctx.getGlobal(f.global);
return Value::visit(value, match_equal{f.values});
}
bool operator() (const Filter::Range& f) const {
auto& value = (f.global == FilterGlobal::undefined)
? props.get(f.key)
: ctx.getGlobal(f.global);
return Value::visit(value, match_range{f});
}
bool operator() (const Filter::Function& f) const {
return ctx.evalFilter(f.id);
}
bool operator() (const none_type& f) const {
return true;
}
};
bool Filter::eval(const Feature& feat, StyleContext& ctx) const {
return Data::visit(data, matcher(feat, ctx));
}
#endif
}
|
use variant::visitor for filter matching
|
perf: use variant::visitor for filter matching
avoid is<> and get<> which seems to be slower than the visitor
template machinery
|
C++
|
mit
|
cleeus/tangram-es,tangrams/tangram-es,quitejonny/tangram-es,tangrams/tangram-es,tangrams/tangram-es,quitejonny/tangram-es,cleeus/tangram-es,tangrams/tangram-es,cleeus/tangram-es,quitejonny/tangram-es,quitejonny/tangram-es,cleeus/tangram-es,quitejonny/tangram-es,tangrams/tangram-es,cleeus/tangram-es,quitejonny/tangram-es,tangrams/tangram-es,cleeus/tangram-es,tangrams/tangram-es
|
add77cae4e9bbbb8d1b1197c0bace9ee69467685
|
Modules/Applications/AppSegmentation/app/otbHooverCompareSegmentation.cxx
|
Modules/Applications/AppSegmentation/app/otbHooverCompareSegmentation.cxx
|
/*
* Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* 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 "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"
#include "otbHooverMatrixFilter.h"
#include "otbHooverInstanceFilter.h"
#include "otbLabelMapToAttributeImageFilter.h"
#include "itkLabelImageToLabelMapFilter.h"
#include "otbUnaryFunctorImageFilter.h"
namespace otb
{
namespace Functor
{
// Functor to color Hoover instances
template<class TInput, class TOutput>
class HooverColorMapping
{
public:
HooverColorMapping() {}
virtual ~HooverColorMapping() {}
typedef std::vector<TOutput> ColorListType;
unsigned int GetOutputSize()
{
return 3;
}
void AddColor(const TOutput& color)
{
m_ScoreColors.push_back(color);
}
void SetBackground(const TOutput& bg)
{
m_Background = bg;
}
inline TOutput operator ()(const TInput& A)
{
TOutput out;
out.SetSize(3);
typename TInput::ValueType max = 0.0;
unsigned int index=0;
for (unsigned int i=0; i<m_ScoreColors.size(); i++)
{
if (A[i] > max)
{
index = i;
max = A[i];
}
}
if (max > 0.01)
{
out = m_ScoreColors[index];
}
else
{
out = m_Background;
}
return out;
}
private:
ColorListType m_ScoreColors;
TOutput m_Background;
};
} // end namespace Functor
namespace Wrapper
{
class HooverCompareSegmentation : public Application
{
public:
/** Standard class typedefs. */
typedef HooverCompareSegmentation Self;
typedef Application Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
/** Standard macro */
itkNewMacro(Self);
itkTypeMacro(HooverCompareSegmentation, otb::Application);
typedef otb::AttributesMapLabelObject<unsigned int, 2, float> LabelObjectType;
typedef itk::LabelMap<LabelObjectType> LabelMapType;
typedef otb::HooverMatrixFilter<LabelMapType> HooverMatrixFilterType;
typedef UInt32ImageType ImageType;
typedef FloatVectorImageType::PixelType FloatPixelType;
typedef Int16VectorImageType::PixelType Int16PixelType;
//typedef otb::VectorImage<float, 2> VectorImageType;
typedef itk::LabelImageToLabelMapFilter
<ImageType, LabelMapType> ImageToLabelMapFilterType;
typedef otb::ImageFileReader<ImageType> ImageReaderType;
typedef HooverMatrixFilterType::MatrixType MatrixType;
typedef otb::HooverInstanceFilter<LabelMapType> InstanceFilterType;
typedef otb::LabelMapToAttributeImageFilter
<LabelMapType, FloatVectorImageType> AttributeImageFilterType;
typedef otb::UnaryFunctorImageFilter
<FloatVectorImageType,
Int16VectorImageType,
Functor::HooverColorMapping
<FloatPixelType, Int16PixelType> > HooverColorFilterType;
private:
void DoInit() override
{
SetName("HooverCompareSegmentation");
SetDescription("Compare two segmentations with Hoover metrics");
// Documentation
SetDocName("Hoover compare segmentation");
SetDocLongDescription("This application compares a machine segmentation (MS) with a partial "
"ground truth segmentation (GT). The Hoover metrics are used to estimate "
"scores for correct detection, over-segmentation, under-segmentation and "
"missed detection.\n\n"
"The application can output the overall Hoover scores along with colored"
"images of the MS and GT segmentation showing the state of each region "
"(correct detection, over-segmentation, under-segmentation, missed).\n\n"
"The Hoover metrics are described in: Hoover et al., \"An experimental"
" comparison of range image segmentation algorithms\", IEEE PAMI vol. 18, no. 7, July 1996.");
SetDocLimitations("None");
SetDocAuthors("OTB-Team");
SetDocSeeAlso("otbHooverMatrixFilter, otbHooverInstanceFilter, otbLabelMapToAttributeImageFilter");
AddDocTag(Tags::Segmentation);
AddParameter(ParameterType_InputImage, "ingt", "Input ground truth");
SetParameterDescription( "ingt", "A partial ground truth segmentation image." );
AddParameter(ParameterType_InputImage, "inms", "Input machine segmentation");
SetParameterDescription( "inms", "A machine segmentation image." );
AddParameter(ParameterType_Int, "bg", "Background label");
SetParameterDescription("bg", "Label value of the background in the input segmentations");
SetDefaultParameterInt("bg", 0);
AddParameter(ParameterType_Float, "th", "Overlapping threshold");
SetParameterDescription("th", "Overlapping threshold used to find Hoover instances.");
SetDefaultParameterFloat("th", 0.75);
AddParameter(ParameterType_OutputImage, "outgt", "Colored ground truth output");
SetParameterDescription( "outgt", "The colored ground truth output image." );
SetDefaultOutputPixelType("outgt",ImagePixelType_uint8);
MandatoryOff("outgt");
AddParameter(ParameterType_OutputImage, "outms", "Colored machine segmentation output");
SetParameterDescription( "outms", "The colored machine segmentation output image." );
SetDefaultOutputPixelType("outms",ImagePixelType_uint8);
MandatoryOff("outms");
// TODO : add color settings ?
AddParameter(ParameterType_Float, "rc", "Correct detection score");
SetParameterDescription("rc", "Overall score for correct detection (RC)");
SetParameterRole("rc", Role_Output);
AddParameter(ParameterType_Float, "rf", "Over-segmentation score");
SetParameterDescription("rf", "Overall score for over segmentation (RF)");
SetParameterRole("rf", Role_Output);
AddParameter(ParameterType_Float, "ra", "Under-segmentation score");
SetParameterDescription("ra", "Overall score for under segmentation (RA)");
SetParameterRole("ra", Role_Output);
AddParameter(ParameterType_Float, "rm", "Missed detection score");
SetParameterDescription("rm", "Overall score for missed detection (RM)");
SetParameterRole("rm", Role_Output);
// Doc example parameter settings
SetDocExampleParameterValue("ingt", "maur_GT.tif");
SetDocExampleParameterValue("inms", "maur_labelled.tif");
SetDocExampleParameterValue("outgt", "maur_colored_GT.tif uint8");
SetOfficialDocLink();
}
void DoUpdateParameters() override
{
// Nothing to do here : all parameters are independent
}
void DoExecute() override
{
UInt32ImageType::Pointer inputGT = GetParameterUInt32Image("ingt");
UInt32ImageType::Pointer inputMS = GetParameterUInt32Image("inms");
m_GTFilter = ImageToLabelMapFilterType::New();
m_GTFilter->SetInput(inputGT);
m_GTFilter->SetBackgroundValue( GetParameterInt("bg") );
m_MSFilter = ImageToLabelMapFilterType::New();
m_MSFilter->SetInput(inputMS);
m_MSFilter->SetBackgroundValue( GetParameterInt("bg") );
m_HooverFilter = HooverMatrixFilterType::New();
m_HooverFilter->SetGroundTruthLabelMap(m_GTFilter->GetOutput());
m_HooverFilter->SetMachineSegmentationLabelMap(m_MSFilter->GetOutput());
m_HooverFilter->Update();
m_InstanceFilter = InstanceFilterType::New();
m_InstanceFilter->SetGroundTruthLabelMap(m_GTFilter->GetOutput());
m_InstanceFilter->SetMachineSegmentationLabelMap(m_MSFilter->GetOutput());
m_InstanceFilter->SetThreshold( GetParameterFloat("th") );
m_InstanceFilter->SetHooverMatrix( m_HooverFilter->GetHooverConfusionMatrix() );
m_InstanceFilter->SetUseExtendedAttributes(false);
m_AttributeImageGT = AttributeImageFilterType::New();
m_AttributeImageGT->SetInput(m_InstanceFilter->GetOutputGroundTruthLabelMap());
m_AttributeImageGT->SetAttributeForNthChannel(0, InstanceFilterType::GetNameFromAttribute(InstanceFilterType::ATTRIBUTE_RC));
m_AttributeImageGT->SetAttributeForNthChannel(1, InstanceFilterType::GetNameFromAttribute(InstanceFilterType::ATTRIBUTE_RF));
m_AttributeImageGT->SetAttributeForNthChannel(2, InstanceFilterType::GetNameFromAttribute(InstanceFilterType::ATTRIBUTE_RA));
m_AttributeImageGT->SetAttributeForNthChannel(3, InstanceFilterType::GetNameFromAttribute(InstanceFilterType::ATTRIBUTE_RM));
m_AttributeImageMS = AttributeImageFilterType::New();
m_AttributeImageMS->SetInput(m_InstanceFilter->GetOutputMachineSegmentationLabelMap());
m_AttributeImageMS->SetAttributeForNthChannel(0, InstanceFilterType::GetNameFromAttribute(InstanceFilterType::ATTRIBUTE_RC));
m_AttributeImageMS->SetAttributeForNthChannel(1, InstanceFilterType::GetNameFromAttribute(InstanceFilterType::ATTRIBUTE_RF));
m_AttributeImageMS->SetAttributeForNthChannel(2, InstanceFilterType::GetNameFromAttribute(InstanceFilterType::ATTRIBUTE_RA));
//m_AttributeImageMS->SetAttributeForNthChannel(3, InstanceFilterType::GetNameFromAttribute(InstanceFilterType::ATTRIBUTE_RN);
m_GTColorFilter = HooverColorFilterType::New();
m_GTColorFilter->SetInput(m_AttributeImageGT->GetOutput());
m_MSColorFilter = HooverColorFilterType::New();
m_MSColorFilter->SetInput(m_AttributeImageMS->GetOutput());
Int16PixelType colorPixel;
colorPixel.SetSize(3);
// Background : white
colorPixel[0] = 255;
colorPixel[1] = 255;
colorPixel[2] = 255;
m_GTColorFilter->GetFunctor().SetBackground(colorPixel);
m_MSColorFilter->GetFunctor().SetBackground(colorPixel);
// Correct detection : green
colorPixel[0] = 0;
colorPixel[1] = 255;
colorPixel[2] = 0;
m_GTColorFilter->GetFunctor().AddColor(colorPixel);
m_MSColorFilter->GetFunctor().AddColor(colorPixel);
// Over-segmentation : magenta
colorPixel[0] = 255;
colorPixel[1] = 0;
colorPixel[2] = 255;
m_GTColorFilter->GetFunctor().AddColor(colorPixel);
m_MSColorFilter->GetFunctor().AddColor(colorPixel);
// Under-segmentation : cyan
colorPixel[0] = 0;
colorPixel[1] = 255;
colorPixel[2] = 255;
m_GTColorFilter->GetFunctor().AddColor(colorPixel);
m_MSColorFilter->GetFunctor().AddColor(colorPixel);
// Missed detection (only for GT) : red
colorPixel[0] = 255;
colorPixel[1] = 0;
colorPixel[2] = 0;
m_GTColorFilter->GetFunctor().AddColor(colorPixel);
if (HasValue("outgt"))
{
SetParameterOutputImage("outgt", m_GTColorFilter->GetOutput());
}
if (HasValue("outms"))
{
SetParameterOutputImage("outms", m_MSColorFilter->GetOutput());
}
m_InstanceFilter->Update();
SetParameterFloat("rc",m_InstanceFilter->GetMeanRC());
SetParameterFloat("rf",m_InstanceFilter->GetMeanRF());
SetParameterFloat("ra",m_InstanceFilter->GetMeanRA());
SetParameterFloat("rm",m_InstanceFilter->GetMeanRM());
}
ImageToLabelMapFilterType::Pointer m_GTFilter;
ImageToLabelMapFilterType::Pointer m_MSFilter;
HooverMatrixFilterType::Pointer m_HooverFilter;
InstanceFilterType::Pointer m_InstanceFilter;
AttributeImageFilterType::Pointer m_AttributeImageGT;
AttributeImageFilterType::Pointer m_AttributeImageMS;
HooverColorFilterType::Pointer m_GTColorFilter;
HooverColorFilterType::Pointer m_MSColorFilter;
};
}
}
OTB_APPLICATION_EXPORT(otb::Wrapper::HooverCompareSegmentation)
|
/*
* Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* 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 "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"
#include "otbHooverMatrixFilter.h"
#include "otbHooverInstanceFilter.h"
#include "otbLabelMapToAttributeImageFilter.h"
#include "itkLabelImageToLabelMapFilter.h"
#include "otbFunctorImageFilter.h"
namespace otb
{
namespace Functor
{
// Functor to color Hoover instances
template<class TInput, class TOutput>
class HooverColorMapping
{
public:
HooverColorMapping() {}
virtual ~HooverColorMapping() {}
typedef std::vector<TOutput> ColorListType;
size_t OutputSize(const std::array<size_t,1> & itkNotUsed(nbBands)) const
{
return 3;
}
void AddColor(const TOutput& color)
{
m_ScoreColors.push_back(color);
}
void SetBackground(const TOutput& bg)
{
m_Background = bg;
}
inline TOutput operator ()(const TInput& A)
{
TOutput out;
out.SetSize(3);
typename TInput::ValueType max = 0.0;
unsigned int index=0;
for (unsigned int i=0; i<m_ScoreColors.size(); i++)
{
if (A[i] > max)
{
index = i;
max = A[i];
}
}
if (max > 0.01)
{
out = m_ScoreColors[index];
}
else
{
out = m_Background;
}
return out;
}
private:
ColorListType m_ScoreColors;
TOutput m_Background;
};
} // end namespace Functor
namespace Wrapper
{
class HooverCompareSegmentation : public Application
{
public:
/** Standard class typedefs. */
typedef HooverCompareSegmentation Self;
typedef Application Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
/** Standard macro */
itkNewMacro(Self);
itkTypeMacro(HooverCompareSegmentation, otb::Application);
typedef otb::AttributesMapLabelObject<unsigned int, 2, float> LabelObjectType;
typedef itk::LabelMap<LabelObjectType> LabelMapType;
typedef otb::HooverMatrixFilter<LabelMapType> HooverMatrixFilterType;
typedef UInt32ImageType ImageType;
typedef FloatVectorImageType::PixelType FloatPixelType;
typedef Int16VectorImageType::PixelType Int16PixelType;
//typedef otb::VectorImage<float, 2> VectorImageType;
typedef itk::LabelImageToLabelMapFilter
<ImageType, LabelMapType> ImageToLabelMapFilterType;
typedef otb::ImageFileReader<ImageType> ImageReaderType;
typedef HooverMatrixFilterType::MatrixType MatrixType;
typedef otb::HooverInstanceFilter<LabelMapType> InstanceFilterType;
typedef otb::LabelMapToAttributeImageFilter
<LabelMapType, FloatVectorImageType> AttributeImageFilterType;
typedef otb::FunctorImageFilter
<Functor::HooverColorMapping
<FloatPixelType, Int16PixelType> > HooverColorFilterType;
private:
void DoInit() override
{
SetName("HooverCompareSegmentation");
SetDescription("Compare two segmentations with Hoover metrics");
// Documentation
SetDocName("Hoover compare segmentation");
SetDocLongDescription("This application compares a machine segmentation (MS) with a partial "
"ground truth segmentation (GT). The Hoover metrics are used to estimate "
"scores for correct detection, over-segmentation, under-segmentation and "
"missed detection.\n\n"
"The application can output the overall Hoover scores along with colored"
"images of the MS and GT segmentation showing the state of each region "
"(correct detection, over-segmentation, under-segmentation, missed).\n\n"
"The Hoover metrics are described in: Hoover et al., \"An experimental"
" comparison of range image segmentation algorithms\", IEEE PAMI vol. 18, no. 7, July 1996.");
SetDocLimitations("None");
SetDocAuthors("OTB-Team");
SetDocSeeAlso("otbHooverMatrixFilter, otbHooverInstanceFilter, otbLabelMapToAttributeImageFilter");
AddDocTag(Tags::Segmentation);
AddParameter(ParameterType_InputImage, "ingt", "Input ground truth");
SetParameterDescription( "ingt", "A partial ground truth segmentation image." );
AddParameter(ParameterType_InputImage, "inms", "Input machine segmentation");
SetParameterDescription( "inms", "A machine segmentation image." );
AddParameter(ParameterType_Int, "bg", "Background label");
SetParameterDescription("bg", "Label value of the background in the input segmentations");
SetDefaultParameterInt("bg", 0);
AddParameter(ParameterType_Float, "th", "Overlapping threshold");
SetParameterDescription("th", "Overlapping threshold used to find Hoover instances.");
SetDefaultParameterFloat("th", 0.75);
AddParameter(ParameterType_OutputImage, "outgt", "Colored ground truth output");
SetParameterDescription( "outgt", "The colored ground truth output image." );
SetDefaultOutputPixelType("outgt",ImagePixelType_uint8);
MandatoryOff("outgt");
AddParameter(ParameterType_OutputImage, "outms", "Colored machine segmentation output");
SetParameterDescription( "outms", "The colored machine segmentation output image." );
SetDefaultOutputPixelType("outms",ImagePixelType_uint8);
MandatoryOff("outms");
// TODO : add color settings ?
AddParameter(ParameterType_Float, "rc", "Correct detection score");
SetParameterDescription("rc", "Overall score for correct detection (RC)");
SetParameterRole("rc", Role_Output);
AddParameter(ParameterType_Float, "rf", "Over-segmentation score");
SetParameterDescription("rf", "Overall score for over segmentation (RF)");
SetParameterRole("rf", Role_Output);
AddParameter(ParameterType_Float, "ra", "Under-segmentation score");
SetParameterDescription("ra", "Overall score for under segmentation (RA)");
SetParameterRole("ra", Role_Output);
AddParameter(ParameterType_Float, "rm", "Missed detection score");
SetParameterDescription("rm", "Overall score for missed detection (RM)");
SetParameterRole("rm", Role_Output);
// Doc example parameter settings
SetDocExampleParameterValue("ingt", "maur_GT.tif");
SetDocExampleParameterValue("inms", "maur_labelled.tif");
SetDocExampleParameterValue("outgt", "maur_colored_GT.tif uint8");
SetOfficialDocLink();
}
void DoUpdateParameters() override
{
// Nothing to do here : all parameters are independent
}
void DoExecute() override
{
UInt32ImageType::Pointer inputGT = GetParameterUInt32Image("ingt");
UInt32ImageType::Pointer inputMS = GetParameterUInt32Image("inms");
m_GTFilter = ImageToLabelMapFilterType::New();
m_GTFilter->SetInput(inputGT);
m_GTFilter->SetBackgroundValue( GetParameterInt("bg") );
m_MSFilter = ImageToLabelMapFilterType::New();
m_MSFilter->SetInput(inputMS);
m_MSFilter->SetBackgroundValue( GetParameterInt("bg") );
m_HooverFilter = HooverMatrixFilterType::New();
m_HooverFilter->SetGroundTruthLabelMap(m_GTFilter->GetOutput());
m_HooverFilter->SetMachineSegmentationLabelMap(m_MSFilter->GetOutput());
m_HooverFilter->Update();
m_InstanceFilter = InstanceFilterType::New();
m_InstanceFilter->SetGroundTruthLabelMap(m_GTFilter->GetOutput());
m_InstanceFilter->SetMachineSegmentationLabelMap(m_MSFilter->GetOutput());
m_InstanceFilter->SetThreshold( GetParameterFloat("th") );
m_InstanceFilter->SetHooverMatrix( m_HooverFilter->GetHooverConfusionMatrix() );
m_InstanceFilter->SetUseExtendedAttributes(false);
m_AttributeImageGT = AttributeImageFilterType::New();
m_AttributeImageGT->SetInput(m_InstanceFilter->GetOutputGroundTruthLabelMap());
m_AttributeImageGT->SetAttributeForNthChannel(0, InstanceFilterType::GetNameFromAttribute(InstanceFilterType::ATTRIBUTE_RC));
m_AttributeImageGT->SetAttributeForNthChannel(1, InstanceFilterType::GetNameFromAttribute(InstanceFilterType::ATTRIBUTE_RF));
m_AttributeImageGT->SetAttributeForNthChannel(2, InstanceFilterType::GetNameFromAttribute(InstanceFilterType::ATTRIBUTE_RA));
m_AttributeImageGT->SetAttributeForNthChannel(3, InstanceFilterType::GetNameFromAttribute(InstanceFilterType::ATTRIBUTE_RM));
m_AttributeImageMS = AttributeImageFilterType::New();
m_AttributeImageMS->SetInput(m_InstanceFilter->GetOutputMachineSegmentationLabelMap());
m_AttributeImageMS->SetAttributeForNthChannel(0, InstanceFilterType::GetNameFromAttribute(InstanceFilterType::ATTRIBUTE_RC));
m_AttributeImageMS->SetAttributeForNthChannel(1, InstanceFilterType::GetNameFromAttribute(InstanceFilterType::ATTRIBUTE_RF));
m_AttributeImageMS->SetAttributeForNthChannel(2, InstanceFilterType::GetNameFromAttribute(InstanceFilterType::ATTRIBUTE_RA));
//m_AttributeImageMS->SetAttributeForNthChannel(3, InstanceFilterType::GetNameFromAttribute(InstanceFilterType::ATTRIBUTE_RN);
m_GTColorFilter = HooverColorFilterType::New();
m_GTColorFilter->SetInput(m_AttributeImageGT->GetOutput());
m_MSColorFilter = HooverColorFilterType::New();
m_MSColorFilter->SetInput(m_AttributeImageMS->GetOutput());
Int16PixelType colorPixel;
colorPixel.SetSize(3);
// Background : white
colorPixel[0] = 255;
colorPixel[1] = 255;
colorPixel[2] = 255;
m_GTColorFilter->GetModifiableFunctor().SetBackground(colorPixel);
m_MSColorFilter->GetModifiableFunctor().SetBackground(colorPixel);
// Correct detection : green
colorPixel[0] = 0;
colorPixel[1] = 255;
colorPixel[2] = 0;
m_GTColorFilter->GetModifiableFunctor().AddColor(colorPixel);
m_MSColorFilter->GetModifiableFunctor().AddColor(colorPixel);
// Over-segmentation : magenta
colorPixel[0] = 255;
colorPixel[1] = 0;
colorPixel[2] = 255;
m_GTColorFilter->GetModifiableFunctor().AddColor(colorPixel);
m_MSColorFilter->GetModifiableFunctor().AddColor(colorPixel);
// Under-segmentation : cyan
colorPixel[0] = 0;
colorPixel[1] = 255;
colorPixel[2] = 255;
m_GTColorFilter->GetModifiableFunctor().AddColor(colorPixel);
m_MSColorFilter->GetModifiableFunctor().AddColor(colorPixel);
// Missed detection (only for GT) : red
colorPixel[0] = 255;
colorPixel[1] = 0;
colorPixel[2] = 0;
m_GTColorFilter->GetModifiableFunctor().AddColor(colorPixel);
if (HasValue("outgt"))
{
SetParameterOutputImage("outgt", m_GTColorFilter->GetOutput());
}
if (HasValue("outms"))
{
SetParameterOutputImage("outms", m_MSColorFilter->GetOutput());
}
m_InstanceFilter->Update();
SetParameterFloat("rc",m_InstanceFilter->GetMeanRC());
SetParameterFloat("rf",m_InstanceFilter->GetMeanRF());
SetParameterFloat("ra",m_InstanceFilter->GetMeanRA());
SetParameterFloat("rm",m_InstanceFilter->GetMeanRM());
}
ImageToLabelMapFilterType::Pointer m_GTFilter;
ImageToLabelMapFilterType::Pointer m_MSFilter;
HooverMatrixFilterType::Pointer m_HooverFilter;
InstanceFilterType::Pointer m_InstanceFilter;
AttributeImageFilterType::Pointer m_AttributeImageGT;
AttributeImageFilterType::Pointer m_AttributeImageMS;
HooverColorFilterType::Pointer m_GTColorFilter;
HooverColorFilterType::Pointer m_MSColorFilter;
};
}
}
OTB_APPLICATION_EXPORT(otb::Wrapper::HooverCompareSegmentation)
|
replace HooverColorMapping by a functorImageFilter
|
REFAC: replace HooverColorMapping by a functorImageFilter
|
C++
|
apache-2.0
|
orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB
|
1f03ebebbf2bcd0a30c1ceae543bd5bed549f191
|
cuda_wrapper/event.hpp
|
cuda_wrapper/event.hpp
|
/* cuda_wrapper/event.hpp
*
* Copyright (C) 2007 Peter Colberg
*
* 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/>.
*/
#ifndef CUDA_EVENT_HPP
#define CUDA_EVENT_HPP
#include <boost/shared_ptr.hpp>
#include <boost/utility.hpp>
#include <cuda_runtime.h>
#include <cuda_wrapper/error.hpp>
#include <cuda_wrapper/stream.hpp>
namespace cuda
{
#if (CUDART_VERSION >= 1010)
/**
* CUDA event wrapper class
*/
class event
{
private:
struct container : boost::noncopyable
{
/**
* creates an event
*/
container()
{
CUDA_CALL(cudaEventCreate(&m_event));
}
/**
* destroys the event
*/
~container() throw() // no-throw guarantee
{
cudaEventDestroy(m_event);
}
cudaEvent_t m_event;
};
public:
/**
* creates an event
*/
event() : m_event(new container) {}
/**
* records an event
*
* after all preceding operations in the CUDA context have been completed
*/
void record()
{
CUDA_CALL(cudaEventRecord(m_event->m_event, 0));
}
/**
* records an event
*
* after all preceding operations in the stream have been completed
*/
void record(const stream& stream)
{
CUDA_CALL(cudaEventRecord(m_event->m_event, stream.data()));
}
/**
* blocks until the event has actually been recorded
*/
void synchronize()
{
CUDA_CALL(cudaEventSynchronize(m_event->m_event));
}
/**
* checks if the event has actually been recorded
*
* WARNING: this function will not detect kernel launch failures
*/
bool query()
{
cudaError_t err = cudaEventQuery(m_event->m_event);
if (cudaSuccess == err)
return true;
else if (cudaErrorNotReady == err)
return false;
CUDA_ERROR(err);
}
/**
* computes the elapsed time between two events
*
* (in seconds with a resolution of around 0.5 microseconds)
*/
float operator-(const event &start)
{
float time;
CUDA_CALL(cudaEventElapsedTime(&time, start.m_event->m_event, m_event->m_event));
return (1.e-3f * time);
}
/**
* returns event
*/
cudaEvent_t data() const
{
return m_event->m_event;
}
private:
boost::shared_ptr<container> m_event;
};
#endif /* CUDART_VERSION >= 1010 */
}
#endif /* ! CUDA_EVENT_HPP */
|
/* cuda_wrapper/event.hpp
*
* Copyright (C) 2007 Peter Colberg
*
* 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/>.
*/
#ifndef CUDA_EVENT_HPP
#define CUDA_EVENT_HPP
#include <boost/shared_ptr.hpp>
#include <boost/utility.hpp>
#include <cuda_runtime.h>
#include <cuda_wrapper/error.hpp>
#include <cuda_wrapper/stream.hpp>
namespace cuda
{
#if (CUDART_VERSION >= 1010)
/**
* CUDA event wrapper class
*/
class event
{
private:
struct container : boost::noncopyable
{
/**
* creates an event
*/
container()
{
CUDA_CALL(cudaEventCreate(&m_event));
}
#if (CUDART_VERSION >= 2020)
/**
* creates an event with given flags
*/
container(int flags)
{
CUDA_CALL(cudaEventCreateWithFlags(&m_event, flags));
}
#endif
/**
* destroys the event
*/
~container() throw() // no-throw guarantee
{
cudaEventDestroy(m_event);
}
cudaEvent_t m_event;
};
public:
/**
* creates an event
*/
event() : m_event(new container) {}
#if (CUDART_VERSION >= 2020)
/**
* creates an event with given flags
*/
event(int flags) : m_event(new container(flags)) {}
#endif
/**
* records an event
*
* after all preceding operations in the CUDA context have been completed
*/
void record()
{
CUDA_CALL(cudaEventRecord(m_event->m_event, 0));
}
/**
* records an event
*
* after all preceding operations in the stream have been completed
*/
void record(const stream& stream)
{
CUDA_CALL(cudaEventRecord(m_event->m_event, stream.data()));
}
/**
* blocks until the event has actually been recorded
*/
void synchronize()
{
CUDA_CALL(cudaEventSynchronize(m_event->m_event));
}
/**
* checks if the event has actually been recorded
*
* WARNING: this function will not detect kernel launch failures
*/
bool query()
{
cudaError_t err = cudaEventQuery(m_event->m_event);
if (cudaSuccess == err)
return true;
else if (cudaErrorNotReady == err)
return false;
CUDA_ERROR(err);
}
/**
* computes the elapsed time between two events
*
* (in seconds with a resolution of around 0.5 microseconds)
*/
float operator-(const event &start)
{
float time;
CUDA_CALL(cudaEventElapsedTime(&time, start.m_event->m_event, m_event->m_event));
return (1.e-3f * time);
}
/**
* returns event
*/
cudaEvent_t data() const
{
return m_event->m_event;
}
private:
boost::shared_ptr<container> m_event;
};
#endif /* CUDART_VERSION >= 1010 */
}
#endif /* ! CUDA_EVENT_HPP */
|
Support events with flags in CUDA ≥ 2.2
|
Support events with flags in CUDA ≥ 2.2
|
C++
|
bsd-3-clause
|
halmd-org/cuda-wrapper
|
d10b5c52e642cf843187100f07aa93f075cff0e9
|
src/platform/qt/AboutScreen.cpp
|
src/platform/qt/AboutScreen.cpp
|
/* Copyright (c) 2013-2015 Jeffrey Pfau
*
* 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/. */
#include "AboutScreen.h"
#include "util/version.h"
#include <QPixmap>
using namespace QGBA;
AboutScreen::AboutScreen(QWidget* parent)
: QDialog(parent)
{
m_ui.setupUi(this);
QPixmap logo(":/res/mgba-1024.png");
logo = logo.scaled(m_ui.logo->minimumSize() * devicePixelRatio(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
logo.setDevicePixelRatio(devicePixelRatio());
m_ui.logo->setPixmap(logo);
m_ui.projectName->setText(QLatin1String(projectName));
m_ui.projectVersion->setText(QLatin1String(projectVersion));
QString gitInfo = m_ui.gitInfo->text();
gitInfo.replace("{gitBranch}", QLatin1String(gitBranch));
gitInfo.replace("{gitCommit}", QLatin1String(gitCommit));
m_ui.gitInfo->setText(gitInfo);
QString description = m_ui.description->text();
description.replace("{projectName}", QLatin1String(projectName));
m_ui.description->setText(description);
QString extraLinks = m_ui.extraLinks->text();
extraLinks.replace("{gitBranch}", QLatin1String(gitBranch));
m_ui.extraLinks->setText(extraLinks);
}
|
/* Copyright (c) 2013-2015 Jeffrey Pfau
*
* 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/. */
#include "AboutScreen.h"
#include "util/version.h"
#include <QPixmap>
using namespace QGBA;
AboutScreen::AboutScreen(QWidget* parent)
: QDialog(parent)
{
m_ui.setupUi(this);
QPixmap logo(":/res/mgba-1024.png");
logo = logo.scaled(m_ui.logo->minimumSize() * devicePixelRatio(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
logo.setDevicePixelRatio(devicePixelRatio());
m_ui.logo->setPixmap(logo);
QLatin1String tree(gitBranch);
if (tree == QLatin1String("(unknown)")) {
tree = QLatin1String(projectVersion);
}
m_ui.projectName->setText(QLatin1String(projectName));
m_ui.projectVersion->setText(QLatin1String(projectVersion));
QString gitInfo = m_ui.gitInfo->text();
gitInfo.replace("{gitBranch}", QLatin1String(gitBranch));
gitInfo.replace("{gitCommit}", QLatin1String(gitCommit));
m_ui.gitInfo->setText(gitInfo);
QString description = m_ui.description->text();
description.replace("{projectName}", QLatin1String(projectName));
m_ui.description->setText(description);
QString extraLinks = m_ui.extraLinks->text();
extraLinks.replace("{gitBranch}", tree);
m_ui.extraLinks->setText(extraLinks);
}
|
Use the version string for the about dialog if the branch is unknown
|
Qt: Use the version string for the about dialog if the branch is unknown
|
C++
|
mpl-2.0
|
zerofalcon/mgba,mgba-emu/mgba,fr500/mgba,Anty-Lemon/mgba,askotx/mgba,zerofalcon/mgba,Touched/mgba,libretro/mgba,Anty-Lemon/mgba,Touched/mgba,Iniquitatis/mgba,jeremyherbert/mgba,jeremyherbert/mgba,mgba-emu/mgba,cassos/mgba,libretro/mgba,AdmiralCurtiss/mgba,jeremyherbert/mgba,MerryMage/mgba,askotx/mgba,AdmiralCurtiss/mgba,iracigt/mgba,Anty-Lemon/mgba,fr500/mgba,askotx/mgba,libretro/mgba,libretro/mgba,iracigt/mgba,sergiobenrocha2/mgba,zerofalcon/mgba,Iniquitatis/mgba,iracigt/mgba,sergiobenrocha2/mgba,askotx/mgba,Iniquitatis/mgba,fr500/mgba,iracigt/mgba,mgba-emu/mgba,Anty-Lemon/mgba,jeremyherbert/mgba,MerryMage/mgba,sergiobenrocha2/mgba,cassos/mgba,Touched/mgba,libretro/mgba,cassos/mgba,fr500/mgba,mgba-emu/mgba,Iniquitatis/mgba,sergiobenrocha2/mgba,sergiobenrocha2/mgba,AdmiralCurtiss/mgba,MerryMage/mgba
|
19fc7be9954c7c5467b1c1d1b61d36666442c395
|
examples/src/calibration_reader.cpp
|
examples/src/calibration_reader.cpp
|
#include <cstdio>
#include <iostream>
#include <string>
// Inludes common necessary includes for development using depthai library
#include "depthai-shared/common/CameraBoardSocket.hpp"
#include "depthai-shared/common/EepromData.hpp"
#include "depthai/depthai.hpp"
void printMatrix(std::vector<std::vector<float>> matrix) {
using namespace std;
std::string out = "[";
for(auto row : matrix) {
out += "[";
for(auto val : row) out += to_string(val) + ", ";
out = out.substr(0, out.size() - 2) + "]\n";
}
out = out.substr(0, out.size() - 1) + "]\n\n";
cout << out;
}
int main(int argc, char** argv) {
using namespace std;
// Connect Device
dai::Device device;
dai::CalibrationHandler calibData = device.readCalibration();
// calibData.eepromToJsonFile(filename);
std::vector<std::vector<float>> intrinsics;
int width, height;
cout << "Intrinsics from defaultIntrinsics function:" << endl;
std::tie(intrinsics, width, height) = calibData.getDefaultIntrinsics(dai::CameraBoardSocket::RIGHT);
printMatrix(intrinsics);
cout << "Width: " << width << endl;
cout << "Height: " << height << endl;
cout << "Stereo baseline distance: " << calibData.getBaselineDistance() << " cm" << endl;
cout << "Mono FOV from camera specs: " << calibData.getFov(dai::CameraBoardSocket::LEFT)
<< ", calculated FOV: " << calibData.getFov(dai::CameraBoardSocket::LEFT, false) << endl;
cout << "Intrinsics from getCameraIntrinsics function full resolution:" << endl;
intrinsics = calibData.getCameraIntrinsics(dai::CameraBoardSocket::RIGHT);
printMatrix(intrinsics);
cout << "Intrinsics from getCameraIntrinsics function 1280 x 720:" << endl;
intrinsics = calibData.getCameraIntrinsics(dai::CameraBoardSocket::RIGHT, 1280, 720);
printMatrix(intrinsics);
cout << "Intrinsics from getCameraIntrinsics function 720 x 450:" << endl;
intrinsics = calibData.getCameraIntrinsics(dai::CameraBoardSocket::RIGHT, 720);
printMatrix(intrinsics);
cout << "Intrinsics from getCameraIntrinsics function 600 x 1280:" << endl;
intrinsics = calibData.getCameraIntrinsics(dai::CameraBoardSocket::RIGHT, 600, 1280);
printMatrix(intrinsics);
std::vector<std::vector<float>> extrinsics;
cout << "Extrinsics from left->right test:" << endl;
extrinsics = calibData.getCameraExtrinsics(dai::CameraBoardSocket::LEFT, dai::CameraBoardSocket::RIGHT);
printMatrix(extrinsics);
cout << "Extrinsics from right->left test:" << endl;
extrinsics = calibData.getCameraExtrinsics(dai::CameraBoardSocket::RIGHT, dai::CameraBoardSocket::LEFT);
printMatrix(extrinsics);
cout << "Extrinsics from right->rgb test:" << endl;
extrinsics = calibData.getCameraExtrinsics(dai::CameraBoardSocket::RIGHT, dai::CameraBoardSocket::RGB);
printMatrix(extrinsics);
cout << "Extrinsics from rgb->right test:" << endl;
extrinsics = calibData.getCameraExtrinsics(dai::CameraBoardSocket::RGB, dai::CameraBoardSocket::RIGHT);
printMatrix(extrinsics);
cout << "Extrinsics from left->rgb test:" << endl;
extrinsics = calibData.getCameraExtrinsics(dai::CameraBoardSocket::LEFT, dai::CameraBoardSocket::RGB);
printMatrix(extrinsics);
return 0;
}
|
#include <cstdio>
#include <iostream>
#include <string>
// Inludes common necessary includes for development using depthai library
#include "depthai-shared/common/CameraBoardSocket.hpp"
#include "depthai-shared/common/EepromData.hpp"
#include "depthai/depthai.hpp"
void printMatrix(std::vector<std::vector<float>> matrix) {
using namespace std;
std::string out = "[";
for(auto row : matrix) {
out += "[";
for(auto val : row) out += to_string(val) + ", ";
out = out.substr(0, out.size() - 2) + "]\n";
}
out = out.substr(0, out.size() - 1) + "]\n\n";
cout << out;
}
int main(int argc, char** argv) {
using namespace std;
// Connect Device
dai::Device device;
dai::CalibrationHandler calibData = device.readCalibration();
// calibData.eepromToJsonFile(filename);
std::vector<std::vector<float>> intrinsics;
int width, height;
cout << "Intrinsics from defaultIntrinsics function:" << endl;
std::tie(intrinsics, width, height) = calibData.getDefaultIntrinsics(dai::CameraBoardSocket::RIGHT);
printMatrix(intrinsics);
cout << "Width: " << width << endl;
cout << "Height: " << height << endl;
cout << "Stereo baseline distance: " << calibData.getBaselineDistance() << " cm" << endl;
cout << "Mono FOV from camera specs: " << calibData.getFov(dai::CameraBoardSocket::LEFT)
<< ", calculated FOV: " << calibData.getFov(dai::CameraBoardSocket::LEFT, false) << endl;
cout << "Intrinsics from getCameraIntrinsics function full resolution:" << endl;
intrinsics = calibData.getCameraIntrinsics(dai::CameraBoardSocket::RIGHT);
printMatrix(intrinsics);
cout << "Intrinsics from getCameraIntrinsics function 1280 x 720:" << endl;
intrinsics = calibData.getCameraIntrinsics(dai::CameraBoardSocket::RIGHT, 1280, 720);
printMatrix(intrinsics);
cout << "Intrinsics from getCameraIntrinsics function 720 x 450:" << endl;
intrinsics = calibData.getCameraIntrinsics(dai::CameraBoardSocket::RIGHT, 720);
printMatrix(intrinsics);
cout << "Intrinsics from getCameraIntrinsics function 600 x 1280:" << endl;
intrinsics = calibData.getCameraIntrinsics(dai::CameraBoardSocket::RIGHT, 600, 1280);
printMatrix(intrinsics);
std::vector<std::vector<float>> extrinsics;
cout << "Extrinsics from left->right test:" << endl;
extrinsics = calibData.getCameraExtrinsics(dai::CameraBoardSocket::LEFT, dai::CameraBoardSocket::RIGHT);
printMatrix(extrinsics);
cout << "Extrinsics from right->left test:" << endl;
extrinsics = calibData.getCameraExtrinsics(dai::CameraBoardSocket::RIGHT, dai::CameraBoardSocket::LEFT);
printMatrix(extrinsics);
cout << "Extrinsics from right->rgb test:" << endl;
extrinsics = calibData.getCameraExtrinsics(dai::CameraBoardSocket::RIGHT, dai::CameraBoardSocket::RGB);
printMatrix(extrinsics);
cout << "Extrinsics from rgb->right test:" << endl;
extrinsics = calibData.getCameraExtrinsics(dai::CameraBoardSocket::RGB, dai::CameraBoardSocket::RIGHT);
printMatrix(extrinsics);
cout << "Extrinsics from left->rgb test:" << endl;
extrinsics = calibData.getCameraExtrinsics(dai::CameraBoardSocket::LEFT, dai::CameraBoardSocket::RGB);
printMatrix(extrinsics);
return 0;
}
|
Update calibration_reader.cpp
|
Update calibration_reader.cpp
|
C++
|
mit
|
luxonis/depthai-core,luxonis/depthai-core,luxonis/depthai-core
|
2f0bb4daf23a6761f094326b7122717c50759e01
|
test/CheckTests.cpp
|
test/CheckTests.cpp
|
#include <catch.hpp>
#include <rapidcheck/catch.h>
#include "rapidcheck/detail/TestListenerAdapter.h"
#include "util/MockTestListener.h"
#include "util/GenUtils.h"
#include "util/Generators.h"
using namespace rc;
using namespace rc::test;
using namespace rc::detail;
namespace {
TestListenerAdapter dummyListener;
} // namespace
TEST_CASE("checkTestable") {
prop("calls onTestFinished with the test results once",
[](const TestMetadata &metadata, const TestParams ¶ms, int limit) {
Maybe<std::tuple<TestMetadata, TestResult>> callbackParams;
MockTestListener listener;
listener.onTestFinishedCallback =
[&](const TestMetadata &metadata, const TestResult &result) {
RC_ASSERT(!callbackParams);
callbackParams.init(metadata, result);
};
const auto result = checkTestable([&] {
const auto x = *gen::arbitrary<int>();
if ((x % 3) == 0) {
RC_DISCARD("");
}
RC_ASSERT(x < limit);
}, metadata, params, listener);
RC_ASSERT(callbackParams);
RC_ASSERT(std::get<0>(*callbackParams) == metadata);
RC_ASSERT(std::get<1>(*callbackParams) == result);
});
SECTION("reproducing (non-properties)") {
TestMetadata metadata;
TestParams params;
std::unordered_map<std::string, Reproduce> reproMap;
SECTION("runs property if Reproduce map is empty") {
metadata.id = "foobar";
const auto result =
checkTestable([] {}, metadata, params, dummyListener, reproMap);
SuccessResult success;
REQUIRE(result.match(success));
// Since the property always succeeds, if the property is actually run
// then
// it should have been run the maximum number of times
REQUIRE(success.numSuccess == params.maxSuccess);
}
SECTION(
"always succeeds with no cases run if ID is empty and Reproduce is "
"non-empty") {
metadata.id = "";
reproMap[""] = Reproduce();
const auto result =
checkTestable([] {}, metadata, params, dummyListener, reproMap);
SuccessResult success;
REQUIRE(result.match(success));
REQUIRE(success.numSuccess == 0);
}
SECTION(
"always succeeds with no cases run if ID is not found in Reproduce "
"map") {
metadata.id = "foobar";
reproMap["barfoo"] = Reproduce();
const auto result =
checkTestable([] {}, metadata, params, dummyListener, reproMap);
SuccessResult success;
REQUIRE(result.match(success));
REQUIRE(success.numSuccess == 0);
}
}
prop("reproduces result from failure",
[](const TestMetadata &metadata, TestParams params) {
RC_PRE(!metadata.id.empty());
const auto max = *gen::inRange<int>(0, 2000);
const auto testable = [=](int a, int b) {
if ((a > max) || (b > max)) {
throw std::to_string(a) + " " + std::to_string(b);
}
};
params.maxSuccess = 2000;
params.maxSize = kNominalSize;
const auto result =
checkTestable(testable,
metadata,
params,
dummyListener,
std::unordered_map<std::string, Reproduce>());
FailureResult failure;
RC_ASSERT(result.match(failure));
std::unordered_map<std::string, Reproduce> reproMap{
{metadata.id, failure.reproduce}};
const auto reproduced =
checkTestable(testable, metadata, params, dummyListener, reproMap);
FailureResult reproducedFailure;
RC_ASSERT(reproduced.match(reproducedFailure));
RC_ASSERT(failure.description == reproducedFailure.description);
RC_ASSERT(failure.reproduce == reproducedFailure.reproduce);
RC_ASSERT(failure.counterExample == reproducedFailure.counterExample);
RC_ASSERT(reproducedFailure.numSuccess == 0);
});
}
|
#include <catch.hpp>
#include <rapidcheck/catch.h>
#include "rapidcheck/detail/TestListenerAdapter.h"
#include "util/MockTestListener.h"
#include "util/GenUtils.h"
#include "util/Generators.h"
using namespace rc;
using namespace rc::test;
using namespace rc::detail;
namespace {
TestListenerAdapter dummyListener;
} // namespace
TEST_CASE("checkTestable") {
prop("calls onTestFinished with the test results once",
[](const TestMetadata &metadata, const TestParams ¶ms, int limit) {
Maybe<std::tuple<TestMetadata, TestResult>> callbackParams;
MockTestListener listener;
listener.onTestFinishedCallback =
[&](const TestMetadata &metadata, const TestResult &result) {
RC_ASSERT(!callbackParams);
callbackParams.init(metadata, result);
};
const auto result = checkTestable([&] {
const auto x = *gen::arbitrary<int>();
if ((x % 3) == 0) {
RC_DISCARD("");
}
RC_ASSERT(x < limit);
}, metadata, params, listener);
RC_ASSERT(callbackParams);
RC_ASSERT(std::get<0>(*callbackParams) == metadata);
RC_ASSERT(std::get<1>(*callbackParams) == result);
});
SECTION("reproducing (non-properties)") {
TestMetadata metadata;
TestParams params;
std::unordered_map<std::string, Reproduce> reproMap;
SECTION("runs property if Reproduce map is empty") {
metadata.id = "foobar";
const auto result =
checkTestable([] {}, metadata, params, dummyListener, reproMap);
SuccessResult success;
REQUIRE(result.match(success));
// Since the property always succeeds, if the property is actually run
// then
// it should have been run the maximum number of times
REQUIRE(success.numSuccess == params.maxSuccess);
}
SECTION(
"always succeeds with no cases run if ID is empty and Reproduce is "
"non-empty") {
metadata.id = "";
reproMap[""] = Reproduce();
const auto result =
checkTestable([] {}, metadata, params, dummyListener, reproMap);
SuccessResult success;
REQUIRE(result.match(success));
REQUIRE(success.numSuccess == 0);
}
SECTION(
"always succeeds with no cases run if ID is not found in Reproduce "
"map") {
metadata.id = "foobar";
reproMap["barfoo"] = Reproduce();
const auto result =
checkTestable([] {}, metadata, params, dummyListener, reproMap);
SuccessResult success;
REQUIRE(result.match(success));
REQUIRE(success.numSuccess == 0);
}
}
prop("reproduces result from failure",
[](const TestMetadata &metadata, TestParams params) {
RC_PRE(!metadata.id.empty());
const auto max = *gen::inRange<int>(0, 2000);
const auto testable = [=](int a, int b) {
if ((a > max) || (b > max)) {
throw std::to_string(a) + " " + std::to_string(b);
}
};
// Find a failure
params.maxSuccess = 2000;
params.maxSize = kNominalSize;
const auto result =
checkTestable(testable,
metadata,
params,
dummyListener,
std::unordered_map<std::string, Reproduce>());
FailureResult failure;
RC_ASSERT(result.match(failure));
// Then reproduce it
std::unordered_map<std::string, Reproduce> reproMap{
{metadata.id, failure.reproduce}};
const auto reproduced =
checkTestable(testable, metadata, params, dummyListener, reproMap);
// Should be the same
FailureResult reproducedFailure;
RC_ASSERT(reproduced.match(reproducedFailure));
RC_ASSERT(failure.description == reproducedFailure.description);
RC_ASSERT(failure.reproduce == reproducedFailure.reproduce);
RC_ASSERT(failure.counterExample == reproducedFailure.counterExample);
// ...except for number of successful tests run, should be none
RC_ASSERT(reproducedFailure.numSuccess == 0);
});
}
|
Clarify reproduce test with comments
|
Clarify reproduce test with comments
|
C++
|
bsd-2-clause
|
unapiedra/rapidfuzz,unapiedra/rapidfuzz,unapiedra/rapidfuzz,emil-e/rapidcheck,emil-e/rapidcheck,emil-e/rapidcheck
|
36ef2ad77e342948163ae9babbc5602d5b5bf091
|
test/exceptions.cpp
|
test/exceptions.cpp
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2011 Gael Guennebaud <[email protected]>
//
// 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/.
// Various sanity tests with exceptions:
// - no memory leak when a custom scalar type trow an exceptions
// - todo: complete the list of tests!
#define EIGEN_STACK_ALLOCATION_LIMIT 100000000
#include "main.h"
struct my_exception
{
my_exception() {}
~my_exception() {}
};
class ScalarWithExceptions
{
public:
ScalarWithExceptions() { init(); }
ScalarWithExceptions(const float& _v) { init(); *v = _v; }
ScalarWithExceptions(const ScalarWithExceptions& other) { init(); *v = *(other.v); }
~ScalarWithExceptions() {
delete v;
instances--;
}
void init() {
v = new float;
instances++;
}
ScalarWithExceptions operator+(const ScalarWithExceptions& other) const
{
countdown--;
if(countdown<=0)
throw my_exception();
return ScalarWithExceptions(*v+*other.v);
}
ScalarWithExceptions operator-(const ScalarWithExceptions& other) const
{ return ScalarWithExceptions(*v-*other.v); }
ScalarWithExceptions operator*(const ScalarWithExceptions& other) const
{ return ScalarWithExceptions((*v)*(*other.v)); }
ScalarWithExceptions& operator+=(const ScalarWithExceptions& other)
{ *v+=*other.v; return *this; }
ScalarWithExceptions& operator-=(const ScalarWithExceptions& other)
{ *v-=*other.v; return *this; }
ScalarWithExceptions& operator=(const ScalarWithExceptions& other)
{ *v = *(other.v); return *this; }
bool operator==(const ScalarWithExceptions& other) const
{ return *v==*other.v; }
bool operator!=(const ScalarWithExceptions& other) const
{ return *v!=*other.v; }
float* v;
static int instances;
static int countdown;
};
int ScalarWithExceptions::instances = 0;
int ScalarWithExceptions::countdown = 0;
#define CHECK_MEMLEAK(OP) { \
ScalarWithExceptions::countdown = 100; \
int before = ScalarWithExceptions::instances; \
bool exception_thrown = false; \
try { OP; } \
catch (my_exception) { \
exception_thrown = true; \
VERIFY(ScalarWithExceptions::instances==before && "memory leak detected in " && EIGEN_MAKESTRING(OP)); \
} \
VERIFY(exception_thrown && " no exception thrown in " && EIGEN_MAKESTRING(OP)); \
}
void memoryleak()
{
typedef Eigen::Matrix<ScalarWithExceptions,Dynamic,1> VectorType;
typedef Eigen::Matrix<ScalarWithExceptions,Dynamic,Dynamic> MatrixType;
{
int n = 50;
VectorType v0(n), v1(n);
MatrixType m0(n,n), m1(n,n), m2(n,n);
v0.setOnes(); v1.setOnes();
m0.setOnes(); m1.setOnes(); m2.setOnes();
CHECK_MEMLEAK(v0 = m0 * m1 * v1);
CHECK_MEMLEAK(m2 = m0 * m1 * m2);
CHECK_MEMLEAK((v0+v1).dot(v0+v1));
}
VERIFY(ScalarWithExceptions::instances==0 && "global memory leak detected in " && EIGEN_MAKESTRING(OP)); \
}
void test_exceptions()
{
CALL_SUBTEST( memoryleak() );
}
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2011 Gael Guennebaud <[email protected]>
//
// 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/.
// Various sanity tests with exceptions:
// - no memory leak when a custom scalar type trow an exceptions
// - todo: complete the list of tests!
#define EIGEN_STACK_ALLOCATION_LIMIT 100000000
#include "main.h"
struct my_exception
{
my_exception() {}
~my_exception() {}
};
class ScalarWithExceptions
{
public:
ScalarWithExceptions() { init(); }
ScalarWithExceptions(const float& _v) { init(); *v = _v; }
ScalarWithExceptions(const ScalarWithExceptions& other) { init(); *v = *(other.v); }
~ScalarWithExceptions() {
delete v;
instances--;
}
void init() {
v = new float;
instances++;
}
ScalarWithExceptions operator+(const ScalarWithExceptions& other) const
{
countdown--;
if(countdown<=0)
throw my_exception();
return ScalarWithExceptions(*v+*other.v);
}
ScalarWithExceptions operator-(const ScalarWithExceptions& other) const
{ return ScalarWithExceptions(*v-*other.v); }
ScalarWithExceptions operator*(const ScalarWithExceptions& other) const
{ return ScalarWithExceptions((*v)*(*other.v)); }
ScalarWithExceptions& operator+=(const ScalarWithExceptions& other)
{ *v+=*other.v; return *this; }
ScalarWithExceptions& operator-=(const ScalarWithExceptions& other)
{ *v-=*other.v; return *this; }
ScalarWithExceptions& operator=(const ScalarWithExceptions& other)
{ *v = *(other.v); return *this; }
bool operator==(const ScalarWithExceptions& other) const
{ return *v==*other.v; }
bool operator!=(const ScalarWithExceptions& other) const
{ return *v!=*other.v; }
float* v;
static int instances;
static int countdown;
};
ScalarWithExceptions real(const ScalarWithExceptions &x) { return x; }
ScalarWithExceptions imag(const ScalarWithExceptions & ) { return 0; }
ScalarWithExceptions conj(const ScalarWithExceptions &x) { return x; }
int ScalarWithExceptions::instances = 0;
int ScalarWithExceptions::countdown = 0;
#define CHECK_MEMLEAK(OP) { \
ScalarWithExceptions::countdown = 100; \
int before = ScalarWithExceptions::instances; \
bool exception_thrown = false; \
try { OP; } \
catch (my_exception) { \
exception_thrown = true; \
VERIFY(ScalarWithExceptions::instances==before && "memory leak detected in " && EIGEN_MAKESTRING(OP)); \
} \
VERIFY(exception_thrown && " no exception thrown in " && EIGEN_MAKESTRING(OP)); \
}
void memoryleak()
{
typedef Eigen::Matrix<ScalarWithExceptions,Dynamic,1> VectorType;
typedef Eigen::Matrix<ScalarWithExceptions,Dynamic,Dynamic> MatrixType;
{
int n = 50;
VectorType v0(n), v1(n);
MatrixType m0(n,n), m1(n,n), m2(n,n);
v0.setOnes(); v1.setOnes();
m0.setOnes(); m1.setOnes(); m2.setOnes();
CHECK_MEMLEAK(v0 = m0 * m1 * v1);
CHECK_MEMLEAK(m2 = m0 * m1 * m2);
CHECK_MEMLEAK((v0+v1).dot(v0+v1));
}
VERIFY(ScalarWithExceptions::instances==0 && "global memory leak detected in " && EIGEN_MAKESTRING(OP)); \
}
void test_exceptions()
{
CALL_SUBTEST( memoryleak() );
}
|
Add a few missing standard functions for ScalarWithExceptions type.
|
Add a few missing standard functions for ScalarWithExceptions type.
|
C++
|
bsd-3-clause
|
robustrobotics/eigen,robustrobotics/eigen,robustrobotics/eigen,robustrobotics/eigen
|
6abd53777bf013d5bf6bab2cd1ddce78c3b5b9ad
|
test/filter_test.cc
|
test/filter_test.cc
|
#include "benchmark/benchmark.h"
#include <cassert>
#include <cmath>
#include <cstdint>
#include <cstdlib>
#include <iostream>
#include <limits>
#include <sstream>
#include <string>
namespace {
class TestReporter : public benchmark::ConsoleReporter {
public:
virtual bool ReportContext(const Context& context) {
return ConsoleReporter::ReportContext(context);
};
virtual void ReportRuns(const std::vector<Run>& report) {
++count_;
ConsoleReporter::ReportRuns(report);
};
TestReporter() : count_(0) {}
virtual ~TestReporter() {}
size_t GetCount() const {
return count_;
}
private:
mutable size_t count_;
};
} // end namespace
static void NoPrefix(benchmark::State& state) {
while (state.KeepRunning()) {}
}
BENCHMARK(NoPrefix);
static void BM_Foo(benchmark::State& state) {
while (state.KeepRunning()) {}
}
BENCHMARK(BM_Foo);
static void BM_Bar(benchmark::State& state) {
while (state.KeepRunning()) {}
}
BENCHMARK(BM_Bar);
static void BM_FooBar(benchmark::State& state) {
while (state.KeepRunning()) {}
}
BENCHMARK(BM_FooBar);
static void BM_FooBa(benchmark::State& state) {
while (state.KeepRunning()) {}
}
BENCHMARK(BM_FooBa);
int main(int argc, char* argv[]) {
benchmark::Initialize(&argc, argv);
TestReporter test_reporter;
benchmark::RunSpecifiedBenchmarks(&test_reporter);
// Make sure we ran all of the tests
const size_t count = test_reporter.GetCount();
const size_t expected = (argc == 2) ? std::atol(argv[1]) : count;
if (count != expected) {
std::cerr << "ERROR: Expected " << expected << " tests to be ran but only "
<< count << " completed" << std::endl;
return -1;
}
}
|
#include "benchmark/benchmark.h"
#include <cassert>
#include <cmath>
#include <cstdint>
#include <cstdlib>
#include <iostream>
#include <limits>
#include <sstream>
#include <string>
namespace {
class TestReporter : public benchmark::ConsoleReporter {
public:
virtual bool ReportContext(const Context& context) {
return ConsoleReporter::ReportContext(context);
};
virtual void ReportRuns(const std::vector<Run>& report) {
++count_;
ConsoleReporter::ReportRuns(report);
};
TestReporter() : count_(0) {}
virtual ~TestReporter() {}
size_t GetCount() const {
return count_;
}
private:
mutable size_t count_;
};
} // end namespace
static void NoPrefix(benchmark::State& state) {
while (state.KeepRunning()) {}
}
BENCHMARK(NoPrefix);
static void BM_Foo(benchmark::State& state) {
while (state.KeepRunning()) {}
}
BENCHMARK(BM_Foo);
static void BM_Bar(benchmark::State& state) {
while (state.KeepRunning()) {}
}
BENCHMARK(BM_Bar);
static void BM_FooBar(benchmark::State& state) {
while (state.KeepRunning()) {}
}
BENCHMARK(BM_FooBar);
static void BM_FooBa(benchmark::State& state) {
while (state.KeepRunning()) {}
}
BENCHMARK(BM_FooBa);
int main(int argc, char* argv[]) {
benchmark::Initialize(&argc, argv);
TestReporter test_reporter;
benchmark::RunSpecifiedBenchmarks(&test_reporter);
if (argc == 2) {
// Make sure we ran all of the tests
std::stringstream ss(argv[1]);
size_t expected;
ss >> expected;
const size_t count = test_reporter.GetCount();
if (count != expected) {
std::cerr << "ERROR: Expected " << expected << " tests to be ran but only "
<< count << " completed" << std::endl;
return -1;
}
}
return 0;
}
|
Use stringstream instead of atoi to avoid sign error.
|
Use stringstream instead of atoi to avoid sign error.
The sane thing here would be to use std::stoul but this is not available in the android-ndk...
|
C++
|
apache-2.0
|
efcs/benchmark,nickhutchinson/benchmark-cxx03,ntx-/benchmark,ntx-/benchmark,fuchsia-mirror/third_party-benchmark,xlqian/benchmark,eliben/benchmark,xlqian/benchmark,codygray/benchmark,xlqian/benchmark,eliben/benchmark,nickhutchinson/benchmark,chemhack/benchmark,codygray/benchmark,chemhack/benchmark,everbase/benchmark,nickhutchinson/benchmark-cxx03,disconnect3d/benchmark,disconnect3d/benchmark,chemhack/benchmark,everbase/benchmark,mockingbirdnest/benchmark,nickhutchinson/benchmark,disconnect3d/benchmark,nickhutchinson/benchmark,mockingbirdnest/benchmark,disconnect3d/benchmark,nickhutchinson/benchmark-cxx03,fuchsia-mirror/third_party-benchmark,fuchsia-mirror/third_party-benchmark,eliben/benchmark,efcs/benchmark,fuchsia-mirror/third_party-benchmark,codygray/benchmark,ntx-/benchmark,xlqian/benchmark,chemhack/benchmark,efcs/benchmark,LepelTsmok/benchmark,everbase/benchmark,google/benchmark,mockingbirdnest/benchmark,LepelTsmok/benchmark,eliben/benchmark,ntx-/benchmark,google/benchmark,codygray/benchmark,LepelTsmok/benchmark,everbase/benchmark,google/benchmark,LepelTsmok/benchmark,efcs/benchmark,nickhutchinson/benchmark,mockingbirdnest/benchmark,nickhutchinson/benchmark-cxx03
|
c4666c7aacc0cabba06c73e5b1f76a66b2c96e05
|
src/AnnGameObject.cpp
|
src/AnnGameObject.cpp
|
#include "AnnGameObject.hpp"
#include "AnnTools.h"
using namespace Annwvyn;
AnnGameObject::AnnGameObject()
{
m_node = NULL;
m_entity = NULL;
bulletReady = false;
m_DynamicsWorld = NULL;
m_Body = NULL;
m_Shape = NULL;
m_AudioEngine = NULL;
alGenSources(1,&m_Source);
m_anim = NULL;
animIsLooping = false;
animIsPlaying = false;
animIsSetted = false;
}
AnnGameObject::~AnnGameObject()
{
alSourceStop(m_Source);
alDeleteSources(1,&m_Source);
alDeleteBuffers(1,&m_Buffer);
}
void AnnGameObject::setAudioEngine(AnnAudioEngine* AudioEngine)
{
m_AudioEngine = AudioEngine;
}
void AnnGameObject::playSound(std::string path, bool loop, float volume)
{
m_Buffer = m_AudioEngine->loadSndFile(path);
alSourcei(m_Source, AL_BUFFER, m_Buffer);
if(loop)
alSourcei(m_Source, AL_LOOPING, AL_TRUE);
alSourcef(m_Source, AL_GAIN, volume);
alSource3f(m_Source, AL_POSITION,
m_node->getPosition().x,
m_node->getPosition().y,
m_node->getPosition().z);
alSourcePlay(m_Source);
}
void AnnGameObject::updateOpenAlPos()
{
alSource3f(m_Source, AL_POSITION,
pos().x,
pos().y,
pos().z);
}
void AnnGameObject::setPos(float x, float y, float z)
{
if(m_node == NULL)
return;
/*
*Position of object have to be the same in each part of the engine
*(graphics, physics, audio)
*/
//change BulletPosition
if(bulletReady)
{
m_Body->translate(btVector3(x - m_node->getPosition().x,
y - m_node->getPosition().y,
z - m_node->getPosition().z));
}
//change OgrePosition
m_node->setPosition(x,y,z);
//change OpenAL Source Position
alSource3f(m_Source, AL_POSITION,
m_node->getPosition().x,
m_node->getPosition().y,
m_node->getPosition().z);
}
void AnnGameObject::translate(float x, float y, float z)
{
//Ogre
m_node->translate(x,y,z);
//Bullet
m_Body->translate(btVector3(x,y,z));
//OpenAL
alSource3f(m_Source, AL_POSITION,
m_node->getPosition().x,
m_node->getPosition().y,
m_node->getPosition().z);
}
void AnnGameObject::setPos(Ogre::Vector3 pos)
{
setPos(pos.x,pos.y,pos.z);
}
void AnnGameObject::setOrientation(float w, float x, float y, float z)
{
//Ogre3D
if(m_node != NULL)
m_node->setOrientation(w,x,y,z);
//bullet
if(m_Body != NULL)
{
btTransform t = m_Body->getCenterOfMassTransform();
t.setRotation(btQuaternion(x,y,z,w));
m_Body->setCenterOfMassTransform(t);
}
//OpenAL
}
void AnnGameObject::setOrientation(Ogre::Quaternion orient)
{
setOrientation(orient.w,orient.x,orient.y,orient.z);
}
void AnnGameObject::setScale(Ogre::Vector3 scale)
{
setScale(scale.x,scale.y,scale.z);
}
void AnnGameObject::setScale(float x, float y, float z)
{
m_node->setScale(Ogre::Vector3(x,y,z));
}
Ogre::Vector3 AnnGameObject::pos()
{
if(m_node != NULL)
return m_node->getPosition();
return Ogre::Vector3(0,0,0);
}
Ogre::Quaternion AnnGameObject::Orientation()
{
if(m_node != NULL)
return m_node->getOrientation();
return Ogre::Quaternion(1,0,0,0);
}
void AnnGameObject::setNode(Ogre::SceneNode* node)
{
m_node = node;
}
void AnnGameObject::setEntity(Ogre::Entity* entity)
{
m_entity = entity;
}
void AnnGameObject::setBulletDynamicsWorld(btDiscreteDynamicsWorld* dynamicsWorld)
{
m_DynamicsWorld = dynamicsWorld;
}
void AnnGameObject::setUpBullet(float mass, phyShapeType type)
{
//check if everything is OK
if(m_DynamicsWorld == NULL)
return;
if(m_node == NULL)
return;
if(m_entity == NULL)
return;
//init shap converter
BtOgre::StaticMeshToShapeConverter converter(m_entity);
//create the correct shape
switch(type)
{
case boxShape:
m_Shape = converter.createBox();
break;
case cylinderShape:
m_Shape = converter.createCylinder();
break;
case capsuleShape:
m_Shape = converter.createCapsule();
break;
case convexShape:
m_Shape = converter.createConvex();
break;
case staticShape:
m_Shape = converter.createTrimesh();
break;
default:
return;
}
if(m_Shape == NULL)
return;
Ogre::Vector3 scale = node()->getScale();
m_Shape->setLocalScaling(btVector3(scale.x,scale.y,scale.z));
btVector3 inertia;
if(mass != 0)
m_Shape->calculateLocalInertia(mass, inertia);
else
inertia = btVector3(0,0,0);
BtOgre::RigidBodyState *state = new BtOgre::RigidBodyState(m_node);
//create rigidBody from shape
m_Body = new btRigidBody(mass,state,m_Shape,inertia);
if(m_Body != NULL)
{
/* m_Body->translate(btVector3(this->node()->getPosition().x,
this->node()->getPosition().y,
this->node()->getPosition().z));*/
m_DynamicsWorld->addRigidBody(m_Body);
}
else
return;
bulletReady = true;
}
Ogre::SceneNode* AnnGameObject::node()
{
return m_node;
}
Ogre::Entity* AnnGameObject::Entity()
{
return m_entity;
}
btRigidBody* AnnGameObject::RigidBody()
{
return m_Body;
}
float AnnGameObject::getDistance(AnnGameObject *otherObject)
{
return Tools::Geometry::distance(this,otherObject);
}
btRigidBody* AnnGameObject::getBody()
{
return m_Body;
}
std::vector<struct collisionTest*> AnnGameObject::getCollisionMask()
{
return collisionMask;
}
bool AnnGameObject::collideWith(AnnGameObject* Object)
{
for(size_t i = 0; i < collisionMask.size(); i++)
if(collisionMask[i]->Object == Object)
return collisionMask[i]->collisionState;
return false;
}
void AnnGameObject::updateCollisionStateWith(AnnGameObject* Object, bool state)
{
for(size_t i = 0; i < collisionMask.size(); i++)
if(collisionMask[i]->Object == Object)
collisionMask[i]->collisionState = state;
}
void AnnGameObject::cleanCollisionMask()
{
for(size_t i = 0; i < collisionMask.size(); i++)
{
delete collisionMask[i];
collisionMask.erase(collisionMask.begin()+i);
}
}
void AnnGameObject::resetCollisionMask()
{
for (size_t i = 0; i < collisionMask.size(); i++)
collisionMask[i]->collisionState = false;
}
void AnnGameObject::testCollisionWith(AnnGameObject* Object)
{
if(Object == this) return; //Explain me how I can colide with myself.
struct collisionTest* tester = new collisionTest;
tester->collisionState = false;
tester->Object = Object;
tester->Receiver = this;
collisionMask.push_back(tester);
}
void AnnGameObject::stopGettingCollisionWith(AnnGameObject* Object)
{
for(size_t i = 0; i < collisionMask.size(); i++)
if(collisionMask[i]->Object == Object)
{
delete(collisionMask[i]);
collisionMask.erase(collisionMask.begin()+i);
}
}
void AnnGameObject::setAnimation(const char name[])
{
if(animIsSetted)
{
m_anim->setEnabled(false);
m_anim->setLoop(false);
animIsSetted = false;
animIsLooping = false;
animIsPlaying = false;
m_anim = NULL;
}
m_anim = m_entity->getAnimationState(name);
if (m_anim != NULL)
animIsSetted = true;
}
void AnnGameObject::playAnimation(bool play)
{
if(animIsSetted)
{
m_anim->setEnabled(play);
animIsPlaying = play;
}
}
void AnnGameObject::loopAnimation(bool loop)
{
if(animIsSetted)
{
m_anim->setLoop(loop);
animIsLooping = loop;
}
}
void AnnGameObject::addTime(float offset)
{
if(!animIsSetted || !animIsPlaying)
return;
m_anim->addTime(offset);
}
void AnnGameObject::applyImpulse(Ogre::Vector3 force)
{
m_Body->applyCentralImpulse(btVector3(force.x,force.y,force.z));
}
void AnnGameObject::applyForce(Ogre::Vector3 force)
{
m_Body->applyCentralForce(btVector3(force.x,force.y,force.z));
}
|
#include "AnnGameObject.hpp"
#include "AnnTools.h"
using namespace Annwvyn;
AnnGameObject::AnnGameObject()
{
m_node = NULL;
m_entity = NULL;
bulletReady = false;
m_DynamicsWorld = NULL;
m_Body = NULL;
m_Shape = NULL;
m_AudioEngine = NULL;
alGenSources(1,&m_Source);
m_anim = NULL;
animIsLooping = false;
animIsPlaying = false;
animIsSetted = false;
}
AnnGameObject::~AnnGameObject()
{
alSourceStop(m_Source);
alDeleteSources(1,&m_Source);
alDeleteBuffers(1,&m_Buffer);
}
void AnnGameObject::setAudioEngine(AnnAudioEngine* AudioEngine)
{
m_AudioEngine = AudioEngine;
}
void AnnGameObject::playSound(std::string path, bool loop, float volume)
{
m_Buffer = m_AudioEngine->loadSndFile(path);
alSourcei(m_Source, AL_BUFFER, m_Buffer);
if(loop)
alSourcei(m_Source, AL_LOOPING, AL_TRUE);
alSourcef(m_Source, AL_GAIN, volume);
alSource3f(m_Source, AL_POSITION,
m_node->getPosition().x,
m_node->getPosition().y,
m_node->getPosition().z);
alSourcePlay(m_Source);
}
void AnnGameObject::updateOpenAlPos()
{
alSource3f(m_Source, AL_POSITION,
pos().x,
pos().y,
pos().z);
}
void AnnGameObject::setPos(float x, float y, float z)
{
if(m_node == NULL)
return;
/*
*Position of object have to be the same in each part of the engine
*(graphics, physics, audio)
*/
//change BulletPosition
if(bulletReady)
{
m_Body->translate(btVector3(x - m_node->getPosition().x,
y - m_node->getPosition().y,
z - m_node->getPosition().z));
}
//change OgrePosition
m_node->setPosition(x,y,z);
//change OpenAL Source Position
alSource3f(m_Source, AL_POSITION,
m_node->getPosition().x,
m_node->getPosition().y,
m_node->getPosition().z);
}
void AnnGameObject::translate(float x, float y, float z)
{
//Ogre
m_node->translate(x,y,z);
//Bullet
m_Body->translate(btVector3(x,y,z));
//OpenAL
alSource3f(m_Source, AL_POSITION,
m_node->getPosition().x,
m_node->getPosition().y,
m_node->getPosition().z);
}
void AnnGameObject::setPos(Ogre::Vector3 pos)
{
setPos(pos.x,pos.y,pos.z);
}
void AnnGameObject::setOrientation(float w, float x, float y, float z)
{
//Ogre3D
if(m_node != NULL)
m_node->setOrientation(w,x,y,z);
//bullet
if(m_Body != NULL)
{
btTransform t = m_Body->getCenterOfMassTransform();
t.setRotation(btQuaternion(x,y,z,w));
m_Body->setCenterOfMassTransform(t);
}
//OpenAL
}
void AnnGameObject::setOrientation(Ogre::Quaternion orient)
{
setOrientation(orient.w,orient.x,orient.y,orient.z);
}
void AnnGameObject::setScale(Ogre::Vector3 scale)
{
setScale(scale.x,scale.y,scale.z);
}
void AnnGameObject::setScale(float x, float y, float z)
{
m_node->setScale(Ogre::Vector3(x,y,z));
}
Ogre::Vector3 AnnGameObject::pos()
{
if(m_node != NULL)
return m_node->getPosition();
return Ogre::Vector3(0,0,0);
}
Ogre::Quaternion AnnGameObject::Orientation()
{
if(m_node != NULL)
return m_node->getOrientation();
return Ogre::Quaternion(1,0,0,0);
}
void AnnGameObject::setNode(Ogre::SceneNode* node)
{
m_node = node;
}
void AnnGameObject::setEntity(Ogre::Entity* entity)
{
m_entity = entity;
}
void AnnGameObject::setBulletDynamicsWorld(btDiscreteDynamicsWorld* dynamicsWorld)
{
m_DynamicsWorld = dynamicsWorld;
}
void AnnGameObject::setUpBullet(float mass, phyShapeType type)
{
//check if everything is OK
if(m_DynamicsWorld == NULL)
return;
if(m_node == NULL)
return;
if(m_entity == NULL)
return;
//init shap converter
BtOgre::StaticMeshToShapeConverter converter(m_entity);
//create the correct shape
switch(type)
{
case boxShape:
m_Shape = converter.createBox();
break;
case cylinderShape:
m_Shape = converter.createCylinder();
break;
case capsuleShape:
m_Shape = converter.createCapsule();
break;
case convexShape:
m_Shape = converter.createConvex();
break;
case staticShape:
m_Shape = converter.createTrimesh();
break;
default:
return;
}
if(m_Shape == NULL)
return;
Ogre::Vector3 scale = node()->getScale();
m_Shape->setLocalScaling(btVector3(scale.x,scale.y,scale.z));
btVector3 inertia;
if(mass != 0)
m_Shape->calculateLocalInertia(mass, inertia);
else
inertia = btVector3(0,0,0);
BtOgre::RigidBodyState *state = new BtOgre::RigidBodyState(m_node);
//create rigidBody from shape
m_Body = new btRigidBody(mass,state,m_Shape,inertia);
if(m_Body != NULL)
{
/* m_Body->translate(btVector3(this->node()->getPosition().x,
this->node()->getPosition().y,
this->node()->getPosition().z));*/
m_DynamicsWorld->addRigidBody(m_Body);
}
else
return;
bulletReady = true;
}
Ogre::SceneNode* AnnGameObject::node()
{
return m_node;
}
Ogre::Entity* AnnGameObject::Entity()
{
return m_entity;
}
btRigidBody* AnnGameObject::RigidBody()
{
return m_Body;
}
float AnnGameObject::getDistance(AnnGameObject *otherObject)
{
return Tools::Geometry::distance(this,otherObject);
}
btRigidBody* AnnGameObject::getBody()
{
return m_Body;
}
std::vector<struct collisionTest*> AnnGameObject::getCollisionMask()
{
return collisionMask;
}
bool AnnGameObject::collideWith(AnnGameObject* Object)
{
for(size_t i = 0; i < collisionMask.size(); i++)
if(collisionMask[i]->Object == Object)
return collisionMask[i]->collisionState;
return false;
}
void AnnGameObject::updateCollisionStateWith(AnnGameObject* Object, bool state)
{
for(size_t i = 0; i < collisionMask.size(); i++)
if(collisionMask[i]->Object == Object)
collisionMask[i]->collisionState = state;
}
void AnnGameObject::cleanCollisionMask()
{
for(size_t i = 0; i < collisionMask.size(); i++)
{
delete collisionMask[i];
collisionMask.erase(collisionMask.begin()+i);
}
}
void AnnGameObject::resetCollisionMask()
{
for (size_t i = 0; i < collisionMask.size(); i++)
collisionMask[i]->collisionState = false;
}
void AnnGameObject::testCollisionWith(AnnGameObject* Object)
{
if(Object == this) return; //Explain me how I can colide with myself o.O
struct collisionTest* tester = new collisionTest;
tester->collisionState = false;
tester->Object = Object;
tester->Receiver = this;
collisionMask.push_back(tester);
}
void AnnGameObject::stopGettingCollisionWith(AnnGameObject* Object)
{
for(size_t i = 0; i < collisionMask.size(); i++)
if(collisionMask[i]->Object == Object)
{
delete(collisionMask[i]);
collisionMask.erase(collisionMask.begin()+i);
}
}
void AnnGameObject::setAnimation(const char name[])
{
if(animIsSetted)
{
m_anim->setEnabled(false);
m_anim->setLoop(false);
animIsSetted = false;
animIsLooping = false;
animIsPlaying = false;
m_anim = NULL;
}
m_anim = m_entity->getAnimationState(name);
if (m_anim != NULL)
animIsSetted = true;
}
void AnnGameObject::playAnimation(bool play)
{
if(animIsSetted)
{
m_anim->setEnabled(play);
animIsPlaying = play;
}
}
void AnnGameObject::loopAnimation(bool loop)
{
if(animIsSetted)
{
m_anim->setLoop(loop);
animIsLooping = loop;
}
}
void AnnGameObject::addTime(float offset)
{
if(!animIsSetted || !animIsPlaying)
return;
m_anim->addTime(offset);
}
void AnnGameObject::applyImpulse(Ogre::Vector3 force)
{
m_Body->applyCentralImpulse(btVector3(force.x,force.y,force.z));
}
void AnnGameObject::applyForce(Ogre::Vector3 force)
{
m_Body->applyCentralForce(btVector3(force.x,force.y,force.z));
}
|
make a funny comment even more funny (useless powaa (6:30 am and srsly need to go to bed))
|
make a funny comment even more funny (useless powaa (6:30 am and srsly need to go to bed))
|
C++
|
mit
|
Ybalrid/Annwvyn,Ybalrid/Annwvyn,Ybalrid/Annwvyn
|
3a4d2d7064bcdbb32e30af4e6135fbec02a0777c
|
src/sdk/responder/node_state.cc
|
src/sdk/responder/node_state.cc
|
#include "dsa_common.h"
#include "node_state.h"
#include "core/session.h"
#include "message/request/invoke_request_message.h"
#include "message/request/set_request_message.h"
#include "stream/responder/outgoing_invoke_stream.h"
#include "stream/responder/outgoing_list_stream.h"
#include "stream/responder/outgoing_set_stream.h"
#include "stream/responder/outgoing_subscribe_stream.h"
namespace dsa {
NodeStateWaitingCache::NodeStateWaitingCache() = default;
NodeStateWaitingCache::~NodeStateWaitingCache() = default;
NodeState::NodeState(NodeStateOwner &owner, ref_<NodeState> &&parent)
: _owner(owner),
_parent(std::move(parent)),
_merged_subscribe_options(QosLevel::_0, -1) {}
NodeState::~NodeState() = default;
ref_<NodeState> NodeState::get_child(const std::string &name, bool create) {
// find existing node
auto result = _children.find(name);
if (result != _children.end()) {
return result->second;
} else if (create) {
auto child = new NodeStateChild(_owner, get_ref(), name);
child->_path = _path.get_child_path(name);
_children[name] = child;
return child->get_ref();
}
// not found, return a nullptr
return ref_<NodeState>();
}
ref_<NodeState> NodeState::create_child(const Path &path,
NodeState &last_modeled_state,
bool allows_runtime_change) {
const std::string &name = path.current_name();
// find existing node
auto result = _children.find(name);
if (result != _children.end()) {
if (path.is_last()) {
return result->second;
}
// let child state decide
if (result->second->_model != nullptr) {
if (!allows_runtime_change &&
result->second->_model->allows_runtime_child_change()) {
allows_runtime_change = true;
}
return result->second->create_child(path.next(), *result->second,
allows_runtime_change);
} else {
return result->second->create_child(path.next(), last_modeled_state,
allows_runtime_change);
}
}
if (allows_runtime_change) {
// create new node
ref_<NodeState> new_state = ref_<NodeState>(
static_cast<NodeState *>(new NodeStateChild(_owner, get_ref(), name)));
_children[name] = new_state;
if (path.is_last()) {
new_state->_path = path;
if (_model_status == MODEL_UNKNOWN) {
set_model(last_modeled_state._model->on_demand_create_child(
path.move_pos(last_modeled_state._path.current_pos() + 1)));
} else if (_model_status == MODEL_CONNECTED) {
set_model(_model->on_demand_create_child(path));
} else {
new_state->_model_status = _model_status;
}
return new_state;
}
return _children[name]->create_child(path.next(), last_modeled_state, true);
}
// not found, return a nullptr
return ref_<NodeState>();
}
ref_<NodeState> NodeState::find_child(const Path &path) {
const std::string &name = path.current_name();
auto result = _children.find(name);
if (result != _children.end()) {
if (path.is_last()) {
return result->second;
}
return result->second->find_child(path.next());
}
return ref_<NodeState>();
}
void NodeState::remove_child(const std::string &name) { _children.erase(name); }
void NodeState::set_model(ModelRef &&model) {
if (model == nullptr) {
_model.reset();
_model_status = MODEL_INVALID;
} else if (model->_strand == nullptr) { // Other Invalid Models
_model.reset();
if (model == NodeModelBase::WAITING) {
_model_status = MODEL_WAITING;
if (_watiging_cache == nullptr) {
_watiging_cache.reset(new NodeStateWaitingCache());
}
} else if (model == NodeModelBase::UNAVAILABLE) {
_model_status = MODEL_UNAVAILABLE;
} else {
_model_status = MODEL_INVALID;
}
} else {
_model = std::move(model);
_model->_state = get_ref();
_model_status = MODEL_CONNECTED;
_model->initialize();
// TODO send request to model
// send _watiging_cache;
}
}
bool NodeState::periodic_check(size_t ts) {
for (auto it = _children.begin(); it != _children.end();) {
if (it->second->periodic_check(ts)) {
it = _children.erase(it);
} else {
it++;
}
}
if ((_model == nullptr ||
_model->periodic_check(ts)) // check if model is still in use
&& _children.empty() && _subscription_streams.empty()) {
destroy();
return true;
}
return false;
}
void NodeState::new_subscribe_response(SubscribeResponseMessageCRef &&message) {
for (auto &it : _subscription_streams) {
it.first->send_response(copy_ref_(message));
}
}
void NodeState::check_subscribe_options() {
SubscribeOptions new_options(QosLevel::_0, -1);
for (auto &stream : _subscription_streams) {
new_options.mergeFrom(stream.first->options());
}
if (new_options != _merged_subscribe_options) {
_merged_subscribe_options = new_options;
if (_model != nullptr) {
if (new_options.is_invalid()) {
_model->unsubscribe();
} else {
// update options only
_model->subscribe(new_options);
}
}
}
}
void NodeState::subscribe(ref_<OutgoingSubscribeStream> &&stream) {
auto p = stream.get();
_subscription_streams[p] = std::move(stream);
if (_merged_subscribe_options.mergeFrom(p->options())) {
if (_model_status == MODEL_CONNECTED) {
_model->subscribe(_merged_subscribe_options);
}
// TODO update model;
}
p->on_option_change([ this, keep_ref = get_ref() ](
OutgoingSubscribeStream & stream, const SubscribeOptions &old_options) {
if (stream.is_destroyed()) {
_subscription_streams.erase(&stream);
if (_subscription_streams.empty() ||
_merged_subscribe_options.needUpdateOnRemoval(stream.options())) {
check_subscribe_options();
}
} else {
if (_merged_subscribe_options.needUpdateOnChange(old_options,
stream.options())) {
check_subscribe_options();
}
}
});
if (_model != nullptr && _model->_cached_value != nullptr) {
p->send_response(copy_ref_(_model->_cached_value));
}
}
void NodeState::update_list_value(const std::string &key, BytesRef &value) {
for (auto &it : _list_streams) {
it.first->update_value(key, value);
}
}
void NodeState::list(ref_<OutgoingListStream> &&stream) {
auto p = stream.get();
_list_streams[p] = std::move(stream);
p->on_close([ this, keep_ref = get_ref() ](OutgoingListStream & s) {
_list_streams.erase(&s);
if (_list_streams.empty() && _model != nullptr) {
_model->unlist();
}
});
if (_model != nullptr) {
_model->list(*p);
}
}
void NodeState::invoke(ref_<OutgoingInvokeStream> &&stream) {
if (_model != nullptr) {
_model->on_invoke(std::move(stream), _parent);
} else if (_model_status == MODEL_WAITING) {
_watiging_cache->invokes.emplace_back(std::move(stream));
} else {
auto response = make_ref_<InvokeResponseMessage>();
if (_model_status == MODEL_UNAVAILABLE) {
response->set_status(MessageStatus::DISCONNECTED);
} else {
response->set_status(MessageStatus::NOT_SUPPORTED);
}
stream->send_response(std::move(response));
}
}
void NodeState::set(ref_<OutgoingSetStream> &&stream) {
if (_model != nullptr) {
_model->on_set(std::move(stream));
} else if (_model_status == MODEL_WAITING) {
_watiging_cache->sets.emplace_back(std::move(stream));
} else {
auto response = make_ref_<SetResponseMessage>();
if (_model_status == MODEL_UNAVAILABLE) {
response->set_status(MessageStatus::DISCONNECTED);
} else {
response->set_status(MessageStatus::NOT_SUPPORTED);
}
stream->send_response(std::move(response));
}
}
void NodeState::destroy_impl() {
if (_model != nullptr) {
_model->destroy();
_model.reset();
_model_status = MODEL_UNKNOWN;
_owner.remove_state(_path.full_str());
_parent.reset();
}
}
NodeStateChild::NodeStateChild(NodeStateOwner &owner, ref_<NodeState> &&parent,
const std::string &name)
: NodeState(owner, std::move(parent)), name(name) {}
NodeStateRoot::NodeStateRoot(NodeStateOwner &owner, ModelRef &&model)
: NodeState(owner, ref_<NodeState>()) {
_path = Path("");
set_model(std::move(model));
};
} // namespace dsa
|
#include "dsa_common.h"
#include "node_state.h"
#include "core/session.h"
#include "message/request/invoke_request_message.h"
#include "message/request/set_request_message.h"
#include "stream/responder/outgoing_invoke_stream.h"
#include "stream/responder/outgoing_list_stream.h"
#include "stream/responder/outgoing_set_stream.h"
#include "stream/responder/outgoing_subscribe_stream.h"
namespace dsa {
NodeStateWaitingCache::NodeStateWaitingCache() = default;
NodeStateWaitingCache::~NodeStateWaitingCache() = default;
NodeState::NodeState(NodeStateOwner &owner, ref_<NodeState> &&parent)
: _owner(owner),
_parent(std::move(parent)),
_merged_subscribe_options(QosLevel::_0, -1) {}
NodeState::~NodeState() = default;
ref_<NodeState> NodeState::get_child(const std::string &name, bool create) {
// find existing node
auto result = _children.find(name);
if (result != _children.end()) {
return result->second;
} else if (create) {
auto child = new NodeStateChild(_owner, get_ref(), name);
child->_path = _path.get_child_path(name);
_children[name] = child;
return child->get_ref();
}
// not found, return a nullptr
return ref_<NodeState>();
}
ref_<NodeState> NodeState::create_child(const Path &path,
NodeState &last_modeled_state,
bool allows_runtime_change) {
const std::string &name = path.current_name();
// find existing node
auto result = _children.find(name);
if (result != _children.end()) {
if (path.is_last()) {
return result->second;
}
// let child state decide
if (result->second->_model != nullptr) {
if (!allows_runtime_change &&
result->second->_model->allows_runtime_child_change()) {
allows_runtime_change = true;
}
return result->second->create_child(path.next(), *result->second,
allows_runtime_change);
} else {
return result->second->create_child(path.next(), last_modeled_state,
allows_runtime_change);
}
}
if (allows_runtime_change) {
// create new node
ref_<NodeState> new_state = ref_<NodeState>(
static_cast<NodeState *>(new NodeStateChild(_owner, get_ref(), name)));
_children[name] = new_state;
if (path.is_last()) {
new_state->_path = path;
if (_model_status == MODEL_UNKNOWN) {
set_model(last_modeled_state._model->on_demand_create_child(
path.move_pos(last_modeled_state._path.current_pos() + 1)));
} else if (_model_status == MODEL_CONNECTED) {
set_model(_model->on_demand_create_child(path));
} else {
new_state->_model_status = _model_status;
}
return new_state;
}
return _children[name]->create_child(path.next(), last_modeled_state, true);
}
// not found, return a nullptr
return ref_<NodeState>();
}
ref_<NodeState> NodeState::find_child(const Path &path) {
const std::string &name = path.current_name();
auto result = _children.find(name);
if (result != _children.end()) {
if (path.is_last()) {
return result->second;
}
return result->second->find_child(path.next());
}
return ref_<NodeState>();
}
void NodeState::remove_child(const std::string &name) { _children.erase(name); }
void NodeState::set_model(ModelRef &&model) {
if (model == nullptr) {
_model.reset();
_model_status = MODEL_INVALID;
} else if (model->_strand == nullptr) { // Other Invalid Models
_model.reset();
if (model == NodeModelBase::WAITING) {
_model_status = MODEL_WAITING;
if (_watiging_cache == nullptr) {
_watiging_cache.reset(new NodeStateWaitingCache());
}
} else if (model == NodeModelBase::UNAVAILABLE) {
_model_status = MODEL_UNAVAILABLE;
} else {
_model_status = MODEL_INVALID;
}
} else {
_model = std::move(model);
_model->_state = get_ref();
_model_status = MODEL_CONNECTED;
_model->initialize();
// send all waiting streams
// subscribe streams
if (!_merged_subscribe_options.is_invalid()) {
_model->subscribe(_merged_subscribe_options);
if (_model->_cached_value != nullptr) {
for (auto &subscribe_stream : _subscription_streams) {
subscribe_stream.first->send_response(
copy_ref_(_model->_cached_value));
}
}
}
// list streams
for (auto &list_stream : _list_streams) {
_model->list(*list_stream.first);
}
// invoke and set streams
if (_watiging_cache != nullptr) {
for (auto &invoke_stream : _watiging_cache->invokes) {
_model->on_invoke(std::move(invoke_stream), _parent);
}
for (auto &set_stream : _watiging_cache->sets) {
_model->on_set(std::move(set_stream));
}
_watiging_cache.reset();
}
}
}
bool NodeState::periodic_check(size_t ts) {
for (auto it = _children.begin(); it != _children.end();) {
if (it->second->periodic_check(ts)) {
it = _children.erase(it);
} else {
it++;
}
}
if ((_model == nullptr ||
_model->periodic_check(ts)) // check if model is still in use
&& _children.empty() && _subscription_streams.empty()) {
destroy();
return true;
}
return false;
}
void NodeState::new_subscribe_response(SubscribeResponseMessageCRef &&message) {
for (auto &it : _subscription_streams) {
it.first->send_response(copy_ref_(message));
}
}
void NodeState::check_subscribe_options() {
SubscribeOptions new_options(QosLevel::_0, -1);
for (auto &stream : _subscription_streams) {
new_options.mergeFrom(stream.first->options());
}
if (new_options != _merged_subscribe_options) {
_merged_subscribe_options = new_options;
if (_model != nullptr) {
if (new_options.is_invalid()) {
_model->unsubscribe();
} else {
// update options only
_model->subscribe(new_options);
}
}
}
}
void NodeState::subscribe(ref_<OutgoingSubscribeStream> &&stream) {
auto p = stream.get();
_subscription_streams[p] = std::move(stream);
if (_merged_subscribe_options.mergeFrom(p->options())) {
if (_model_status == MODEL_CONNECTED) {
_model->subscribe(_merged_subscribe_options);
}
// TODO update model;
}
p->on_option_change([ this, keep_ref = get_ref() ](
OutgoingSubscribeStream & stream, const SubscribeOptions &old_options) {
if (stream.is_destroyed()) {
_subscription_streams.erase(&stream);
if (_subscription_streams.empty() ||
_merged_subscribe_options.needUpdateOnRemoval(stream.options())) {
check_subscribe_options();
}
} else {
if (_merged_subscribe_options.needUpdateOnChange(old_options,
stream.options())) {
check_subscribe_options();
}
}
});
if (_model != nullptr && _model->_cached_value != nullptr) {
p->send_response(copy_ref_(_model->_cached_value));
}
}
void NodeState::update_list_value(const std::string &key, BytesRef &value) {
for (auto &it : _list_streams) {
it.first->update_value(key, value);
}
}
void NodeState::list(ref_<OutgoingListStream> &&stream) {
auto p = stream.get();
_list_streams[p] = std::move(stream);
p->on_close([ this, keep_ref = get_ref() ](OutgoingListStream & s) {
_list_streams.erase(&s);
if (_list_streams.empty() && _model != nullptr) {
_model->unlist();
}
});
if (_model != nullptr) {
_model->list(*p);
}
}
void NodeState::invoke(ref_<OutgoingInvokeStream> &&stream) {
if (_model != nullptr) {
_model->on_invoke(std::move(stream), _parent);
} else if (_model_status == MODEL_WAITING) {
_watiging_cache->invokes.emplace_back(std::move(stream));
} else {
auto response = make_ref_<InvokeResponseMessage>();
if (_model_status == MODEL_UNAVAILABLE) {
response->set_status(MessageStatus::DISCONNECTED);
} else {
response->set_status(MessageStatus::NOT_SUPPORTED);
}
stream->send_response(std::move(response));
}
}
void NodeState::set(ref_<OutgoingSetStream> &&stream) {
if (_model != nullptr) {
_model->on_set(std::move(stream));
} else if (_model_status == MODEL_WAITING) {
_watiging_cache->sets.emplace_back(std::move(stream));
} else {
auto response = make_ref_<SetResponseMessage>();
if (_model_status == MODEL_UNAVAILABLE) {
response->set_status(MessageStatus::DISCONNECTED);
} else {
response->set_status(MessageStatus::NOT_SUPPORTED);
}
stream->send_response(std::move(response));
}
}
void NodeState::destroy_impl() {
if (_model != nullptr) {
_model->destroy();
_model.reset();
_model_status = MODEL_UNKNOWN;
_owner.remove_state(_path.full_str());
_parent.reset();
}
}
NodeStateChild::NodeStateChild(NodeStateOwner &owner, ref_<NodeState> &&parent,
const std::string &name)
: NodeState(owner, std::move(parent)), name(name) {}
NodeStateRoot::NodeStateRoot(NodeStateOwner &owner, ModelRef &&model)
: NodeState(owner, ref_<NodeState>()) {
_path = Path("");
set_model(std::move(model));
};
} // namespace dsa
|
attach streams to NodeModel when it's connected to NodeState
|
attach streams to NodeModel when it's connected to NodeState
|
C++
|
apache-2.0
|
iot-dsa-v2/sdk-dslink-cpp,iot-dsa-v2/sdk-dslink-cpp,iot-dsa-v2/sdk-dslink-cpp,iot-dsa-v2/sdk-dslink-cpp
|
135b165d2bca7a9a7302eb4f771dc713c8100edb
|
chrome/browser/history/snippet.cc
|
chrome/browser/history/snippet.cc
|
// Copyright (c) 2006-2008 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 "chrome/browser/history/snippet.h"
#include <algorithm>
#include "base/logging.h"
#include "base/scoped_ptr.h"
#include "base/string_util.h"
#include "unicode/brkiter.h"
#include "unicode/utext.h"
#include "unicode/utf8.h"
namespace {
bool PairFirstLessThan(const Snippet::MatchPosition& a,
const Snippet::MatchPosition& b) {
return a.first < b.first;
}
// Combines all pairs after offset in match_positions that are contained
// or touch the pair at offset.
void CoalescePositionsFrom(size_t offset,
Snippet::MatchPositions* match_positions) {
DCHECK(offset < match_positions->size());
Snippet::MatchPosition& pair((*match_positions)[offset]);
++offset;
while (offset < match_positions->size() &&
pair.second >= (*match_positions)[offset].first) {
pair.second = std::max(pair.second, (*match_positions)[offset].second);
match_positions->erase(match_positions->begin() + offset);
}
}
// Makes sure there is a pair in match_positions that contains the specified
// range. This keeps the pairs ordered in match_positions by first, and makes
// sure none of the pairs in match_positions touch each other.
void AddMatch(size_t start,
size_t end,
Snippet::MatchPositions* match_positions) {
DCHECK(start < end);
DCHECK(match_positions);
Snippet::MatchPosition pair(start, end);
if (match_positions->empty()) {
match_positions->push_back(pair);
return;
}
// There's at least one match. Find the position of the new match,
// potentially extending pairs around it.
Snippet::MatchPositions::iterator i =
std::lower_bound(match_positions->begin(), match_positions->end(),
pair, &PairFirstLessThan);
if (i != match_positions->end() && i->first == start) {
// Match not at the end and there is already a pair with the same
// start.
if (end > i->second) {
// New pair extends beyond existing pair. Extend existing pair and
// coalesce matches after it.
i->second = end;
CoalescePositionsFrom(i - match_positions->begin(), match_positions);
} // else case, new pair completely contained in existing pair, nothing
// to do.
} else if (i == match_positions->begin()) {
// Match at the beginning and the first pair doesn't have the same
// start. Insert new pair and coalesce matches after it.
match_positions->insert(i, pair);
CoalescePositionsFrom(0, match_positions);
} else {
// Not at the beginning (but may be at the end).
--i;
if (start <= i->second && end > i->second) {
// Previous element contains match. Extend it and coalesce.
i->second = end;
CoalescePositionsFrom(i - match_positions->begin(), match_positions);
} else if (end > i->second) {
// Region doesn't touch previous element. See if region touches current
// element.
++i;
if (i == match_positions->end() || end < i->first) {
match_positions->insert(i, pair);
} else {
i->first = start;
i->second = end;
CoalescePositionsFrom(i - match_positions->begin(), match_positions);
}
}
}
}
// Converts an index in a utf8 string into the index in the corresponding wide
// string and returns the wide index. This is intended to be called in a loop
// iterating through a utf8 string.
//
// utf8_string: the utf8 string.
// utf8_length: length of the utf8 string.
// offset: the utf8 offset to convert.
// utf8_pos: current offset in the utf8 string. This is modified and on return
// matches offset.
// wide_pos: current index in the wide string. This is the same as the return
// value.
size_t AdvanceAndReturnWidePos(const char* utf8_string,
int32_t utf8_length,
int32_t offset,
int32_t* utf8_pos,
size_t* wide_pos) {
DCHECK(offset >= *utf8_pos && offset <= utf8_length);
UChar32 wide_char;
while (*utf8_pos < offset) {
U8_NEXT(utf8_string, *utf8_pos, utf8_length, wide_char);
*wide_pos += (wide_char <= 0xFFFF) ? 1 : 2;
}
return *wide_pos;
}
// Given a character break iterator over a UTF-8 string, set the iterator
// position to |*utf8_pos| and move by |count| characters. |count| can
// be either positive or negative.
void MoveByNGraphemes(BreakIterator* bi, int count, size_t* utf8_pos) {
// Ignore the return value. A side effect of the current position
// being set at or following |*utf8_pos| is exploited here.
// It's simpler than calling following(n) and then previous().
// isBoundary() is not very fast, but should be good enough for the
// snippet generation. If not, revisit the way we scan in ComputeSnippet.
bi->isBoundary(*utf8_pos);
bi->next(count);
*utf8_pos = static_cast<size_t>(bi->current());
}
// The amount of context to include for a given hit. Note that it's counted
// in terms of graphemes rather than bytes.
const int kSnippetContext = 50;
// Returns true if next match falls within a snippet window
// from the previous match. The window size is counted in terms
// of graphemes rather than bytes in UTF-8.
bool IsNextMatchWithinSnippetWindow(BreakIterator* bi,
size_t previous_match_end,
size_t next_match_start) {
// If it's within a window in terms of bytes, it's certain
// that it's within a window in terms of graphemes as well.
if (next_match_start < previous_match_end + kSnippetContext)
return true;
bi->isBoundary(previous_match_end);
// An alternative to this is to call |bi->next()| at most
// kSnippetContext times, compare |bi->current()| with |next_match_start|
// after each call and return early if possible. There are other
// heuristics to speed things up if necessary, but it's not likely that
// we need to bother.
bi->next(kSnippetContext);
int64 current = bi->current();
return (next_match_start < static_cast<uint64>(current) ||
current == BreakIterator::DONE);
}
} // namespace
// static
void Snippet::ExtractMatchPositions(const std::string& offsets_str,
const std::string& column_num,
MatchPositions* match_positions) {
DCHECK(match_positions);
if (offsets_str.empty())
return;
std::vector<std::string> offsets;
SplitString(offsets_str, ' ', &offsets);
// SQLite offsets are sets of four integers:
// column, query term, match offset, match length
// Matches within a string are marked by (start, end) pairs.
for (size_t i = 0; i < offsets.size() - 3; i += 4) {
if (offsets[i] != column_num)
continue;
const size_t start = atoi(offsets[i + 2].c_str());
const size_t end = start + atoi(offsets[i + 3].c_str());
AddMatch(start, end, match_positions);
}
}
// static
void Snippet::ConvertMatchPositionsToWide(
const std::string& utf8_string,
Snippet::MatchPositions* match_positions) {
DCHECK(match_positions);
int32_t utf8_pos = 0;
size_t wide_pos = 0;
const char* utf8_cstring = utf8_string.c_str();
const int32_t utf8_length = static_cast<int32_t>(utf8_string.size());
for (Snippet::MatchPositions::iterator i = match_positions->begin();
i != match_positions->end(); ++i) {
i->first = AdvanceAndReturnWidePos(utf8_cstring, utf8_length,
i->first, &utf8_pos, &wide_pos);
i->second = AdvanceAndReturnWidePos(utf8_cstring, utf8_length,
i->second, &utf8_pos, &wide_pos);
}
}
void Snippet::ComputeSnippet(const MatchPositions& match_positions,
const std::string& document) {
// The length of snippets we try to produce.
// We can generate longer snippets but stop once we cross kSnippetMaxLength.
const size_t kSnippetMaxLength = 200;
const std::wstring kEllipsis = L" ... ";
UText* document_utext = NULL;
UErrorCode status = U_ZERO_ERROR;
document_utext = utext_openUTF8(document_utext, document.data(),
document.size(), &status);
// Locale does not matter because there's no per-locale customization
// for character iterator.
scoped_ptr<BreakIterator> bi(
BreakIterator::createCharacterInstance(Locale::getDefault(), status));
bi->setText(document_utext, status);
DCHECK(U_SUCCESS(status));
// We build the snippet by iterating through the matches and then grabbing
// context around each match. If matches are near enough each other (within
// kSnippetContext), we skip the "..." between them.
std::wstring snippet;
size_t start = 0;
for (size_t i = 0; i < match_positions.size(); ++i) {
// Some shorter names for the current match.
const size_t match_start = match_positions[i].first;
const size_t match_end = match_positions[i].second;
// Add the context, if any, to show before the match.
size_t context_start = match_start;
MoveByNGraphemes(bi.get(), -kSnippetContext, &context_start);
start = std::max(start, context_start);
if (start < match_start) {
if (start > 0)
snippet += kEllipsis;
snippet += UTF8ToWide(document.substr(start, match_start - start));
}
// Add the match.
const size_t first = snippet.size();
snippet += UTF8ToWide(document.substr(match_start,
match_end - match_start));
matches_.push_back(std::make_pair(first, snippet.size()));
// Compute the context, if any, to show after the match.
size_t end;
// Check if the next match falls within our snippet window.
if (i + 1 < match_positions.size() &&
IsNextMatchWithinSnippetWindow(bi.get(), match_end,
match_positions[i + 1].first)) {
// Yes, it's within the window. Make the end context extend just up
// to the next match.
end = match_positions[i + 1].first;
snippet += UTF8ToWide(document.substr(match_end, end - match_end));
} else {
// No, there's either no next match or the next match is too far away.
end = match_end;
MoveByNGraphemes(bi.get(), kSnippetContext, &end);
snippet += UTF8ToWide(document.substr(match_end, end - match_end));
if (end < document.size())
snippet += kEllipsis;
}
start = end;
// Stop here if we have enough snippet computed.
if (snippet.size() >= kSnippetMaxLength)
break;
}
utext_close(document_utext);
swap(text_, snippet);
}
|
// Copyright (c) 2006-2008 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 "chrome/browser/history/snippet.h"
#include <algorithm>
#include "base/logging.h"
#include "base/scoped_ptr.h"
#include "base/string_util.h"
#include "unicode/brkiter.h"
#include "unicode/utext.h"
#include "unicode/utf8.h"
namespace {
bool PairFirstLessThan(const Snippet::MatchPosition& a,
const Snippet::MatchPosition& b) {
return a.first < b.first;
}
// Combines all pairs after offset in match_positions that are contained
// or touch the pair at offset.
void CoalescePositionsFrom(size_t offset,
Snippet::MatchPositions* match_positions) {
DCHECK(offset < match_positions->size());
Snippet::MatchPosition& pair((*match_positions)[offset]);
++offset;
while (offset < match_positions->size() &&
pair.second >= (*match_positions)[offset].first) {
pair.second = std::max(pair.second, (*match_positions)[offset].second);
match_positions->erase(match_positions->begin() + offset);
}
}
// Makes sure there is a pair in match_positions that contains the specified
// range. This keeps the pairs ordered in match_positions by first, and makes
// sure none of the pairs in match_positions touch each other.
void AddMatch(size_t start,
size_t end,
Snippet::MatchPositions* match_positions) {
DCHECK(start < end);
DCHECK(match_positions);
Snippet::MatchPosition pair(start, end);
if (match_positions->empty()) {
match_positions->push_back(pair);
return;
}
// There's at least one match. Find the position of the new match,
// potentially extending pairs around it.
Snippet::MatchPositions::iterator i =
std::lower_bound(match_positions->begin(), match_positions->end(),
pair, &PairFirstLessThan);
if (i != match_positions->end() && i->first == start) {
// Match not at the end and there is already a pair with the same
// start.
if (end > i->second) {
// New pair extends beyond existing pair. Extend existing pair and
// coalesce matches after it.
i->second = end;
CoalescePositionsFrom(i - match_positions->begin(), match_positions);
} // else case, new pair completely contained in existing pair, nothing
// to do.
} else if (i == match_positions->begin()) {
// Match at the beginning and the first pair doesn't have the same
// start. Insert new pair and coalesce matches after it.
match_positions->insert(i, pair);
CoalescePositionsFrom(0, match_positions);
} else {
// Not at the beginning (but may be at the end).
--i;
if (start <= i->second && end > i->second) {
// Previous element contains match. Extend it and coalesce.
i->second = end;
CoalescePositionsFrom(i - match_positions->begin(), match_positions);
} else if (end > i->second) {
// Region doesn't touch previous element. See if region touches current
// element.
++i;
if (i == match_positions->end() || end < i->first) {
match_positions->insert(i, pair);
} else {
i->first = start;
i->second = end;
CoalescePositionsFrom(i - match_positions->begin(), match_positions);
}
}
}
}
// Converts an index in a utf8 string into the index in the corresponding wide
// string and returns the wide index. This is intended to be called in a loop
// iterating through a utf8 string.
//
// utf8_string: the utf8 string.
// utf8_length: length of the utf8 string.
// offset: the utf8 offset to convert.
// utf8_pos: current offset in the utf8 string. This is modified and on return
// matches offset.
// wide_pos: current index in the wide string. This is the same as the return
// value.
size_t AdvanceAndReturnWidePos(const char* utf8_string,
int32_t utf8_length,
int32_t offset,
int32_t* utf8_pos,
size_t* wide_pos) {
DCHECK(offset >= *utf8_pos && offset <= utf8_length);
UChar32 wide_char;
while (*utf8_pos < offset) {
U8_NEXT(utf8_string, *utf8_pos, utf8_length, wide_char);
*wide_pos += (wide_char <= 0xFFFF) ? 1 : 2;
}
return *wide_pos;
}
// Given a character break iterator over a UTF-8 string, set the iterator
// position to |*utf8_pos| and move by |count| characters. |count| can
// be either positive or negative.
void MoveByNGraphemes(BreakIterator* bi, int count, size_t* utf8_pos) {
// Ignore the return value. A side effect of the current position
// being set at or following |*utf8_pos| is exploited here.
// It's simpler than calling following(n) and then previous().
// isBoundary() is not very fast, but should be good enough for the
// snippet generation. If not, revisit the way we scan in ComputeSnippet.
bi->isBoundary(*utf8_pos);
bi->next(count);
*utf8_pos = static_cast<size_t>(bi->current());
}
// The amount of context to include for a given hit. Note that it's counted
// in terms of graphemes rather than bytes.
const int kSnippetContext = 50;
// Returns true if next match falls within a snippet window
// from the previous match. The window size is counted in terms
// of graphemes rather than bytes in UTF-8.
bool IsNextMatchWithinSnippetWindow(BreakIterator* bi,
size_t previous_match_end,
size_t next_match_start) {
// If it's within a window in terms of bytes, it's certain
// that it's within a window in terms of graphemes as well.
if (next_match_start < previous_match_end + kSnippetContext)
return true;
bi->isBoundary(previous_match_end);
// An alternative to this is to call |bi->next()| at most
// kSnippetContext times, compare |bi->current()| with |next_match_start|
// after each call and return early if possible. There are other
// heuristics to speed things up if necessary, but it's not likely that
// we need to bother.
bi->next(kSnippetContext);
int64 current = bi->current();
return (next_match_start < static_cast<uint64>(current) ||
current == BreakIterator::DONE);
}
} // namespace
// static
void Snippet::ExtractMatchPositions(const std::string& offsets_str,
const std::string& column_num,
MatchPositions* match_positions) {
DCHECK(match_positions);
if (offsets_str.empty())
return;
std::vector<std::string> offsets;
SplitString(offsets_str, ' ', &offsets);
// SQLite offsets are sets of four integers:
// column, query term, match offset, match length
// Matches within a string are marked by (start, end) pairs.
for (size_t i = 0; i < offsets.size() - 3; i += 4) {
if (offsets[i] != column_num)
continue;
const size_t start = atoi(offsets[i + 2].c_str());
const size_t end = start + atoi(offsets[i + 3].c_str());
// Switch to DCHECK after debugging http://crbug.com/15261.
CHECK(end >= start);
AddMatch(start, end, match_positions);
}
}
// static
void Snippet::ConvertMatchPositionsToWide(
const std::string& utf8_string,
Snippet::MatchPositions* match_positions) {
DCHECK(match_positions);
int32_t utf8_pos = 0;
size_t wide_pos = 0;
const char* utf8_cstring = utf8_string.c_str();
const int32_t utf8_length = static_cast<int32_t>(utf8_string.size());
for (Snippet::MatchPositions::iterator i = match_positions->begin();
i != match_positions->end(); ++i) {
i->first = AdvanceAndReturnWidePos(utf8_cstring, utf8_length,
i->first, &utf8_pos, &wide_pos);
i->second = AdvanceAndReturnWidePos(utf8_cstring, utf8_length,
i->second, &utf8_pos, &wide_pos);
}
}
void Snippet::ComputeSnippet(const MatchPositions& match_positions,
const std::string& document) {
// The length of snippets we try to produce.
// We can generate longer snippets but stop once we cross kSnippetMaxLength.
const size_t kSnippetMaxLength = 200;
const std::wstring kEllipsis = L" ... ";
UText* document_utext = NULL;
UErrorCode status = U_ZERO_ERROR;
document_utext = utext_openUTF8(document_utext, document.data(),
document.size(), &status);
// Locale does not matter because there's no per-locale customization
// for character iterator.
scoped_ptr<BreakIterator> bi(
BreakIterator::createCharacterInstance(Locale::getDefault(), status));
bi->setText(document_utext, status);
DCHECK(U_SUCCESS(status));
// We build the snippet by iterating through the matches and then grabbing
// context around each match. If matches are near enough each other (within
// kSnippetContext), we skip the "..." between them.
std::wstring snippet;
size_t start = 0;
for (size_t i = 0; i < match_positions.size(); ++i) {
// Some shorter names for the current match.
const size_t match_start = match_positions[i].first;
const size_t match_end = match_positions[i].second;
// Switch to DCHECK after debugging http://crbug.com/15261.
CHECK(match_end > match_start);
CHECK(match_end <= document.size());
// Add the context, if any, to show before the match.
size_t context_start = match_start;
MoveByNGraphemes(bi.get(), -kSnippetContext, &context_start);
start = std::max(start, context_start);
if (start < match_start) {
if (start > 0)
snippet += kEllipsis;
// Switch to DCHECK after debugging http://crbug.com/15261.
CHECK(start < document.size());
snippet += UTF8ToWide(document.substr(start, match_start - start));
}
// Add the match.
const size_t first = snippet.size();
snippet += UTF8ToWide(document.substr(match_start,
match_end - match_start));
matches_.push_back(std::make_pair(first, snippet.size()));
// Compute the context, if any, to show after the match.
size_t end;
// Check if the next match falls within our snippet window.
if (i + 1 < match_positions.size() &&
IsNextMatchWithinSnippetWindow(bi.get(), match_end,
match_positions[i + 1].first)) {
// Yes, it's within the window. Make the end context extend just up
// to the next match.
end = match_positions[i + 1].first;
// Switch to DCHECK after debugging http://crbug.com/15261.
CHECK(end >= match_end);
CHECK(end <= document.size());
snippet += UTF8ToWide(document.substr(match_end, end - match_end));
} else {
// No, there's either no next match or the next match is too far away.
end = match_end;
MoveByNGraphemes(bi.get(), kSnippetContext, &end);
// Switch to DCHECK after debugging http://crbug.com/15261.
CHECK(end >= match_end);
CHECK(end <= document.size());
snippet += UTF8ToWide(document.substr(match_end, end - match_end));
if (end < document.size())
snippet += kEllipsis;
}
start = end;
// Stop here if we have enough snippet computed.
if (snippet.size() >= kSnippetMaxLength)
break;
}
utext_close(document_utext);
swap(text_, snippet);
}
|
Add CHECKs to track down source of history std::string out of range exceptions. BUG=http://crbug.com/15261
|
Linux: Add CHECKs to track down source of history std::string out of range exceptions.
BUG=http://crbug.com/15261
Review URL: http://codereview.chromium.org/164191
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@23086 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
hgl888/chromium-crosswalk,zcbenz/cefode-chromium,anirudhSK/chromium,rogerwang/chromium,Jonekee/chromium.src,keishi/chromium,dushu1203/chromium.src,Chilledheart/chromium,krieger-od/nwjs_chromium.src,robclark/chromium,anirudhSK/chromium,TheTypoMaster/chromium-crosswalk,keishi/chromium,robclark/chromium,hgl888/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,pozdnyakov/chromium-crosswalk,Pluto-tv/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,junmin-zhu/chromium-rivertrail,patrickm/chromium.src,Jonekee/chromium.src,nacl-webkit/chrome_deps,hgl888/chromium-crosswalk,Fireblend/chromium-crosswalk,ChromiumWebApps/chromium,zcbenz/cefode-chromium,markYoungH/chromium.src,PeterWangIntel/chromium-crosswalk,keishi/chromium,keishi/chromium,Pluto-tv/chromium-crosswalk,rogerwang/chromium,anirudhSK/chromium,nacl-webkit/chrome_deps,ltilve/chromium,littlstar/chromium.src,zcbenz/cefode-chromium,axinging/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Just-D/chromium-1,junmin-zhu/chromium-rivertrail,markYoungH/chromium.src,fujunwei/chromium-crosswalk,keishi/chromium,nacl-webkit/chrome_deps,littlstar/chromium.src,pozdnyakov/chromium-crosswalk,ltilve/chromium,Jonekee/chromium.src,bright-sparks/chromium-spacewalk,zcbenz/cefode-chromium,anirudhSK/chromium,fujunwei/chromium-crosswalk,axinging/chromium-crosswalk,timopulkkinen/BubbleFish,anirudhSK/chromium,ltilve/chromium,chuan9/chromium-crosswalk,hujiajie/pa-chromium,Pluto-tv/chromium-crosswalk,nacl-webkit/chrome_deps,Pluto-tv/chromium-crosswalk,junmin-zhu/chromium-rivertrail,ChromiumWebApps/chromium,krieger-od/nwjs_chromium.src,mogoweb/chromium-crosswalk,ltilve/chromium,Chilledheart/chromium,krieger-od/nwjs_chromium.src,dednal/chromium.src,mohamed--abdel-maksoud/chromium.src,hujiajie/pa-chromium,timopulkkinen/BubbleFish,ChromiumWebApps/chromium,patrickm/chromium.src,Fireblend/chromium-crosswalk,robclark/chromium,junmin-zhu/chromium-rivertrail,junmin-zhu/chromium-rivertrail,mohamed--abdel-maksoud/chromium.src,dednal/chromium.src,hujiajie/pa-chromium,Fireblend/chromium-crosswalk,keishi/chromium,TheTypoMaster/chromium-crosswalk,keishi/chromium,ltilve/chromium,jaruba/chromium.src,krieger-od/nwjs_chromium.src,timopulkkinen/BubbleFish,rogerwang/chromium,Chilledheart/chromium,ChromiumWebApps/chromium,mohamed--abdel-maksoud/chromium.src,ondra-novak/chromium.src,mohamed--abdel-maksoud/chromium.src,dushu1203/chromium.src,Jonekee/chromium.src,rogerwang/chromium,markYoungH/chromium.src,keishi/chromium,hujiajie/pa-chromium,bright-sparks/chromium-spacewalk,pozdnyakov/chromium-crosswalk,Just-D/chromium-1,PeterWangIntel/chromium-crosswalk,pozdnyakov/chromium-crosswalk,ondra-novak/chromium.src,M4sse/chromium.src,TheTypoMaster/chromium-crosswalk,zcbenz/cefode-chromium,markYoungH/chromium.src,dednal/chromium.src,jaruba/chromium.src,hgl888/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,dushu1203/chromium.src,nacl-webkit/chrome_deps,patrickm/chromium.src,jaruba/chromium.src,dednal/chromium.src,fujunwei/chromium-crosswalk,hujiajie/pa-chromium,Fireblend/chromium-crosswalk,Fireblend/chromium-crosswalk,pozdnyakov/chromium-crosswalk,littlstar/chromium.src,fujunwei/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Jonekee/chromium.src,hgl888/chromium-crosswalk,ChromiumWebApps/chromium,timopulkkinen/BubbleFish,markYoungH/chromium.src,Fireblend/chromium-crosswalk,ltilve/chromium,crosswalk-project/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,timopulkkinen/BubbleFish,anirudhSK/chromium,bright-sparks/chromium-spacewalk,axinging/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,rogerwang/chromium,mohamed--abdel-maksoud/chromium.src,jaruba/chromium.src,bright-sparks/chromium-spacewalk,ondra-novak/chromium.src,M4sse/chromium.src,anirudhSK/chromium,ondra-novak/chromium.src,M4sse/chromium.src,hujiajie/pa-chromium,nacl-webkit/chrome_deps,dednal/chromium.src,hgl888/chromium-crosswalk,dushu1203/chromium.src,robclark/chromium,axinging/chromium-crosswalk,hgl888/chromium-crosswalk,Fireblend/chromium-crosswalk,anirudhSK/chromium,robclark/chromium,junmin-zhu/chromium-rivertrail,robclark/chromium,dednal/chromium.src,Just-D/chromium-1,dednal/chromium.src,zcbenz/cefode-chromium,bright-sparks/chromium-spacewalk,ondra-novak/chromium.src,dushu1203/chromium.src,pozdnyakov/chromium-crosswalk,ondra-novak/chromium.src,krieger-od/nwjs_chromium.src,ChromiumWebApps/chromium,PeterWangIntel/chromium-crosswalk,mogoweb/chromium-crosswalk,Pluto-tv/chromium-crosswalk,pozdnyakov/chromium-crosswalk,jaruba/chromium.src,chuan9/chromium-crosswalk,mogoweb/chromium-crosswalk,junmin-zhu/chromium-rivertrail,anirudhSK/chromium,chuan9/chromium-crosswalk,Chilledheart/chromium,nacl-webkit/chrome_deps,PeterWangIntel/chromium-crosswalk,krieger-od/nwjs_chromium.src,Jonekee/chromium.src,patrickm/chromium.src,patrickm/chromium.src,chuan9/chromium-crosswalk,fujunwei/chromium-crosswalk,Fireblend/chromium-crosswalk,mogoweb/chromium-crosswalk,hujiajie/pa-chromium,crosswalk-project/chromium-crosswalk-efl,dednal/chromium.src,junmin-zhu/chromium-rivertrail,timopulkkinen/BubbleFish,axinging/chromium-crosswalk,rogerwang/chromium,rogerwang/chromium,chuan9/chromium-crosswalk,dushu1203/chromium.src,mogoweb/chromium-crosswalk,hgl888/chromium-crosswalk,chuan9/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,Pluto-tv/chromium-crosswalk,pozdnyakov/chromium-crosswalk,zcbenz/cefode-chromium,Fireblend/chromium-crosswalk,fujunwei/chromium-crosswalk,jaruba/chromium.src,markYoungH/chromium.src,zcbenz/cefode-chromium,dednal/chromium.src,Just-D/chromium-1,robclark/chromium,timopulkkinen/BubbleFish,TheTypoMaster/chromium-crosswalk,Jonekee/chromium.src,littlstar/chromium.src,Jonekee/chromium.src,hgl888/chromium-crosswalk-efl,M4sse/chromium.src,ChromiumWebApps/chromium,crosswalk-project/chromium-crosswalk-efl,mogoweb/chromium-crosswalk,patrickm/chromium.src,mogoweb/chromium-crosswalk,axinging/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,dushu1203/chromium.src,littlstar/chromium.src,Just-D/chromium-1,hgl888/chromium-crosswalk-efl,nacl-webkit/chrome_deps,pozdnyakov/chromium-crosswalk,fujunwei/chromium-crosswalk,Chilledheart/chromium,axinging/chromium-crosswalk,hgl888/chromium-crosswalk-efl,pozdnyakov/chromium-crosswalk,chuan9/chromium-crosswalk,markYoungH/chromium.src,dednal/chromium.src,jaruba/chromium.src,dushu1203/chromium.src,robclark/chromium,Pluto-tv/chromium-crosswalk,keishi/chromium,junmin-zhu/chromium-rivertrail,mohamed--abdel-maksoud/chromium.src,zcbenz/cefode-chromium,krieger-od/nwjs_chromium.src,jaruba/chromium.src,patrickm/chromium.src,axinging/chromium-crosswalk,timopulkkinen/BubbleFish,timopulkkinen/BubbleFish,rogerwang/chromium,Jonekee/chromium.src,Chilledheart/chromium,littlstar/chromium.src,mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,hgl888/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,dushu1203/chromium.src,fujunwei/chromium-crosswalk,axinging/chromium-crosswalk,krieger-od/nwjs_chromium.src,pozdnyakov/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,anirudhSK/chromium,ChromiumWebApps/chromium,Pluto-tv/chromium-crosswalk,Jonekee/chromium.src,crosswalk-project/chromium-crosswalk-efl,Jonekee/chromium.src,ondra-novak/chromium.src,chuan9/chromium-crosswalk,chuan9/chromium-crosswalk,Chilledheart/chromium,rogerwang/chromium,Chilledheart/chromium,ltilve/chromium,anirudhSK/chromium,ChromiumWebApps/chromium,M4sse/chromium.src,patrickm/chromium.src,krieger-od/nwjs_chromium.src,ChromiumWebApps/chromium,markYoungH/chromium.src,dushu1203/chromium.src,robclark/chromium,fujunwei/chromium-crosswalk,hujiajie/pa-chromium,PeterWangIntel/chromium-crosswalk,M4sse/chromium.src,nacl-webkit/chrome_deps,M4sse/chromium.src,mogoweb/chromium-crosswalk,bright-sparks/chromium-spacewalk,M4sse/chromium.src,krieger-od/nwjs_chromium.src,markYoungH/chromium.src,dushu1203/chromium.src,hgl888/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,zcbenz/cefode-chromium,axinging/chromium-crosswalk,hujiajie/pa-chromium,timopulkkinen/BubbleFish,mohamed--abdel-maksoud/chromium.src,nacl-webkit/chrome_deps,mogoweb/chromium-crosswalk,Just-D/chromium-1,ltilve/chromium,mogoweb/chromium-crosswalk,markYoungH/chromium.src,nacl-webkit/chrome_deps,hujiajie/pa-chromium,bright-sparks/chromium-spacewalk,jaruba/chromium.src,jaruba/chromium.src,ChromiumWebApps/chromium,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk-efl,Just-D/chromium-1,hgl888/chromium-crosswalk-efl,littlstar/chromium.src,junmin-zhu/chromium-rivertrail,jaruba/chromium.src,PeterWangIntel/chromium-crosswalk,Just-D/chromium-1,bright-sparks/chromium-spacewalk,ondra-novak/chromium.src,keishi/chromium,PeterWangIntel/chromium-crosswalk,ltilve/chromium,markYoungH/chromium.src,littlstar/chromium.src,junmin-zhu/chromium-rivertrail,hujiajie/pa-chromium,ondra-novak/chromium.src,hgl888/chromium-crosswalk-efl,timopulkkinen/BubbleFish,patrickm/chromium.src,PeterWangIntel/chromium-crosswalk,keishi/chromium,krieger-od/nwjs_chromium.src,M4sse/chromium.src,ChromiumWebApps/chromium,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk-efl,Chilledheart/chromium,rogerwang/chromium,anirudhSK/chromium,Just-D/chromium-1,zcbenz/cefode-chromium,dednal/chromium.src,robclark/chromium
|
634e5b0af2b652d162097c1f532f86ce113d9cc6
|
lib/sanitizer_common/tests/sanitizer_thread_registry_test.cc
|
lib/sanitizer_common/tests/sanitizer_thread_registry_test.cc
|
//===-- sanitizer_thread_registry_test.cc ---------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a part of shared sanitizer runtime.
//
//===----------------------------------------------------------------------===//
#include "sanitizer_common/sanitizer_thread_registry.h"
#include "gtest/gtest.h"
#include <vector>
namespace __sanitizer {
static BlockingMutex tctx_allocator_lock(LINKER_INITIALIZED);
static LowLevelAllocator tctx_allocator;
template<typename TCTX>
static ThreadContextBase *GetThreadContext(u32 tid) {
BlockingMutexLock l(&tctx_allocator_lock);
return new(tctx_allocator) TCTX(tid);
}
static const u32 kMaxRegistryThreads = 1000;
static const u32 kRegistryQuarantine = 2;
static void CheckThreadQuantity(ThreadRegistry *registry, uptr exp_total,
uptr exp_running, uptr exp_alive) {
uptr total, running, alive;
registry->GetNumberOfThreads(&total, &running, &alive);
EXPECT_EQ(exp_total, total);
EXPECT_EQ(exp_running, running);
EXPECT_EQ(exp_alive, alive);
}
static bool is_detached(u32 tid) {
return (tid % 2 == 0);
}
static uptr get_uid(u32 tid) {
return tid * 2;
}
static bool HasName(ThreadContextBase *tctx, void *arg) {
char *name = (char*)arg;
return (tctx->name && 0 == internal_strcmp(tctx->name, name));
}
static bool HasUid(ThreadContextBase *tctx, void *arg) {
uptr uid = (uptr)arg;
return (tctx->user_id == uid);
}
static void MarkUidAsPresent(ThreadContextBase *tctx, void *arg) {
bool *arr = (bool*)arg;
arr[tctx->tid] = true;
}
static void TestRegistry(ThreadRegistry *registry, bool has_quarantine) {
// Create and start a main thread.
EXPECT_EQ(0U, registry->CreateThread(get_uid(0), true, -1, 0));
registry->StartThread(0, 0, 0);
// Create a bunch of threads.
for (u32 i = 1; i <= 10; i++) {
EXPECT_EQ(i, registry->CreateThread(get_uid(i), is_detached(i), 0, 0));
}
CheckThreadQuantity(registry, 11, 1, 11);
// Start some of them.
for (u32 i = 1; i <= 5; i++) {
registry->StartThread(i, 0, 0);
}
CheckThreadQuantity(registry, 11, 6, 11);
// Finish, create and start more threads.
for (u32 i = 1; i <= 5; i++) {
registry->FinishThread(i);
if (!is_detached(i))
registry->JoinThread(i, 0);
}
for (u32 i = 6; i <= 10; i++) {
registry->StartThread(i, 0, 0);
}
std::vector<u32> new_tids;
for (u32 i = 11; i <= 15; i++) {
new_tids.push_back(
registry->CreateThread(get_uid(i), is_detached(i), 0, 0));
}
ASSERT_LE(kRegistryQuarantine, 5U);
u32 exp_total = 16 - (has_quarantine ? 5 - kRegistryQuarantine : 0);
CheckThreadQuantity(registry, exp_total, 6, 11);
// Test SetThreadName and FindThread.
registry->SetThreadName(6, "six");
registry->SetThreadName(7, "seven");
EXPECT_EQ(7U, registry->FindThread(HasName, (void*)"seven"));
EXPECT_EQ(ThreadRegistry::kUnknownTid,
registry->FindThread(HasName, (void*)"none"));
EXPECT_EQ(0U, registry->FindThread(HasUid, (void*)get_uid(0)));
EXPECT_EQ(10U, registry->FindThread(HasUid, (void*)get_uid(10)));
EXPECT_EQ(ThreadRegistry::kUnknownTid,
registry->FindThread(HasUid, (void*)0x1234));
// Detach and finish and join remaining threads.
for (u32 i = 6; i <= 10; i++) {
registry->DetachThread(i);
registry->FinishThread(i);
}
for (u32 i = 0; i < new_tids.size(); i++) {
u32 tid = new_tids[i];
registry->StartThread(tid, 0, 0);
registry->DetachThread(tid);
registry->FinishThread(tid);
}
CheckThreadQuantity(registry, exp_total, 1, 1);
// Test methods that require the caller to hold a ThreadRegistryLock.
bool has_tid[16];
internal_memset(&has_tid[0], 0, sizeof(has_tid));
{
ThreadRegistryLock l(registry);
registry->RunCallbackForEachThreadLocked(MarkUidAsPresent, &has_tid[0]);
}
for (u32 i = 0; i < exp_total; i++) {
EXPECT_TRUE(has_tid[i]);
}
{
ThreadRegistryLock l(registry);
registry->CheckLocked();
ThreadContextBase *main_thread = registry->GetThreadLocked(0);
EXPECT_EQ(main_thread, registry->FindThreadContextLocked(
HasUid, (void*)get_uid(0)));
}
EXPECT_EQ(11U, registry->GetMaxAliveThreads());
}
TEST(SanitizerCommon, ThreadRegistryTest) {
ThreadRegistry quarantine_registry(GetThreadContext<ThreadContextBase>,
kMaxRegistryThreads,
kRegistryQuarantine);
TestRegistry(&quarantine_registry, true);
ThreadRegistry no_quarantine_registry(GetThreadContext<ThreadContextBase>,
kMaxRegistryThreads,
kMaxRegistryThreads);
TestRegistry(&no_quarantine_registry, false);
}
static const int kThreadsPerShard = 20;
static const int kNumShards = 25;
static int num_created[kNumShards + 1];
static int num_started[kNumShards + 1];
static int num_joined[kNumShards + 1];
namespace {
struct RunThreadArgs {
ThreadRegistry *registry;
uptr shard; // started from 1.
};
class TestThreadContext : public ThreadContextBase {
public:
explicit TestThreadContext(int tid) : ThreadContextBase(tid) {}
void OnJoined(void *arg) {
uptr shard = (uptr)arg;
num_joined[shard]++;
}
void OnStarted(void *arg) {
uptr shard = (uptr)arg;
num_started[shard]++;
}
void OnCreated(void *arg) {
uptr shard = (uptr)arg;
num_created[shard]++;
}
};
} // namespace
void *RunThread(void *arg) {
RunThreadArgs *args = static_cast<RunThreadArgs*>(arg);
std::vector<int> tids;
for (int i = 0; i < kThreadsPerShard; i++)
tids.push_back(
args->registry->CreateThread(0, false, 0, (void*)args->shard));
for (int i = 0; i < kThreadsPerShard; i++)
args->registry->StartThread(tids[i], 0, (void*)args->shard);
for (int i = 0; i < kThreadsPerShard; i++)
args->registry->FinishThread(tids[i]);
for (int i = 0; i < kThreadsPerShard; i++)
args->registry->JoinThread(tids[i], (void*)args->shard);
return 0;
}
static void ThreadedTestRegistry(ThreadRegistry *registry) {
// Create and start a main thread.
EXPECT_EQ(0U, registry->CreateThread(0, true, -1, 0));
registry->StartThread(0, 0, 0);
pthread_t threads[kNumShards];
RunThreadArgs args[kNumShards];
for (int i = 0; i < kNumShards; i++) {
args[i].registry = registry;
args[i].shard = i + 1;
pthread_create(&threads[i], 0, RunThread, &args[i]);
}
for (int i = 0; i < kNumShards; i++) {
pthread_join(threads[i], 0);
}
// Check that each thread created/started/joined correct amount
// of "threads" in thread_registry.
EXPECT_EQ(1, num_created[0]);
EXPECT_EQ(1, num_started[0]);
EXPECT_EQ(0, num_joined[0]);
for (int i = 1; i <= kNumShards; i++) {
EXPECT_EQ(kThreadsPerShard, num_created[i]);
EXPECT_EQ(kThreadsPerShard, num_started[i]);
EXPECT_EQ(kThreadsPerShard, num_joined[i]);
}
}
TEST(SanitizerCommon, ThreadRegistryThreadedTest) {
ThreadRegistry registry(GetThreadContext<TestThreadContext>,
kThreadsPerShard * kNumShards + 1, 10);
ThreadedTestRegistry(®istry);
}
} // namespace __sanitizer
|
//===-- sanitizer_thread_registry_test.cc ---------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a part of shared sanitizer runtime.
//
//===----------------------------------------------------------------------===//
#include "sanitizer_common/sanitizer_thread_registry.h"
#include "gtest/gtest.h"
#include <vector>
namespace __sanitizer {
static BlockingMutex tctx_allocator_lock(LINKER_INITIALIZED);
static LowLevelAllocator tctx_allocator;
template<typename TCTX>
static ThreadContextBase *GetThreadContext(u32 tid) {
BlockingMutexLock l(&tctx_allocator_lock);
return new(tctx_allocator) TCTX(tid);
}
static const u32 kMaxRegistryThreads = 1000;
static const u32 kRegistryQuarantine = 2;
static void CheckThreadQuantity(ThreadRegistry *registry, uptr exp_total,
uptr exp_running, uptr exp_alive) {
uptr total, running, alive;
registry->GetNumberOfThreads(&total, &running, &alive);
EXPECT_EQ(exp_total, total);
EXPECT_EQ(exp_running, running);
EXPECT_EQ(exp_alive, alive);
}
static bool is_detached(u32 tid) {
return (tid % 2 == 0);
}
static uptr get_uid(u32 tid) {
return tid * 2;
}
static bool HasName(ThreadContextBase *tctx, void *arg) {
char *name = (char*)arg;
return (0 == internal_strcmp(tctx->name, name));
}
static bool HasUid(ThreadContextBase *tctx, void *arg) {
uptr uid = (uptr)arg;
return (tctx->user_id == uid);
}
static void MarkUidAsPresent(ThreadContextBase *tctx, void *arg) {
bool *arr = (bool*)arg;
arr[tctx->tid] = true;
}
static void TestRegistry(ThreadRegistry *registry, bool has_quarantine) {
// Create and start a main thread.
EXPECT_EQ(0U, registry->CreateThread(get_uid(0), true, -1, 0));
registry->StartThread(0, 0, 0);
// Create a bunch of threads.
for (u32 i = 1; i <= 10; i++) {
EXPECT_EQ(i, registry->CreateThread(get_uid(i), is_detached(i), 0, 0));
}
CheckThreadQuantity(registry, 11, 1, 11);
// Start some of them.
for (u32 i = 1; i <= 5; i++) {
registry->StartThread(i, 0, 0);
}
CheckThreadQuantity(registry, 11, 6, 11);
// Finish, create and start more threads.
for (u32 i = 1; i <= 5; i++) {
registry->FinishThread(i);
if (!is_detached(i))
registry->JoinThread(i, 0);
}
for (u32 i = 6; i <= 10; i++) {
registry->StartThread(i, 0, 0);
}
std::vector<u32> new_tids;
for (u32 i = 11; i <= 15; i++) {
new_tids.push_back(
registry->CreateThread(get_uid(i), is_detached(i), 0, 0));
}
ASSERT_LE(kRegistryQuarantine, 5U);
u32 exp_total = 16 - (has_quarantine ? 5 - kRegistryQuarantine : 0);
CheckThreadQuantity(registry, exp_total, 6, 11);
// Test SetThreadName and FindThread.
registry->SetThreadName(6, "six");
registry->SetThreadName(7, "seven");
EXPECT_EQ(7U, registry->FindThread(HasName, (void*)"seven"));
EXPECT_EQ(ThreadRegistry::kUnknownTid,
registry->FindThread(HasName, (void*)"none"));
EXPECT_EQ(0U, registry->FindThread(HasUid, (void*)get_uid(0)));
EXPECT_EQ(10U, registry->FindThread(HasUid, (void*)get_uid(10)));
EXPECT_EQ(ThreadRegistry::kUnknownTid,
registry->FindThread(HasUid, (void*)0x1234));
// Detach and finish and join remaining threads.
for (u32 i = 6; i <= 10; i++) {
registry->DetachThread(i);
registry->FinishThread(i);
}
for (u32 i = 0; i < new_tids.size(); i++) {
u32 tid = new_tids[i];
registry->StartThread(tid, 0, 0);
registry->DetachThread(tid);
registry->FinishThread(tid);
}
CheckThreadQuantity(registry, exp_total, 1, 1);
// Test methods that require the caller to hold a ThreadRegistryLock.
bool has_tid[16];
internal_memset(&has_tid[0], 0, sizeof(has_tid));
{
ThreadRegistryLock l(registry);
registry->RunCallbackForEachThreadLocked(MarkUidAsPresent, &has_tid[0]);
}
for (u32 i = 0; i < exp_total; i++) {
EXPECT_TRUE(has_tid[i]);
}
{
ThreadRegistryLock l(registry);
registry->CheckLocked();
ThreadContextBase *main_thread = registry->GetThreadLocked(0);
EXPECT_EQ(main_thread, registry->FindThreadContextLocked(
HasUid, (void*)get_uid(0)));
}
EXPECT_EQ(11U, registry->GetMaxAliveThreads());
}
TEST(SanitizerCommon, ThreadRegistryTest) {
ThreadRegistry quarantine_registry(GetThreadContext<ThreadContextBase>,
kMaxRegistryThreads,
kRegistryQuarantine);
TestRegistry(&quarantine_registry, true);
ThreadRegistry no_quarantine_registry(GetThreadContext<ThreadContextBase>,
kMaxRegistryThreads,
kMaxRegistryThreads);
TestRegistry(&no_quarantine_registry, false);
}
static const int kThreadsPerShard = 20;
static const int kNumShards = 25;
static int num_created[kNumShards + 1];
static int num_started[kNumShards + 1];
static int num_joined[kNumShards + 1];
namespace {
struct RunThreadArgs {
ThreadRegistry *registry;
uptr shard; // started from 1.
};
class TestThreadContext : public ThreadContextBase {
public:
explicit TestThreadContext(int tid) : ThreadContextBase(tid) {}
void OnJoined(void *arg) {
uptr shard = (uptr)arg;
num_joined[shard]++;
}
void OnStarted(void *arg) {
uptr shard = (uptr)arg;
num_started[shard]++;
}
void OnCreated(void *arg) {
uptr shard = (uptr)arg;
num_created[shard]++;
}
};
} // namespace
void *RunThread(void *arg) {
RunThreadArgs *args = static_cast<RunThreadArgs*>(arg);
std::vector<int> tids;
for (int i = 0; i < kThreadsPerShard; i++)
tids.push_back(
args->registry->CreateThread(0, false, 0, (void*)args->shard));
for (int i = 0; i < kThreadsPerShard; i++)
args->registry->StartThread(tids[i], 0, (void*)args->shard);
for (int i = 0; i < kThreadsPerShard; i++)
args->registry->FinishThread(tids[i]);
for (int i = 0; i < kThreadsPerShard; i++)
args->registry->JoinThread(tids[i], (void*)args->shard);
return 0;
}
static void ThreadedTestRegistry(ThreadRegistry *registry) {
// Create and start a main thread.
EXPECT_EQ(0U, registry->CreateThread(0, true, -1, 0));
registry->StartThread(0, 0, 0);
pthread_t threads[kNumShards];
RunThreadArgs args[kNumShards];
for (int i = 0; i < kNumShards; i++) {
args[i].registry = registry;
args[i].shard = i + 1;
pthread_create(&threads[i], 0, RunThread, &args[i]);
}
for (int i = 0; i < kNumShards; i++) {
pthread_join(threads[i], 0);
}
// Check that each thread created/started/joined correct amount
// of "threads" in thread_registry.
EXPECT_EQ(1, num_created[0]);
EXPECT_EQ(1, num_started[0]);
EXPECT_EQ(0, num_joined[0]);
for (int i = 1; i <= kNumShards; i++) {
EXPECT_EQ(kThreadsPerShard, num_created[i]);
EXPECT_EQ(kThreadsPerShard, num_started[i]);
EXPECT_EQ(kThreadsPerShard, num_joined[i]);
}
}
TEST(SanitizerCommon, ThreadRegistryThreadedTest) {
ThreadRegistry registry(GetThreadContext<TestThreadContext>,
kThreadsPerShard * kNumShards + 1, 10);
ThreadedTestRegistry(®istry);
}
} // namespace __sanitizer
|
Remove 'tctx->name' from a logical statement since it is a pointer and always is converted to a true value. Detected by Clang's improved -Wbool-conversion
|
Remove 'tctx->name' from a logical statement since it is a pointer and always
is converted to a true value. Detected by Clang's improved -Wbool-conversion
git-svn-id: c199f293c43da69278bea8e88f92242bf3aa95f7@202223 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
apache-2.0
|
llvm-mirror/compiler-rt,llvm-mirror/compiler-rt,llvm-mirror/compiler-rt,llvm-mirror/compiler-rt,llvm-mirror/compiler-rt
|
49cf59a3c5712b878e01d8642678ec14f89e1f24
|
chrome/test/perf/shutdown_test.cc
|
chrome/test/perf/shutdown_test.cc
|
// Copyright (c) 2011 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/environment.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/stringprintf.h"
#include "base/string_number_conversions.h"
#include "base/sys_info.h"
#include "base/time.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/env_vars.h"
#include "chrome/test/automation/automation_proxy.h"
#include "chrome/test/base/ui_test_utils.h"
#include "chrome/test/perf/perf_test.h"
#include "chrome/test/ui/ui_perf_test.h"
#include "net/base/net_util.h"
using base::TimeDelta;
namespace {
class ShutdownTest : public UIPerfTest {
public:
ShutdownTest() {
show_window_ = true;
}
void SetUp() {}
void TearDown() {}
enum TestSize {
SIMPLE, // Runs with no command line arguments (loads about:blank).
TWENTY_TABS, // Opens 5 copies of 4 different test pages.
};
void SetUpTwentyTabs() {
int window_count;
ASSERT_TRUE(automation()->GetBrowserWindowCount(&window_count));
ASSERT_EQ(1, window_count);
scoped_refptr<BrowserProxy> browser_proxy(
automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser_proxy.get());
const FilePath kFastShutdownDir(FILE_PATH_LITERAL("fast_shutdown"));
const FilePath kCurrentDir(FilePath::kCurrentDirectory);
const FilePath test_cases[] = {
ui_test_utils::GetTestFilePath(kFastShutdownDir,
FilePath(FILE_PATH_LITERAL("on_before_unloader.html"))),
ui_test_utils::GetTestFilePath(kCurrentDir,
FilePath(FILE_PATH_LITERAL("animated-gifs.html"))),
ui_test_utils::GetTestFilePath(kCurrentDir,
FilePath(FILE_PATH_LITERAL("french_page.html"))),
ui_test_utils::GetTestFilePath(kCurrentDir,
FilePath(FILE_PATH_LITERAL("onunload_cookie.html"))),
};
for (size_t i = 0; i < arraysize(test_cases); i++) {
ASSERT_TRUE(file_util::PathExists(test_cases[i]));
for (size_t j = 0; j < 5; j++) {
ASSERT_TRUE(browser_proxy->AppendTab(
net::FilePathToFileURL(test_cases[i])));
}
}
}
void RunShutdownTest(const char* graph, const char* trace,
bool important, TestSize test_size,
ProxyLauncher::ShutdownType shutdown_type) {
const int kNumCyclesMax = 20;
int numCycles = kNumCyclesMax;
scoped_ptr<base::Environment> env(base::Environment::Create());
std::string numCyclesEnv;
if (env->GetVar(env_vars::kStartupTestsNumCycles, &numCyclesEnv) &&
base::StringToInt(numCyclesEnv, &numCycles)) {
if (numCycles <= kNumCyclesMax) {
VLOG(1) << env_vars::kStartupTestsNumCycles
<< " set in environment, so setting numCycles to " << numCycles;
} else {
VLOG(1) << env_vars::kStartupTestsNumCycles
<< " is higher than the max, setting numCycles to "
<< kNumCyclesMax;
numCycles = kNumCyclesMax;
}
}
TimeDelta timings[kNumCyclesMax];
for (int i = 0; i < numCycles; ++i) {
UITest::SetUp();
if (test_size == TWENTY_TABS) {
SetUpTwentyTabs();
}
set_shutdown_type(shutdown_type);
UITest::TearDown();
timings[i] = browser_quit_time();
if (i == 0) {
// Re-use the profile data after first run so that the noise from
// creating databases doesn't impact all the runs.
clear_profile_ = false;
// Clear template_user_data_ so we don't try to copy it over each time
// through.
set_template_user_data(FilePath());
}
}
std::string times;
for (int i = 0; i < numCycles; ++i)
base::StringAppendF(×, "%.2f,", timings[i].InMillisecondsF());
perf_test::PrintResultList(graph, "", trace, times, "ms", important);
}
};
TEST_F(ShutdownTest, SimpleWindowClose) {
RunShutdownTest("shutdown", "simple-window-close",
true, /* important */ SIMPLE, ProxyLauncher::WINDOW_CLOSE);
}
TEST_F(ShutdownTest, SimpleUserQuit) {
RunShutdownTest("shutdown", "simple-user-quit",
true, /* important */ SIMPLE, ProxyLauncher::USER_QUIT);
}
TEST_F(ShutdownTest, SimpleSessionEnding) {
RunShutdownTest("shutdown", "simple-session-ending",
true, /* important */ SIMPLE, ProxyLauncher::SESSION_ENDING);
}
TEST_F(ShutdownTest, TwentyTabsWindowClose) {
RunShutdownTest("shutdown", "twentytabs-window-close",
true, /* important */ TWENTY_TABS,
ProxyLauncher::WINDOW_CLOSE);
}
TEST_F(ShutdownTest, TwentyTabsUserQuit) {
RunShutdownTest("shutdown", "twentytabs-user-quit",
true, /* important */ TWENTY_TABS, ProxyLauncher::USER_QUIT);
}
// http://crbug.com/40671
#if defined(OS_WIN) && !defined(NDEBUG)
#define MAYBE_TwentyTabsSessionEnding DISABLED_TwentyTabsSessionEnding
#else
#define MAYBE_TwentyTabsSessionEnding TwentyTabsSessionEnding
#endif
TEST_F(ShutdownTest, MAYBE_TwentyTabsSessionEnding) {
RunShutdownTest("shutdown", "twentytabs-session-ending",
true, /* important */ TWENTY_TABS,
ProxyLauncher::SESSION_ENDING);
}
} // namespace
|
// 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/environment.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/stringprintf.h"
#include "base/string_number_conversions.h"
#include "base/sys_info.h"
#include "base/time.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/env_vars.h"
#include "chrome/test/automation/automation_proxy.h"
#include "chrome/test/base/ui_test_utils.h"
#include "chrome/test/perf/perf_test.h"
#include "chrome/test/ui/ui_perf_test.h"
#include "net/base/net_util.h"
using base::TimeDelta;
namespace {
class ShutdownTest : public UIPerfTest {
public:
ShutdownTest() {
show_window_ = true;
}
void SetUp() {}
void TearDown() {}
enum TestSize {
SIMPLE, // Runs with no command line arguments (loads about:blank).
TWENTY_TABS, // Opens 5 copies of 4 different test pages.
};
void SetUpTwentyTabs() {
int window_count;
ASSERT_TRUE(automation()->GetBrowserWindowCount(&window_count));
ASSERT_EQ(1, window_count);
scoped_refptr<BrowserProxy> browser_proxy(
automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser_proxy.get());
const FilePath kFastShutdownDir(FILE_PATH_LITERAL("fast_shutdown"));
const FilePath kCurrentDir(FilePath::kCurrentDirectory);
const FilePath test_cases[] = {
ui_test_utils::GetTestFilePath(kFastShutdownDir,
FilePath(FILE_PATH_LITERAL("on_before_unloader.html"))),
ui_test_utils::GetTestFilePath(kCurrentDir,
FilePath(FILE_PATH_LITERAL("animated-gifs.html"))),
ui_test_utils::GetTestFilePath(kCurrentDir,
FilePath(FILE_PATH_LITERAL("french_page.html"))),
ui_test_utils::GetTestFilePath(kCurrentDir,
FilePath(FILE_PATH_LITERAL("onunload_cookie.html"))),
};
for (size_t i = 0; i < arraysize(test_cases); i++) {
ASSERT_TRUE(file_util::PathExists(test_cases[i]));
for (size_t j = 0; j < 5; j++) {
ASSERT_TRUE(browser_proxy->AppendTab(
net::FilePathToFileURL(test_cases[i])));
}
}
}
void RunShutdownTest(const char* graph, const char* trace,
bool important, TestSize test_size,
ProxyLauncher::ShutdownType shutdown_type) {
const int kNumCyclesMax = 20;
int numCycles = kNumCyclesMax;
scoped_ptr<base::Environment> env(base::Environment::Create());
std::string numCyclesEnv;
if (env->GetVar(env_vars::kStartupTestsNumCycles, &numCyclesEnv) &&
base::StringToInt(numCyclesEnv, &numCycles)) {
if (numCycles <= kNumCyclesMax) {
VLOG(1) << env_vars::kStartupTestsNumCycles
<< " set in environment, so setting numCycles to " << numCycles;
} else {
VLOG(1) << env_vars::kStartupTestsNumCycles
<< " is higher than the max, setting numCycles to "
<< kNumCyclesMax;
numCycles = kNumCyclesMax;
}
}
TimeDelta timings[kNumCyclesMax];
for (int i = 0; i < numCycles; ++i) {
UITest::SetUp();
if (test_size == TWENTY_TABS) {
SetUpTwentyTabs();
}
set_shutdown_type(shutdown_type);
UITest::TearDown();
timings[i] = browser_quit_time();
if (i == 0) {
// Re-use the profile data after first run so that the noise from
// creating databases doesn't impact all the runs.
clear_profile_ = false;
// Clear template_user_data_ so we don't try to copy it over each time
// through.
set_template_user_data(FilePath());
}
}
std::string times;
for (int i = 0; i < numCycles; ++i)
base::StringAppendF(×, "%.2f,", timings[i].InMillisecondsF());
perf_test::PrintResultList(graph, "", trace, times, "ms", important);
}
};
TEST_F(ShutdownTest, SimpleWindowClose) {
RunShutdownTest("shutdown", "simple-window-close",
true, /* important */ SIMPLE, ProxyLauncher::WINDOW_CLOSE);
}
TEST_F(ShutdownTest, SimpleUserQuit) {
RunShutdownTest("shutdown", "simple-user-quit",
true, /* important */ SIMPLE, ProxyLauncher::USER_QUIT);
}
TEST_F(ShutdownTest, SimpleSessionEnding) {
RunShutdownTest("shutdown", "simple-session-ending",
true, /* important */ SIMPLE, ProxyLauncher::SESSION_ENDING);
}
// http://crbug.com/110471
#if defined(OS_WIN) && !defined(NDEBUG)
#define MAYBE_TwentyTabsWindowClose DISABLED_TwentyTabsWindowClose
#else
#define MAYBE_TwentyTabsWindowClose TwentyTabsWindowClose
#endif
TEST_F(ShutdownTest, MAYBE_TwentyTabsWindowClose) {
RunShutdownTest("shutdown", "twentytabs-window-close",
true, /* important */ TWENTY_TABS,
ProxyLauncher::WINDOW_CLOSE);
}
TEST_F(ShutdownTest, TwentyTabsUserQuit) {
RunShutdownTest("shutdown", "twentytabs-user-quit",
true, /* important */ TWENTY_TABS, ProxyLauncher::USER_QUIT);
}
// http://crbug.com/40671
#if defined(OS_WIN) && !defined(NDEBUG)
#define MAYBE_TwentyTabsSessionEnding DISABLED_TwentyTabsSessionEnding
#else
#define MAYBE_TwentyTabsSessionEnding TwentyTabsSessionEnding
#endif
TEST_F(ShutdownTest, MAYBE_TwentyTabsSessionEnding) {
RunShutdownTest("shutdown", "twentytabs-session-ending",
true, /* important */ TWENTY_TABS,
ProxyLauncher::SESSION_ENDING);
}
} // namespace
|
Mark TwentyTabsWindowClose on Windows debug disabled for now.
|
Mark TwentyTabsWindowClose on Windows debug disabled for now.
BUG=110471
[email protected]
Review URL: http://codereview.chromium.org/9241018
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@117951 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
yitian134/chromium,ropik/chromium,ropik/chromium,yitian134/chromium,gavinp/chromium,gavinp/chromium,adobe/chromium,adobe/chromium,ropik/chromium,ropik/chromium,yitian134/chromium,adobe/chromium,yitian134/chromium,ropik/chromium,gavinp/chromium,gavinp/chromium,ropik/chromium,gavinp/chromium,adobe/chromium,gavinp/chromium,yitian134/chromium,ropik/chromium,adobe/chromium,gavinp/chromium,adobe/chromium,adobe/chromium,gavinp/chromium,ropik/chromium,adobe/chromium,yitian134/chromium,adobe/chromium,ropik/chromium,gavinp/chromium,yitian134/chromium,adobe/chromium,adobe/chromium,gavinp/chromium,yitian134/chromium,yitian134/chromium,yitian134/chromium
|
9a71577407ae7d153dda877c54b882c414adcb26
|
src/shared/imc/nacl/nacl_imc.cc
|
src/shared/imc/nacl/nacl_imc.cc
|
/*
* Copyright 2008 The Native Client Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can
* be found in the LICENSE file.
*/
// NaCl inter-module communication primitives.
#ifdef __native_client__
#include <nacl/nacl_imc.h>
#else
#include "native_client/src/shared/imc/nacl_imc.h"
#endif // __native_client__
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/nacl_syscalls.h>
#include <algorithm>
namespace nacl {
bool WouldBlock() {
return (errno == EAGAIN) ? true : false;
}
int GetLastErrorString(char* buffer, size_t length) {
// Note newlib provides only GNU version of strerror_r().
if (buffer == NULL || length == 0) {
errno = ERANGE;
return -1;
}
char* message = strerror_r(errno, buffer, length);
if (message != buffer) {
size_t message_bytes = strlen(message) + 1;
length = std::min(message_bytes, length);
memmove(buffer, message, length);
buffer[length - 1] = '\0';
}
return 0;
}
Handle BoundSocket(const SocketAddress* address) {
// TODO(shiki): Switch to the following once the make_bound_sock() prototype
// is cleaned up.
// return make_bound_sock(address);
return -1;
}
int SocketPair(Handle pair[2]) {
return imc_socketpair(pair);
}
int Close(Handle handle) {
return close(handle);
}
int SendDatagram(Handle handle, const MessageHeader* message, int flags) {
return imc_sendmsg(handle, reinterpret_cast<const NaClImcMsgHdr*>(message),
flags);
}
int SendDatagramTo(const MessageHeader* message, int flags,
const SocketAddress* name) {
return -1; // TODO(bsy): how to implement this for NaCl?
}
int ReceiveDatagram(Handle handle, MessageHeader* message, int flags) {
return imc_recvmsg(handle, reinterpret_cast<NaClImcMsgHdr*>(message), flags);
}
Handle CreateMemoryObject(size_t length) {
return imc_mem_obj_create(length);
}
void* Map(void* start, size_t length, int prot, int flags,
Handle memory, off_t offset) {
static int posix_prot[4] = {
PROT_NONE,
PROT_READ,
PROT_WRITE,
PROT_READ | PROT_WRITE
};
int adjusted = 0;
if (flags & kMapShared) {
adjusted |= MAP_SHARED;
}
if (flags & kMapPrivate) {
adjusted |= MAP_PRIVATE;
}
if (flags & kMapFixed) {
adjusted |= MAP_FIXED;
}
return mmap(start, length, posix_prot[prot & 3], adjusted, memory, offset);
}
int Unmap(void* start, size_t length) {
return munmap(start, length);
}
} // namespace nacl
|
/*
* Copyright 2008 The Native Client Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can
* be found in the LICENSE file.
*/
// NaCl inter-module communication primitives.
#ifdef __native_client__
#include <nacl/nacl_imc.h>
#else
#include "native_client/src/shared/imc/nacl_imc.h"
#endif // __native_client__
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/nacl_syscalls.h>
#include <unistd.h>
#include <algorithm>
namespace nacl {
bool WouldBlock() {
return (errno == EAGAIN) ? true : false;
}
int GetLastErrorString(char* buffer, size_t length) {
// Note newlib provides only GNU version of strerror_r().
if (buffer == NULL || length == 0) {
errno = ERANGE;
return -1;
}
char* message = strerror_r(errno, buffer, length);
if (message != buffer) {
size_t message_bytes = strlen(message) + 1;
length = std::min(message_bytes, length);
memmove(buffer, message, length);
buffer[length - 1] = '\0';
}
return 0;
}
Handle BoundSocket(const SocketAddress* address) {
// TODO(shiki): Switch to the following once the make_bound_sock() prototype
// is cleaned up.
// return make_bound_sock(address);
return -1;
}
int SocketPair(Handle pair[2]) {
return imc_socketpair(pair);
}
int Close(Handle handle) {
return close(handle);
}
int SendDatagram(Handle handle, const MessageHeader* message, int flags) {
return imc_sendmsg(handle, reinterpret_cast<const NaClImcMsgHdr*>(message),
flags);
}
int SendDatagramTo(const MessageHeader* message, int flags,
const SocketAddress* name) {
return -1; // TODO(bsy): how to implement this for NaCl?
}
int ReceiveDatagram(Handle handle, MessageHeader* message, int flags) {
return imc_recvmsg(handle, reinterpret_cast<NaClImcMsgHdr*>(message), flags);
}
Handle CreateMemoryObject(size_t length) {
return imc_mem_obj_create(length);
}
void* Map(void* start, size_t length, int prot, int flags,
Handle memory, off_t offset) {
static int posix_prot[4] = {
PROT_NONE,
PROT_READ,
PROT_WRITE,
PROT_READ | PROT_WRITE
};
int adjusted = 0;
if (flags & kMapShared) {
adjusted |= MAP_SHARED;
}
if (flags & kMapPrivate) {
adjusted |= MAP_PRIVATE;
}
if (flags & kMapFixed) {
adjusted |= MAP_FIXED;
}
return mmap(start, length, posix_prot[prot & 3], adjusted, memory, offset);
}
int Unmap(void* start, size_t length) {
return munmap(start, length);
}
} // namespace nacl
|
Fix missing #include in order to build against nacl-glibc
|
Fix missing #include in order to build against nacl-glibc
nacl_imc.cc needs <unistd.h> in order for close() to be defined.
BUG=http://code.google.com/p/nativeclient/issues/detail?id=617
TEST=python build.py -b
Review URL: http://codereview.chromium.org/3170038
git-svn-id: 721b910a23eff8a86f00c8fd261a7587cddf18f8@3088 fcba33aa-ac0c-11dd-b9e7-8d5594d729c2
|
C++
|
bsd-3-clause
|
nacl-webkit/native_client,nacl-webkit/native_client,nacl-webkit/native_client,sbc100/native_client,sbc100/native_client,nacl-webkit/native_client,sbc100/native_client,sbc100/native_client,sbc100/native_client,sbc100/native_client,nacl-webkit/native_client
|
17be65344bee11859050da3a0ce9823da4f9530b
|
src/structures/vroom/amount.cpp
|
src/structures/vroom/amount.cpp
|
/*
This file is part of VROOM.
Copyright (c) 2015-2018, Julien Coupey.
All rights reserved (see LICENSE).
*/
#include "structures/vroom/amount.h"
amount_t& amount_t::operator+=(const amount_t& rhs) {
assert(this->size() == rhs.size());
for (std::size_t i = 0; i < this->size(); ++i) {
(*this)[i] += rhs[i];
}
return *this;
}
amount_t& amount_t::operator-=(const amount_t& rhs) {
assert(this->size() == rhs.size());
for (std::size_t i = 0; i < this->size(); ++i) {
(*this)[i] -= rhs[i];
}
return *this;
}
bool test_check(const amount_t& r, const amount_t& l, const amount_t& g) {
return r + l == g;
}
|
/*
This file is part of VROOM.
Copyright (c) 2015-2018, Julien Coupey.
All rights reserved (see LICENSE).
*/
#include "structures/vroom/amount.h"
amount_t& amount_t::operator+=(const amount_t& rhs) {
assert(this->size() == rhs.size());
for (std::size_t i = 0; i < this->size(); ++i) {
(*this)[i] += rhs[i];
}
return *this;
}
amount_t& amount_t::operator-=(const amount_t& rhs) {
assert(this->size() == rhs.size());
for (std::size_t i = 0; i < this->size(); ++i) {
(*this)[i] -= rhs[i];
}
return *this;
}
|
Remove test function
|
Remove test function
|
C++
|
bsd-2-clause
|
jcoupey/vroom,jcoupey/vroom,VROOM-Project/vroom,VROOM-Project/vroom,VROOM-Project/vroom
|
a6ddc34649735d890b78602e821ae6836786c8e9
|
src/test/test_bitcoin_fuzzy.cpp
|
src/test/test_bitcoin_fuzzy.cpp
|
// Copyright (c) 2009-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include "config/bitcoin-config.h"
#endif
#include "consensus/merkle.h"
#include "primitives/block.h"
#include "script/script.h"
#include "addrman.h"
#include "chain.h"
#include "coins.h"
#include "compressor.h"
#include "net.h"
#include "protocol.h"
#include "streams.h"
#include "undo.h"
#include "version.h"
#include "pubkey.h"
#include <stdint.h>
#include <unistd.h>
#include <algorithm>
#include <vector>
enum TEST_ID {
CBLOCK_DESERIALIZE=0,
CTRANSACTION_DESERIALIZE,
CBLOCKLOCATOR_DESERIALIZE,
CBLOCKMERKLEROOT,
CADDRMAN_DESERIALIZE,
CBLOCKHEADER_DESERIALIZE,
CBANENTRY_DESERIALIZE,
CTXUNDO_DESERIALIZE,
CBLOCKUNDO_DESERIALIZE,
CCOINS_DESERIALIZE,
CNETADDR_DESERIALIZE,
CSERVICE_DESERIALIZE,
CMESSAGEHEADER_DESERIALIZE,
CADDRESS_DESERIALIZE,
CINV_DESERIALIZE,
CBLOOMFILTER_DESERIALIZE,
CDISKBLOCKINDEX_DESERIALIZE,
CTXOUTCOMPRESSOR_DESERIALIZE,
TEST_ID_END
};
bool read_stdin(std::vector<char> &data) {
char buffer[1024];
ssize_t length=0;
while((length = read(STDIN_FILENO, buffer, 1024)) > 0) {
data.insert(data.end(), buffer, buffer+length);
if (data.size() > (1<<20)) return false;
}
return length==0;
}
int do_fuzz()
{
std::vector<char> buffer;
if (!read_stdin(buffer)) return 0;
if (buffer.size() < sizeof(uint32_t)) return 0;
uint32_t test_id = 0xffffffff;
memcpy(&test_id, &buffer[0], sizeof(uint32_t));
buffer.erase(buffer.begin(), buffer.begin() + sizeof(uint32_t));
if (test_id >= TEST_ID_END) return 0;
CDataStream ds(buffer, SER_NETWORK, INIT_PROTO_VERSION);
try {
int nVersion;
ds >> nVersion;
ds.SetVersion(nVersion);
} catch (const std::ios_base::failure& e) {
return 0;
}
switch(test_id) {
case CBLOCK_DESERIALIZE:
{
try
{
CBlock block;
ds >> block;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CTRANSACTION_DESERIALIZE:
{
try
{
CTransaction tx(deserialize, ds);
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CBLOCKLOCATOR_DESERIALIZE:
{
try
{
CBlockLocator bl;
ds >> bl;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CBLOCKMERKLEROOT:
{
try
{
CBlock block;
ds >> block;
bool mutated;
BlockMerkleRoot(block, &mutated);
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CADDRMAN_DESERIALIZE:
{
try
{
CAddrMan am;
ds >> am;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CBLOCKHEADER_DESERIALIZE:
{
try
{
CBlockHeader bh;
ds >> bh;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CBANENTRY_DESERIALIZE:
{
try
{
CBanEntry be;
ds >> be;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CTXUNDO_DESERIALIZE:
{
try
{
CTxUndo tu;
ds >> tu;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CBLOCKUNDO_DESERIALIZE:
{
try
{
CBlockUndo bu;
ds >> bu;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CCOINS_DESERIALIZE:
{
try
{
CCoins block;
ds >> block;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CNETADDR_DESERIALIZE:
{
try
{
CNetAddr na;
ds >> na;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CSERVICE_DESERIALIZE:
{
try
{
CService s;
ds >> s;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CMESSAGEHEADER_DESERIALIZE:
{
CMessageHeader::MessageStartChars pchMessageStart = {0x00, 0x00, 0x00, 0x00};
try
{
CMessageHeader mh(pchMessageStart);
ds >> mh;
if (!mh.IsValid(pchMessageStart)) {return 0;}
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CADDRESS_DESERIALIZE:
{
try
{
CAddress a;
ds >> a;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CINV_DESERIALIZE:
{
try
{
CInv i;
ds >> i;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CBLOOMFILTER_DESERIALIZE:
{
try
{
CBloomFilter bf;
ds >> bf;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CDISKBLOCKINDEX_DESERIALIZE:
{
try
{
CDiskBlockIndex dbi;
ds >> dbi;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CTXOUTCOMPRESSOR_DESERIALIZE:
{
CTxOut to;
CTxOutCompressor toc(to);
try
{
ds >> toc;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
default:
return 0;
}
return 0;
}
int main(int argc, char **argv)
{
ECCVerifyHandle globalVerifyHandle;
#ifdef __AFL_INIT
// Enable AFL deferred forkserver mode. Requires compilation using
// afl-clang-fast++. See fuzzing.md for details.
__AFL_INIT();
#endif
#ifdef __AFL_LOOP
// Enable AFL persistent mode. Requires compilation using afl-clang-fast++.
// See fuzzing.md for details.
while (__AFL_LOOP(1000)) {
do_fuzz();
}
return 0;
#else
return do_fuzz();
#endif
}
|
// Copyright (c) 2009-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include "config/bitcoin-config.h"
#endif
#include "consensus/merkle.h"
#include "primitives/block.h"
#include "script/script.h"
#include "addrman.h"
#include "chain.h"
#include "coins.h"
#include "compressor.h"
#include "net.h"
#include "protocol.h"
#include "streams.h"
#include "undo.h"
#include "version.h"
#include "pubkey.h"
#include <stdint.h>
#include <unistd.h>
#include <algorithm>
#include <vector>
enum TEST_ID {
CBLOCK_DESERIALIZE=0,
CTRANSACTION_DESERIALIZE,
CBLOCKLOCATOR_DESERIALIZE,
CBLOCKMERKLEROOT,
CADDRMAN_DESERIALIZE,
CBLOCKHEADER_DESERIALIZE,
CBANENTRY_DESERIALIZE,
CTXUNDO_DESERIALIZE,
CBLOCKUNDO_DESERIALIZE,
CCOINS_DESERIALIZE,
CNETADDR_DESERIALIZE,
CSERVICE_DESERIALIZE,
CMESSAGEHEADER_DESERIALIZE,
CADDRESS_DESERIALIZE,
CINV_DESERIALIZE,
CBLOOMFILTER_DESERIALIZE,
CDISKBLOCKINDEX_DESERIALIZE,
CTXOUTCOMPRESSOR_DESERIALIZE,
TEST_ID_END
};
bool read_stdin(std::vector<uint8_t> &data) {
uint8_t buffer[1024];
ssize_t length=0;
while((length = read(STDIN_FILENO, buffer, 1024)) > 0) {
data.insert(data.end(), buffer, buffer+length);
if (data.size() > (1<<20)) return false;
}
return length==0;
}
int test_one_input(std::vector<uint8_t> buffer) {
if (buffer.size() < sizeof(uint32_t)) return 0;
uint32_t test_id = 0xffffffff;
memcpy(&test_id, &buffer[0], sizeof(uint32_t));
buffer.erase(buffer.begin(), buffer.begin() + sizeof(uint32_t));
if (test_id >= TEST_ID_END) return 0;
CDataStream ds(buffer, SER_NETWORK, INIT_PROTO_VERSION);
try {
int nVersion;
ds >> nVersion;
ds.SetVersion(nVersion);
} catch (const std::ios_base::failure& e) {
return 0;
}
switch(test_id) {
case CBLOCK_DESERIALIZE:
{
try
{
CBlock block;
ds >> block;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CTRANSACTION_DESERIALIZE:
{
try
{
CTransaction tx(deserialize, ds);
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CBLOCKLOCATOR_DESERIALIZE:
{
try
{
CBlockLocator bl;
ds >> bl;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CBLOCKMERKLEROOT:
{
try
{
CBlock block;
ds >> block;
bool mutated;
BlockMerkleRoot(block, &mutated);
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CADDRMAN_DESERIALIZE:
{
try
{
CAddrMan am;
ds >> am;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CBLOCKHEADER_DESERIALIZE:
{
try
{
CBlockHeader bh;
ds >> bh;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CBANENTRY_DESERIALIZE:
{
try
{
CBanEntry be;
ds >> be;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CTXUNDO_DESERIALIZE:
{
try
{
CTxUndo tu;
ds >> tu;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CBLOCKUNDO_DESERIALIZE:
{
try
{
CBlockUndo bu;
ds >> bu;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CCOINS_DESERIALIZE:
{
try
{
CCoins block;
ds >> block;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CNETADDR_DESERIALIZE:
{
try
{
CNetAddr na;
ds >> na;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CSERVICE_DESERIALIZE:
{
try
{
CService s;
ds >> s;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CMESSAGEHEADER_DESERIALIZE:
{
CMessageHeader::MessageStartChars pchMessageStart = {0x00, 0x00, 0x00, 0x00};
try
{
CMessageHeader mh(pchMessageStart);
ds >> mh;
if (!mh.IsValid(pchMessageStart)) {return 0;}
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CADDRESS_DESERIALIZE:
{
try
{
CAddress a;
ds >> a;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CINV_DESERIALIZE:
{
try
{
CInv i;
ds >> i;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CBLOOMFILTER_DESERIALIZE:
{
try
{
CBloomFilter bf;
ds >> bf;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CDISKBLOCKINDEX_DESERIALIZE:
{
try
{
CDiskBlockIndex dbi;
ds >> dbi;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CTXOUTCOMPRESSOR_DESERIALIZE:
{
CTxOut to;
CTxOutCompressor toc(to);
try
{
ds >> toc;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
default:
return 0;
}
return 0;
}
static std::unique_ptr<ECCVerifyHandle> globalVerifyHandle;
void initialize() {
globalVerifyHandle = std::unique_ptr<ECCVerifyHandle>(new ECCVerifyHandle());
}
// This function is used by libFuzzer
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
test_one_input(std::vector<uint8_t>(data, data + size));
return 0;
}
// This function is used by libFuzzer
extern "C" int LLVMFuzzerInitialize(int *argc, char ***argv) {
initialize();
return 0;
}
// Disabled under WIN32 due to clash with Cygwin's WinMain.
#ifndef WIN32
// Declare main(...) "weak" to allow for libFuzzer linking. libFuzzer provides
// the main(...) function.
__attribute__((weak))
#endif
int main(int argc, char **argv)
{
initialize();
#ifdef __AFL_INIT
// Enable AFL deferred forkserver mode. Requires compilation using
// afl-clang-fast++. See fuzzing.md for details.
__AFL_INIT();
#endif
#ifdef __AFL_LOOP
// Enable AFL persistent mode. Requires compilation using afl-clang-fast++.
// See fuzzing.md for details.
int ret = 0;
while (__AFL_LOOP(1000)) {
std::vector<uint8_t> buffer;
if (!read_stdin(buffer)) {
continue;
}
ret = test_one_input(buffer);
}
return ret;
#else
std::vector<uint8_t> buffer;
if (!read_stdin(buffer)) {
return 0;
}
return test_one_input(buffer);
#endif
}
|
Add libFuzzer support.
|
[tests] Add libFuzzer support.
See http://llvm.org/docs/LibFuzzer.html#fuzzer-usage for usage instructions.
|
C++
|
mit
|
chaincoin/chaincoin,chaincoin/chaincoin,chaincoin/chaincoin,chaincoin/chaincoin,chaincoin/chaincoin,chaincoin/chaincoin
|
38125a0edb0013b91480d6b4ff72a90b7cb7d32b
|
test/socket_test.cc
|
test/socket_test.cc
|
// Copyright 2012 M-Lab. 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.
#if defined(OS_LINUX) || defined(OS_MACOSX) || defined(OS_FREEBSD)
#include <arpa/inet.h>
#elif defined(OS_WINDOWS)
#else
#error Undefined platform.
#endif
#include <errno.h>
#include <pthread.h>
#include <semaphore.h>
#include <stdlib.h>
#if defined(OS_WINDOWS)
#include <winsock2.h>
#endif
#include "gtest/gtest.h"
#include "log.h"
#include "mlab/accepted_socket.h"
#include "mlab/client_socket.h"
#include "mlab/host.h"
#include "mlab/listen_socket.h"
#include "scoped_ptr.h"
namespace mlab {
namespace {
const char message_str[] = "hello";
// TODO: Test multiple connections to one server socket.
class SocketTestBase : public ::testing::Test {
protected:
static const Packet message;
static const int port;
SocketTestBase() {
// Start up server thread.
pthread_t server_thread_id;
sem_init(&server_ready_, 0, 0);
pthread_create(&server_thread_id, 0, &ServerThread, this);
pthread_detach(server_thread_id);
}
virtual ~SocketTestBase() { }
virtual void SetUp() {
// Wait for server to be listening.
sem_wait(&server_ready_);
}
virtual void Server() = 0;
sem_t server_ready_;
private:
static void* ServerThread(void* that) {
SocketTestBase* self = static_cast<SocketTestBase*>(that);
self->Server();
return NULL;
}
};
// static
const Packet SocketTestBase::message((std::string(message_str)));
// static
const int SocketTestBase::port = 5000;
template<SocketType T, SocketFamily F>
struct TypeFamilyPair {
static const SocketType type = T;
static const SocketFamily family = F;
static std::string ToString() {
std::string str;
switch (type) {
case SOCKETTYPE_TCP: str += "TCP"; break;
case SOCKETTYPE_UDP: str += "UDP"; break;
default: ASSERT(false); break;
};
str += "|";
switch (family) {
case SOCKETFAMILY_IPV4: str += "IPv4"; break;
case SOCKETFAMILY_IPV6: str += "IPv6"; break;
default: ASSERT(false); break;
};
return str;
}
};
template<typename T>
class SocketTest : public SocketTestBase {
protected:
static const mlab::Host localhost;
SocketTest() : SocketTestBase() {
ASSERT(T::family == SOCKETFAMILY_IPV4 || T::family == SOCKETFAMILY_IPV6);
}
virtual ~SocketTest() { }
virtual void Server() {
LOG(INFO, ">> Starting server...");
mlab::scoped_ptr<mlab::ListenSocket> listen_socket(
mlab::ListenSocket::CreateOrDie(port, T::type, T::family));
LOG(INFO, ">> Bound...");
sem_post(&server_ready_);
listen_socket->SelectWithTimeout(5);
LOG(INFO, ">> Selected!");
mlab::scoped_ptr<mlab::AcceptedSocket> accepted_socket(
listen_socket->AcceptOrDie());
LOG(INFO, ">> Accepted!");
// set get recv buffer size
accepted_socket->SetRecvBufferSize(900000);
EXPECT_GE(accepted_socket->GetRecvBufferSize(), 900000U);
Packet recv_str = accepted_socket->ReceiveOrDie(message.length());
ASSERT_GT(recv_str.length(), 0U);
LOG(INFO, ">> Received %s", recv_str.buffer());
LOG(INFO, ">> Sending %s", recv_str.buffer());
ssize_t num_send_bytes = accepted_socket->SendOrDie(recv_str);
ASSERT_GT(num_send_bytes, 0);
EXPECT_EQ(recv_str.length(), static_cast<size_t>(num_send_bytes));
}
void SendAndReceive() {
// Send a message.
const mlab::Host& host = localhost;
LOG(INFO, "<< Connecting %s %d", host.original_hostname.c_str(), port);
mlab::scoped_ptr<mlab::ClientSocket> client_socket(
mlab::ClientSocket::CreateOrDie(host, port, T::type, T::family));
// set get send buffer size
client_socket->SetSendBufferSize(900000);
EXPECT_GE(client_socket->GetSendBufferSize(), 900000U);
LOG(INFO, "<< Sending %s", message_str);
EXPECT_EQ(message.length(),
static_cast<size_t>(client_socket->SendOrDie(message)));
// Recv it back.
size_t bytecount = message.length();
LOG(INFO, "<< Receiving %zu bytes.", bytecount);
Packet buffer = client_socket->ReceiveOrDie(bytecount);
LOG(INFO, "<< Received %s", buffer.buffer());
EXPECT_STREQ(message_str, buffer.buffer());
}
};
typedef TypeFamilyPair<SOCKETTYPE_TCP, SOCKETFAMILY_IPV4> TCPIPv4;
typedef TypeFamilyPair<SOCKETTYPE_UDP, SOCKETFAMILY_IPV4> UDPIPv4;
typedef TypeFamilyPair<SOCKETTYPE_TCP, SOCKETFAMILY_IPV6> TCPIPv6;
typedef TypeFamilyPair<SOCKETTYPE_UDP, SOCKETFAMILY_IPV6> UDPIPv6;
// static
template<>
const mlab::Host SocketTest<TCPIPv4>::localhost("127.0.0.1");
// static
template<>
const mlab::Host SocketTest<UDPIPv4>::localhost("127.0.0.1");
// static
template<>
const mlab::Host SocketTest<TCPIPv6>::localhost("::1");
// static
template<>
const mlab::Host SocketTest<UDPIPv6>::localhost("::1");
} // namespace
typedef ::testing::Types<TCPIPv4, UDPIPv4, TCPIPv6, UDPIPv6> TestParameters;
TYPED_TEST_CASE(SocketTest, TestParameters);
TYPED_TEST(SocketTest, SendAndReceive) {
this->SendAndReceive();
}
} // namespace mlab
|
// Copyright 2012 M-Lab. 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.
#if defined(OS_LINUX) || defined(OS_MACOSX) || defined(OS_FREEBSD)
#include <arpa/inet.h>
#elif defined(OS_WINDOWS)
#else
#error Undefined platform.
#endif
#include <errno.h>
#include <pthread.h>
#include <semaphore.h>
#include <stdlib.h>
#if defined(OS_WINDOWS)
#include <winsock2.h>
#endif
#include "gtest/gtest.h"
#include "log.h"
#include "mlab/accepted_socket.h"
#include "mlab/client_socket.h"
#include "mlab/host.h"
#include "mlab/listen_socket.h"
#include "scoped_ptr.h"
namespace mlab {
namespace {
const char message_str[] = "hello";
// TODO: Test multiple connections to one server socket.
class SocketTestBase : public ::testing::Test {
protected:
static const Packet message;
static const int port;
SocketTestBase() {
// Start up server thread.
pthread_t server_thread_id;
sem_init(&server_ready_, 0, 0);
pthread_create(&server_thread_id, 0, &ServerThread, this);
pthread_detach(server_thread_id);
}
virtual ~SocketTestBase() { }
virtual void SetUp() {
// Wait for server to be listening.
sem_wait(&server_ready_);
}
virtual void Server() = 0;
sem_t server_ready_;
private:
static void* ServerThread(void* that) {
SocketTestBase* self = static_cast<SocketTestBase*>(that);
self->Server();
return NULL;
}
};
// static
const Packet SocketTestBase::message((std::string(message_str)));
// static
const int SocketTestBase::port = 5000;
template<SocketType T, SocketFamily F>
struct TypeFamilyPair {
static const SocketType type = T;
static const SocketFamily family = F;
static std::string ToString() {
std::string str;
switch (type) {
case SOCKETTYPE_TCP: str += "TCP"; break;
case SOCKETTYPE_UDP: str += "UDP"; break;
default: ASSERT(false); break;
};
str += "|";
switch (family) {
case SOCKETFAMILY_IPV4: str += "IPv4"; break;
case SOCKETFAMILY_IPV6: str += "IPv6"; break;
default: ASSERT(false); break;
};
return str;
}
};
template<typename T>
class SocketTest : public SocketTestBase {
protected:
static const mlab::Host localhost;
SocketTest() : SocketTestBase() {
ASSERT(T::family == SOCKETFAMILY_IPV4 || T::family == SOCKETFAMILY_IPV6);
}
virtual ~SocketTest() { }
virtual void Server() {
LOG(INFO, ">> Starting server...");
mlab::scoped_ptr<mlab::ListenSocket> listen_socket(
mlab::ListenSocket::CreateOrDie(port, T::type, T::family));
LOG(INFO, ">> Bound...");
sem_post(&server_ready_);
listen_socket->SelectWithTimeout(5);
LOG(INFO, ">> Selected!");
mlab::scoped_ptr<mlab::AcceptedSocket> accepted_socket(
listen_socket->AcceptOrDie());
LOG(INFO, ">> Accepted!");
Packet recv_str = accepted_socket->ReceiveOrDie(message.length());
ASSERT_GT(recv_str.length(), 0U);
LOG(INFO, ">> Received %s", recv_str.str().c_str());
LOG(INFO, ">> Sending %s", recv_str.str().c_str());
ssize_t num_send_bytes = accepted_socket->SendOrDie(recv_str);
ASSERT_GT(num_send_bytes, 0);
EXPECT_EQ(recv_str.length(), static_cast<size_t>(num_send_bytes));
}
void SendAndReceive() {
// Send a message.
const mlab::Host& host = localhost;
LOG(INFO, "<< Connecting %s %d", host.original_hostname.c_str(), port);
mlab::scoped_ptr<mlab::ClientSocket> client_socket(
mlab::ClientSocket::CreateOrDie(host, port, T::type, T::family));
LOG(INFO, "<< Sending %s", message_str);
EXPECT_EQ(message.length(),
static_cast<size_t>(client_socket->SendOrDie(message)));
// Recv it back.
size_t bytecount = message.length();
LOG(INFO, "<< Receiving %zu bytes.", bytecount);
Packet buffer = client_socket->ReceiveOrDie(bytecount);
LOG(INFO, "<< Received %s", buffer.buffer());
EXPECT_STREQ(message_str, buffer.str().c_str());
}
};
typedef TypeFamilyPair<SOCKETTYPE_TCP, SOCKETFAMILY_IPV4> TCPIPv4;
typedef TypeFamilyPair<SOCKETTYPE_UDP, SOCKETFAMILY_IPV4> UDPIPv4;
typedef TypeFamilyPair<SOCKETTYPE_TCP, SOCKETFAMILY_IPV6> TCPIPv6;
typedef TypeFamilyPair<SOCKETTYPE_UDP, SOCKETFAMILY_IPV6> UDPIPv6;
// static
template<>
const mlab::Host SocketTest<TCPIPv4>::localhost("127.0.0.1");
// static
template<>
const mlab::Host SocketTest<UDPIPv4>::localhost("127.0.0.1");
// static
template<>
const mlab::Host SocketTest<TCPIPv6>::localhost("::1");
// static
template<>
const mlab::Host SocketTest<UDPIPv6>::localhost("::1");
} // namespace
typedef ::testing::Types<TCPIPv4, UDPIPv4, TCPIPv6, UDPIPv6> TestParameters;
TYPED_TEST_CASE(SocketTest, TestParameters);
TYPED_TEST(SocketTest, SendAndReceive) {
this->SendAndReceive();
}
TEST(SocketTest, BufferSize) {
mlab::scoped_ptr<mlab::ListenSocket> listen_socket(
mlab::ListenSocket::CreateOrDie(1234, SOCKETTYPE_TCP, SOCKETFAMILY_IPV4));
listen_socket->SetSendBufferSize(900000U);
EXPECT_GE(listen_socket->GetSendBufferSize(), 900000U);
listen_socket->SetRecvBufferSize(600000U);
EXPECT_GE(listen_socket->GetRecvBufferSize(), 600000U);
}
} // namespace mlab
|
Fix expectations and split out buffer size tests
|
Fix expectations and split out buffer size tests
|
C++
|
apache-2.0
|
m-lab/libraries,m-lab/libraries,m-lab/libraries,m-lab/libraries,m-lab/libraries
|
743fb629d7a25b63ce530de6583d389c5ec2ea70
|
src/vw/Plate/SnapshotManager.cc
|
src/vw/Plate/SnapshotManager.cc
|
// __BEGIN_LICENSE__
// Copyright (C) 2006-2011 United States Government as represented by
// the Administrator of the National Aeronautics and Space Administration.
// All Rights Reserved.
// __END_LICENSE__
#include <vw/Plate/SnapshotManager.h>
#include <vw/Plate/PlateFile.h>
#include <vw/Plate/TileManipulation.h>
#include <vw/Mosaic/ImageComposite.h>
#include <vw/Image/ImageView.h>
#include <boost/foreach.hpp>
#include <set>
namespace vw {
namespace platefile {
typedef std::map<uint32, TileHeader> tilemap_t;
// ----------------------- WeightedAvg blending -------------------------------
// Performs alpha blending with un-premultiplied alpha
template <class PixelT>
struct WeightedAvgBlendFunctor : ReturnFixedType<PixelT> {
inline PixelT operator()( PixelT const& pixel_a, PixelT const& pixel_b ) const {
typedef typename PixelChannelType<PixelT>::type channel_type;
// Extract the alpha channels
channel_type weight_a = alpha_channel(pixel_a);
channel_type weight_b = alpha_channel(pixel_b);
// Compute the new pixel values
// PixelT result = pixel_a * weight_a + pixel_b * weight_b * (1-weight_a); // For debugging: alpha blending
PixelT result = pixel_a * weight_a + pixel_b * (1-weight_a);
// This check in necessary to make sure that NaNs and Inf, -Inf
// don't slip through the cracks. This can happen sometimes
// when you mask out bad values, but leave the NaNs in the
// grayscale channel of the image. The NaN will propagate
// through the computation regardless of whether they are
// "masked out", and appear in the output DEM. This prevents
// this from ever happening!
if (result[0] != result[0]) {
return PixelT();
}
// Compute the new weight value as the max of the individual weight values.
// result.a() = weight_a + weight_b * (1-weight_a); // For debugging: alpha blending
result.a() = std::max(weight_a, weight_b);
// This check ensures that the data value in the snapshot is
// zero if the alpha value is zero.
if (result.a() == 0)
return PixelT();
return result;
}
};
/// Create a new view which is the alpha blended version of two
/// image views. Image A ends up on top of image B.
template <class ImageT>
inline BinaryPerPixelView<ImageT, ImageT, WeightedAvgBlendFunctor<typename ImageT::pixel_type> > weighted_avg_blend( ImageViewBase<ImageT> const& image_a, ImageViewBase<ImageT> const& image_b ) {
VW_ASSERT( image_a.impl().rows() == image_b.impl().rows() &&
image_a.impl().cols() == image_b.impl().cols(),
ArgumentErr()
<< "platefile::weighted_avg_blend() failed. Image dimensions do not match." );
return BinaryPerPixelView<ImageT,ImageT,WeightedAvgBlendFunctor<typename ImageT::pixel_type> >( image_a.impl(), image_b.impl() );
}
// ----------------------- Utilities -------------------------------
bool is_leaf(boost::shared_ptr<PlateFile> platefile, TileHeader const& tile_header) {
uint32 current_col = tile_header.col();
uint32 current_row = tile_header.row();
for (uint32 new_row = current_row*2; new_row < current_row*2+2; ++new_row) {
for (uint32 new_col = current_col*2; new_col < current_col*2+2; ++new_col) {
std::list<TileHeader> tile_records =
platefile->search_by_location(new_col, new_row, tile_header.level() + 1, TransactionRange(tile_header.transaction_id()));
// If this node has child tiles, then it is not a leaf node.
if (tile_records.size() > 0)
return false;
}
}
// If not child tiles were found, then this is a leaf node.
return true;
}
namespace detail {
BBox2i move_down(const BBox2i& input, uint32 level_change) {
BBox2i output(input);
output.min() *= 1<<(level_change+1);
output.max() *= 1<<(level_change+1);
return output;
}
void collect(boost::shared_ptr<PlateFile> plate, tilemap_t& all_tiles, uint32 col, uint32 row, uint32 level, vw::BBox2i const& target_region, uint32 target_level, const TransactionRange& range)
{
std::list<TileHeader> tiles = plate->search_by_location(col, row, level, range);
// This branch is empty. nothing to find.
if (tiles.empty())
return;
// Add the current level to the list (we already verified that these are in-region)
BOOST_FOREACH(const TileHeader& t, tiles)
all_tiles.insert(std::make_pair(t.transaction_id(), t));
if (target_level == level)
return;
for (uint32 row2 = row*2; row2 < row*2+2; ++row2)
for (uint32 col2 = col*2; col2 < col*2+2; ++col2)
if (move_down(BBox2i(col2, row2, 1, 1), target_level - level).intersects(target_region))
collect(plate, all_tiles, col2, row2, level+1, target_region, target_level, range);
}
}
template <class PixelT>
int SnapshotManager<PixelT>::snapshot_helper(uint32 current_col,
uint32 current_row,
uint32 current_level,
vw::BBox2i const& target_region,
uint32 target_level,
TransactionRange read_transaction_range) const
{
tilemap_t composite_tiles;
detail::collect(m_platefile, composite_tiles, current_col, current_row, current_level, target_region, target_level, read_transaction_range);
vw_out(DebugMessage, "plate::snapshot") << "Collected tiles for snapshot: " << composite_tiles.size() << std::endl;
// If we arrive at the target level and find that we have fewer
// than two tiles to composite, then there's no actual
// compositing that needs to be done. We can safely bail on
// this tile.
if (composite_tiles.size() < 2)
return 0;
// Create a tile into which we will accumulate composited data.
ImageView<PixelT> composite_tile(m_platefile->default_tile_size(),
m_platefile->default_tile_size());
vw_out(DebugMessage, "plate::snapshot") << "Starting Compositing run...\n";
int num_composited = 0;
BOOST_REVERSE_FOREACH(const tilemap_t::value_type& tile, composite_tiles) {
const TileHeader& hdr = tile.second;
ImageView<PixelT> new_tile(m_platefile->default_tile_size(), m_platefile->default_tile_size());
// Tile access is highly localized during snapshotting, so it
// speeds things up considerably to cache them here. We check
// the cache first and then read the tile from the platefile
// if nothing is found.
if ( !(this->restore_tile(new_tile, hdr.col(), hdr.row(), hdr.level(), hdr.transaction_id())) ) {
try {
// If the tile isn't in our cache, then we take the
// performance hit and read the tile from the platefile.
m_platefile->read(new_tile, hdr.col(), hdr.row(), hdr.level(), hdr.transaction_id(), true); // exact_transaction_match
} catch (const BlobIoErr &e) {
m_platefile->error_log() << "BlobIoErr, tile[" << hdr << "]: " << e.what() << "\n";
} catch (const IOErr &e) {
m_platefile->error_log() << "IOErr, tile[" << hdr << "]: " << e.what() << "\n";
}
// Save the tile to the read cache.
this->save_tile(new_tile, hdr.col(), hdr.row(), hdr.level(), hdr.transaction_id());
}
vw_out(DebugMessage, "plate::snapshot") << "\t--> Adding tile: " << hdr << "\n";
// If this is the first tile in this location, it's already at
// the target_level, and it's opaque (which is a very common
// case), then we don't need to save it as part of the
// snapshot since its already the top tile in the snapshot.
// This optimization saves us both space and time!
if ( hdr.level() == target_level && &tile == &(*composite_tiles.rbegin()) && is_opaque(new_tile) ) {
return 0;
}
// If we are compositing a tile from a lower resolution in the
// pyramid, it needs to be supersampled and cropped before we
// can use it here.
if (hdr.level() != target_level) {
new_tile = resample_img_from_level(
new_tile, hdr.col(), hdr.row(), hdr.level(), current_col, current_row, target_level);
}
// Add the new tile UNDERNEATH the tiles we have already composited.
//
// If we are snapshotting terrain, we do this with a weighted
// average. Otherwise we use normal alpha blending.
if (m_tweak_settings_for_terrain) {
composite_tile = weighted_avg_blend(composite_tile, new_tile);
} else {
vw::mosaic::ImageComposite<PixelT> composite;
composite.insert(new_tile, 0, 0);
composite.insert(composite_tile, 0, 0);
composite.set_draft_mode( true );
composite.prepare();
composite_tile = composite;
}
++num_composited;
// Check to see if the composite tile is opaque. If it is,
// then there's no point in compositing any more tiles because
// they will end up hidden anyway.
if ( is_opaque(composite_tile) ) {
break;
}
}
if (num_composited > 0) {
// -- debug
vw_out(DebugMessage, "plate::snapshot") << "\t Compositing " << current_col << " "
<< current_row << " @ " << current_level
<< " [ " << num_composited << " ]\n";
m_platefile->write_update(composite_tile, current_col, current_row, current_level);
return 1;
} else {
return 0;
}
}
template <class PixelT>
void SnapshotManager<PixelT>::snapshot(uint32 level, BBox2i const& tile_region,
TransactionRange read_transaction_range) const {
// Subdivide the bbox into smaller workunits if necessary.
// This helps to keep operations efficient.
std::list<BBox2i> tile_workunits = bbox_tiles(tile_region, 1024, 1024);
for ( std::list<BBox2i>::iterator region_iter = tile_workunits.begin();
region_iter != tile_workunits.end(); ++region_iter) {
// Create an empty list of composite tiles and then kick off the
// recursive snapshotting process.
int num_tiles_updated = snapshot_helper(0, 0, 0, *region_iter, level, read_transaction_range);
if (num_tiles_updated > 0)
vw_out() << "\t--> Snapshot " << *region_iter << " @ level " << level
<< " (" << num_tiles_updated << " tiles updated).\n";
}
}
// Create a full snapshot of every level and every region in the mosaic.
template <class PixelT>
void SnapshotManager<PixelT>::full_snapshot(TransactionRange read_transaction_range) const {
for (uint32 level = 0; level < m_platefile->num_levels(); ++level) {
// For debugging:
// for (int level = 0; level < 10; ++level) {
// Snapshot the entire region at each level. These region will be
// broken down into smaller work units in snapshot().
uint32 region_size = 1 << level;
uint32 subdivided_region_size = region_size / 16;
if (subdivided_region_size < 1024) subdivided_region_size = 1024;
BBox2i full_region(0,0,region_size,region_size);
std::list<BBox2i> workunits = bbox_tiles(full_region,
subdivided_region_size,
subdivided_region_size);
for ( std::list<BBox2i>::iterator region_iter = workunits.begin();
region_iter != workunits.end(); ++region_iter) {
snapshot(level, *region_iter, read_transaction_range);
}
}
}
}} // namespace vw::platefile
// Explicit template instatiation
#define _VW_INSTANTIATE(Px)\
template\
void vw::platefile::SnapshotManager<Px >::snapshot(uint32 level, BBox2i const& bbox, TransactionRange) const;\
template\
void vw::platefile::SnapshotManager<Px >::full_snapshot(TransactionRange) const;
_VW_INSTANTIATE(vw::PixelGrayA<vw::uint8>);
_VW_INSTANTIATE(vw::PixelGrayA<vw::int16>);
_VW_INSTANTIATE(vw::PixelGrayA<vw::float32>);
_VW_INSTANTIATE(vw::PixelRGBA<vw::uint8>);
|
// __BEGIN_LICENSE__
// Copyright (C) 2006-2011 United States Government as represented by
// the Administrator of the National Aeronautics and Space Administration.
// All Rights Reserved.
// __END_LICENSE__
#include <vw/Plate/SnapshotManager.h>
#include <vw/Plate/PlateFile.h>
#include <vw/Plate/TileManipulation.h>
#include <vw/Mosaic/ImageComposite.h>
#include <vw/Image/ImageView.h>
#include <boost/foreach.hpp>
#include <set>
namespace vw {
namespace platefile {
typedef std::map<uint32, TileHeader> tilemap_t;
// ----------------------- WeightedAvg blending -------------------------------
// Performs alpha blending with un-premultiplied alpha
template <class PixelT>
struct WeightedAvgBlendFunctor : ReturnFixedType<PixelT> {
inline PixelT operator()( PixelT const& pixel_a, PixelT const& pixel_b ) const {
typedef typename PixelChannelType<PixelT>::type channel_type;
// Extract the alpha channels
channel_type weight_a = alpha_channel(pixel_a);
channel_type weight_b = alpha_channel(pixel_b);
// Compute the new pixel values
// PixelT result = pixel_a * weight_a + pixel_b * weight_b * (1-weight_a); // For debugging: alpha blending
PixelT result = pixel_a * weight_a + pixel_b * (1-weight_a);
// This check in necessary to make sure that NaNs and Inf, -Inf
// don't slip through the cracks. This can happen sometimes
// when you mask out bad values, but leave the NaNs in the
// grayscale channel of the image. The NaN will propagate
// through the computation regardless of whether they are
// "masked out", and appear in the output DEM. This prevents
// this from ever happening!
if (result[0] != result[0]) {
return PixelT();
}
// Compute the new weight value as the max of the individual weight values.
// result.a() = weight_a + weight_b * (1-weight_a); // For debugging: alpha blending
result.a() = std::max(weight_a, weight_b);
// This check ensures that the data value in the snapshot is
// zero if the alpha value is zero.
if (result.a() == 0)
return PixelT();
return result;
}
};
/// Create a new view which is the alpha blended version of two
/// image views. Image A ends up on top of image B.
template <class ImageT>
inline BinaryPerPixelView<ImageT, ImageT, WeightedAvgBlendFunctor<typename ImageT::pixel_type> > weighted_avg_blend( ImageViewBase<ImageT> const& image_a, ImageViewBase<ImageT> const& image_b ) {
VW_ASSERT( image_a.impl().rows() == image_b.impl().rows() &&
image_a.impl().cols() == image_b.impl().cols(),
ArgumentErr()
<< "platefile::weighted_avg_blend() failed. Image dimensions do not match." );
return BinaryPerPixelView<ImageT,ImageT,WeightedAvgBlendFunctor<typename ImageT::pixel_type> >( image_a.impl(), image_b.impl() );
}
// ----------------------- Utilities -------------------------------
bool is_leaf(boost::shared_ptr<PlateFile> platefile, TileHeader const& tile_header) {
uint32 current_col = tile_header.col();
uint32 current_row = tile_header.row();
for (uint32 new_row = current_row*2; new_row < current_row*2+2; ++new_row) {
for (uint32 new_col = current_col*2; new_col < current_col*2+2; ++new_col) {
std::list<TileHeader> tile_records =
platefile->search_by_location(new_col, new_row, tile_header.level() + 1, TransactionRange(tile_header.transaction_id()));
// If this node has child tiles, then it is not a leaf node.
if (tile_records.size() > 0)
return false;
}
}
// If not child tiles were found, then this is a leaf node.
return true;
}
namespace detail {
BBox2i move_down(const BBox2i& input, uint32 level_change) {
return input * (1 << level_change);
}
void collect(boost::shared_ptr<PlateFile> plate, tilemap_t& all_tiles, uint32 col, uint32 row, uint32 level, vw::BBox2i const& target_region, uint32 target_level, const TransactionRange& range)
{
std::list<TileHeader> tiles = plate->search_by_location(col, row, level, range);
// This branch is empty. nothing to find.
if (tiles.empty())
return;
// Add the current level to the list (we already verified that these are in-region)
BOOST_FOREACH(const TileHeader& t, tiles)
all_tiles.insert(std::make_pair(t.transaction_id(), t));
if (target_level == level)
return;
for (uint32 row2 = row*2; row2 < row*2+2; ++row2)
for (uint32 col2 = col*2; col2 < col*2+2; ++col2)
if (move_down(BBox2i(col2, row2, 1, 1), target_level - level).intersects(target_region))
collect(plate, all_tiles, col2, row2, level+1, target_region, target_level, range);
}
}
template <class PixelT>
int SnapshotManager<PixelT>::snapshot_helper(uint32 current_col,
uint32 current_row,
uint32 current_level,
vw::BBox2i const& target_region,
uint32 target_level,
TransactionRange read_transaction_range) const
{
tilemap_t composite_tiles;
detail::collect(m_platefile, composite_tiles, current_col, current_row, current_level, target_region, target_level, read_transaction_range);
vw_out(DebugMessage, "plate::snapshot") << "Collected tiles for snapshot: " << composite_tiles.size() << std::endl;
// If we arrive at the target level and find that we have fewer
// than two tiles to composite, then there's no actual
// compositing that needs to be done. We can safely bail on
// this tile.
if (composite_tiles.size() < 2)
return 0;
// Create a tile into which we will accumulate composited data.
ImageView<PixelT> composite_tile(m_platefile->default_tile_size(),
m_platefile->default_tile_size());
vw_out(DebugMessage, "plate::snapshot") << "Starting Compositing run...\n";
int num_composited = 0;
BOOST_REVERSE_FOREACH(const tilemap_t::value_type& tile, composite_tiles) {
const TileHeader& hdr = tile.second;
ImageView<PixelT> new_tile(m_platefile->default_tile_size(), m_platefile->default_tile_size());
// Tile access is highly localized during snapshotting, so it
// speeds things up considerably to cache them here. We check
// the cache first and then read the tile from the platefile
// if nothing is found.
if ( !(this->restore_tile(new_tile, hdr.col(), hdr.row(), hdr.level(), hdr.transaction_id())) ) {
try {
// If the tile isn't in our cache, then we take the
// performance hit and read the tile from the platefile.
m_platefile->read(new_tile, hdr.col(), hdr.row(), hdr.level(), hdr.transaction_id(), true); // exact_transaction_match
} catch (const BlobIoErr &e) {
m_platefile->error_log() << "BlobIoErr, tile[" << hdr << "]: " << e.what() << "\n";
} catch (const IOErr &e) {
m_platefile->error_log() << "IOErr, tile[" << hdr << "]: " << e.what() << "\n";
}
// Save the tile to the read cache.
this->save_tile(new_tile, hdr.col(), hdr.row(), hdr.level(), hdr.transaction_id());
}
vw_out(DebugMessage, "plate::snapshot") << "\t--> Adding tile: " << hdr << "\n";
// If this is the first tile in this location, it's already at
// the target_level, and it's opaque (which is a very common
// case), then we don't need to save it as part of the
// snapshot since its already the top tile in the snapshot.
// This optimization saves us both space and time!
if ( hdr.level() == target_level && &tile == &(*composite_tiles.rbegin()) && is_opaque(new_tile) ) {
return 0;
}
// If we are compositing a tile from a lower resolution in the
// pyramid, it needs to be supersampled and cropped before we
// can use it here.
if (hdr.level() != target_level) {
new_tile = resample_img_from_level(
new_tile, hdr.col(), hdr.row(), hdr.level(), current_col, current_row, target_level);
}
// Add the new tile UNDERNEATH the tiles we have already composited.
//
// If we are snapshotting terrain, we do this with a weighted
// average. Otherwise we use normal alpha blending.
if (m_tweak_settings_for_terrain) {
composite_tile = weighted_avg_blend(composite_tile, new_tile);
} else {
vw::mosaic::ImageComposite<PixelT> composite;
composite.insert(new_tile, 0, 0);
composite.insert(composite_tile, 0, 0);
composite.set_draft_mode( true );
composite.prepare();
composite_tile = composite;
}
++num_composited;
// Check to see if the composite tile is opaque. If it is,
// then there's no point in compositing any more tiles because
// they will end up hidden anyway.
if ( is_opaque(composite_tile) ) {
break;
}
}
if (num_composited > 0) {
// -- debug
vw_out(DebugMessage, "plate::snapshot") << "\t Compositing " << current_col << " "
<< current_row << " @ " << current_level
<< " [ " << num_composited << " ]\n";
m_platefile->write_update(composite_tile, current_col, current_row, current_level);
return 1;
} else {
return 0;
}
}
template <class PixelT>
void SnapshotManager<PixelT>::snapshot(uint32 level, BBox2i const& tile_region,
TransactionRange read_transaction_range) const {
// Subdivide the bbox into smaller workunits if necessary.
// This helps to keep operations efficient.
std::list<BBox2i> tile_workunits = bbox_tiles(tile_region, 1024, 1024);
for ( std::list<BBox2i>::iterator region_iter = tile_workunits.begin();
region_iter != tile_workunits.end(); ++region_iter) {
// Create an empty list of composite tiles and then kick off the
// recursive snapshotting process.
int num_tiles_updated = snapshot_helper(0, 0, 0, *region_iter, level, read_transaction_range);
if (num_tiles_updated > 0)
vw_out() << "\t--> Snapshot " << *region_iter << " @ level " << level
<< " (" << num_tiles_updated << " tiles updated).\n";
}
}
// Create a full snapshot of every level and every region in the mosaic.
template <class PixelT>
void SnapshotManager<PixelT>::full_snapshot(TransactionRange read_transaction_range) const {
for (uint32 level = 0; level < m_platefile->num_levels(); ++level) {
// For debugging:
// for (int level = 0; level < 10; ++level) {
// Snapshot the entire region at each level. These region will be
// broken down into smaller work units in snapshot().
uint32 region_size = 1 << level;
uint32 subdivided_region_size = region_size / 16;
if (subdivided_region_size < 1024) subdivided_region_size = 1024;
BBox2i full_region(0,0,region_size,region_size);
std::list<BBox2i> workunits = bbox_tiles(full_region,
subdivided_region_size,
subdivided_region_size);
for ( std::list<BBox2i>::iterator region_iter = workunits.begin();
region_iter != workunits.end(); ++region_iter) {
snapshot(level, *region_iter, read_transaction_range);
}
}
}
}} // namespace vw::platefile
// Explicit template instatiation
#define _VW_INSTANTIATE(Px)\
template\
void vw::platefile::SnapshotManager<Px >::snapshot(uint32 level, BBox2i const& bbox, TransactionRange) const;\
template\
void vw::platefile::SnapshotManager<Px >::full_snapshot(TransactionRange) const;
_VW_INSTANTIATE(vw::PixelGrayA<vw::uint8>);
_VW_INSTANTIATE(vw::PixelGrayA<vw::int16>);
_VW_INSTANTIATE(vw::PixelGrayA<vw::float32>);
_VW_INSTANTIATE(vw::PixelRGBA<vw::uint8>);
|
fix move_down thinko (moved down too far)
|
SnapshotManager.cc: fix move_down thinko (moved down too far)
|
C++
|
apache-2.0
|
AveRapina/visionworkbench,DougFirErickson/visionworkbench,fengzhyuan/visionworkbench,fengzhyuan/visionworkbench,DougFirErickson/visionworkbench,AveRapina/visionworkbench,AveRapina/visionworkbench,fengzhyuan/visionworkbench,AveRapina/visionworkbench,fengzhyuan/visionworkbench,DougFirErickson/visionworkbench,fengzhyuan/visionworkbench,AveRapina/visionworkbench,DougFirErickson/visionworkbench,AveRapina/visionworkbench,fengzhyuan/visionworkbench,DougFirErickson/visionworkbench,DougFirErickson/visionworkbench,fengzhyuan/visionworkbench
|
9d9dab74ebec49bce88cae441cd3252c93805fea
|
src/widgets/backuptabwidget.cpp
|
src/widgets/backuptabwidget.cpp
|
#include "backuptabwidget.h"
WARNINGS_DISABLE
#include <QDateTime>
#include <QFileDialog>
#include <QSettings>
#include <QWidget>
#include "ui_backuptabwidget.h"
WARNINGS_ENABLE
#include "backuplistwidgetitem.h"
#include "persistentmodel/archive.h"
#include "utils.h"
// HACK: using _filePickerDialog(this) produces a segfault on MacOS X in
// QTabBarPrivate::updateMacBorderMetrics() with tests/mainwindow when using
// -platform offscreen. I have no idea why, but I have no leads left to
// investigate and I've spent way longer than I expected on this refactoring,
// so I'm moving on.
BackupTabWidget::BackupTabWidget(QWidget *parent)
: QWidget(parent), _ui(new Ui::BackupTabWidget), _filePickerDialog(parent)
{
// Ui initialization
_ui->setupUi(this);
_ui->backupListWidget->setAttribute(Qt::WA_MacShowFocusRect, false);
// Messages between widgets on this tab
connect(_ui->appendTimestampCheckBox, &QCheckBox::toggled, this,
&BackupTabWidget::appendTimestampCheckBoxToggled);
connect(_ui->backupListInfoLabel, &ElidedClickableLabel::clicked,
_ui->actionBrowseItems, &QAction::trigger);
connect(_ui->backupNameLineEdit, &QLineEdit::textChanged,
[&](const QString text) {
if(text.isEmpty())
_ui->appendTimestampCheckBox->setChecked(false);
validateBackupTab();
});
connect(_ui->backupListWidget, &BackupListWidget::itemWithUrlAdded,
&_filePickerDialog, &FilePickerDialog::selectUrl);
connect(_ui->backupListWidget, &BackupListWidget::itemTotals, this,
&BackupTabWidget::updateBackupItemTotals);
// Bottom-right button
_ui->backupButton->setDefaultAction(_ui->actionBackupNow);
_ui->backupButton->addAction(_ui->actionBackupMorphIntoJob);
connect(_ui->actionBackupNow, &QAction::triggered, this,
&BackupTabWidget::backupButtonClicked);
connect(_ui->actionBackupMorphIntoJob, &QAction::triggered, this,
&BackupTabWidget::backupMorphIntoJobClicked);
// Right-click context menu
_ui->backupListWidget->addAction(_ui->actionBrowseItems);
_ui->backupListWidget->addAction(_ui->actionAddFiles);
_ui->backupListWidget->addAction(_ui->actionAddDirectory);
_ui->backupListWidget->addAction(_ui->actionClearList);
// Handle the Backup-related actions
connect(_ui->actionBrowseItems, &QAction::triggered, this,
&BackupTabWidget::browseForBackupItems);
connect(_ui->actionAddFiles, &QAction::triggered, this,
&BackupTabWidget::addFiles);
connect(_ui->actionAddDirectory, &QAction::triggered, this,
&BackupTabWidget::addDirectory);
connect(_ui->actionClearList, &QAction::triggered, this,
&BackupTabWidget::clearList);
updateUi();
}
BackupTabWidget::~BackupTabWidget()
{
delete _ui;
}
void BackupTabWidget::changeEvent(QEvent *event)
{
if(event->type() == QEvent::LanguageChange)
{
_ui->retranslateUi(this);
updateUi();
}
QWidget::changeEvent(event);
}
void BackupTabWidget::updateUi()
{
_ui->backupListInfoLabel->setToolTip(
_ui->backupListInfoLabel->toolTip().arg(
_ui->actionBrowseItems->shortcut().toString(
QKeySequence::NativeText)));
_ui->backupListInfoLabel->setText(_ui->backupListInfoLabel->text().arg(
_ui->actionBrowseItems->shortcut().toString(QKeySequence::NativeText)));
}
void BackupTabWidget::validateBackupTab()
{
bool valid = true;
QString name = _ui->backupNameLineEdit->text();
// We need a name and at least one item
if(name.isEmpty() || (_ui->backupListWidget->count() == 0))
valid = false;
// Check that we don't have any leading or trailing whitespace
if(name.simplified() != name)
valid = false;
_ui->actionBackupNow->setEnabled(valid);
_ui->actionBackupMorphIntoJob->setEnabled(valid);
emit backupTabValidStatus(valid);
}
void BackupTabWidget::appendTimestampCheckBoxToggled(bool checked)
{
if(checked)
{
QString text = _ui->backupNameLineEdit->text();
_lastTimestamp.clear();
_lastTimestamp.append(
QDateTime::currentDateTime().toString(ARCHIVE_TIMESTAMP_FORMAT));
text.append(_lastTimestamp);
_ui->backupNameLineEdit->setText(text);
_ui->backupNameLineEdit->setCursorPosition(0);
}
else
{
QString text = _ui->backupNameLineEdit->text();
if(!_lastTimestamp.isEmpty() && text.endsWith(_lastTimestamp))
{
text.chop(_lastTimestamp.length());
_ui->backupNameLineEdit->setText(text);
}
}
}
void BackupTabWidget::updateBackupItemTotals(quint64 count, quint64 size)
{
if(count != 0)
{
_ui->backupDetailLabel->setText(
tr("%1 %2 (%3)")
.arg(count)
.arg(count == 1 ? tr("item") : tr("items"))
.arg(Utils::humanBytes(size)));
}
else
{
_ui->backupDetailLabel->clear();
}
validateBackupTab();
}
void BackupTabWidget::backupMorphIntoJobClicked()
{
emit morphBackupIntoJob(_ui->backupListWidget->itemUrls(),
_ui->backupNameLineEdit->text());
}
void BackupTabWidget::backupButtonClicked()
{
QList<QUrl> urls;
for(int i = 0; i < _ui->backupListWidget->count(); ++i)
urls << static_cast<BackupListWidgetItem *>(
_ui->backupListWidget->item(i))
->url();
BackupTaskPtr backup(new BackupTask);
backup->setName(_ui->backupNameLineEdit->text());
backup->setUrls(urls);
emit backupNow(backup);
_ui->appendTimestampCheckBox->setChecked(false);
}
void BackupTabWidget::browseForBackupItems()
{
_filePickerDialog.setSelectedUrls(_ui->backupListWidget->itemUrls());
if(_filePickerDialog.exec())
_ui->backupListWidget->setItemsWithUrls(
_filePickerDialog.getSelectedUrls());
}
void BackupTabWidget::addFiles()
{
QList<QUrl> urls = QFileDialog::getOpenFileUrls(
this, tr("Browse for files to add to the Backup list"));
if(urls.count())
_ui->backupListWidget->addItemsWithUrls(urls);
}
void BackupTabWidget::addDirectory()
{
QUrl url = QFileDialog::getExistingDirectoryUrl(
this, tr("Browse for directory to add to the Backup list"));
if(!url.isEmpty())
_ui->backupListWidget->addItemWithUrl(url);
}
void BackupTabWidget::clearList()
{
_ui->backupListWidget->clear();
}
|
#include "backuptabwidget.h"
WARNINGS_DISABLE
#include <QDateTime>
#include <QFileDialog>
#include <QWidget>
#include "ui_backuptabwidget.h"
WARNINGS_ENABLE
#include "backuplistwidgetitem.h"
#include "persistentmodel/archive.h"
#include "utils.h"
// HACK: using _filePickerDialog(this) produces a segfault on MacOS X in
// QTabBarPrivate::updateMacBorderMetrics() with tests/mainwindow when using
// -platform offscreen. I have no idea why, but I have no leads left to
// investigate and I've spent way longer than I expected on this refactoring,
// so I'm moving on.
BackupTabWidget::BackupTabWidget(QWidget *parent)
: QWidget(parent), _ui(new Ui::BackupTabWidget), _filePickerDialog(parent)
{
// Ui initialization
_ui->setupUi(this);
_ui->backupListWidget->setAttribute(Qt::WA_MacShowFocusRect, false);
// Messages between widgets on this tab
connect(_ui->appendTimestampCheckBox, &QCheckBox::toggled, this,
&BackupTabWidget::appendTimestampCheckBoxToggled);
connect(_ui->backupListInfoLabel, &ElidedClickableLabel::clicked,
_ui->actionBrowseItems, &QAction::trigger);
connect(_ui->backupNameLineEdit, &QLineEdit::textChanged,
[&](const QString text) {
if(text.isEmpty())
_ui->appendTimestampCheckBox->setChecked(false);
validateBackupTab();
});
connect(_ui->backupListWidget, &BackupListWidget::itemWithUrlAdded,
&_filePickerDialog, &FilePickerDialog::selectUrl);
connect(_ui->backupListWidget, &BackupListWidget::itemTotals, this,
&BackupTabWidget::updateBackupItemTotals);
// Bottom-right button
_ui->backupButton->setDefaultAction(_ui->actionBackupNow);
_ui->backupButton->addAction(_ui->actionBackupMorphIntoJob);
connect(_ui->actionBackupNow, &QAction::triggered, this,
&BackupTabWidget::backupButtonClicked);
connect(_ui->actionBackupMorphIntoJob, &QAction::triggered, this,
&BackupTabWidget::backupMorphIntoJobClicked);
// Right-click context menu
_ui->backupListWidget->addAction(_ui->actionBrowseItems);
_ui->backupListWidget->addAction(_ui->actionAddFiles);
_ui->backupListWidget->addAction(_ui->actionAddDirectory);
_ui->backupListWidget->addAction(_ui->actionClearList);
// Handle the Backup-related actions
connect(_ui->actionBrowseItems, &QAction::triggered, this,
&BackupTabWidget::browseForBackupItems);
connect(_ui->actionAddFiles, &QAction::triggered, this,
&BackupTabWidget::addFiles);
connect(_ui->actionAddDirectory, &QAction::triggered, this,
&BackupTabWidget::addDirectory);
connect(_ui->actionClearList, &QAction::triggered, this,
&BackupTabWidget::clearList);
updateUi();
}
BackupTabWidget::~BackupTabWidget()
{
delete _ui;
}
void BackupTabWidget::changeEvent(QEvent *event)
{
if(event->type() == QEvent::LanguageChange)
{
_ui->retranslateUi(this);
updateUi();
}
QWidget::changeEvent(event);
}
void BackupTabWidget::updateUi()
{
_ui->backupListInfoLabel->setToolTip(
_ui->backupListInfoLabel->toolTip().arg(
_ui->actionBrowseItems->shortcut().toString(
QKeySequence::NativeText)));
_ui->backupListInfoLabel->setText(_ui->backupListInfoLabel->text().arg(
_ui->actionBrowseItems->shortcut().toString(QKeySequence::NativeText)));
}
void BackupTabWidget::validateBackupTab()
{
bool valid = true;
QString name = _ui->backupNameLineEdit->text();
// We need a name and at least one item
if(name.isEmpty() || (_ui->backupListWidget->count() == 0))
valid = false;
// Check that we don't have any leading or trailing whitespace
if(name.simplified() != name)
valid = false;
_ui->actionBackupNow->setEnabled(valid);
_ui->actionBackupMorphIntoJob->setEnabled(valid);
emit backupTabValidStatus(valid);
}
void BackupTabWidget::appendTimestampCheckBoxToggled(bool checked)
{
if(checked)
{
QString text = _ui->backupNameLineEdit->text();
_lastTimestamp.clear();
_lastTimestamp.append(
QDateTime::currentDateTime().toString(ARCHIVE_TIMESTAMP_FORMAT));
text.append(_lastTimestamp);
_ui->backupNameLineEdit->setText(text);
_ui->backupNameLineEdit->setCursorPosition(0);
}
else
{
QString text = _ui->backupNameLineEdit->text();
if(!_lastTimestamp.isEmpty() && text.endsWith(_lastTimestamp))
{
text.chop(_lastTimestamp.length());
_ui->backupNameLineEdit->setText(text);
}
}
}
void BackupTabWidget::updateBackupItemTotals(quint64 count, quint64 size)
{
if(count != 0)
{
_ui->backupDetailLabel->setText(
tr("%1 %2 (%3)")
.arg(count)
.arg(count == 1 ? tr("item") : tr("items"))
.arg(Utils::humanBytes(size)));
}
else
{
_ui->backupDetailLabel->clear();
}
validateBackupTab();
}
void BackupTabWidget::backupMorphIntoJobClicked()
{
emit morphBackupIntoJob(_ui->backupListWidget->itemUrls(),
_ui->backupNameLineEdit->text());
}
void BackupTabWidget::backupButtonClicked()
{
QList<QUrl> urls;
for(int i = 0; i < _ui->backupListWidget->count(); ++i)
urls << static_cast<BackupListWidgetItem *>(
_ui->backupListWidget->item(i))
->url();
BackupTaskPtr backup(new BackupTask);
backup->setName(_ui->backupNameLineEdit->text());
backup->setUrls(urls);
emit backupNow(backup);
_ui->appendTimestampCheckBox->setChecked(false);
}
void BackupTabWidget::browseForBackupItems()
{
_filePickerDialog.setSelectedUrls(_ui->backupListWidget->itemUrls());
if(_filePickerDialog.exec())
_ui->backupListWidget->setItemsWithUrls(
_filePickerDialog.getSelectedUrls());
}
void BackupTabWidget::addFiles()
{
QList<QUrl> urls = QFileDialog::getOpenFileUrls(
this, tr("Browse for files to add to the Backup list"));
if(urls.count())
_ui->backupListWidget->addItemsWithUrls(urls);
}
void BackupTabWidget::addDirectory()
{
QUrl url = QFileDialog::getExistingDirectoryUrl(
this, tr("Browse for directory to add to the Backup list"));
if(!url.isEmpty())
_ui->backupListWidget->addItemWithUrl(url);
}
void BackupTabWidget::clearList()
{
_ui->backupListWidget->clear();
}
|
remove extra <QSettings>
|
BackTabWidget: remove extra <QSettings>
|
C++
|
bsd-2-clause
|
Tarsnap/tarsnap-gui,Tarsnap/tarsnap-gui,Tarsnap/tarsnap-gui,Tarsnap/tarsnap-gui,Tarsnap/tarsnap-gui
|
0272dc03114f2d76b62ea40cd0d487516f47d48d
|
src/CodeGen_Posix.cpp
|
src/CodeGen_Posix.cpp
|
#include <iostream>
#include "CodeGen_Posix.h"
#include "CodeGen_Internal.h"
#include "LLVM_Headers.h"
#include "IR.h"
#include "IROperator.h"
#include "Debug.h"
#include "IRPrinter.h"
#include "Simplify.h"
#include "CSE.h"
namespace Halide {
namespace Internal {
using std::vector;
using std::string;
using std::map;
using std::pair;
using std::make_pair;
using namespace llvm;
CodeGen_Posix::CodeGen_Posix(Target t) :
CodeGen_LLVM(t) {
}
Value *CodeGen_Posix::codegen_allocation_size(const std::string &name, Type type, const std::vector<Expr> &extents) {
// Compute size from list of extents checking for overflow.
Expr overflow = make_zero(UInt(64));
Expr total_size = make_const(UInt(64), type.lanes() * type.bytes());
// We'll multiply all the extents into the 64-bit value
// total_size. We'll also track (total_size >> 32) as a 64-bit
// value to check for overflow as we go. The loop invariant will
// be that either the overflow Expr is non-zero, or total_size_hi
// only occupies the bottom 32-bits. Overflow could be more simply
// checked for using division, but that's slower at runtime. This
// method generates much better assembly.
Expr total_size_hi = make_zero(UInt(64));
Expr low_mask = make_const(UInt(64), (uint64_t)(0xffffffff));
for (size_t i = 0; i < extents.size(); i++) {
Expr next_extent = cast(UInt(32), extents[i]);
// Update total_size >> 32. This math can't overflow due to
// the loop invariant:
total_size_hi *= next_extent;
// Deal with carry from the low bits. Still can't overflow.
total_size_hi += ((total_size & low_mask) * next_extent) >> 32;
// Update total_size. This may overflow.
total_size *= next_extent;
// We can check for overflow by asserting that total_size_hi
// is still a 32-bit number.
overflow = overflow | (total_size_hi >> 32);
}
Expr max_size = make_const(UInt(64), target.maximum_buffer_size());
Expr size_check = (overflow == 0) && (total_size <= max_size);
// For constant-sized allocations this check should simplify away.
size_check = common_subexpression_elimination(simplify(size_check));
if (!is_one(size_check)) {
create_assertion(codegen(size_check),
Call::make(Int(32), "halide_error_buffer_allocation_too_large",
{name, total_size, max_size}, Call::Extern));
}
total_size = simplify(total_size);
return codegen(total_size);
}
int CodeGen_Posix::allocation_padding(Type type) const {
// We potentially load one scalar value past the end of the
// buffer, so pad the allocation with an extra instance of the
// scalar type.
return type.bytes();
}
CodeGen_Posix::Allocation CodeGen_Posix::create_allocation(const std::string &name, Type type,
const std::vector<Expr> &extents, Expr condition,
Expr new_expr, std::string free_function) {
Value *llvm_size = nullptr;
int64_t stack_bytes = 0;
int32_t constant_bytes = Allocate::constant_allocation_size(extents, name);
if (constant_bytes > 0) {
constant_bytes *= type.bytes();
stack_bytes = constant_bytes;
if (stack_bytes > target.maximum_buffer_size()) {
const string str_max_size = target.has_feature(Target::LargeBuffers) ? "2^63 - 1" : "2^31 - 1";
user_error << "Total size for allocation " << name << " is constant but exceeds " << str_max_size << ".";
} else if (!can_allocation_fit_on_stack(stack_bytes)) {
stack_bytes = 0;
llvm_size = codegen(Expr(constant_bytes));
}
} else {
llvm_size = codegen_allocation_size(name, type, extents);
}
// Only allocate memory if the condition is true, otherwise 0.
Value *llvm_condition = codegen(condition);
if (llvm_size != nullptr) {
// Add the requested padding to the allocation size. If the
// allocation is on the stack, we can just read past the top
// of the stack, so we only need this for heap allocations.
Value *padding = ConstantInt::get(llvm_size->getType(), allocation_padding(type));
llvm_size = builder->CreateAdd(llvm_size, padding);
llvm_size = builder->CreateSelect(llvm_condition,
llvm_size,
ConstantInt::get(llvm_size->getType(), 0));
}
Allocation allocation;
allocation.constant_bytes = constant_bytes;
allocation.stack_bytes = new_expr.defined() ? 0 : stack_bytes;
allocation.type = type;
allocation.ptr = nullptr;
allocation.destructor = nullptr;
allocation.destructor_function = nullptr;
allocation.name = name;
if (!new_expr.defined() && extents.empty()) {
// If it's a scalar allocation, don't try anything clever. We
// want llvm to be able to promote it to a register.
allocation.ptr = create_alloca_at_entry(llvm_type_of(type), 1, false, name);
allocation.stack_bytes = stack_bytes;
} else if (!new_expr.defined() && stack_bytes != 0) {
// Try to find a free stack allocation we can use.
vector<Allocation>::iterator free = free_stack_allocs.end();
for (free = free_stack_allocs.begin(); free != free_stack_allocs.end(); ++free) {
AllocaInst *alloca_inst = dyn_cast<AllocaInst>(free->ptr);
llvm::Function *allocated_in = alloca_inst ? alloca_inst->getParent()->getParent() : nullptr;
llvm::Function *current_func = builder->GetInsertBlock()->getParent();
if (allocated_in == current_func &&
free->type == type &&
free->stack_bytes >= stack_bytes) {
break;
}
}
if (free != free_stack_allocs.end()) {
debug(4) << "Reusing freed stack allocation of " << free->stack_bytes
<< " bytes for allocation " << name
<< " of " << stack_bytes << " bytes.\n";
// Use a free alloc we found.
allocation.ptr = free->ptr;
allocation.stack_bytes = free->stack_bytes;
allocation.name = free->name;
// This allocation isn't free anymore.
free_stack_allocs.erase(free);
} else {
debug(4) << "Allocating " << stack_bytes << " bytes on the stack for " << name << "\n";
// We used to do the alloca locally and save and restore the
// stack pointer, but this makes llvm generate streams of
// spill/reloads.
int64_t stack_size = (stack_bytes + type.bytes() - 1) / type.bytes();
// Handles are stored as uint64s
llvm::Type *t =
llvm_type_of(type.is_handle() ? UInt(64, type.lanes()) : type);
allocation.ptr = create_alloca_at_entry(t, stack_size, false, name);
allocation.stack_bytes = stack_bytes;
}
cur_stack_alloc_total += allocation.stack_bytes;
debug(4) << "cur_stack_alloc_total += " << allocation.stack_bytes << " -> " << cur_stack_alloc_total << " for " << name << "\n";
} else {
if (new_expr.defined()) {
allocation.ptr = codegen(new_expr);
} else {
// call malloc
llvm::Function *malloc_fn = module->getFunction("halide_malloc");
internal_assert(malloc_fn) << "Could not find halide_malloc in module\n";
malloc_fn->setDoesNotAlias(0);
llvm::Function::arg_iterator arg_iter = malloc_fn->arg_begin();
++arg_iter; // skip the user context *
llvm_size = builder->CreateIntCast(llvm_size, arg_iter->getType(), false);
debug(4) << "Creating call to halide_malloc for allocation " << name
<< " of size " << type.bytes();
for (Expr e : extents) {
debug(4) << " x " << e;
}
debug(4) << "\n";
Value *args[2] = { get_user_context(), llvm_size };
Value *call = builder->CreateCall(malloc_fn, args);
// Fix the type to avoid pointless bitcasts later
call = builder->CreatePointerCast(call, llvm_type_of(type)->getPointerTo());
allocation.ptr = call;
}
// Assert that the allocation worked.
Value *check = builder->CreateIsNotNull(allocation.ptr);
if (llvm_size) {
Value *zero_size = builder->CreateIsNull(llvm_size);
check = builder->CreateOr(check, zero_size);
}
if (!is_one(condition)) {
// If the condition is false, it's OK for the new_expr to be null.
Value *condition_is_false = builder->CreateIsNull(llvm_condition);
check = builder->CreateOr(check, condition_is_false);
}
create_assertion(check, Call::make(Int(32), "halide_error_out_of_memory",
std::vector<Expr>(), Call::Extern));
// Register a destructor for this allocation.
if (free_function.empty()) {
free_function = "halide_free";
}
llvm::Function *free_fn = module->getFunction(free_function);
internal_assert(free_fn) << "Could not find " << free_function << " in module.\n";
allocation.destructor = register_destructor(free_fn, allocation.ptr, OnError);
allocation.destructor_function = free_fn;
}
// Push the allocation base pointer onto the symbol table
debug(3) << "Pushing allocation called " << name << ".host onto the symbol table\n";
allocations.push(name, allocation);
return allocation;
}
void CodeGen_Posix::free_allocation(const std::string &name) {
Allocation alloc = allocations.get(name);
if (alloc.stack_bytes) {
// Remember this allocation so it can be re-used by a later allocation.
free_stack_allocs.push_back(alloc);
cur_stack_alloc_total -= alloc.stack_bytes;
debug(4) << "cur_stack_alloc_total += " << alloc.stack_bytes << " -> " << cur_stack_alloc_total << " for " << name << "\n";
} else {
internal_assert(alloc.destructor);
trigger_destructor(alloc.destructor_function, alloc.destructor);
}
allocations.pop(name);
sym_pop(name + ".host");
}
string CodeGen_Posix::get_allocation_name(const std::string &n) {
if (allocations.contains(n)) {
return allocations.get(n).name;
} else {
return n;
}
}
void CodeGen_Posix::visit(const Allocate *alloc) {
if (sym_exists(alloc->name + ".host")) {
user_error << "Can't have two different buffers with the same name: "
<< alloc->name << "\n";
}
Allocation allocation = create_allocation(alloc->name, alloc->type,
alloc->extents, alloc->condition,
alloc->new_expr, alloc->free_function);
sym_push(alloc->name + ".host", allocation.ptr);
codegen(alloc->body);
// If there was no early free, free it now.
if (allocations.contains(alloc->name)) {
free_allocation(alloc->name);
}
}
void CodeGen_Posix::visit(const Free *stmt) {
free_allocation(stmt->name);
}
}}
|
#include <iostream>
#include "CodeGen_Posix.h"
#include "CodeGen_Internal.h"
#include "LLVM_Headers.h"
#include "IR.h"
#include "IROperator.h"
#include "Debug.h"
#include "IRPrinter.h"
#include "Simplify.h"
#include "CSE.h"
namespace Halide {
namespace Internal {
using std::vector;
using std::string;
using std::map;
using std::pair;
using std::make_pair;
using namespace llvm;
CodeGen_Posix::CodeGen_Posix(Target t) :
CodeGen_LLVM(t) {
}
Value *CodeGen_Posix::codegen_allocation_size(const std::string &name, Type type, const std::vector<Expr> &extents) {
// Compute size from list of extents checking for overflow.
Expr overflow = make_zero(UInt(64));
Expr total_size = make_const(UInt(64), type.lanes() * type.bytes());
// We'll multiply all the extents into the 64-bit value
// total_size. We'll also track (total_size >> 32) as a 64-bit
// value to check for overflow as we go. The loop invariant will
// be that either the overflow Expr is non-zero, or total_size_hi
// only occupies the bottom 32-bits. Overflow could be more simply
// checked for using division, but that's slower at runtime. This
// method generates much better assembly.
Expr total_size_hi = make_zero(UInt(64));
Expr low_mask = make_const(UInt(64), (uint64_t)(0xffffffff));
for (size_t i = 0; i < extents.size(); i++) {
Expr next_extent = cast(UInt(32), extents[i]);
// Update total_size >> 32. This math can't overflow due to
// the loop invariant:
total_size_hi *= next_extent;
// Deal with carry from the low bits. Still can't overflow.
total_size_hi += ((total_size & low_mask) * next_extent) >> 32;
// Update total_size. This may overflow.
total_size *= next_extent;
// We can check for overflow by asserting that total_size_hi
// is still a 32-bit number.
overflow = overflow | (total_size_hi >> 32);
}
Expr max_size = make_const(UInt(64), target.maximum_buffer_size());
Expr size_check = (overflow == 0) && (total_size <= max_size);
// For constant-sized allocations this check should simplify away.
size_check = common_subexpression_elimination(simplify(size_check));
if (!is_one(size_check)) {
create_assertion(codegen(size_check),
Call::make(Int(32), "halide_error_buffer_allocation_too_large",
{name, total_size, max_size}, Call::Extern));
}
total_size = simplify(total_size);
return codegen(total_size);
}
int CodeGen_Posix::allocation_padding(Type type) const {
// We potentially load one scalar value past the end of the
// buffer, so pad the allocation with an extra instance of the
// scalar type.
return type.bytes();
}
CodeGen_Posix::Allocation CodeGen_Posix::create_allocation(const std::string &name, Type type,
const std::vector<Expr> &extents, Expr condition,
Expr new_expr, std::string free_function) {
Value *llvm_size = nullptr;
int64_t stack_bytes = 0;
int32_t constant_bytes = Allocate::constant_allocation_size(extents, name);
if (constant_bytes > 0) {
constant_bytes *= type.bytes();
stack_bytes = constant_bytes;
if (stack_bytes > target.maximum_buffer_size()) {
const string str_max_size = target.has_feature(Target::LargeBuffers) ? "2^63 - 1" : "2^31 - 1";
user_error << "Total size for allocation " << name << " is constant but exceeds " << str_max_size << ".";
} else if (!can_allocation_fit_on_stack(stack_bytes)) {
stack_bytes = 0;
llvm_size = codegen(Expr(constant_bytes));
}
} else {
llvm_size = codegen_allocation_size(name, type, extents);
}
// Only allocate memory if the condition is true, otherwise 0.
Value *llvm_condition = codegen(condition);
if (llvm_size != nullptr) {
// Add the requested padding to the allocation size. If the
// allocation is on the stack, we can just read past the top
// of the stack, so we only need this for heap allocations.
Value *padding = ConstantInt::get(llvm_size->getType(), allocation_padding(type));
llvm_size = builder->CreateAdd(llvm_size, padding);
llvm_size = builder->CreateSelect(llvm_condition,
llvm_size,
ConstantInt::get(llvm_size->getType(), 0));
}
Allocation allocation;
allocation.constant_bytes = constant_bytes;
allocation.stack_bytes = new_expr.defined() ? 0 : stack_bytes;
allocation.type = type;
allocation.ptr = nullptr;
allocation.destructor = nullptr;
allocation.destructor_function = nullptr;
allocation.name = name;
if (!new_expr.defined() && extents.empty()) {
// If it's a scalar allocation, don't try anything clever. We
// want llvm to be able to promote it to a register.
allocation.ptr = create_alloca_at_entry(llvm_type_of(type), 1, false, name);
allocation.stack_bytes = stack_bytes;
cur_stack_alloc_total += allocation.stack_bytes;
debug(4) << "cur_stack_alloc_total += " << allocation.stack_bytes << " -> " << cur_stack_alloc_total << " for " << name << "\n";
} else if (!new_expr.defined() && stack_bytes != 0) {
// Try to find a free stack allocation we can use.
vector<Allocation>::iterator free = free_stack_allocs.end();
for (free = free_stack_allocs.begin(); free != free_stack_allocs.end(); ++free) {
AllocaInst *alloca_inst = dyn_cast<AllocaInst>(free->ptr);
llvm::Function *allocated_in = alloca_inst ? alloca_inst->getParent()->getParent() : nullptr;
llvm::Function *current_func = builder->GetInsertBlock()->getParent();
if (allocated_in == current_func &&
free->type == type &&
free->stack_bytes >= stack_bytes) {
break;
}
}
if (free != free_stack_allocs.end()) {
debug(4) << "Reusing freed stack allocation of " << free->stack_bytes
<< " bytes for allocation " << name
<< " of " << stack_bytes << " bytes.\n";
// Use a free alloc we found.
allocation.ptr = free->ptr;
allocation.stack_bytes = free->stack_bytes;
allocation.name = free->name;
// This allocation isn't free anymore.
free_stack_allocs.erase(free);
} else {
debug(4) << "Allocating " << stack_bytes << " bytes on the stack for " << name << "\n";
// We used to do the alloca locally and save and restore the
// stack pointer, but this makes llvm generate streams of
// spill/reloads.
int64_t stack_size = (stack_bytes + type.bytes() - 1) / type.bytes();
// Handles are stored as uint64s
llvm::Type *t =
llvm_type_of(type.is_handle() ? UInt(64, type.lanes()) : type);
allocation.ptr = create_alloca_at_entry(t, stack_size, false, name);
allocation.stack_bytes = stack_bytes;
}
cur_stack_alloc_total += allocation.stack_bytes;
debug(4) << "cur_stack_alloc_total += " << allocation.stack_bytes << " -> " << cur_stack_alloc_total << " for " << name << "\n";
} else {
if (new_expr.defined()) {
allocation.ptr = codegen(new_expr);
} else {
// call malloc
llvm::Function *malloc_fn = module->getFunction("halide_malloc");
internal_assert(malloc_fn) << "Could not find halide_malloc in module\n";
malloc_fn->setDoesNotAlias(0);
llvm::Function::arg_iterator arg_iter = malloc_fn->arg_begin();
++arg_iter; // skip the user context *
llvm_size = builder->CreateIntCast(llvm_size, arg_iter->getType(), false);
debug(4) << "Creating call to halide_malloc for allocation " << name
<< " of size " << type.bytes();
for (Expr e : extents) {
debug(4) << " x " << e;
}
debug(4) << "\n";
Value *args[2] = { get_user_context(), llvm_size };
Value *call = builder->CreateCall(malloc_fn, args);
// Fix the type to avoid pointless bitcasts later
call = builder->CreatePointerCast(call, llvm_type_of(type)->getPointerTo());
allocation.ptr = call;
}
// Assert that the allocation worked.
Value *check = builder->CreateIsNotNull(allocation.ptr);
if (llvm_size) {
Value *zero_size = builder->CreateIsNull(llvm_size);
check = builder->CreateOr(check, zero_size);
}
if (!is_one(condition)) {
// If the condition is false, it's OK for the new_expr to be null.
Value *condition_is_false = builder->CreateIsNull(llvm_condition);
check = builder->CreateOr(check, condition_is_false);
}
create_assertion(check, Call::make(Int(32), "halide_error_out_of_memory",
std::vector<Expr>(), Call::Extern));
// Register a destructor for this allocation.
if (free_function.empty()) {
free_function = "halide_free";
}
llvm::Function *free_fn = module->getFunction(free_function);
internal_assert(free_fn) << "Could not find " << free_function << " in module.\n";
allocation.destructor = register_destructor(free_fn, allocation.ptr, OnError);
allocation.destructor_function = free_fn;
}
// Push the allocation base pointer onto the symbol table
debug(3) << "Pushing allocation called " << name << ".host onto the symbol table\n";
allocations.push(name, allocation);
return allocation;
}
void CodeGen_Posix::free_allocation(const std::string &name) {
Allocation alloc = allocations.get(name);
if (alloc.stack_bytes) {
// Remember this allocation so it can be re-used by a later allocation.
free_stack_allocs.push_back(alloc);
cur_stack_alloc_total -= alloc.stack_bytes;
debug(4) << "cur_stack_alloc_total += " << alloc.stack_bytes << " -> " << cur_stack_alloc_total << " for " << name << "\n";
} else {
internal_assert(alloc.destructor);
trigger_destructor(alloc.destructor_function, alloc.destructor);
}
allocations.pop(name);
sym_pop(name + ".host");
}
string CodeGen_Posix::get_allocation_name(const std::string &n) {
if (allocations.contains(n)) {
return allocations.get(n).name;
} else {
return n;
}
}
void CodeGen_Posix::visit(const Allocate *alloc) {
if (sym_exists(alloc->name + ".host")) {
user_error << "Can't have two different buffers with the same name: "
<< alloc->name << "\n";
}
Allocation allocation = create_allocation(alloc->name, alloc->type,
alloc->extents, alloc->condition,
alloc->new_expr, alloc->free_function);
sym_push(alloc->name + ".host", allocation.ptr);
codegen(alloc->body);
// If there was no early free, free it now.
if (allocations.contains(alloc->name)) {
free_allocation(alloc->name);
}
}
void CodeGen_Posix::visit(const Free *stmt) {
free_allocation(stmt->name);
}
}}
|
Add missing cur_stack_alloc_total branch
|
Add missing cur_stack_alloc_total branch
Former-commit-id: 10685387c65e4d484058e2c58e457e872b13cbc4
|
C++
|
mit
|
Trass3r/Halide,darkbuck/Halide,Trass3r/Halide,Trass3r/Halide,darkbuck/Halide,darkbuck/Halide,darkbuck/Halide,darkbuck/Halide,Trass3r/Halide,Trass3r/Halide,darkbuck/Halide,darkbuck/Halide,Trass3r/Halide,Trass3r/Halide
|
b02f23ec8c20eb32351a02bf47a584261074d3f5
|
src/DeviceUpdates.cpp
|
src/DeviceUpdates.cpp
|
/***************************************************************************
* This file is part of libmygpo-qt *
* Copyright (c) 2010 - 2013 Stefan Derkits <[email protected]> *
* Copyright (c) 2010 - 2011 Christian Wagner <[email protected]> *
* Copyright (c) 2010 - 2011 Felix Winter <[email protected]> *
* *
* 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 "DeviceUpdates_p.h"
#include "qjsonwrapper/Json.h"
using namespace mygpo;
DeviceUpdatesPrivate::DeviceUpdatesPrivate( DeviceUpdates* qq, QNetworkReply* reply ): q( qq ), m_timestamp( 0 ), m_reply( reply ), m_error( QNetworkReply::NoError )
{
QObject::connect( m_reply, SIGNAL( finished() ), this, SLOT( parseData() ) );
QObject::connect( m_reply, SIGNAL( error( QNetworkReply::NetworkError ) ), this, SLOT( error( QNetworkReply::NetworkError ) ) );
}
DeviceUpdatesPrivate::~DeviceUpdatesPrivate()
{
}
QVariant DeviceUpdatesPrivate::add() const
{
return m_add;
}
QList< PodcastPtr > DeviceUpdatesPrivate::addList() const
{
QVariantList updateVarList = m_add.toList();
QList<PodcastPtr> ret;
foreach( const QVariant & var, updateVarList )
{
ret.append( PodcastPtr( new Podcast( var ) ) );
}
return ret;
}
QVariant DeviceUpdatesPrivate::remove() const
{
return m_remove;
}
QList< QUrl > DeviceUpdatesPrivate::removeList() const
{
QVariantList updateVarList = m_remove.toList();
QList<QUrl> ret;
foreach( const QVariant & var, updateVarList )
{
if( var.canConvert( QVariant::Url ) )
ret.append( var.toUrl() );
}
return ret;
}
QVariant DeviceUpdatesPrivate::update() const
{
return m_update;
}
QList< EpisodePtr > DeviceUpdatesPrivate::updateList() const
{
QVariantList updateVarList = m_update.toList();
QList<EpisodePtr> ret;
foreach( const QVariant & var, updateVarList )
{
ret.append( EpisodePtr( new Episode( var ) ) );
}
return ret;
}
bool DeviceUpdatesPrivate::parse( const QVariant& data )
{
if( !data.canConvert( QVariant::Map ) )
return false;
QVariantMap varMap = data.toMap();
m_add = varMap.value( QLatin1String( "add" ) );
m_remove = varMap.value( QLatin1String( "remove" ) );
m_update = varMap.value( QLatin1String( "updates" ) );
if( varMap.value( QLatin1String( "timestamp" ) ).canConvert( QVariant::LongLong ) )
m_timestamp = varMap.value( QLatin1String( "timestamp" ) ).toLongLong();
return true;
}
bool DeviceUpdatesPrivate::parse( const QByteArray& data )
{
bool ok;
QVariant variant = QJsonWrapper::parseJson( data, &ok );
if( ok )
{
ok = ( parse( variant ) );
}
return ok;
}
void DeviceUpdatesPrivate::parseData()
{
if( m_reply->error() == QNetworkReply::NoError )
{
if( parse( m_reply->readAll() ) )
{
emit q->finished();
}
else
{
emit q->parseError();
}
}
m_reply->deleteLater();
}
void DeviceUpdatesPrivate::error( QNetworkReply::NetworkError error )
{
m_error = error;
emit q->requestError( error );
}
qulonglong DeviceUpdatesPrivate::timestamp() const
{
return m_timestamp;
}
DeviceUpdates::DeviceUpdates( QNetworkReply* reply, QObject* parent ): QObject( parent ), d( new DeviceUpdatesPrivate( this, reply ) )
{
}
DeviceUpdates::~DeviceUpdates()
{
delete d;
}
QVariant DeviceUpdates::add() const
{
return d->add();
}
QList< PodcastPtr > DeviceUpdates::addList() const
{
return d->addList();
}
QVariant mygpo::DeviceUpdates::remove() const
{
return d->remove();
}
QList< QUrl > mygpo::DeviceUpdates::removeList() const
{
return d->removeList();
}
QVariant mygpo::DeviceUpdates::update() const
{
return d->update();
}
QList< mygpo::EpisodePtr > mygpo::DeviceUpdates::updateList() const
{
return d->updateList();
}
qulonglong DeviceUpdates::timestamp() const
{
return d->timestamp();
}
|
/***************************************************************************
* This file is part of libmygpo-qt *
* Copyright (c) 2010 - 2013 Stefan Derkits <[email protected]> *
* Copyright (c) 2010 - 2011 Christian Wagner <[email protected]> *
* Copyright (c) 2010 - 2011 Felix Winter <[email protected]> *
* *
* 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 "DeviceUpdates_p.h"
#include "qjsonwrapper/Json.h"
using namespace mygpo;
DeviceUpdatesPrivate::DeviceUpdatesPrivate( DeviceUpdates* qq, QNetworkReply* reply ): q( qq ), m_timestamp( 0 ), m_reply( reply ), m_error( QNetworkReply::NoError )
{
QObject::connect( m_reply, SIGNAL( finished() ), this, SLOT( parseData() ) );
QObject::connect( m_reply, SIGNAL( error( QNetworkReply::NetworkError ) ), this, SLOT( error( QNetworkReply::NetworkError ) ) );
}
DeviceUpdatesPrivate::~DeviceUpdatesPrivate()
{
}
QVariant DeviceUpdatesPrivate::add() const
{
return m_add;
}
QList< PodcastPtr > DeviceUpdatesPrivate::addList() const
{
QVariantList updateVarList = m_add.toList();
QList<PodcastPtr> ret;
foreach( const QVariant & var, updateVarList )
{
ret.append( PodcastPtr( new Podcast( var ) ) );
}
return ret;
}
QVariant DeviceUpdatesPrivate::remove() const
{
return m_remove;
}
QList< QUrl > DeviceUpdatesPrivate::removeList() const
{
QVariantList updateVarList = m_remove.toList();
QList<QUrl> ret;
foreach( const QVariant & var, updateVarList )
{
if( var.canConvert( QVariant::Url ) )
ret.append( var.toUrl() );
}
return ret;
}
QVariant DeviceUpdatesPrivate::update() const
{
return m_update;
}
QList< EpisodePtr > DeviceUpdatesPrivate::updateList() const
{
QVariantList updateVarList = m_update.toList();
QList<EpisodePtr> ret;
foreach( const QVariant & var, updateVarList )
{
ret.append( EpisodePtr( new Episode( var ) ) );
}
return ret;
}
bool DeviceUpdatesPrivate::parse( const QVariant& data )
{
if( !data.canConvert( QVariant::Map ) )
return false;
QVariantMap varMap = data.toMap();
m_add = varMap.value( QLatin1String( "add" ) );
m_remove = varMap.value( QLatin1String( "rem" ) );
m_update = varMap.value( QLatin1String( "updates" ) );
if( varMap.value( QLatin1String( "timestamp" ) ).canConvert( QVariant::LongLong ) )
m_timestamp = varMap.value( QLatin1String( "timestamp" ) ).toLongLong();
return true;
}
bool DeviceUpdatesPrivate::parse( const QByteArray& data )
{
bool ok;
QVariant variant = QJsonWrapper::parseJson( data, &ok );
if( ok )
{
ok = ( parse( variant ) );
}
return ok;
}
void DeviceUpdatesPrivate::parseData()
{
if( m_reply->error() == QNetworkReply::NoError )
{
if( parse( m_reply->readAll() ) )
{
emit q->finished();
}
else
{
emit q->parseError();
}
}
m_reply->deleteLater();
}
void DeviceUpdatesPrivate::error( QNetworkReply::NetworkError error )
{
m_error = error;
emit q->requestError( error );
}
qulonglong DeviceUpdatesPrivate::timestamp() const
{
return m_timestamp;
}
DeviceUpdates::DeviceUpdates( QNetworkReply* reply, QObject* parent ): QObject( parent ), d( new DeviceUpdatesPrivate( this, reply ) )
{
}
DeviceUpdates::~DeviceUpdates()
{
delete d;
}
QVariant DeviceUpdates::add() const
{
return d->add();
}
QList< PodcastPtr > DeviceUpdates::addList() const
{
return d->addList();
}
QVariant mygpo::DeviceUpdates::remove() const
{
return d->remove();
}
QList< QUrl > mygpo::DeviceUpdates::removeList() const
{
return d->removeList();
}
QVariant mygpo::DeviceUpdates::update() const
{
return d->update();
}
QList< mygpo::EpisodePtr > mygpo::DeviceUpdates::updateList() const
{
return d->updateList();
}
qulonglong DeviceUpdates::timestamp() const
{
return d->timestamp();
}
|
Fix removeList of DeviceUpdates
|
Fix removeList of DeviceUpdates
The gpodder.net server returns the list of subscriptions to be removed
under the "rem" tag, not "remove" as the API documentation seems to
suggest. Hence, libmygpo-qt is not picking up any subscription
removals.
As reference, see gpodder.net server source code (line 73):
https://github.com/gpodder/mygpo/blob/master/mygpo/api/advanced/updates.py
|
C++
|
lgpl-2.1
|
gpodder/libmygpo-qt,gpodder/libmygpo-qt
|
413ab99ed2a7da0c658388ef9ce77592e96cfda0
|
src/DynamicVector.hpp
|
src/DynamicVector.hpp
|
#ifndef AX_DYNAMIC_VECTOR_H
#define AX_DYNAMIC_VECTOR_H
#include "DynamicVectorExp.hpp"
#include <iostream>
#include <vector>
#include <array>
namespace ax
{
template<typename T_elem, int I_dim,
typename std::enable_if<is_dynamic_dimention<I_dim>::value
>::type*& = enabler>
class Vector
{
public:
using tag = vector_tag;
using elem_t = T_elem;
constexpr static std::size_t dim = I_dim;
public:
Vector(){}
~Vector() = default;
Vector(const std::size_t size) : values_(size, 0e0){}
Vector(const std::size_t size, const double v) : values_(size, v){}
Vector(const std::vector<double>& v) : values_(v){}
Vector(std::vector<double>&& v): values_(std::move(v)){}
template<std::size_t N>
Vector(const std::array<double, N>& v): values_(N)
{
for(std::size_t i=0; i<N; ++i) values_[i] = v[i];
}
// from dynamic Vector
Vector(const Vector<elem_t, dim>& vec) : values_(vec.values_){}
Vector(Vector<elem_t, dim>&& vec) : values_(std::move(vec.values_)){}
// from static Vector
template<int D, typename std::enable_if<
is_static_dimention<D>::value>::type*& = enabler>
Vector(const Vector<elem_t, D>& vec) : values_(D)
{
for(std::size_t i=0; i<D; ++i) this->values_[i] = vec[i];
}
// from dynamic Vector expression
template<class T_expr, typename std::enable_if<
is_vector_expression<typename T_expr::tag>::value&&
is_dynamic_dimention<T_expr::dim>::value>::type*& = enabler>
Vector(const T_expr& expr) : values_(expr.size())
{
for(std::size_t i=0; i<expr.size(); ++i) this->values_[i] = expr[i];
}
// from static Vector
template<class T_expr, typename std::enable_if<
is_vector_expression<typename T_expr::tag>::value&&
is_static_dimention<T_expr::dim>::value>::type*& = enabler>
Vector(const T_expr& expr) : values_(T_expr::dim)
{
for(std::size_t i=0; i<T_expr::dim; ++i) this->values_[i] = expr[i];
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ operator = ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Vector<elem_t, dim>& operator=(const std::vector<double>& v)
{
this->values_ = v; return *this;
}
Vector<elem_t, dim>& operator=(std::vector<double>&& v)
{
this->values_ = std::move(v); return *this;
}
Vector<elem_t, dim>& operator=(const Vector<elem_t, dim>& vec)
{
this->values_ = vec.values_; return *this;
}
Vector<elem_t, dim>& operator=(Vector<elem_t, dim>&& vec)
{
this->values_ = std::move(vec.values_);return *this;
}
template<class T_expr,
typename std::enable_if<
is_vector_expression<typename T_expr::tag>::value&&
is_dynamic_dimention<T_expr::dim>::value>::type*& = enabler>
Vector<elem_t, dim>& operator=(const T_expr& expr)
{
this->values_.resize(expr.size(), 0e0);
for(std::size_t i=0; i<expr.size(); ++i) this->values_[i] = expr[i];
return *this;
}
template<class T_expr,
typename std::enable_if<
is_vector_expression<typename T_expr::tag>::value&&
is_static_dimention<T_expr::dim>::value>::type*& = enabler>
Vector<elem_t, dim>& operator=(const T_expr& expr)
{
this->values_.resize(T_expr::dim, 0e0);
for(std::size_t i=0; i<T_expr::dim; ++i) this->values_[i] = expr[i];
return *this;
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ operator += ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// for dynamic += dynamic
template<class T_expr,
typename std::enable_if<
is_vector_expression<typename T_expr::tag>::value&&
is_dynamic_dimention<T_expr::dim>::value>::type*& = enabler>
Vector<elem_t, dim>& operator+=(const T_expr& expr)
{
if(this->size() != expr.size())
throw std::invalid_argument("add different size vector");
return *this = (*this + expr);
}
// for dynamic += static
template<class T_expr,
typename std::enable_if<
is_vector_expression<typename T_expr::tag>::value&&
is_static_dimention<T_expr::dim>::value>::type*& = enabler>
Vector<elem_t, dim>& operator+=(const T_expr& expr)
{
if(this->size() != T_expr::dim)
throw std::invalid_argument("add different size vector");
return *this = (*this + expr);
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ operator -= ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// for dynamic -= dynamic
template<class T_expr,
typename std::enable_if<
is_vector_expression<typename T_expr::tag>::value&&
is_dynamic_dimention<T_expr::dim>::value>::type*& = enabler>
Vector<elem_t, dim>& operator-=(const T_expr& expr)
{
if(this->size() != expr.size())
throw std::invalid_argument("add different size vector");
return *this = (*this - expr);
}
// for dynamic -= static
template<class T_expr,
typename std::enable_if<
is_vector_expression<typename T_expr::tag>::value&&
is_static_dimention<T_expr::dim>::value>::type*& = enabler>
Vector<elem_t, dim>& operator-=(const T_expr& expr)
{
if(this->size() != T_expr::dim)
throw std::invalid_argument("add different size vector");
return *this = (*this - expr);
}
Vector<elem_t, dim>& operator*=(const elem_t& scl)
{
return *this = (*this * scl);
}
Vector<elem_t, dim>& operator/=(const elem_t& scl)
{
return *this = (*this / scl);
}
elem_t const& operator[](const std::size_t i) const {return values_[i];}
elem_t& operator[](const std::size_t i) {return values_[i];}
elem_t const& at(const std::size_t i) const {return values_.at(i);}
elem_t& at(const std::size_t i) {return values_.at(i);}
std::size_t size() const {return values_.size();}
private:
std::vector<elem_t> values_;
};
}
#endif /* AX_DYNAMIC_VECTOR */
|
#ifndef AX_DYNAMIC_VECTOR_H
#define AX_DYNAMIC_VECTOR_H
#include "VectorExp.hpp"
#include <iostream>
#include <vector>
#include <array>
namespace ax
{
template<typename T_elem, dimension_type I_dim,
typename std::enable_if<is_dynamic_dimension<I_dim>::value
>::type*& = enabler>
class Vector
{
public:
using tag = vector_tag;
using elem_t = T_elem;
constexpr static dimension_type dim = I_dim;
public:
Vector(){}
~Vector() = default;
Vector(const std::size_t size) : values_(size, 0e0){}
Vector(const std::size_t size, const double v) : values_(size, v){}
Vector(const std::vector<double>& v) : values_(v){}
Vector(std::vector<double>&& v): values_(std::move(v)){}
template<std::size_t N>
Vector(const std::array<double, N>& v): values_(N)
{
for(std::size_t i=0; i<N; ++i) values_[i] = v[i];
}
// from dynamic Vector
Vector(const Vector<elem_t, dim>& vec) : values_(vec.values_){}
Vector(Vector<elem_t, dim>&& vec) : values_(std::move(vec.values_)){}
// from static Vector
template<dimension_type D, typename std::enable_if<
is_static_dimension<D>::value>::type*& = enabler>
Vector(const Vector<elem_t, D>& vec) : values_(D)
{
for(std::size_t i=0; i<D; ++i) this->values_[i] = vec[i];
}
// from dynamic Vector expression
template<class T_expr, typename std::enable_if<
is_vector_expression<typename T_expr::tag>::value&&
is_dynamic_dimension<T_expr::dim>::value>::type*& = enabler>
Vector(const T_expr& expr) : values_(dimension(expr))
{
for(std::size_t i=0; i<dimension(expr); ++i) this->values_[i] = expr[i];
}
// from static Vector
template<class T_expr, typename std::enable_if<
is_vector_expression<typename T_expr::tag>::value&&
is_static_dimension<T_expr::dim>::value>::type*& = enabler>
Vector(const T_expr& expr) : values_(T_expr::dim)
{
for(std::size_t i=0; i<T_expr::dim; ++i) this->values_[i] = expr[i];
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ operator = ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Vector<elem_t, dim>& operator=(const std::vector<double>& v)
{
this->values_ = v; return *this;
}
Vector<elem_t, dim>& operator=(std::vector<double>&& v)
{
this->values_ = std::move(v); return *this;
}
Vector<elem_t, dim>& operator=(const Vector<elem_t, dim>& vec)
{
this->values_ = vec.values_; return *this;
}
Vector<elem_t, dim>& operator=(Vector<elem_t, dim>&& vec)
{
this->values_ = std::move(vec.values_);return *this;
}
template<class T_expr,
typename std::enable_if<
is_vector_expression<typename T_expr::tag>::value&&
is_dynamic_dimension<T_expr::dim>::value>::type*& = enabler>
Vector<elem_t, dim>& operator=(const T_expr& expr)
{
this->values_.resize(dimension(expr), 0e0);
for(std::size_t i=0; i<dimension(expr); ++i) this->values_[i] = expr[i];
return *this;
}
template<class T_expr,
typename std::enable_if<
is_vector_expression<typename T_expr::tag>::value&&
is_static_dimension<T_expr::dim>::value>::type*& = enabler>
Vector<elem_t, dim>& operator=(const T_expr& expr)
{
this->values_.resize(T_expr::dim, 0e0);
for(std::size_t i=0; i<T_expr::dim; ++i) this->values_[i] = expr[i];
return *this;
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ operator += ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// for dynamic += dynamic
template<class T_expr,
typename std::enable_if<
is_vector_expression<typename T_expr::tag>::value&&
is_dynamic_dimension<T_expr::dim>::value>::type*& = enabler>
Vector<elem_t, dim>& operator+=(const T_expr& expr)
{
if(this->size() != dimension(expr))
throw std::invalid_argument("add different size vector");
return *this = (*this + expr);
}
// for dynamic += static
template<class T_expr,
typename std::enable_if<
is_vector_expression<typename T_expr::tag>::value&&
is_static_dimension<T_expr::dim>::value>::type*& = enabler>
Vector<elem_t, dim>& operator+=(const T_expr& expr)
{
if(this->size() != T_expr::dim)
throw std::invalid_argument("add different size vector");
return *this = (*this + expr);
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ operator -= ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// for dynamic -= dynamic
template<class T_expr,
typename std::enable_if<
is_vector_expression<typename T_expr::tag>::value&&
is_dynamic_dimension<T_expr::dim>::value>::type*& = enabler>
Vector<elem_t, dim>& operator-=(const T_expr& expr)
{
if(this->size() != dimension(expr))
throw std::invalid_argument("add different size vector");
return *this = (*this - expr);
}
// for dynamic -= static
template<class T_expr,
typename std::enable_if<
is_vector_expression<typename T_expr::tag>::value&&
is_static_dimension<T_expr::dim>::value>::type*& = enabler>
Vector<elem_t, dim>& operator-=(const T_expr& expr)
{
if(this->size() != T_expr::dim)
throw std::invalid_argument("add different size vector");
return *this = (*this - expr);
}
Vector<elem_t, dim>& operator*=(const elem_t& scl)
{
return *this = (*this * scl);
}
Vector<elem_t, dim>& operator/=(const elem_t& scl)
{
return *this = (*this / scl);
}
elem_t const& operator[](const std::size_t i) const {return values_[i];}
elem_t& operator[](const std::size_t i) {return values_[i];}
elem_t const& at(const std::size_t i) const {return values_.at(i);}
elem_t& at(const std::size_t i) {return values_.at(i);}
std::size_t size() const {return values_.size();}
private:
std::vector<elem_t> values_;
};
}
#endif /* AX_DYNAMIC_VECTOR */
|
use dimension() instead of foo.size()
|
use dimension() instead of foo.size()
|
C++
|
mit
|
ToruNiina/AX
|
71314bcda467a6b8533b57ae7ea28b8d95956c16
|
tests/base/timer.cc
|
tests/base/timer.cc
|
//---------------------------- timer.cc ---------------------------
// $Id$
// Version: $Name$
//
// Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003 by the deal.II authors
//
// This file is subject to QPL and may not be distributed
// without copyright and license information. Please refer
// to the file deal.II/doc/license.html for the text and
// further information on this license.
//
//---------------------------- timer.cc ---------------------------
#include <base/timer.h>
#include <base/logstream.h>
#include <fstream>
#include <cmath>
#include <iostream>
// compute the ratio of two measurements and compare to
// the expected value.
void compare (double t1, double t2, double ratio)
{
double r = t2/t1;
double d = std::fabs(r-ratio) / ratio;
// relative error < 10%?
if (d <= .1)
{
deallog << "OK" << std::endl;
} else {
deallog << "Ratio " << r << " should be " << ratio << std::endl;
}
}
// burn computer time
void burn (unsigned int n)
{
double s = 0.;
for (unsigned int i=0 ; i<n ; ++i)
{
for (unsigned int j=1 ; j<100000 ; ++j)
{
s += 1./j * i;
}
}
}
int main ()
{
std::ofstream logfile("timer.output");
deallog.attach(logfile);
deallog.depth_console(0);
Timer t1,t2;
burn (20);
double s01 = t1.stop();
double s02 = t2();
burn (20);
double s11 = t1.stop();
double s12 = t2();
t1.start();
burn (20);
double s21 = t1();
double s22 = t2();
burn (20);
double s31 = t1();
double s32 = t2();
compare (s01,s02,1.);
compare (s11,s12,2.);
compare (s21,s22,3./2.);
compare (s31,s32,4./3.);
}
|
//---------------------------- timer.cc ---------------------------
// $Id$
// Version: $Name$
//
// Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003 by the deal.II authors
//
// This file is subject to QPL and may not be distributed
// without copyright and license information. Please refer
// to the file deal.II/doc/license.html for the text and
// further information on this license.
//
//---------------------------- timer.cc ---------------------------
#include <base/timer.h>
#include <base/logstream.h>
#include <fstream>
#include <cmath>
#include <iostream>
// compute the ratio of two measurements and compare to
// the expected value.
void compare (double t1, double t2, double ratio)
{
double r = t2/t1;
double d = std::fabs(r-ratio) / ratio;
// relative error < 15%?
if (d <= .15)
{
deallog << "OK" << std::endl;
} else {
deallog << "Ratio " << r << " should be " << ratio << std::endl;
}
}
// burn computer time
void burn (unsigned int n)
{
double s = 0.;
for (unsigned int i=0 ; i<n ; ++i)
{
for (unsigned int j=1 ; j<100000 ; ++j)
{
s += 1./j * i;
}
}
}
int main ()
{
std::ofstream logfile("timer.output");
deallog.attach(logfile);
deallog.depth_console(0);
Timer t1,t2;
burn (20);
double s01 = t1.stop();
double s02 = t2();
burn (20);
double s11 = t1.stop();
double s12 = t2();
t1.start();
burn (20);
double s21 = t1();
double s22 = t2();
burn (20);
double s31 = t1();
double s32 = t2();
compare (s01,s02,1.);
compare (s11,s12,2.);
compare (s21,s22,3./2.);
compare (s31,s32,4./3.);
}
|
Allow for 15 % to get us over one problem.
|
Allow for 15 % to get us over one problem.
git-svn-id: 31d9d2f6432a47c86a3640814024c107794ea77c@7509 0785d39b-7218-0410-832d-ea1e28bc413d
|
C++
|
lgpl-2.1
|
andreamola/dealii,naliboff/dealii,angelrca/dealii,YongYang86/dealii,johntfoster/dealii,johntfoster/dealii,ibkim11/dealii,maieneuro/dealii,msteigemann/dealii,natashasharma/dealii,YongYang86/dealii,lue/dealii,nicolacavallini/dealii,kalj/dealii,adamkosik/dealii,pesser/dealii,mtezzele/dealii,nicolacavallini/dealii,adamkosik/dealii,Arezou-gh/dealii,gpitton/dealii,shakirbsm/dealii,EGP-CIG-REU/dealii,shakirbsm/dealii,jperryhouts/dealii,natashasharma/dealii,nicolacavallini/dealii,lue/dealii,lue/dealii,adamkosik/dealii,pesser/dealii,andreamola/dealii,ESeNonFossiIo/dealii,ESeNonFossiIo/dealii,JaeryunYim/dealii,sairajat/dealii,naliboff/dealii,lpolster/dealii,jperryhouts/dealii,flow123d/dealii,JaeryunYim/dealii,adamkosik/dealii,spco/dealii,angelrca/dealii,gpitton/dealii,lpolster/dealii,lpolster/dealii,jperryhouts/dealii,andreamola/dealii,naliboff/dealii,kalj/dealii,natashasharma/dealii,nicolacavallini/dealii,nicolacavallini/dealii,shakirbsm/dealii,mtezzele/dealii,spco/dealii,YongYang86/dealii,kalj/dealii,natashasharma/dealii,shakirbsm/dealii,danshapero/dealii,sriharisundar/dealii,mac-a/dealii,Arezou-gh/dealii,YongYang86/dealii,ESeNonFossiIo/dealii,lpolster/dealii,flow123d/dealii,natashasharma/dealii,Arezou-gh/dealii,johntfoster/dealii,danshapero/dealii,gpitton/dealii,ibkim11/dealii,jperryhouts/dealii,sriharisundar/dealii,flow123d/dealii,spco/dealii,natashasharma/dealii,shakirbsm/dealii,mtezzele/dealii,angelrca/dealii,ibkim11/dealii,mtezzele/dealii,naliboff/dealii,EGP-CIG-REU/dealii,rrgrove6/dealii,pesser/dealii,mac-a/dealii,maieneuro/dealii,johntfoster/dealii,mtezzele/dealii,kalj/dealii,nicolacavallini/dealii,angelrca/dealii,rrgrove6/dealii,pesser/dealii,mac-a/dealii,Arezou-gh/dealii,Arezou-gh/dealii,mac-a/dealii,danshapero/dealii,danshapero/dealii,ESeNonFossiIo/dealii,rrgrove6/dealii,msteigemann/dealii,lue/dealii,shakirbsm/dealii,ESeNonFossiIo/dealii,adamkosik/dealii,jperryhouts/dealii,maieneuro/dealii,ibkim11/dealii,rrgrove6/dealii,ESeNonFossiIo/dealii,sairajat/dealii,Arezou-gh/dealii,nicolacavallini/dealii,lue/dealii,rrgrove6/dealii,kalj/dealii,mac-a/dealii,ibkim11/dealii,maieneuro/dealii,maieneuro/dealii,gpitton/dealii,sriharisundar/dealii,msteigemann/dealii,flow123d/dealii,sairajat/dealii,EGP-CIG-REU/dealii,maieneuro/dealii,rrgrove6/dealii,danshapero/dealii,gpitton/dealii,ESeNonFossiIo/dealii,andreamola/dealii,naliboff/dealii,johntfoster/dealii,naliboff/dealii,gpitton/dealii,pesser/dealii,sairajat/dealii,JaeryunYim/dealii,lue/dealii,msteigemann/dealii,JaeryunYim/dealii,maieneuro/dealii,JaeryunYim/dealii,angelrca/dealii,flow123d/dealii,sriharisundar/dealii,EGP-CIG-REU/dealii,andreamola/dealii,YongYang86/dealii,mtezzele/dealii,spco/dealii,danshapero/dealii,flow123d/dealii,angelrca/dealii,EGP-CIG-REU/dealii,sriharisundar/dealii,andreamola/dealii,pesser/dealii,msteigemann/dealii,sairajat/dealii,andreamola/dealii,flow123d/dealii,sairajat/dealii,gpitton/dealii,johntfoster/dealii,mac-a/dealii,EGP-CIG-REU/dealii,shakirbsm/dealii,YongYang86/dealii,adamkosik/dealii,YongYang86/dealii,lue/dealii,natashasharma/dealii,jperryhouts/dealii,sriharisundar/dealii,kalj/dealii,msteigemann/dealii,spco/dealii,danshapero/dealii,lpolster/dealii,lpolster/dealii,adamkosik/dealii,sairajat/dealii,JaeryunYim/dealii,Arezou-gh/dealii,spco/dealii,lpolster/dealii,ibkim11/dealii,jperryhouts/dealii,johntfoster/dealii,pesser/dealii,kalj/dealii,mac-a/dealii,ibkim11/dealii,EGP-CIG-REU/dealii,spco/dealii,angelrca/dealii,naliboff/dealii,rrgrove6/dealii,sriharisundar/dealii,mtezzele/dealii,JaeryunYim/dealii,msteigemann/dealii
|
546005a315bc0083c40d10c2f11f3516a95778cf
|
src/IntegrateTFDH.cpp
|
src/IntegrateTFDH.cpp
|
#include "IntegrateTFDH.h"
#include "Element.h"
#include "PlasmaFunctions.h"
#include "PlasmaState.h"
#include "PhysicalConstants.h"
#include "RadialFunction.h"
#include <cassert>
#include <cmath>
#include <vector>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_odeiv2.h>
namespace {
struct TfdhParams {
const Element& e;
const PlasmaState& p;
TfdhParams(const Element& re, const PlasmaState& rp) : e(re), p(rp) {}
};
int tfdhOde(double r, const double f[], double dfdr[], void *params) {
const double& qe = PhysicalConstantsCGS::ElectronCharge;
const double phi = qe*f[0]/r;
const PlasmaState& p = static_cast<TfdhParams*>(params)->p;
const double ne = Plasma::ne(phi, p);
const double ionChargeDensity = Plasma::totalIonChargeDensity(phi, p);
dfdr[0] = f[1];
dfdr[1] = -4.0*M_PI*qe * r * (ionChargeDensity - ne);
return 0;
}
}
RadialFunction TFDH::solve(const Element& e, const PlasmaState& p)
{
// set parameters here:
const double ri = 1e-10;
const double rf = 1e-6;
const double dv0 = findPotentialRoot(e, p, ri, rf);
return integrateODE(e, p, ri, rf, dv0);
}
RadialFunction TFDH::integrateODE(const Element& e, const PlasmaState& p,
const double r_init, const double r_final, const double dv0)
{
const double dr_start = r_init;
const double eps_abs = 1e-6;
const double eps_rel = 0;
TfdhParams params(e,p);
gsl_odeiv2_system sys = {tfdhOde, nullptr, 2, ¶ms};
gsl_odeiv2_driver* d = gsl_odeiv2_driver_alloc_y_new(&sys,
gsl_odeiv2_step_rk8pd, dr_start, eps_abs, eps_rel);
// TODO -- clean all this up
const double& qe = PhysicalConstantsCGS::ElectronCharge;
double r = r_init;
double solution[2] = {qe*e.Z + r_init*dv0, dv0};
std::vector<double> radii, potentials;
const int numsteps = 100;
for (int i=0; i<numsteps; ++i) {
const double ri = r_init + (i+1)*(r_final-r_init)/numsteps;
const int status = gsl_odeiv2_driver_apply(d, &r, ri, solution);
assert(status==GSL_SUCCESS);
radii.push_back(ri);
potentials.push_back(solution[0]/ri);
}
gsl_odeiv2_driver_free(d);
return RadialFunction(radii, potentials);
}
double TFDH::findPotentialRoot(const Element& e, const PlasmaState& p,
const double r_init, const double r_final)
{
// find interval that brackets correct potential
double v_low = 0;
double v_high = 0;
{
bool success = false;
const double v_step = 1.0;
const int bracket_attempts = 100;
for (int i=0; i<bracket_attempts; ++i) {
const auto& rf = integrateODE(e, p, r_init, r_final, v_low);
if (rf.data.back() < 0.0) {
success = true;
break;
}
v_high = v_low;
v_low -= v_step;
}
assert(success and "failed to bracket potential root");
}
// iterate guess
// avoid fancy rootfinders here, because we aren't dealing with a smooth
// function and its root -- rather, we are trying to find the boundary
// between two distinct sets: v too large, v too small
double v_mid = 0.0;
{
bool success = false;
const int root_attempts = 100;
for (int i=0; i<root_attempts; ++i) {
v_mid = (v_low + v_high)/2.0;
if (v_mid==v_low or v_mid==v_high) { // underflow
success = true;
break;
}
const auto& rf = integrateODE(e, p, r_init, r_final, v_mid);
if (rf.data.back() >= 0.0) {
v_high = v_mid;
} else {
v_low = v_mid;
}
}
assert(success and "failed to find potential root within bracket");
}
return v_mid;
}
|
#include "IntegrateTFDH.h"
#include "Element.h"
#include "PlasmaFunctions.h"
#include "PlasmaState.h"
#include "PhysicalConstants.h"
#include "RadialFunction.h"
#include <cassert>
#include <cmath>
#include <vector>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_odeiv2.h>
namespace {
struct TfdhParams {
const Element& e;
const PlasmaState& p;
TfdhParams(const Element& re, const PlasmaState& rp) : e(re), p(rp) {}
};
int tfdhOde(double r, const double f[], double dfdr[], void *params) {
const double& qe = PhysicalConstantsCGS::ElectronCharge;
const double phi = qe*f[0]/r;
const PlasmaState& p = static_cast<TfdhParams*>(params)->p;
const double ne = Plasma::ne(phi, p);
const double ionChargeDensity = Plasma::totalIonChargeDensity(phi, p);
dfdr[0] = f[1];
dfdr[1] = -4.0*M_PI*qe * r * (ionChargeDensity - ne);
return 0;
}
}
RadialFunction TFDH::solve(const Element& e, const PlasmaState& p)
{
// set parameters here:
const double ri = 1e-10;
const double rf = 1e-6;
const double dv0 = findPotentialRoot(e, p, ri, rf);
return integrateODE(e, p, ri, rf, dv0);
}
RadialFunction TFDH::integrateODE(const Element& e, const PlasmaState& p,
const double r_init, const double r_final, const double dv0)
{
const double dr_start = r_init;
const double eps_abs = 1e-6;
const double eps_rel = 0;
TfdhParams params(e,p);
gsl_odeiv2_system sys = {tfdhOde, nullptr, 2, ¶ms};
gsl_odeiv2_driver* d = gsl_odeiv2_driver_alloc_y_new(&sys,
gsl_odeiv2_step_rk8pd, dr_start, eps_abs, eps_rel);
// TODO -- clean all this up
const double& qe = PhysicalConstantsCGS::ElectronCharge;
double r = r_init;
double solution[2] = {qe*e.Z + r_init*dv0, dv0};
std::vector<double> radii, potentials;
const int numsteps = 100;
for (int i=0; i<numsteps; ++i) {
const double ri = r_init + (i+1)*(r_final-r_init)/numsteps;
const int status = gsl_odeiv2_driver_apply(d, &r, ri, solution);
assert(status==GSL_SUCCESS);
radii.push_back(ri);
potentials.push_back(solution[0]/ri);
}
gsl_odeiv2_driver_free(d);
return RadialFunction(radii, potentials);
}
double TFDH::findPotentialRoot(const Element& e, const PlasmaState& p,
const double r_init, const double r_final)
{
// find interval that brackets correct potential
double v_low = 0;
double v_high = 0;
{
bool success = false;
const double v_step = 1.0;
const int bracket_attempts = 100;
for (int i=0; i<bracket_attempts; ++i) {
const auto& rf = integrateODE(e, p, r_init, r_final, v_low);
if (rf.data.back() < 0.0) {
success = true;
break;
}
v_high = v_low;
v_low -= v_step;
}
assert(success and "failed to bracket potential root");
}
// iterate guess
// avoid fancy rootfinders here, because we aren't dealing with a smooth
// function and its root -- rather, we are trying to find the boundary
// between two distinct sets: v too large, v too small
double v_mid = 0.0;
{
bool success = false;
const int root_attempts = 100;
for (int i=0; i<root_attempts; ++i) {
v_mid = (v_low + v_high)/2.0;
if (v_mid==v_low or v_mid==v_high) { // underflow
success = true;
break;
}
const auto& rf = integrateODE(e, p, r_init, r_final, v_mid);
((rf.data.back() >= 0.0) ? v_high : v_low) = v_mid;
}
assert(success and "failed to find potential root within bracket");
}
return v_mid;
}
|
Use lvalue ternary to simplify code
|
IntegrateTFDH: Use lvalue ternary to simplify code
|
C++
|
mit
|
fhebert/tfdh
|
e96b79e868b278b90f5012e8a5e50145c96105d5
|
src/external_plugins/term_direct_gl_ui/default_term_window.cpp
|
src/external_plugins/term_direct_gl_ui/default_term_window.cpp
|
#include <pybind11/embed.h>
#include "default_term_window.h"
#include "term_buffer.h"
#include "term_context.h"
#include "term_network.h"
#include "color_theme.h"
#include "char_width.h"
#include <iostream>
#include <iterator>
#include <functional>
#include <locale>
#include <codecvt>
#include "base64.h"
#define PADDING (5)
static
std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> wcharconv;
// ---------------------------------------------------------------- reshape ---
static
void reshape( GLFWwindow* window, int width, int height )
{
(void)window;
glViewport(0, 0, width, height);
DefaultTermWindow * plugin = (DefaultTermWindow *)glfwGetWindowUserPointer(window);
if (!plugin)
return;
int w_height;
int w_width;
glfwGetWindowSize(window, &w_width, &w_height);
std::cout << "reshape w:" << width << ", h:" << height << std::endl;
plugin->OnSize(w_width, w_height);
}
// --------------------------------------------------------------- keyboard ---
static
void keyboard( GLFWwindow* window, int key, int scancode, int action, int mods )
{
(void)window;
(void)key;
(void)scancode;
(void)action;
(void)mods;
DefaultTermWindow * plugin = (DefaultTermWindow *)glfwGetWindowUserPointer(window);
if (!plugin)
return;
if (action == GLFW_PRESS || action == GLFW_REPEAT)
plugin->OnKeyDown(key, scancode, mods, action == GLFW_REPEAT);
}
static
void charmods_callback(GLFWwindow* window, unsigned int codepoint, int mods)
{
(void)window;
(void)codepoint;
(void)mods;
DefaultTermWindow * plugin = (DefaultTermWindow *)glfwGetWindowUserPointer(window);
if (!plugin)
return;
plugin->OnChar(codepoint, mods);
}
// ---------------------------------------------------------------- display ---
static
void display( GLFWwindow* window )
{
(void)window;
DefaultTermWindow * plugin = (DefaultTermWindow *)glfwGetWindowUserPointer(window);
if (!plugin)
return;
plugin->OnDraw();
}
static
void close( GLFWwindow* window )
{
glfwSetWindowShouldClose( window, GL_TRUE );
}
static
void scroll_callback(GLFWwindow* window, double xoffset, double yoffset)
{
DefaultTermWindow * plugin = (DefaultTermWindow *)glfwGetWindowUserPointer(window);
if (!plugin)
return;
plugin->OnMouseWheel(xoffset, yoffset);
}
static
void mouse_button_callback(GLFWwindow* window, int button, int action, int mods)
{
DefaultTermWindow * plugin = (DefaultTermWindow *)glfwGetWindowUserPointer(window);
if (!plugin)
return;
double xpos, ypos;
glfwGetCursorPos(window, &xpos, &ypos);
plugin->OnMouseButton(button, action, mods, xpos, ypos);
}
static
void cursor_position_callback(GLFWwindow* window, double xpos, double ypos)
{
DefaultTermWindow * plugin = (DefaultTermWindow *)glfwGetWindowUserPointer(window);
if (!plugin)
return;
plugin->OnMouseMove(xpos, ypos);
}
DefaultTermWindow::DefaultTermWindow()
: PluginBase("term_gl_window", "opengl terminal window plugin", 1)
, m_MainDlg {nullptr}
, m_FreeTypeGLContext {nullptr}
, m_TextBuffer {nullptr}
, m_RefreshNow {0}
, m_ProcessedKey {0}
, m_ProcessedMod {0}
, m_SavedMouseButton {-1}
, m_EnableMouseTrack {false}
, m_Width {0}
, m_Height {0} {
}
void DefaultTermWindow::Refresh() {
{
std::lock_guard<std::mutex> lk(m_RefreshLock);
m_RefreshNow++;
}
glfwPostEmptyEvent();
}
void DefaultTermWindow::InitFreeTypeGLContext() {
if (!m_FreeTypeGLContext) {
m_FreeTypeGLContext = freetype_gl_init(m_Viewport);
TermContextPtr context = std::dynamic_pointer_cast<TermContext>(GetPluginContext());
if (context) {
AppConfigPtr appConfig = context->GetAppConfig();
auto font_size = appConfig->GetEntryUInt64("/term/font/size", 16);
auto font_name = appConfig->GetEntry("/term/font/name", "Monospace");
auto font_lang = appConfig->GetEntry("/term/font/lang", "zh-CN");
int height = 0;
glfwGetFramebufferSize(m_MainDlg, NULL, &height);
int w_height;
glfwGetWindowSize(m_MainDlg, NULL, &w_height);
font_size = ceil((double)font_size / w_height * height);
m_FreeTypeGLContext->init_font(font_name, font_size, font_lang);
}
}
}
void DefaultTermWindow::Show() {
const GLFWvidmode* mode = glfwGetVideoMode(glfwGetPrimaryMonitor());
int width = mode->width;
int height = mode->height;
if (!m_MainDlg) {
m_MainDlg = glfwCreateWindow( width, height, "wxglTerm",
NULL,
NULL );
GLFWcursor* cursor = glfwCreateStandardCursor(GLFW_IBEAM_CURSOR);
glfwSetCursor(m_MainDlg, cursor);
glfwMakeContextCurrent(m_MainDlg);
glfwSwapInterval( 1 );
glfwSetWindowUserPointer(m_MainDlg, this);
InitViewPort();
InitFreeTypeGLContext();
glfwSetFramebufferSizeCallback(m_MainDlg, reshape );
glfwSetWindowRefreshCallback(m_MainDlg, display );
glfwSetKeyCallback(m_MainDlg, keyboard );
glfwSetWindowCloseCallback(m_MainDlg, close);
glfwSetCharModsCallback(m_MainDlg, charmods_callback);
glfwSetCursorPosCallback(m_MainDlg, cursor_position_callback);
glfwSetMouseButtonCallback(m_MainDlg, mouse_button_callback);
glfwSetScrollCallback(m_MainDlg, scroll_callback);
#ifndef __APPLE__
GLenum err = glewInit();
if (GLEW_OK != err)
{
/* Problem: glewInit failed, something is seriously wrong. */
fprintf( stderr, "Error: %s\n", glewGetErrorString(err) );
}
fprintf( stderr, "Using GLEW %s\n", glewGetString(GLEW_VERSION) );
#endif
InitColorTable();
} else {
glfwMakeContextCurrent(m_MainDlg);
glfwSwapInterval( 1 );
}
Init();
glfwShowWindow(m_MainDlg);
}
void DefaultTermWindow::Close() {
if (!m_MainDlg) return;
glfwSetWindowShouldClose( m_MainDlg, GL_TRUE );
}
void DefaultTermWindow::SetWindowTitle(const std::string & title) {
glfwSetWindowTitle(m_MainDlg, title.c_str());
}
uint32_t DefaultTermWindow::GetColorByIndex(uint32_t index) {
ftdgl::text::color_s c = __GetColorByIndex(index);
#define COLOR(x) ((uint32_t)((x) * 255))
uint32_t cv = (COLOR(c.r) << 24)
| (COLOR(c.g) << 16)
| (COLOR(c.b) << 8)
| (COLOR(c.a));
#undef COLOR
return cv;
}
void DefaultTermWindow::SetColorByIndex(uint32_t index, uint32_t v) {
if (index >= TermCell::ColorIndexCount)
return;
#define C2V(x) static_cast<float>((x) / 255.0)
m_ColorTable[index] = {C2V((v >> 24) & 0xFF),
C2V((v >> 16) & 0xFF),
C2V((v >> 8) & 0xFF),
C2V((v & 0xFF))
};
#undef C2V
}
std::string DefaultTermWindow::GetSelectionData() {
std::string sel_data {};
auto data = glfwGetClipboardString(m_MainDlg);
if (data) {
if (!Base64::Encode(data, &sel_data)) {
sel_data.clear();
}
}
return sel_data;
}
void DefaultTermWindow::SetSelectionData(const std::string & sel_data) {
std::string decoded {};
if (sel_data.size() == 0) {
decoded.clear();
return;
} else {
if (!Base64::Decode(sel_data, &decoded)) {
decoded.clear();
}
}
glfwSetClipboardString(m_MainDlg, decoded.c_str());
}
void DefaultTermWindow::OnSize(int width, int height) {
TermContextPtr context = std::dynamic_pointer_cast<TermContext>(GetPluginContext());
if (!context)
return;
TermBufferPtr buffer = context->GetTermBuffer();
if (!buffer)
return;
m_Width = width;
m_Height = height;
buffer->Resize((height - PADDING * 2) / m_FreeTypeGLContext->line_height,
(width - PADDING * 2) / m_FreeTypeGLContext->col_width);
std::cout << "row:" << buffer->GetRows()
<< ", cols:" << buffer->GetCols()
<< ", w:" << width
<< ", h:" << height
<< std::endl;
TermNetworkPtr network = context->GetTermNetwork();
if (network)
network->Resize(buffer->GetRows(),
buffer->GetCols());
}
bool DefaultTermWindow::ShouldClose() {
if (!m_MainDlg)
return false;
return glfwWindowShouldClose(m_MainDlg);
}
void DefaultTermWindow::InitColorTable()
{
#define C2V(x) static_cast<float>((x) / 255.0)
TermContextPtr context = std::dynamic_pointer_cast<TermContext>(GetPluginContext());
TermColorThemePtr color_theme = context->GetTermColorTheme();
try
{
pybind11::gil_scoped_acquire acquire;
for(int i = 0; i < TermCell::ColorIndexCount;i++)
{
TermColorPtr color = color_theme->GetColor(i);
m_ColorTable[i] = {C2V(color->r),
C2V(color->g),
C2V(color->b),
C2V(color->a)
};
}
}
catch(std::exception & e)
{
std::cerr << "!!Error InitColorTable:"
<< std::endl
<< e.what()
<< std::endl;
PyErr_Print();
}
catch(...)
{
std::cerr << "!!Error InitColorTable"
<< std::endl;
PyErr_Print();
}
#undef C2V
}
void DefaultTermWindow::Init() {
if (!m_TextBuffer) {
m_TextBuffer = ftdgl::text::CreateTextBuffer(m_Viewport);
m_Render = ftdgl::render::CreateRender();
}
}
void DefaultTermWindow::UpdateWindow() {
int refresh_now = 0;
{
std::lock_guard<std::mutex> lk(m_RefreshLock);
refresh_now = m_RefreshNow;
}
if (refresh_now && m_MainDlg)
OnDraw();
{
std::lock_guard<std::mutex> lk(m_RefreshLock);
m_RefreshNow -= refresh_now;
}
}
void DefaultTermWindow::EnableMouseTrack(bool enable) {
m_EnableMouseTrack = enable;
}
void DefaultTermWindow::InitViewPort() {
int pixel_height = 0, pixel_width = 0;
glfwGetFramebufferSize(m_MainDlg, &pixel_width, &pixel_height);
const GLFWvidmode* mode = glfwGetVideoMode(glfwGetPrimaryMonitor());
int widthMM, heightMM;
glfwGetMonitorPhysicalSize(glfwGetPrimaryMonitor(), &widthMM, &heightMM);
float dpi = mode->width / (widthMM / 25.4);
float dpi_height = (mode->height / (heightMM / 25.4));
int w_height, w_width;
glfwGetWindowSize(m_MainDlg, &w_width, &w_height);
std::cout << "pw:" << pixel_width << ", ph:" << pixel_height
<< "w:" << w_width << ", h:" << w_height
<< ", dpi:" << dpi
<< ", " << dpi_height
<< std::endl;
m_Viewport = {
0, 0,
pixel_width, pixel_height,
w_width, w_height,
dpi, dpi_height
};
}
|
#include <pybind11/embed.h>
#include "default_term_window.h"
#include "term_buffer.h"
#include "term_context.h"
#include "term_network.h"
#include "color_theme.h"
#include "char_width.h"
#include <iostream>
#include <iterator>
#include <functional>
#include <locale>
#include <codecvt>
#include "base64.h"
#define PADDING (5)
static
std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> wcharconv;
// ---------------------------------------------------------------- reshape ---
static
void reshape( GLFWwindow* window, int width, int height )
{
(void)window;
glViewport(0, 0, width, height);
DefaultTermWindow * plugin = (DefaultTermWindow *)glfwGetWindowUserPointer(window);
if (!plugin)
return;
int w_height;
int w_width;
glfwGetWindowSize(window, &w_width, &w_height);
std::cout << "reshape w:" << width << ", h:" << height << std::endl;
plugin->OnSize(w_width, w_height);
}
// --------------------------------------------------------------- keyboard ---
static
void keyboard( GLFWwindow* window, int key, int scancode, int action, int mods )
{
(void)window;
(void)key;
(void)scancode;
(void)action;
(void)mods;
DefaultTermWindow * plugin = (DefaultTermWindow *)glfwGetWindowUserPointer(window);
if (!plugin)
return;
if (action == GLFW_PRESS || action == GLFW_REPEAT)
plugin->OnKeyDown(key, scancode, mods, action == GLFW_REPEAT);
}
static
void charmods_callback(GLFWwindow* window, unsigned int codepoint, int mods)
{
(void)window;
(void)codepoint;
(void)mods;
DefaultTermWindow * plugin = (DefaultTermWindow *)glfwGetWindowUserPointer(window);
if (!plugin)
return;
plugin->OnChar(codepoint, mods);
}
// ---------------------------------------------------------------- display ---
static
void display( GLFWwindow* window )
{
(void)window;
DefaultTermWindow * plugin = (DefaultTermWindow *)glfwGetWindowUserPointer(window);
if (!plugin)
return;
plugin->OnDraw();
}
static
void close( GLFWwindow* window )
{
glfwSetWindowShouldClose( window, GL_TRUE );
}
static
void scroll_callback(GLFWwindow* window, double xoffset, double yoffset)
{
DefaultTermWindow * plugin = (DefaultTermWindow *)glfwGetWindowUserPointer(window);
if (!plugin)
return;
plugin->OnMouseWheel(xoffset, yoffset);
}
static
void mouse_button_callback(GLFWwindow* window, int button, int action, int mods)
{
DefaultTermWindow * plugin = (DefaultTermWindow *)glfwGetWindowUserPointer(window);
if (!plugin)
return;
double xpos, ypos;
glfwGetCursorPos(window, &xpos, &ypos);
plugin->OnMouseButton(button, action, mods, xpos, ypos);
}
static
void cursor_position_callback(GLFWwindow* window, double xpos, double ypos)
{
DefaultTermWindow * plugin = (DefaultTermWindow *)glfwGetWindowUserPointer(window);
if (!plugin)
return;
plugin->OnMouseMove(xpos, ypos);
}
DefaultTermWindow::DefaultTermWindow()
: PluginBase("term_gl_window", "opengl terminal window plugin", 1)
, m_MainDlg {nullptr}
, m_FreeTypeGLContext {nullptr}
, m_TextBuffer {nullptr}
, m_RefreshNow {0}
, m_ProcessedKey {0}
, m_ProcessedMod {0}
, m_SavedMouseButton {-1}
, m_EnableMouseTrack {false}
, m_Width {0}
, m_Height {0} {
}
void DefaultTermWindow::Refresh() {
{
std::lock_guard<std::mutex> lk(m_RefreshLock);
m_RefreshNow++;
}
glfwPostEmptyEvent();
}
void DefaultTermWindow::InitFreeTypeGLContext() {
if (!m_FreeTypeGLContext) {
m_FreeTypeGLContext = freetype_gl_init(m_Viewport);
TermContextPtr context = std::dynamic_pointer_cast<TermContext>(GetPluginContext());
if (context) {
AppConfigPtr appConfig = context->GetAppConfig();
auto font_size = appConfig->GetEntryUInt64("/term/font/size", 16);
auto font_name = appConfig->GetEntry("/term/font/name", "Monospace");
auto font_lang = appConfig->GetEntry("/term/font/lang", "zh-CN");
int height = 0;
glfwGetFramebufferSize(m_MainDlg, NULL, &height);
int w_height;
glfwGetWindowSize(m_MainDlg, NULL, &w_height);
font_size = ceil((double)font_size / w_height * height);
m_FreeTypeGLContext->init_font(font_name, font_size, font_lang);
m_Viewport.line_height = m_FreeTypeGLContext->line_height;
}
}
}
void DefaultTermWindow::Show() {
const GLFWvidmode* mode = glfwGetVideoMode(glfwGetPrimaryMonitor());
int width = mode->width;
int height = mode->height;
if (!m_MainDlg) {
m_MainDlg = glfwCreateWindow( width, height, "wxglTerm",
NULL,
NULL );
GLFWcursor* cursor = glfwCreateStandardCursor(GLFW_IBEAM_CURSOR);
glfwSetCursor(m_MainDlg, cursor);
glfwMakeContextCurrent(m_MainDlg);
glfwSwapInterval( 1 );
glfwSetWindowUserPointer(m_MainDlg, this);
InitViewPort();
InitFreeTypeGLContext();
glfwSetFramebufferSizeCallback(m_MainDlg, reshape );
glfwSetWindowRefreshCallback(m_MainDlg, display );
glfwSetKeyCallback(m_MainDlg, keyboard );
glfwSetWindowCloseCallback(m_MainDlg, close);
glfwSetCharModsCallback(m_MainDlg, charmods_callback);
glfwSetCursorPosCallback(m_MainDlg, cursor_position_callback);
glfwSetMouseButtonCallback(m_MainDlg, mouse_button_callback);
glfwSetScrollCallback(m_MainDlg, scroll_callback);
#ifndef __APPLE__
GLenum err = glewInit();
if (GLEW_OK != err)
{
/* Problem: glewInit failed, something is seriously wrong. */
fprintf( stderr, "Error: %s\n", glewGetErrorString(err) );
}
fprintf( stderr, "Using GLEW %s\n", glewGetString(GLEW_VERSION) );
#endif
InitColorTable();
} else {
glfwMakeContextCurrent(m_MainDlg);
glfwSwapInterval( 1 );
}
Init();
glfwShowWindow(m_MainDlg);
}
void DefaultTermWindow::Close() {
if (!m_MainDlg) return;
glfwSetWindowShouldClose( m_MainDlg, GL_TRUE );
}
void DefaultTermWindow::SetWindowTitle(const std::string & title) {
glfwSetWindowTitle(m_MainDlg, title.c_str());
}
uint32_t DefaultTermWindow::GetColorByIndex(uint32_t index) {
ftdgl::text::color_s c = __GetColorByIndex(index);
#define COLOR(x) ((uint32_t)((x) * 255))
uint32_t cv = (COLOR(c.r) << 24)
| (COLOR(c.g) << 16)
| (COLOR(c.b) << 8)
| (COLOR(c.a));
#undef COLOR
return cv;
}
void DefaultTermWindow::SetColorByIndex(uint32_t index, uint32_t v) {
if (index >= TermCell::ColorIndexCount)
return;
#define C2V(x) static_cast<float>((x) / 255.0)
m_ColorTable[index] = {C2V((v >> 24) & 0xFF),
C2V((v >> 16) & 0xFF),
C2V((v >> 8) & 0xFF),
C2V((v & 0xFF))
};
#undef C2V
}
std::string DefaultTermWindow::GetSelectionData() {
std::string sel_data {};
auto data = glfwGetClipboardString(m_MainDlg);
if (data) {
if (!Base64::Encode(data, &sel_data)) {
sel_data.clear();
}
}
return sel_data;
}
void DefaultTermWindow::SetSelectionData(const std::string & sel_data) {
std::string decoded {};
if (sel_data.size() == 0) {
decoded.clear();
return;
} else {
if (!Base64::Decode(sel_data, &decoded)) {
decoded.clear();
}
}
glfwSetClipboardString(m_MainDlg, decoded.c_str());
}
void DefaultTermWindow::OnSize(int width, int height) {
TermContextPtr context = std::dynamic_pointer_cast<TermContext>(GetPluginContext());
if (!context)
return;
TermBufferPtr buffer = context->GetTermBuffer();
if (!buffer)
return;
m_Width = width;
m_Height = height;
buffer->Resize((height - PADDING * 2) / m_FreeTypeGLContext->line_height,
(width - PADDING * 2) / m_FreeTypeGLContext->col_width);
std::cout << "row:" << buffer->GetRows()
<< ", cols:" << buffer->GetCols()
<< ", w:" << width
<< ", h:" << height
<< std::endl;
TermNetworkPtr network = context->GetTermNetwork();
if (network)
network->Resize(buffer->GetRows(),
buffer->GetCols());
}
bool DefaultTermWindow::ShouldClose() {
if (!m_MainDlg)
return false;
return glfwWindowShouldClose(m_MainDlg);
}
void DefaultTermWindow::InitColorTable()
{
#define C2V(x) static_cast<float>((x) / 255.0)
TermContextPtr context = std::dynamic_pointer_cast<TermContext>(GetPluginContext());
TermColorThemePtr color_theme = context->GetTermColorTheme();
try
{
pybind11::gil_scoped_acquire acquire;
for(int i = 0; i < TermCell::ColorIndexCount;i++)
{
TermColorPtr color = color_theme->GetColor(i);
m_ColorTable[i] = {C2V(color->r),
C2V(color->g),
C2V(color->b),
C2V(color->a)
};
}
}
catch(std::exception & e)
{
std::cerr << "!!Error InitColorTable:"
<< std::endl
<< e.what()
<< std::endl;
PyErr_Print();
}
catch(...)
{
std::cerr << "!!Error InitColorTable"
<< std::endl;
PyErr_Print();
}
#undef C2V
}
void DefaultTermWindow::Init() {
if (!m_TextBuffer) {
m_TextBuffer = ftdgl::text::CreateTextBuffer(m_Viewport);
m_Render = ftdgl::render::CreateRender();
}
}
void DefaultTermWindow::UpdateWindow() {
int refresh_now = 0;
{
std::lock_guard<std::mutex> lk(m_RefreshLock);
refresh_now = m_RefreshNow;
}
if (refresh_now && m_MainDlg)
OnDraw();
{
std::lock_guard<std::mutex> lk(m_RefreshLock);
m_RefreshNow -= refresh_now;
}
}
void DefaultTermWindow::EnableMouseTrack(bool enable) {
m_EnableMouseTrack = enable;
}
void DefaultTermWindow::InitViewPort() {
int pixel_height = 0, pixel_width = 0;
glfwGetFramebufferSize(m_MainDlg, &pixel_width, &pixel_height);
const GLFWvidmode* mode = glfwGetVideoMode(glfwGetPrimaryMonitor());
int widthMM, heightMM;
glfwGetMonitorPhysicalSize(glfwGetPrimaryMonitor(), &widthMM, &heightMM);
float dpi = mode->width / (widthMM / 25.4);
float dpi_height = (mode->height / (heightMM / 25.4));
int w_height, w_width;
glfwGetWindowSize(m_MainDlg, &w_width, &w_height);
std::cout << "pw:" << pixel_width << ", ph:" << pixel_height
<< "w:" << w_width << ", h:" << w_height
<< ", dpi:" << dpi
<< ", " << dpi_height
<< std::endl;
m_Viewport = {
0, 0,
pixel_width, pixel_height,
w_width, w_height,
dpi, dpi_height,
0 //line height will be reset after opengl context initialized
};
}
|
set line height to override default font height
|
set line height to override default font height
|
C++
|
mit
|
stonewell/wxglterm,stonewell/wxglterm,stonewell/wxglterm,stonewell/wxglterm
|
5fd81b2a5b4efb9cf62e714aa69e0bce929659bb
|
rmol/bom/EMDetruncator.cpp
|
rmol/bom/EMDetruncator.cpp
|
// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <iostream>
#include <cmath>
#include <vector>
#include <cassert>
// StdAir
#include <stdair/stdair_basic_types.hpp>
#include <stdair/service/Logger.hpp>
// RMOL
#include <rmol/bom/HistoricalBookingHolder.hpp>
#include <rmol/bom/EMDetruncator.hpp>
namespace RMOL {
// ////////////////////////////////////////////////////////////////////
void EMDetruncator::unconstrain
(HistoricalBookingHolder& ioHistoricalBookingHolder) {
// Number of flights.
const short lNbOfFlights =
ioHistoricalBookingHolder.getNbOfFlights();
// Number of uncensored booking data.
const short lNbOfUncensoredData =
ioHistoricalBookingHolder.getNbOfUncensoredData();
if (lNbOfUncensoredData > 1) {
// Number of uncensored bookings.
const stdair::NbOfBookings_T lNbOfUncensoredBookings =
ioHistoricalBookingHolder.getNbOfUncensoredBookings();
const double lMeanOfUncensoredBookings =
static_cast<double>(lNbOfUncensoredBookings/lNbOfUncensoredData);
const double lStdDevOfUncensoredBookings =
ioHistoricalBookingHolder.getUncensoredStandardDeviation
(lMeanOfUncensoredBookings, lNbOfUncensoredData);
std::vector<bool> toBeUnconstrained =
ioHistoricalBookingHolder.getListOfToBeUnconstrainedFlags();
double lDemandMean = lMeanOfUncensoredBookings;
double lStdDev = lStdDevOfUncensoredBookings;
// DEBUG
// STDAIR_LOG_DEBUG ("mean: " << lDemandMean << ", std: " << lStdDev);
if (lStdDev != 0) {
bool stopUnconstraining = false;
while (stopUnconstraining == false) {
stopUnconstraining = true;
for (short i = 0; i < lNbOfFlights; ++i) {
if (toBeUnconstrained.at(i) == true) {
// Get the unconstrained demand of the (i+1)-th flight.
const stdair::NbOfBookings_T demand =
ioHistoricalBookingHolder.getUnconstrainedDemand (i);
//STDAIR_LOG_DEBUG ("demand: " << demand);
// Execute the Expectation step.
const stdair::NbOfBookings_T expectedDemand =
ioHistoricalBookingHolder.
calculateExpectedDemand (lDemandMean, lStdDev, i, demand);
//STDAIR_LOG_DEBUG ("expected: " << expectedDemand);
assert (expectedDemand >= 0 || expectedDemand < 0);
double absDiff =
static_cast<double>(expectedDemand - demand);
if (absDiff < 0) {
absDiff = - absDiff;
}
if (absDiff < 0.001) {
toBeUnconstrained.at (i) = false;
}
else {
stopUnconstraining = false;
}
ioHistoricalBookingHolder.setUnconstrainedDemand (expectedDemand,
i);
}
}
if (stopUnconstraining == false) {
lDemandMean = ioHistoricalBookingHolder.getDemandMean();
lStdDev =
ioHistoricalBookingHolder.getStandardDeviation (lDemandMean);
}
}
}
}
}
}
|
// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <iostream>
#include <cmath>
#include <vector>
#include <cassert>
// StdAir
#include <stdair/stdair_basic_types.hpp>
#include <stdair/service/Logger.hpp>
// RMOL
#include <rmol/bom/HistoricalBookingHolder.hpp>
#include <rmol/bom/EMDetruncator.hpp>
namespace RMOL {
// ////////////////////////////////////////////////////////////////////
void EMDetruncator::unconstrain
(HistoricalBookingHolder& ioHistoricalBookingHolder) {
// Number of flights.
const short lNbOfFlights =
ioHistoricalBookingHolder.getNbOfFlights();
// Number of uncensored booking data.
const short lNbOfUncensoredData =
ioHistoricalBookingHolder.getNbOfUncensoredData();
if (lNbOfUncensoredData > 1) {
// Number of uncensored bookings.
const stdair::NbOfBookings_T lNbOfUncensoredBookings =
ioHistoricalBookingHolder.getNbOfUncensoredBookings();
const double lMeanOfUncensoredBookings =
static_cast<double>(lNbOfUncensoredBookings/lNbOfUncensoredData);
const double lStdDevOfUncensoredBookings =
ioHistoricalBookingHolder.getUncensoredStandardDeviation
(lMeanOfUncensoredBookings, lNbOfUncensoredData);
std::vector<bool> toBeUnconstrained =
ioHistoricalBookingHolder.getListOfToBeUnconstrainedFlags();
double lDemandMean = lMeanOfUncensoredBookings;
double lStdDev = lStdDevOfUncensoredBookings;
// DEBUG
// STDAIR_LOG_DEBUG ("mean: " << lDemandMean << ", std: " << lStdDev);
if (lStdDev != 0) {
bool stopUnconstraining = false;
while (stopUnconstraining == false) {
stopUnconstraining = true;
for (short i = 0; i < lNbOfFlights; ++i) {
if (toBeUnconstrained.at(i) == true) {
// Get the unconstrained demand of the (i+1)-th flight.
const stdair::NbOfBookings_T demand =
ioHistoricalBookingHolder.getUnconstrainedDemand (i);
//STDAIR_LOG_DEBUG ("demand: " << demand);
// Execute the Expectation step.
const stdair::NbOfBookings_T expectedDemand =
ioHistoricalBookingHolder.
calculateExpectedDemand (lDemandMean, lStdDev, i, demand);
//STDAIR_LOG_DEBUG ("expected: " << expectedDemand);
double absDiff =
static_cast<double>(expectedDemand - demand);
if (absDiff < 0) {
absDiff = - absDiff;
}
if (absDiff < 0.001) {
toBeUnconstrained.at (i) = false;
}
else {
stopUnconstraining = false;
}
ioHistoricalBookingHolder.setUnconstrainedDemand (expectedDemand,
i);
}
}
if (stopUnconstraining == false) {
lDemandMean = ioHistoricalBookingHolder.getDemandMean();
lStdDev =
ioHistoricalBookingHolder.getStandardDeviation (lDemandMean);
}
}
}
}
}
}
|
Update EMDetruncator.cpp
|
Update EMDetruncator.cpp
Suppressed a useless assertion (which was always true).
|
C++
|
lgpl-2.1
|
jwakely/rmol,airsim/rmol,jwakely/rmol,jwakely/rmol,jwakely/rmol,airsim/rmol,airsim/rmol,airsim/rmol
|
f5ab5f3a461257319a9753bfe498642986b5496b
|
src/plugins/coreplugin/progressmanager/progressmanager_win.cpp
|
src/plugins/coreplugin/progressmanager/progressmanager_win.cpp
|
/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include <QVariant>
#include <QMainWindow>
#include <QFont>
#include <QFontMetrics>
#include <QPixmap>
#include <QPainter>
#if QT_VERSION >= 0x050000
# include <QGuiApplication>
# include <QWindow>
# include <qpa/qplatformnativeinterface.h>
#endif
#include <QLabel>
#include <coreplugin/icore.h>
#include "progressmanager_p.h"
// for windows progress bar
#ifndef __GNUC__
# include <shobjidl.h>
#endif
// Windows 7 SDK required
#ifdef __ITaskbarList3_INTERFACE_DEFINED__
namespace {
int total = 0;
ITaskbarList3* pITask = 0;
}
#if QT_VERSION >= 0x050000
Q_GUI_EXPORT HICON qt_pixmapToWinHICON(const QPixmap &p);
static inline QWindow *windowOfWidget(const QWidget *widget)
{
if (QWindow *window = widget->windowHandle())
return window;
if (QWidget *topLevel = widget->nativeParentWidget())
return topLevel->windowHandle();
return 0;
}
static inline HWND hwndOfWidget(const QWidget *w)
{
void *result = 0;
if (QWindow *window = windowOfWidget(w))
result = QGuiApplication::platformNativeInterface()->nativeResourceForWindow("handle", window);
return static_cast<HWND>(result);
}
#else
static inline HWND hwndOfWidget(const QWidget *w)
{
return w->winId();
}
#endif
void Core::Internal::ProgressManagerPrivate::initInternal()
{
CoInitialize(NULL);
HRESULT hRes = CoCreateInstance(CLSID_TaskbarList,
NULL,CLSCTX_INPROC_SERVER,
IID_ITaskbarList3,(LPVOID*) &pITask);
if (FAILED(hRes))
{
pITask = 0;
CoUninitialize();
return;
}
pITask->HrInit();
return;
}
void Core::Internal::ProgressManagerPrivate::cleanup()
{
if (pITask) {
pITask->Release();
pITask = NULL;
CoUninitialize();
}
}
void Core::Internal::ProgressManagerPrivate::setApplicationLabel(const QString &text)
{
if (!pITask)
return;
const HWND winId = hwndOfWidget(Core::ICore::mainWindow());
if (text.isEmpty()) {
pITask->SetOverlayIcon(winId, NULL, NULL);
} else {
QPixmap pix = QPixmap(QLatin1String(":/projectexplorer/images/compile_error.png"));
QPainter p(&pix);
p.setPen(Qt::white);
QFont font = p.font();
font.setPointSize(font.pointSize()-2);
p.setFont(font);
p.drawText(QRect(QPoint(0,0), pix.size()), Qt::AlignHCenter|Qt::AlignCenter, text);
#if QT_VERSION >= 0x050000
const HICON icon = qt_pixmapToWinHICON(pix);
#else
const HICON icon = pix.toWinHICON();
#endif
pITask->SetOverlayIcon(winId, icon, (wchar_t*)text.utf16());
DestroyIcon(icon);
}
}
void Core::Internal::ProgressManagerPrivate::setApplicationProgressRange(int min, int max)
{
total = max-min;
}
void Core::Internal::ProgressManagerPrivate::setApplicationProgressValue(int value)
{
if (pITask) {
const HWND winId = hwndOfWidget(Core::ICore::mainWindow());
pITask->SetProgressValue(winId, value, total);
}
}
void Core::Internal::ProgressManagerPrivate::setApplicationProgressVisible(bool visible)
{
if (!pITask)
return;
const HWND winId = hwndOfWidget(Core::ICore::mainWindow());
if (visible)
pITask->SetProgressState(winId, TBPF_NORMAL);
else
pITask->SetProgressState(winId, TBPF_NOPROGRESS);
}
#else
void Core::Internal::ProgressManagerPrivate::initInternal()
{
}
void Core::Internal::ProgressManagerPrivate::cleanup()
{
}
void Core::Internal::ProgressManagerPrivate::setApplicationLabel(const QString &text)
{
Q_UNUSED(text)
}
void Core::Internal::ProgressManagerPrivate::setApplicationProgressRange(int min, int max)
{
Q_UNUSED(min)
Q_UNUSED(max)
}
void Core::Internal::ProgressManagerPrivate::setApplicationProgressValue(int value)
{
Q_UNUSED(value)
}
void Core::Internal::ProgressManagerPrivate::setApplicationProgressVisible(bool visible)
{
Q_UNUSED(visible)
}
#endif // __ITaskbarList2_INTERFACE_DEFINED__
|
/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include <QVariant>
#include <QMainWindow>
#include <QFont>
#include <QFontMetrics>
#include <QPixmap>
#include <QPainter>
#if QT_VERSION >= 0x050000
# include <QGuiApplication>
# include <QWindow>
# include <qpa/qplatformnativeinterface.h>
#endif
#include <QLabel>
#include <coreplugin/icore.h>
#include "progressmanager_p.h"
// for windows progress bar
#ifndef __GNUC__
# include <shobjidl.h>
#endif
// Windows 7 SDK required
#ifdef __ITaskbarList3_INTERFACE_DEFINED__
namespace {
int total = 0;
ITaskbarList3* pITask = 0;
}
#if QT_VERSION >= 0x050000
QT_BEGIN_NAMESPACE
Q_GUI_EXPORT HICON qt_pixmapToWinHICON(const QPixmap &p);
QT_END_NAMESPACE
static inline QWindow *windowOfWidget(const QWidget *widget)
{
if (QWindow *window = widget->windowHandle())
return window;
if (QWidget *topLevel = widget->nativeParentWidget())
return topLevel->windowHandle();
return 0;
}
static inline HWND hwndOfWidget(const QWidget *w)
{
void *result = 0;
if (QWindow *window = windowOfWidget(w))
result = QGuiApplication::platformNativeInterface()->nativeResourceForWindow("handle", window);
return static_cast<HWND>(result);
}
#else
static inline HWND hwndOfWidget(const QWidget *w)
{
return w->winId();
}
#endif
void Core::Internal::ProgressManagerPrivate::initInternal()
{
CoInitialize(NULL);
HRESULT hRes = CoCreateInstance(CLSID_TaskbarList,
NULL,CLSCTX_INPROC_SERVER,
IID_ITaskbarList3,(LPVOID*) &pITask);
if (FAILED(hRes))
{
pITask = 0;
CoUninitialize();
return;
}
pITask->HrInit();
return;
}
void Core::Internal::ProgressManagerPrivate::cleanup()
{
if (pITask) {
pITask->Release();
pITask = NULL;
CoUninitialize();
}
}
void Core::Internal::ProgressManagerPrivate::setApplicationLabel(const QString &text)
{
if (!pITask)
return;
const HWND winId = hwndOfWidget(Core::ICore::mainWindow());
if (text.isEmpty()) {
pITask->SetOverlayIcon(winId, NULL, NULL);
} else {
QPixmap pix = QPixmap(QLatin1String(":/projectexplorer/images/compile_error.png"));
QPainter p(&pix);
p.setPen(Qt::white);
QFont font = p.font();
font.setPointSize(font.pointSize()-2);
p.setFont(font);
p.drawText(QRect(QPoint(0,0), pix.size()), Qt::AlignHCenter|Qt::AlignCenter, text);
#if QT_VERSION >= 0x050000
const HICON icon = qt_pixmapToWinHICON(pix);
#else
const HICON icon = pix.toWinHICON();
#endif
pITask->SetOverlayIcon(winId, icon, (wchar_t*)text.utf16());
DestroyIcon(icon);
}
}
void Core::Internal::ProgressManagerPrivate::setApplicationProgressRange(int min, int max)
{
total = max-min;
}
void Core::Internal::ProgressManagerPrivate::setApplicationProgressValue(int value)
{
if (pITask) {
const HWND winId = hwndOfWidget(Core::ICore::mainWindow());
pITask->SetProgressValue(winId, value, total);
}
}
void Core::Internal::ProgressManagerPrivate::setApplicationProgressVisible(bool visible)
{
if (!pITask)
return;
const HWND winId = hwndOfWidget(Core::ICore::mainWindow());
if (visible)
pITask->SetProgressState(winId, TBPF_NORMAL);
else
pITask->SetProgressState(winId, TBPF_NOPROGRESS);
}
#else
void Core::Internal::ProgressManagerPrivate::initInternal()
{
}
void Core::Internal::ProgressManagerPrivate::cleanup()
{
}
void Core::Internal::ProgressManagerPrivate::setApplicationLabel(const QString &text)
{
Q_UNUSED(text)
}
void Core::Internal::ProgressManagerPrivate::setApplicationProgressRange(int min, int max)
{
Q_UNUSED(min)
Q_UNUSED(max)
}
void Core::Internal::ProgressManagerPrivate::setApplicationProgressValue(int value)
{
Q_UNUSED(value)
}
void Core::Internal::ProgressManagerPrivate::setApplicationProgressVisible(bool visible)
{
Q_UNUSED(visible)
}
#endif // __ITaskbarList2_INTERFACE_DEFINED__
|
fix build for namespaced Qt
|
fix build for namespaced Qt
Change-Id: Idd25bbea2c5adafbf893a10e107d4a8bfc2d221f
Reviewed-by: Friedemann Kleint <[email protected]>
|
C++
|
lgpl-2.1
|
amyvmiwei/qt-creator,Distrotech/qtcreator,omniacreator/qtcreator,omniacreator/qtcreator,duythanhphan/qt-creator,richardmg/qtcreator,maui-packages/qt-creator,amyvmiwei/qt-creator,xianian/qt-creator,darksylinc/qt-creator,duythanhphan/qt-creator,maui-packages/qt-creator,amyvmiwei/qt-creator,martyone/sailfish-qtcreator,martyone/sailfish-qtcreator,martyone/sailfish-qtcreator,danimo/qt-creator,richardmg/qtcreator,AltarBeastiful/qt-creator,kuba1/qtcreator,AltarBeastiful/qt-creator,malikcjm/qtcreator,farseerri/git_code,richardmg/qtcreator,danimo/qt-creator,amyvmiwei/qt-creator,omniacreator/qtcreator,richardmg/qtcreator,Distrotech/qtcreator,maui-packages/qt-creator,farseerri/git_code,danimo/qt-creator,danimo/qt-creator,danimo/qt-creator,amyvmiwei/qt-creator,richardmg/qtcreator,martyone/sailfish-qtcreator,darksylinc/qt-creator,darksylinc/qt-creator,xianian/qt-creator,richardmg/qtcreator,malikcjm/qtcreator,AltarBeastiful/qt-creator,kuba1/qtcreator,malikcjm/qtcreator,maui-packages/qt-creator,Distrotech/qtcreator,omniacreator/qtcreator,danimo/qt-creator,xianian/qt-creator,kuba1/qtcreator,maui-packages/qt-creator,duythanhphan/qt-creator,farseerri/git_code,farseerri/git_code,colede/qtcreator,Distrotech/qtcreator,kuba1/qtcreator,omniacreator/qtcreator,xianian/qt-creator,duythanhphan/qt-creator,colede/qtcreator,danimo/qt-creator,danimo/qt-creator,darksylinc/qt-creator,xianian/qt-creator,omniacreator/qtcreator,xianian/qt-creator,colede/qtcreator,farseerri/git_code,AltarBeastiful/qt-creator,darksylinc/qt-creator,malikcjm/qtcreator,maui-packages/qt-creator,colede/qtcreator,martyone/sailfish-qtcreator,malikcjm/qtcreator,darksylinc/qt-creator,kuba1/qtcreator,AltarBeastiful/qt-creator,colede/qtcreator,maui-packages/qt-creator,martyone/sailfish-qtcreator,kuba1/qtcreator,martyone/sailfish-qtcreator,omniacreator/qtcreator,richardmg/qtcreator,amyvmiwei/qt-creator,duythanhphan/qt-creator,amyvmiwei/qt-creator,Distrotech/qtcreator,xianian/qt-creator,farseerri/git_code,duythanhphan/qt-creator,martyone/sailfish-qtcreator,danimo/qt-creator,AltarBeastiful/qt-creator,xianian/qt-creator,farseerri/git_code,colede/qtcreator,Distrotech/qtcreator,malikcjm/qtcreator,darksylinc/qt-creator,darksylinc/qt-creator,farseerri/git_code,malikcjm/qtcreator,duythanhphan/qt-creator,kuba1/qtcreator,kuba1/qtcreator,colede/qtcreator,Distrotech/qtcreator,xianian/qt-creator,martyone/sailfish-qtcreator,kuba1/qtcreator,AltarBeastiful/qt-creator,amyvmiwei/qt-creator,AltarBeastiful/qt-creator
|
c128a15d70a75008b919fb7af05408c693191a85
|
src/RemoteCounter.cpp
|
src/RemoteCounter.cpp
|
/*
* (C) Copyright 2015 ETH Zurich Systems Group (http://www.systems.ethz.ch/) and others.
*
* 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.
*
* Contributors:
* Markus Pilman <[email protected]>
* Simon Loesing <[email protected]>
* Thomas Etter <[email protected]>
* Kevin Bocksrocker <[email protected]>
* Lucas Braun <[email protected]>
*/
#include "RemoteCounter.hpp"
namespace tell {
namespace db {
namespace {
const crossbow::string gCounterFieldName = crossbow::string("counter");
store::GenericTuple createCounterTuple(uint64_t counter) {
return store::GenericTuple({
std::make_pair(gCounterFieldName, static_cast<int64_t>(counter))
});
}
} // anonymous namespace
std::shared_ptr<store::Table> RemoteCounter::createTable(store::ClientHandle& handle, const crossbow::string& name) {
store::Schema schema(store::TableType::NON_TRANSACTIONAL);
schema.addField(store::FieldType::BIGINT, gCounterFieldName, true);
return std::make_shared<store::Table>(handle.createTable(name, std::move(schema)));
}
RemoteCounter::RemoteCounter(std::shared_ptr<store::Table> counterTable, uint64_t counterId)
: mCounterTable(std::move(counterTable)),
mCounterId(counterId),
mInit(false),
mCounter(0x0u),
mReserved(0x0u),
mNextCounter(0x0u) {
}
uint64_t RemoteCounter::incrementAndGet(store::ClientHandle& handle) {
if (mCounter == 0x0u && !mInit) {
mInit = true;
requestNewBatch(handle);
}
mFreshKeys.wait(handle.fiber(), [this] () {
return (mCounter != mReserved) || (mNextCounter != 0x0u);
});
if (mCounter == mReserved) {
LOG_ASSERT(mNextCounter != 0x0u, "Next counter must be non 0");
mCounter = mNextCounter;
mReserved = mNextCounter + RESERVED_BATCH;
mNextCounter = 0x0u;
}
auto key = ++mCounter;
if (mCounter + THRESHOLD == mReserved) {
requestNewBatch(handle);
}
return key;
}
uint64_t RemoteCounter::remoteValue(store::ClientHandle& handle) const {
auto getFuture = handle.get(*mCounterTable, mCounterId);
auto tuple = getFuture->get();
if (!tuple->found()) {
return 0x0u;
}
return static_cast<uint64_t>(mCounterTable->field<int64_t>(gCounterFieldName, tuple->data()));
}
void RemoteCounter::requestNewBatch(store::ClientHandle& handle) {
uint64_t nextCounter;
while (true) {
auto getFuture = handle.get(*mCounterTable, mCounterId);
auto tuple = getFuture->get();
std::shared_ptr<store::ModificationResponse> counterFuture;
if (tuple->found()) {
nextCounter = static_cast<uint64_t>(mCounterTable->field<int64_t>(gCounterFieldName, tuple->data()));
counterFuture = handle.update(*mCounterTable, mCounterId, tuple->version(),
createCounterTuple(nextCounter + RESERVED_BATCH));
} else {
nextCounter = 0x0u;
counterFuture = handle.insert(*mCounterTable, mCounterId, 0x0u, createCounterTuple(RESERVED_BATCH));
}
auto ec = counterFuture->error();
if (!ec) {
break;
}
if (ec != store::error::not_in_snapshot) {
throw std::system_error(ec);
}
}
if (mCounter == mReserved) {
mCounter = nextCounter;
mReserved = nextCounter + RESERVED_BATCH;
} else {
mNextCounter = nextCounter;
}
mFreshKeys.notify_all();
}
} // namespace db
} // namespace tell
|
/*
* (C) Copyright 2015 ETH Zurich Systems Group (http://www.systems.ethz.ch/) and others.
*
* 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.
*
* Contributors:
* Markus Pilman <[email protected]>
* Simon Loesing <[email protected]>
* Thomas Etter <[email protected]>
* Kevin Bocksrocker <[email protected]>
* Lucas Braun <[email protected]>
*/
#include "RemoteCounter.hpp"
namespace tell {
namespace db {
namespace {
const crossbow::string gCounterFieldName = crossbow::string("counter");
store::GenericTuple createCounterTuple(uint64_t counter) {
return store::GenericTuple({
std::make_pair(gCounterFieldName, static_cast<int64_t>(counter))
});
}
} // anonymous namespace
std::shared_ptr<store::Table> RemoteCounter::createTable(store::ClientHandle& handle, const crossbow::string& name) {
store::Schema schema(store::TableType::NON_TRANSACTIONAL);
schema.addField(store::FieldType::BIGINT, gCounterFieldName, true);
return std::make_shared<store::Table>(handle.createTable(name, std::move(schema)));
}
RemoteCounter::RemoteCounter(std::shared_ptr<store::Table> counterTable, uint64_t counterId)
: mCounterTable(std::move(counterTable)),
mCounterId(counterId),
mInit(false),
mCounter(0x0u),
mReserved(0x0u),
mNextCounter(0x0u) {
}
uint64_t RemoteCounter::incrementAndGet(store::ClientHandle& handle) {
if (mCounter == 0x0u && !mInit) {
mInit = true;
requestNewBatch(handle);
}
mFreshKeys.wait(handle.fiber(), [this] () {
return (mCounter != mReserved) || (mNextCounter != 0x0u);
});
if (mCounter == mReserved) {
LOG_ASSERT(mNextCounter != 0x0u, "Next counter must be non 0");
mCounter = mNextCounter;
mReserved = mNextCounter + RESERVED_BATCH;
mNextCounter = 0x0u;
}
auto key = ++mCounter;
if (mCounter + THRESHOLD == mReserved) {
requestNewBatch(handle);
}
return key;
}
uint64_t RemoteCounter::remoteValue(store::ClientHandle& handle) const {
auto getFuture = handle.get(*mCounterTable, mCounterId);
auto tuple = getFuture->get();
if (!tuple->found()) {
return 0x0u;
}
return static_cast<uint64_t>(mCounterTable->field<int64_t>(gCounterFieldName, tuple->data()));
}
void RemoteCounter::requestNewBatch(store::ClientHandle& handle) {
uint64_t nextCounter;
while (true) {
auto getFuture = handle.get(*mCounterTable, mCounterId);
std::shared_ptr<store::ModificationResponse> counterFuture;
if (getFuture->waitForResult()) {
auto tuple = getFuture->get();
nextCounter = static_cast<uint64_t>(mCounterTable->field<int64_t>(gCounterFieldName, tuple->data()));
counterFuture = handle.update(*mCounterTable, mCounterId, tuple->version(),
createCounterTuple(nextCounter + RESERVED_BATCH));
} else if (getFuture->error() == store::error::not_found) {
nextCounter = 0x0u;
counterFuture = handle.insert(*mCounterTable, mCounterId, 0x0u, createCounterTuple(RESERVED_BATCH));
} else {
throw std::system_error(getFuture->error());
}
if (counterFuture->waitForResult()) {
break;
} else if (counterFuture->error() != store::error::not_in_snapshot) {
throw std::system_error(counterFuture->error());
}
}
if (mCounter == mReserved) {
mCounter = nextCounter;
mReserved = nextCounter + RESERVED_BATCH;
} else {
mNextCounter = nextCounter;
}
mFreshKeys.notify_all();
}
} // namespace db
} // namespace tell
|
Fix RemoteCounter not handling tuple not found errors
|
Fix RemoteCounter not handling tuple not found errors
|
C++
|
apache-2.0
|
tellproject/telldb
|
e523b6b1af47e9a80161ecd9cf4ab713ea7fe2ac
|
photoeffects/test/tint_test.cpp
|
photoeffects/test/tint_test.cpp
|
#include "photoeffects.hpp"
#include "test_utils.hpp"
#include <gtest/gtest.h>
using namespace cv;
TEST(photoeffects, TintTest) {
Mat src(10, 10, CV_8UC3), dst;
Vec3b color;
EXPECT_EQ(0, tint(src, dst, color, 0.0f));
}
TEST(photoeffects, TintWrongImage)
{
Mat src(10, 10, CV_8UC2), dst;
Vec3b color;
EXPECT_ERROR(CV_StsAssert, tint(src, dst, color, 0.5f));
}
TEST(photoeffects, TintWrongDensity)
{
Mat src(10, 10, CV_8UC3), dst;
Vec3b color;
EXPECT_ERROR(CV_StsAssert, tint(src, dst, color, 15.0f));
EXPECT_ERROR(CV_StsAssert, tint(src, dst, color, -1.0f));
}
TEST(photoeffects, TintTestOutputImage)
{
Mat src(256, 256, CV_8UC3), dstOrigin(256, 256, CV_8UC3), dstFromAlg;
Vec3b color(255, 0, 255);
float den = 0.2f;
float negDen = 1 - den;
for (int i = 0; i < 256; i++)
{
for (int j = 0; j < 256; j++)
{
src.at<Vec3b>(i, j) = Vec3b(i, j, 0);
dstOrigin.at<Vec3b>(i, j) = color * den + Vec3b(i, j, 0) * negDen;
}
}
tint(src, dstFromAlg, color, den);
Mat diff = abs(dstOrigin - dstFromAlg);
Mat mask = diff.reshape(1) > 1;
EXPECT_EQ(0, countNonZero(mask));
}
|
#include "photoeffects.hpp"
#include "test_utils.hpp"
#include <gtest/gtest.h>
using namespace cv;
TEST(photoeffects, TintTest) {
Mat src(10, 10, CV_8UC3), dst;
Vec3b color;
EXPECT_EQ(0, tint(src, dst, color, 0.0f));
}
TEST(photoeffects, TintWrongImage)
{
Mat src(10, 10, CV_8UC2), dst;
Vec3b color;
EXPECT_ERROR(CV_StsAssert, tint(src, dst, color, 0.5f));
}
TEST(photoeffects, TintWrongDensity)
{
Mat src(10, 10, CV_8UC3), dst;
Vec3b color;
EXPECT_ERROR(CV_StsAssert, tint(src, dst, color, 15.0f));
EXPECT_ERROR(CV_StsAssert, tint(src, dst, color, -1.0f));
}
TEST(photoeffects, TintTestOutputImage)
{
Mat src(256, 256, CV_8UC3), dstOrigin(256, 256, CV_8UC3), dstFromAlg;
Vec3b color(255, 0, 255);
float den = 0.2f;
float negDen = 1 - den;
for (int i = 0; i < 256; i++)
{
for (int j = 0; j < 256; j++)
{
src.at<Vec3b>(i, j) = Vec3b(i, j, 0);
dstOrigin.at<Vec3b>(i, j) = color * den + Vec3b(i, j, 0) * negDen;
}
}
tint(src, dstFromAlg, color, den);
Mat diff = abs(dstOrigin - dstFromAlg);
Mat mask = diff.reshape(1) > 1;
EXPECT_EQ(0, countNonZero(mask));
}
|
Resolve conflicts
|
Resolve conflicts
|
C++
|
bsd-3-clause
|
ITLab-Vision/itlab-vision,ITLab-Vision/itlab-vision
|
eabfeae578a6747293cf933e97f9ff4fdadc8b05
|
src/WallToolPaths.cpp
|
src/WallToolPaths.cpp
|
// Copyright (c) 2020 Ultimaker B.V.
// CuraEngine is released under the terms of the AGPLv3 or higher.
#include <algorithm> //For std::partition_copy and std::min_element.
#include <unordered_set>
#include "WallToolPaths.h"
#include "SkeletalTrapezoidation.h"
#include "utils/SparsePointGrid.h" //To stitch the inner contour.
#include "utils/polygonUtils.h"
#include "ExtruderTrain.h"
#include "utils/PolylineStitcher.h"
namespace cura
{
WallToolPaths::WallToolPaths(const Polygons& outline, const coord_t nominal_bead_width, const size_t inset_count, const coord_t wall_0_inset,
const Settings& settings)
: outline(outline)
, bead_width_0(nominal_bead_width)
, bead_width_x(nominal_bead_width)
, inset_count(inset_count)
, wall_0_inset(wall_0_inset)
, strategy_type(settings.get<StrategyType>("beading_strategy_type"))
, print_thin_walls(settings.get<bool>("fill_outline_gaps"))
, min_feature_size(settings.get<coord_t>("min_feature_size"))
, min_bead_width(settings.get<coord_t>("min_bead_width"))
, small_area_length(INT2MM(static_cast<double>(nominal_bead_width) / 2))
, toolpaths_generated(false)
, settings(settings)
{
}
WallToolPaths::WallToolPaths(const Polygons& outline, const coord_t bead_width_0, const coord_t bead_width_x,
const size_t inset_count, const coord_t wall_0_inset, const Settings& settings)
: outline(outline)
, bead_width_0(bead_width_0)
, bead_width_x(bead_width_x)
, inset_count(inset_count)
, wall_0_inset(wall_0_inset)
, strategy_type(settings.get<StrategyType>("beading_strategy_type"))
, print_thin_walls(settings.get<bool>("fill_outline_gaps"))
, min_feature_size(settings.get<coord_t>("min_feature_size"))
, min_bead_width(settings.get<coord_t>("min_bead_width"))
, small_area_length(INT2MM(static_cast<double>(bead_width_0) / 2))
, toolpaths_generated(false)
, settings(settings)
{
}
const VariableWidthPaths& WallToolPaths::generate()
{
const coord_t smallest_segment = settings.get<coord_t>("meshfix_maximum_resolution");
const coord_t allowed_distance = settings.get<coord_t>("meshfix_maximum_deviation");
const coord_t epsilon_offset = (allowed_distance / 2) - 1;
const AngleRadians transitioning_angle = settings.get<AngleRadians>("wall_transition_angle");
constexpr coord_t discretization_step_size = MM2INT(0.8);
// Simplify outline for boost::voronoi consumption. Absolutely no self intersections or near-self intersections allowed:
// TODO: Open question: Does this indeed fix all (or all-but-one-in-a-million) cases for manifold but otherwise possibly complex polygons?
Polygons prepared_outline = outline.offset(-epsilon_offset).offset(epsilon_offset * 2).offset(-epsilon_offset);
prepared_outline.simplify(smallest_segment, allowed_distance);
PolygonUtils::fixSelfIntersections(epsilon_offset, prepared_outline);
prepared_outline.removeDegenerateVerts();
prepared_outline.removeColinearEdges(AngleRadians(0.005));
// Removing collinear edges may introduce self intersections, so we need to fix them again
PolygonUtils::fixSelfIntersections(epsilon_offset, prepared_outline);
prepared_outline.removeDegenerateVerts();
prepared_outline.removeSmallAreas(small_area_length * small_area_length, false);
if (prepared_outline.area() <= 0)
{
assert(toolpaths.empty());
return toolpaths;
}
const coord_t wall_transition_length = settings.get<coord_t>("wall_transition_length");
const Ratio wall_split_middle_threshold = settings.get<Ratio>("wall_split_middle_threshold"); // For an uneven nr. of lines: When to split the middle wall into two.
const Ratio wall_add_middle_threshold = settings.get<Ratio>("wall_add_middle_threshold"); // For an even nr. of lines: When to add a new middle in between the innermost two walls.
const int wall_distribution_count = settings.get<int>("wall_distribution_count");
const size_t max_bead_count = (inset_count < std::numeric_limits<coord_t>::max() / 2) ? 2 * inset_count : std::numeric_limits<coord_t>::max();
const auto beading_strat = BeadingStrategyFactory::makeStrategy
(
strategy_type,
bead_width_0,
bead_width_x,
wall_transition_length,
transitioning_angle,
print_thin_walls,
min_bead_width,
min_feature_size,
wall_split_middle_threshold,
wall_add_middle_threshold,
max_bead_count,
wall_0_inset,
wall_distribution_count
);
const coord_t transition_filter_dist = settings.get<coord_t>("wall_transition_filter_distance");
SkeletalTrapezoidation wall_maker
(
prepared_outline,
*beading_strat,
beading_strat->getTransitioningAngle(),
discretization_step_size,
transition_filter_dist,
wall_transition_length
);
wall_maker.generateToolpaths(toolpaths);
stitchToolPaths(toolpaths, settings);
removeSmallLines(toolpaths);
separateOutInnerContour();
simplifyToolPaths(toolpaths, settings);
removeEmptyToolPaths(toolpaths);
assert(std::is_sorted(toolpaths.cbegin(), toolpaths.cend(),
[](const VariableWidthLines& l, const VariableWidthLines& r)
{
return l.front().inset_idx < r.front().inset_idx;
}) && "WallToolPaths should be sorted from the outer 0th to inner_walls");
toolpaths_generated = true;
return toolpaths;
}
void WallToolPaths::stitchToolPaths(VariableWidthPaths& toolpaths, const Settings& settings)
{
const coord_t stitch_distance = settings.get<coord_t>("wall_line_width_x") / 4;
for (unsigned int wall_idx = 0; wall_idx < toolpaths.size(); wall_idx++)
{
VariableWidthLines& wall_lines = toolpaths[wall_idx];
VariableWidthLines stitched_polylines;
VariableWidthLines closed_polygons;
PolylineStitcher<VariableWidthLines, ExtrusionLine, ExtrusionJunction>::stitch(wall_lines, stitched_polylines, closed_polygons, stitch_distance);
#ifdef DEBUG
for (const ExtrusionLine& line : stitched_polylines)
{
if ( ! line.is_odd &&
line.polylineLength() > 3 * stitch_distance && line.size() > 3)
{
logError("Some even contour lines could not be closed into polygons!\n");
AABB aabb;
for (auto line2 : wall_lines)
for (auto j : line2)
aabb.include(j.p);
{
SVG svg("/tmp/contours_before.svg", aabb);
SVG::Color col = SVG::Color::GRAY;
for (auto& inset : toolpaths)
for (auto& line2 : inset)
{
// svg.writePolyline(line2.toPolygon(), col);
Polygon poly = line2.toPolygon();
Point last = poly.front();
for (size_t idx = 1 ; idx < poly.size(); idx++)
{
Point here = poly[idx];
svg.writeLine(last, here, col);
svg.writeText((last + here) / 2, std::to_string(line2.junctions[idx].region_id), SVG::Color::BLACK, 2.0);
last = here;
}
svg.writePoint(poly[0], false, 2.0, col);
svg.nextLayer();
// svg.writePoints(poly, true, 0.1);
// svg.nextLayer();
col = SVG::Color((int(col) + 1) % int(SVG::Color::NONE));
}
}
{
SVG svg("/tmp/contours.svg", aabb);
for (auto& inset : toolpaths)
for (auto& line2 : inset)
svg.writePolyline(line2.toPolygon(), SVG::Color::GRAY);
for (auto& line2 : stitched_polylines)
{
SVG::Color col = line2.is_odd ? SVG::Color::GRAY : SVG::Color::RED;
if ( ! line2.is_odd) std::cerr << "Non-closed even wall of size: " << line2.size() << " at " << line2.front().p << "\n";
if ( ! line2.is_odd) svg.writePoint(line2.front().p, true, 1.0);
Polygon poly = line2.toPolygon();
Point last = poly.front();
for (size_t idx = 1 ; idx < poly.size(); idx++)
{
Point here = poly[idx];
svg.writeLine(last, here, col);
last = here;
}
}
for (auto line2 : closed_polygons)
svg.writePolygon(line2.toPolygon());
}
}
}
#endif // DEBUG
wall_lines = stitched_polylines; // replace input toolpaths with stitched polylines
for (ExtrusionLine& wall_polygon : closed_polygons)
{
if (wall_polygon.junctions.empty())
{
continue;
}
wall_polygon.is_closed = true;
wall_lines.emplace_back(std::move(wall_polygon)); // add stitched polygons to result
}
#ifdef DEBUG
for (ExtrusionLine& line : wall_lines)
{
assert(line.inset_idx == wall_idx);
}
#endif // DEBUG
}
}
void WallToolPaths::removeSmallLines(VariableWidthPaths& toolpaths)
{
for (VariableWidthLines& inset : toolpaths)
{
for (size_t line_idx = 0; line_idx < inset.size(); line_idx++)
{
ExtrusionLine& line = inset[line_idx];
coord_t min_width = std::numeric_limits<coord_t>::max();
for (const ExtrusionJunction& j : line)
{
min_width = std::min(min_width, j.w);
}
if (line.is_odd && ! line.is_closed && shorterThan(line, min_width / 2))
{ // remove line
line = std::move(inset.back());
inset.erase(--inset.end());
line_idx--; // reconsider the current position
}
}
}
}
void WallToolPaths::simplifyToolPaths(VariableWidthPaths& toolpaths, const Settings& settings)
{
for (size_t toolpaths_idx = 0; toolpaths_idx < toolpaths.size(); ++toolpaths_idx)
{
const coord_t maximum_resolution = settings.get<coord_t>("meshfix_maximum_resolution");
const coord_t maximum_deviation = settings.get<coord_t>("meshfix_maximum_deviation");
const coord_t maximum_extrusion_area_deviation = settings.get<int>("meshfix_maximum_extrusion_area_deviation"); // unit: μm²
for (auto& line : toolpaths[toolpaths_idx])
{
line.simplify(maximum_resolution * maximum_resolution, maximum_deviation * maximum_deviation, maximum_extrusion_area_deviation);
}
}
}
const VariableWidthPaths& WallToolPaths::getToolPaths()
{
if (!toolpaths_generated)
{
return generate();
}
return toolpaths;
}
void WallToolPaths::pushToolPaths(VariableWidthPaths& paths)
{
if (! toolpaths_generated)
{
generate();
}
paths.insert(paths.end(), toolpaths.begin(), toolpaths.end());
}
void WallToolPaths::separateOutInnerContour()
{
//We'll remove all 0-width paths from the original toolpaths and store them separately as polygons.
VariableWidthPaths actual_toolpaths;
actual_toolpaths.reserve(toolpaths.size()); //A bit too much, but the correct order of magnitude.
VariableWidthPaths contour_paths;
contour_paths.reserve(toolpaths.size() / inset_count);
inner_contour.clear();
for (const VariableWidthLines& inset : toolpaths)
{
if (inset.empty()) continue;
bool is_contour = false;
for (const ExtrusionLine& line : inset)
{
for (const ExtrusionJunction& j : line)
{
if (j.w == 0)
{
is_contour = true;
}
else
{
is_contour = false;
}
break;
}
}
if (is_contour)
{
#ifdef DEBUG
for (const ExtrusionLine& line : inset)
for (const ExtrusionJunction& j : line)
assert(j.w == 0);
#endif // DEBUG
for (const ExtrusionLine& line : inset)
{
if (line.is_odd)
{
continue; // odd lines don't contribute to the contour
}
else if (line.is_closed) // sometimes an very small even polygonal wall is not stitched into a polygon
{
inner_contour.emplace_back(line.toPolygon());
}
}
}
else
{
actual_toolpaths.emplace_back(inset);
}
}
if (! actual_toolpaths.empty())
{
toolpaths = std::move(actual_toolpaths); //Filtered out the 0-width paths.
}
else
{
toolpaths.clear();
}
//The output walls from the skeletal trapezoidation have no known winding order, especially if they are joined together from polylines.
//They can be in any direction, clockwise or counter-clockwise, regardless of whether the shapes are positive or negative.
//To get a correct shape, we need to make the outside contour positive and any holes inside negative.
//This can be done by applying the even-odd rule to the shape. This rule is not sensitive to the winding order of the polygon.
//The even-odd rule would be incorrect if the polygon self-intersects, but that should never be generated by the skeletal trapezoidation.
inner_contour = inner_contour.processEvenOdd();
}
const Polygons& WallToolPaths::getInnerContour()
{
if (!toolpaths_generated && inset_count > 0)
{
generate();
}
else if(inset_count == 0)
{
return outline;
}
return inner_contour;
}
bool WallToolPaths::removeEmptyToolPaths(VariableWidthPaths& toolpaths)
{
toolpaths.erase(std::remove_if(toolpaths.begin(), toolpaths.end(), [](const VariableWidthLines& lines)
{
return lines.empty();
}), toolpaths.end());
return toolpaths.empty();
}
} // namespace cura
|
// Copyright (c) 2020 Ultimaker B.V.
// CuraEngine is released under the terms of the AGPLv3 or higher.
#include <algorithm> //For std::partition_copy and std::min_element.
#include <unordered_set>
#include "WallToolPaths.h"
#include "SkeletalTrapezoidation.h"
#include "utils/SparsePointGrid.h" //To stitch the inner contour.
#include "utils/polygonUtils.h"
#include "ExtruderTrain.h"
#include "utils/PolylineStitcher.h"
namespace cura
{
WallToolPaths::WallToolPaths(const Polygons& outline, const coord_t nominal_bead_width, const size_t inset_count, const coord_t wall_0_inset,
const Settings& settings)
: outline(outline)
, bead_width_0(nominal_bead_width)
, bead_width_x(nominal_bead_width)
, inset_count(inset_count)
, wall_0_inset(wall_0_inset)
, strategy_type(settings.get<StrategyType>("beading_strategy_type"))
, print_thin_walls(settings.get<bool>("fill_outline_gaps"))
, min_feature_size(settings.get<coord_t>("min_feature_size"))
, min_bead_width(settings.get<coord_t>("min_bead_width"))
, small_area_length(INT2MM(static_cast<double>(nominal_bead_width) / 2))
, toolpaths_generated(false)
, settings(settings)
{
}
WallToolPaths::WallToolPaths(const Polygons& outline, const coord_t bead_width_0, const coord_t bead_width_x,
const size_t inset_count, const coord_t wall_0_inset, const Settings& settings)
: outline(outline)
, bead_width_0(bead_width_0)
, bead_width_x(bead_width_x)
, inset_count(inset_count)
, wall_0_inset(wall_0_inset)
, strategy_type(settings.get<StrategyType>("beading_strategy_type"))
, print_thin_walls(settings.get<bool>("fill_outline_gaps"))
, min_feature_size(settings.get<coord_t>("min_feature_size"))
, min_bead_width(settings.get<coord_t>("min_bead_width"))
, small_area_length(INT2MM(static_cast<double>(bead_width_0) / 2))
, toolpaths_generated(false)
, settings(settings)
{
}
const VariableWidthPaths& WallToolPaths::generate()
{
const coord_t smallest_segment = settings.get<coord_t>("meshfix_maximum_resolution");
const coord_t allowed_distance = settings.get<coord_t>("meshfix_maximum_deviation");
const coord_t epsilon_offset = (allowed_distance / 2) - 1;
const AngleRadians transitioning_angle = settings.get<AngleRadians>("wall_transition_angle");
constexpr coord_t discretization_step_size = MM2INT(0.8);
// Simplify outline for boost::voronoi consumption. Absolutely no self intersections or near-self intersections allowed:
// TODO: Open question: Does this indeed fix all (or all-but-one-in-a-million) cases for manifold but otherwise possibly complex polygons?
Polygons prepared_outline = outline.offset(-epsilon_offset).offset(epsilon_offset * 2).offset(-epsilon_offset);
prepared_outline.simplify(smallest_segment, allowed_distance);
PolygonUtils::fixSelfIntersections(epsilon_offset, prepared_outline);
prepared_outline.removeDegenerateVerts();
prepared_outline.removeColinearEdges(AngleRadians(0.005));
// Removing collinear edges may introduce self intersections, so we need to fix them again
PolygonUtils::fixSelfIntersections(epsilon_offset, prepared_outline);
prepared_outline.removeDegenerateVerts();
prepared_outline.removeSmallAreas(small_area_length * small_area_length, false);
if (prepared_outline.area() <= 0)
{
assert(toolpaths.empty());
return toolpaths;
}
const coord_t wall_transition_length = settings.get<coord_t>("wall_transition_length");
const Ratio wall_split_middle_threshold = settings.get<Ratio>("wall_split_middle_threshold"); // For an uneven nr. of lines: When to split the middle wall into two.
const Ratio wall_add_middle_threshold = settings.get<Ratio>("wall_add_middle_threshold"); // For an even nr. of lines: When to add a new middle in between the innermost two walls.
const int wall_distribution_count = settings.get<int>("wall_distribution_count");
const size_t max_bead_count = (inset_count < std::numeric_limits<coord_t>::max() / 2) ? 2 * inset_count : std::numeric_limits<coord_t>::max();
const auto beading_strat = BeadingStrategyFactory::makeStrategy
(
strategy_type,
bead_width_0,
bead_width_x,
wall_transition_length,
transitioning_angle,
print_thin_walls,
min_bead_width,
min_feature_size,
wall_split_middle_threshold,
wall_add_middle_threshold,
max_bead_count,
wall_0_inset,
wall_distribution_count
);
const coord_t transition_filter_dist = settings.get<coord_t>("wall_transition_filter_distance");
SkeletalTrapezoidation wall_maker
(
prepared_outline,
*beading_strat,
beading_strat->getTransitioningAngle(),
discretization_step_size,
transition_filter_dist,
wall_transition_length
);
wall_maker.generateToolpaths(toolpaths);
stitchToolPaths(toolpaths, settings);
removeSmallLines(toolpaths);
separateOutInnerContour();
simplifyToolPaths(toolpaths, settings);
removeEmptyToolPaths(toolpaths);
assert(std::is_sorted(toolpaths.cbegin(), toolpaths.cend(),
[](const VariableWidthLines& l, const VariableWidthLines& r)
{
return l.front().inset_idx < r.front().inset_idx;
}) && "WallToolPaths should be sorted from the outer 0th to inner_walls");
toolpaths_generated = true;
return toolpaths;
}
void WallToolPaths::stitchToolPaths(VariableWidthPaths& toolpaths, const Settings& settings)
{
const coord_t stitch_distance = settings.get<coord_t>("wall_line_width_x") / 4;
for (unsigned int wall_idx = 0; wall_idx < toolpaths.size(); wall_idx++)
{
VariableWidthLines& wall_lines = toolpaths[wall_idx];
VariableWidthLines stitched_polylines;
VariableWidthLines closed_polygons;
PolylineStitcher<VariableWidthLines, ExtrusionLine, ExtrusionJunction>::stitch(wall_lines, stitched_polylines, closed_polygons, stitch_distance);
#ifdef DEBUG
for (const ExtrusionLine& line : stitched_polylines)
{
if ( ! line.is_odd &&
line.polylineLength() > 3 * stitch_distance && line.size() > 3)
{
logError("Some even contour lines could not be closed into polygons!\n");
assert(false && "Some even contour lines could not be closed into polygons!");
// NOTE: if this assertion fails then revert the debugging code removed in this commit (git blame on this line)
}
}
#endif // DEBUG
wall_lines = stitched_polylines; // replace input toolpaths with stitched polylines
for (ExtrusionLine& wall_polygon : closed_polygons)
{
if (wall_polygon.junctions.empty())
{
continue;
}
wall_polygon.is_closed = true;
wall_lines.emplace_back(std::move(wall_polygon)); // add stitched polygons to result
}
#ifdef DEBUG
for (ExtrusionLine& line : wall_lines)
{
assert(line.inset_idx == wall_idx);
}
#endif // DEBUG
}
}
void WallToolPaths::removeSmallLines(VariableWidthPaths& toolpaths)
{
for (VariableWidthLines& inset : toolpaths)
{
for (size_t line_idx = 0; line_idx < inset.size(); line_idx++)
{
ExtrusionLine& line = inset[line_idx];
coord_t min_width = std::numeric_limits<coord_t>::max();
for (const ExtrusionJunction& j : line)
{
min_width = std::min(min_width, j.w);
}
if (line.is_odd && ! line.is_closed && shorterThan(line, min_width / 2))
{ // remove line
line = std::move(inset.back());
inset.erase(--inset.end());
line_idx--; // reconsider the current position
}
}
}
}
void WallToolPaths::simplifyToolPaths(VariableWidthPaths& toolpaths, const Settings& settings)
{
for (size_t toolpaths_idx = 0; toolpaths_idx < toolpaths.size(); ++toolpaths_idx)
{
const coord_t maximum_resolution = settings.get<coord_t>("meshfix_maximum_resolution");
const coord_t maximum_deviation = settings.get<coord_t>("meshfix_maximum_deviation");
const coord_t maximum_extrusion_area_deviation = settings.get<int>("meshfix_maximum_extrusion_area_deviation"); // unit: μm²
for (auto& line : toolpaths[toolpaths_idx])
{
line.simplify(maximum_resolution * maximum_resolution, maximum_deviation * maximum_deviation, maximum_extrusion_area_deviation);
}
}
}
const VariableWidthPaths& WallToolPaths::getToolPaths()
{
if (!toolpaths_generated)
{
return generate();
}
return toolpaths;
}
void WallToolPaths::pushToolPaths(VariableWidthPaths& paths)
{
if (! toolpaths_generated)
{
generate();
}
paths.insert(paths.end(), toolpaths.begin(), toolpaths.end());
}
void WallToolPaths::separateOutInnerContour()
{
//We'll remove all 0-width paths from the original toolpaths and store them separately as polygons.
VariableWidthPaths actual_toolpaths;
actual_toolpaths.reserve(toolpaths.size()); //A bit too much, but the correct order of magnitude.
VariableWidthPaths contour_paths;
contour_paths.reserve(toolpaths.size() / inset_count);
inner_contour.clear();
for (const VariableWidthLines& inset : toolpaths)
{
if (inset.empty()) continue;
bool is_contour = false;
for (const ExtrusionLine& line : inset)
{
for (const ExtrusionJunction& j : line)
{
if (j.w == 0)
{
is_contour = true;
}
else
{
is_contour = false;
}
break;
}
}
if (is_contour)
{
#ifdef DEBUG
for (const ExtrusionLine& line : inset)
for (const ExtrusionJunction& j : line)
assert(j.w == 0);
#endif // DEBUG
for (const ExtrusionLine& line : inset)
{
if (line.is_odd)
{
continue; // odd lines don't contribute to the contour
}
else if (line.is_closed) // sometimes an very small even polygonal wall is not stitched into a polygon
{
inner_contour.emplace_back(line.toPolygon());
}
}
}
else
{
actual_toolpaths.emplace_back(inset);
}
}
if (! actual_toolpaths.empty())
{
toolpaths = std::move(actual_toolpaths); //Filtered out the 0-width paths.
}
else
{
toolpaths.clear();
}
//The output walls from the skeletal trapezoidation have no known winding order, especially if they are joined together from polylines.
//They can be in any direction, clockwise or counter-clockwise, regardless of whether the shapes are positive or negative.
//To get a correct shape, we need to make the outside contour positive and any holes inside negative.
//This can be done by applying the even-odd rule to the shape. This rule is not sensitive to the winding order of the polygon.
//The even-odd rule would be incorrect if the polygon self-intersects, but that should never be generated by the skeletal trapezoidation.
inner_contour = inner_contour.processEvenOdd();
}
const Polygons& WallToolPaths::getInnerContour()
{
if (!toolpaths_generated && inset_count > 0)
{
generate();
}
else if(inset_count == 0)
{
return outline;
}
return inner_contour;
}
bool WallToolPaths::removeEmptyToolPaths(VariableWidthPaths& toolpaths)
{
toolpaths.erase(std::remove_if(toolpaths.begin(), toolpaths.end(), [](const VariableWidthLines& lines)
{
return lines.empty();
}), toolpaths.end());
return toolpaths.empty();
}
} // namespace cura
|
remove debugging code
|
remove debugging code
|
C++
|
agpl-3.0
|
Ultimaker/CuraEngine,Ultimaker/CuraEngine
|
0998c93941f07bc7845d13b3a5977cc5ca60ee18
|
src/WallToolPaths.cpp
|
src/WallToolPaths.cpp
|
// Copyright (c) 2020 Ultimaker B.V.
// CuraEngine is released under the terms of the AGPLv3 or higher.
#include <algorithm> //For std::partition_copy and std::min_element.
#include <unordered_set>
#include "WallToolPaths.h"
#include "SkeletalTrapezoidation.h"
#include "BeadingStrategy/BeadingOrderOptimizer.h"
#include "utils/SparsePointGrid.h" //To stitch the inner contour.
#include "utils/polygonUtils.h"
#include "ExtruderTrain.h"
namespace cura
{
WallToolPaths::WallToolPaths(const Polygons& outline, const coord_t nominal_bead_width, const size_t inset_count, const coord_t wall_0_inset,
const Settings& settings)
: outline(outline)
, bead_width_0(nominal_bead_width)
, bead_width_x(nominal_bead_width)
, inset_count(inset_count)
, wall_0_inset(wall_0_inset)
, strategy_type(settings.get<StrategyType>("beading_strategy_type"))
, print_thin_walls(settings.get<bool>("fill_outline_gaps"))
, min_feature_size(settings.get<coord_t>("min_feature_size"))
, min_bead_width(settings.get<coord_t>("min_bead_width"))
, small_area_length(INT2MM(static_cast<double>(nominal_bead_width) / 2))
, toolpaths_generated(false)
, settings(settings)
{
}
WallToolPaths::WallToolPaths(const Polygons& outline, const coord_t bead_width_0, const coord_t bead_width_x,
const size_t inset_count, const coord_t wall_0_inset, const Settings& settings)
: outline(outline)
, bead_width_0(bead_width_0)
, bead_width_x(bead_width_x)
, inset_count(inset_count)
, wall_0_inset(wall_0_inset)
, strategy_type(settings.get<StrategyType>("beading_strategy_type"))
, print_thin_walls(settings.get<bool>("fill_outline_gaps"))
, min_feature_size(settings.get<coord_t>("min_feature_size"))
, min_bead_width(settings.get<coord_t>("min_bead_width"))
, small_area_length(INT2MM(static_cast<double>(bead_width_0) / 2))
, toolpaths_generated(false)
, settings(settings)
{
}
const VariableWidthPaths& WallToolPaths::generate()
{
const coord_t smallest_segment = settings.get<coord_t>("meshfix_maximum_resolution");
const coord_t allowed_distance = settings.get<coord_t>("meshfix_maximum_deviation");
const coord_t epsilon_offset = (allowed_distance / 2) - 1;
const AngleRadians transitioning_angle = settings.get<AngleRadians>("wall_transition_angle");
constexpr coord_t discretization_step_size = MM2INT(0.8);
// Simplify outline for boost::voronoi consumption. Absolutely no self intersections or near-self intersections allowed:
// TODO: Open question: Does this indeed fix all (or all-but-one-in-a-million) cases for manifold but otherwise possibly complex polygons?
Polygons prepared_outline = outline.offset(-epsilon_offset).offset(epsilon_offset);
prepared_outline.simplify(smallest_segment, allowed_distance);
PolygonUtils::fixSelfIntersections(epsilon_offset, prepared_outline);
prepared_outline.removeDegenerateVerts();
prepared_outline.removeColinearEdges();
prepared_outline.removeSmallAreas(small_area_length * small_area_length, false);
if (prepared_outline.area() > 0)
{
const coord_t wall_transition_length = settings.get<coord_t>("wall_transition_length");
const Ratio wall_transition_threshold = settings.get<Ratio>("wall_transition_threshold");
const size_t max_bead_count = 2 * inset_count;
const auto beading_strat = std::unique_ptr<BeadingStrategy>(BeadingStrategyFactory::makeStrategy(
strategy_type, bead_width_0, bead_width_x, wall_transition_length, transitioning_angle, print_thin_walls, min_bead_width,
min_feature_size, wall_transition_threshold, max_bead_count, wall_0_inset));
const coord_t transition_filter_dist = settings.get<coord_t>("wall_transition_filter_distance");
SkeletalTrapezoidation wall_maker(prepared_outline, *beading_strat, beading_strat->transitioning_angle, discretization_step_size, transition_filter_dist, wall_transition_length);
wall_maker.generateToolpaths(toolpaths);
computeInnerContour();
}
simplifyToolPaths(toolpaths, settings);
removeEmptyToolPaths(toolpaths);
assert(std::is_sorted(toolpaths.cbegin(), toolpaths.cend(),
[](const VariableWidthLines& l, const VariableWidthLines& r)
{
return l.front().inset_idx < r.front().inset_idx;
}) && "WallToolPaths should be sorted from the outer 0th to inner_walls");
toolpaths_generated = true;
return toolpaths;
}
void WallToolPaths::simplifyToolPaths(VariableWidthPaths& toolpaths, const Settings& settings)
{
for (size_t toolpaths_idx = 0; toolpaths_idx < toolpaths.size(); ++toolpaths_idx)
{
const coord_t maximum_resolution = settings.get<coord_t>("meshfix_maximum_resolution");
const coord_t maximum_deviation = settings.get<coord_t>("meshfix_maximum_deviation");
const coord_t maximum_extrusion_area_deviation = settings.get<int>("meshfix_maximum_extrusion_area_deviation"); // unit: μm²
for (auto& line : toolpaths[toolpaths_idx])
{
line.simplify(maximum_resolution, maximum_deviation, maximum_extrusion_area_deviation);
}
}
}
const VariableWidthPaths& WallToolPaths::getToolPaths()
{
if (!toolpaths_generated)
{
return generate();
}
return toolpaths;
}
void WallToolPaths::computeInnerContour()
{
//We'll remove all 0-width paths from the original toolpaths and store them separately as polygons.
VariableWidthPaths actual_toolpaths;
actual_toolpaths.reserve(toolpaths.size()); //A bit too much, but the correct order of magnitude.
VariableWidthPaths contour_paths;
contour_paths.reserve(toolpaths.size() / inset_count);
std::partition_copy(toolpaths.begin(), toolpaths.end(), std::back_inserter(actual_toolpaths), std::back_inserter(contour_paths),
[](const VariableWidthLines& path)
{
for(const ExtrusionLine& line : path)
{
for(const ExtrusionJunction& junction : line.junctions)
{
return junction.w != 0; //On the first actual junction, decide: If it's got 0 width, this is a contour. Otherwise it is an actual toolpath.
}
}
return true; //No junctions with any vertices? Classify it as a toolpath then.
});
toolpaths = std::move(actual_toolpaths); //Filtered out the 0-width paths.
//Now convert the contour_paths to Polygons to denote the inner contour of the walled areas.
inner_contour.clear();
//We're going to have to stitch these paths since not all walls may be closed contours.
//Since these walls have 0 width they should theoretically be closed. But there may be rounding errors.
const coord_t minimum_line_width = bead_width_0 / 2;
stitchContours(contour_paths, minimum_line_width, inner_contour);
//The output walls from the skeletal trapezoidation have no known winding order, especially if they are joined together from polylines.
//They can be in any direction, clockwise or counter-clockwise, regardless of whether the shapes are positive or negative.
//To get a correct shape, we need to make the outside contour positive and any holes inside negative.
//This can be done by applying the even-odd rule to the shape. This rule is not sensitive to the winding order of the polygon.
//The even-odd rule would be incorrect if the polygon self-intersects, but that should never be generated by the skeletal trapezoidation.
inner_contour = inner_contour.unionPolygons(Polygons(), ClipperLib::pftEvenOdd);
}
const Polygons& WallToolPaths::getInnerContour()
{
if (!toolpaths_generated && inset_count > 0)
{
generate();
}
else if(inset_count == 0)
{
return outline;
}
return inner_contour;
}
bool WallToolPaths::removeEmptyToolPaths(VariableWidthPaths& toolpaths)
{
toolpaths.erase(std::remove_if(toolpaths.begin(), toolpaths.end(), [](const VariableWidthLines& lines)
{
return lines.empty();
}), toolpaths.end());
return toolpaths.empty();
}
void WallToolPaths::stitchContours(const VariableWidthPaths& input, const coord_t stitch_distance, Polygons& output)
{
//Create a bucket grid to find endpoints that are close together.
struct ExtrusionLineStartLocator
{
Point operator()(const ExtrusionLine* line)
{
return Point(line->junctions.front().p);
}
};
struct ExtrusionLineEndLocator
{
Point operator()(const ExtrusionLine* line)
{
return Point(line->junctions.back().p);
}
};
SparsePointGrid<const ExtrusionLine*, ExtrusionLineStartLocator> line_starts(stitch_distance); //Only find endpoints closer than minimum_line_width, so we can't ever accidentally make crossing contours.
SparsePointGrid<const ExtrusionLine*, ExtrusionLineEndLocator> line_ends(stitch_distance);
for(const VariableWidthLines& path : input)
{
for(const ExtrusionLine& line : path)
{
line_starts.insert(&line);
line_ends.insert(&line);
}
}
//Then go through all lines and construct chains of polylines if the endpoints are nearby.
std::unordered_set<const ExtrusionLine*> processed_lines; //Track which lines were already processed to not process them twice.
for(const VariableWidthLines& path : input)
{
for(const ExtrusionLine& line : path)
{
if(processed_lines.find(&line) != processed_lines.end()) //We already added this line before. It got added as a nearby line.
{
continue;
}
//We'll create a chain of polylines that get joined together. We can add polylines on both ends!
std::deque<const ExtrusionLine*> chain;
std::deque<bool> is_reversed; //Lines could need to be inserted in reverse. Must coincide with the `chain` deque.
const ExtrusionLine* nearest = &line; //At every iteration, add the polyline that joins together most closely.
bool nearest_reverse = false; //Whether the next line to insert must be inserted in reverse.
bool nearest_before = false; //Whether the next line to insert must be inserted in the front of the chain.
while(nearest)
{
if(processed_lines.find(nearest) != processed_lines.end())
{
break; //Looping. This contour is already processed.
}
processed_lines.insert(nearest);
if(nearest_before)
{
chain.push_front(nearest);
is_reversed.push_front(nearest_reverse);
}
else
{
chain.push_back(nearest);
is_reversed.push_back(nearest_reverse);
}
//Find any nearby lines to attach. Look on both ends of our current chain and find both ends of polylines.
const Point chain_start = is_reversed.front() ? chain.front()->junctions.back().p : chain.front()->junctions.front().p;
const Point chain_end = is_reversed.back() ? chain.back()->junctions.front().p : chain.back()->junctions.back().p;
std::vector<const ExtrusionLine*> starts_near_start = line_starts.getNearby(chain_start, stitch_distance);
std::vector<const ExtrusionLine*> ends_near_start = line_ends.getNearby(chain_start, stitch_distance);
std::vector<const ExtrusionLine*> starts_near_end = line_starts.getNearby(chain_end, stitch_distance);
std::vector<const ExtrusionLine*> ends_near_end = line_ends.getNearby(chain_end, stitch_distance);
nearest = nullptr;
coord_t nearest_dist2 = std::numeric_limits<coord_t>::max();
for(const ExtrusionLine* candidate : starts_near_start)
{
if(processed_lines.find(candidate) != processed_lines.end())
{
continue; //Already processed this line before. It's linked to something else.
}
const coord_t dist2 = vSize2(candidate->junctions.front().p - chain_start);
if(dist2 < nearest_dist2)
{
nearest = candidate;
nearest_dist2 = dist2;
nearest_reverse = true;
nearest_before = true;
}
}
for(const ExtrusionLine* candidate : ends_near_start)
{
if(processed_lines.find(candidate) != processed_lines.end())
{
continue;
}
const coord_t dist2 = vSize2(candidate->junctions.back().p - chain_start);
if(dist2 < nearest_dist2)
{
nearest = candidate;
nearest_dist2 = dist2;
nearest_reverse = false;
nearest_before = true;
}
}
for(const ExtrusionLine* candidate : starts_near_end)
{
if(processed_lines.find(candidate) != processed_lines.end())
{
continue; //Already processed this line before. It's linked to something else.
}
const coord_t dist2 = vSize2(candidate->junctions.front().p - chain_start);
if(dist2 < nearest_dist2)
{
nearest = candidate;
nearest_dist2 = dist2;
nearest_reverse = false;
nearest_before = false;
}
}
for(const ExtrusionLine* candidate : ends_near_end)
{
if(processed_lines.find(candidate) != processed_lines.end())
{
continue;
}
const coord_t dist2 = vSize2(candidate->junctions.back().p - chain_start);
if(dist2 < nearest_dist2)
{
nearest = candidate;
nearest_dist2 = dist2;
nearest_reverse = true;
nearest_before = false;
}
}
}
//Now serialize the entire chain into one polygon.
output.emplace_back();
for(size_t i = 0; i < chain.size(); ++i)
{
if(!is_reversed[i])
{
for(const ExtrusionJunction& junction : chain[i]->junctions)
{
output.back().add(junction.p);
}
}
else
{
for(auto junction = chain[i]->junctions.rbegin(); junction != chain[i]->junctions.rend(); ++junction)
{
output.back().add(junction->p);
}
}
}
}
}
}
} // namespace cura
|
// Copyright (c) 2020 Ultimaker B.V.
// CuraEngine is released under the terms of the AGPLv3 or higher.
#include <algorithm> //For std::partition_copy and std::min_element.
#include <unordered_set>
#include "WallToolPaths.h"
#include "SkeletalTrapezoidation.h"
#include "BeadingStrategy/BeadingOrderOptimizer.h"
#include "utils/SparsePointGrid.h" //To stitch the inner contour.
#include "utils/polygonUtils.h"
#include "ExtruderTrain.h"
namespace cura
{
WallToolPaths::WallToolPaths(const Polygons& outline, const coord_t nominal_bead_width, const size_t inset_count, const coord_t wall_0_inset,
const Settings& settings)
: outline(outline)
, bead_width_0(nominal_bead_width)
, bead_width_x(nominal_bead_width)
, inset_count(inset_count)
, wall_0_inset(wall_0_inset)
, strategy_type(settings.get<StrategyType>("beading_strategy_type"))
, print_thin_walls(settings.get<bool>("fill_outline_gaps"))
, min_feature_size(settings.get<coord_t>("min_feature_size"))
, min_bead_width(settings.get<coord_t>("min_bead_width"))
, small_area_length(INT2MM(static_cast<double>(nominal_bead_width) / 2))
, toolpaths_generated(false)
, settings(settings)
{
}
WallToolPaths::WallToolPaths(const Polygons& outline, const coord_t bead_width_0, const coord_t bead_width_x,
const size_t inset_count, const coord_t wall_0_inset, const Settings& settings)
: outline(outline)
, bead_width_0(bead_width_0)
, bead_width_x(bead_width_x)
, inset_count(inset_count)
, wall_0_inset(wall_0_inset)
, strategy_type(settings.get<StrategyType>("beading_strategy_type"))
, print_thin_walls(settings.get<bool>("fill_outline_gaps"))
, min_feature_size(settings.get<coord_t>("min_feature_size"))
, min_bead_width(settings.get<coord_t>("min_bead_width"))
, small_area_length(INT2MM(static_cast<double>(bead_width_0) / 2))
, toolpaths_generated(false)
, settings(settings)
{
}
const VariableWidthPaths& WallToolPaths::generate()
{
const coord_t smallest_segment = settings.get<coord_t>("meshfix_maximum_resolution");
const coord_t allowed_distance = settings.get<coord_t>("meshfix_maximum_deviation");
const coord_t epsilon_offset = (allowed_distance / 2) - 1;
const AngleRadians transitioning_angle = settings.get<AngleRadians>("wall_transition_angle");
constexpr coord_t discretization_step_size = MM2INT(0.8);
// Simplify outline for boost::voronoi consumption. Absolutely no self intersections or near-self intersections allowed:
// TODO: Open question: Does this indeed fix all (or all-but-one-in-a-million) cases for manifold but otherwise possibly complex polygons?
Polygons prepared_outline = outline.offset(-epsilon_offset).offset(epsilon_offset);
prepared_outline.simplify(smallest_segment, allowed_distance);
PolygonUtils::fixSelfIntersections(epsilon_offset, prepared_outline);
prepared_outline.removeDegenerateVerts();
prepared_outline.removeColinearEdges();
prepared_outline.removeSmallAreas(small_area_length * small_area_length, false);
if (prepared_outline.area() > 0)
{
const coord_t wall_transition_length = settings.get<coord_t>("wall_transition_length");
const Ratio wall_transition_threshold = settings.get<Ratio>("wall_transition_threshold");
const size_t max_bead_count = 2 * inset_count;
const auto beading_strat = std::unique_ptr<BeadingStrategy>(BeadingStrategyFactory::makeStrategy(
strategy_type, bead_width_0, bead_width_x, wall_transition_length, transitioning_angle, print_thin_walls, min_bead_width,
min_feature_size, wall_transition_threshold, max_bead_count, wall_0_inset));
const coord_t transition_filter_dist = settings.get<coord_t>("wall_transition_filter_distance");
SkeletalTrapezoidation wall_maker(prepared_outline, *beading_strat, beading_strat->transitioning_angle, discretization_step_size, transition_filter_dist, wall_transition_length);
wall_maker.generateToolpaths(toolpaths);
computeInnerContour();
}
simplifyToolPaths(toolpaths, settings);
removeEmptyToolPaths(toolpaths);
assert(std::is_sorted(toolpaths.cbegin(), toolpaths.cend(),
[](const VariableWidthLines& l, const VariableWidthLines& r)
{
return l.front().inset_idx < r.front().inset_idx;
}) && "WallToolPaths should be sorted from the outer 0th to inner_walls");
toolpaths_generated = true;
return toolpaths;
}
void WallToolPaths::simplifyToolPaths(VariableWidthPaths& toolpaths, const Settings& settings)
{
for (size_t toolpaths_idx = 0; toolpaths_idx < toolpaths.size(); ++toolpaths_idx)
{
const coord_t maximum_resolution = settings.get<coord_t>("meshfix_maximum_resolution");
const coord_t maximum_deviation = settings.get<coord_t>("meshfix_maximum_deviation");
const coord_t maximum_extrusion_area_deviation = settings.get<int>("meshfix_maximum_extrusion_area_deviation"); // unit: μm²
for (auto& line : toolpaths[toolpaths_idx])
{
line.simplify(maximum_resolution, maximum_deviation, maximum_extrusion_area_deviation);
}
}
}
const VariableWidthPaths& WallToolPaths::getToolPaths()
{
if (!toolpaths_generated)
{
return generate();
}
return toolpaths;
}
void WallToolPaths::computeInnerContour()
{
//We'll remove all 0-width paths from the original toolpaths and store them separately as polygons.
VariableWidthPaths actual_toolpaths;
actual_toolpaths.reserve(toolpaths.size()); //A bit too much, but the correct order of magnitude.
VariableWidthPaths contour_paths;
contour_paths.reserve(toolpaths.size() / inset_count);
std::partition_copy(toolpaths.begin(), toolpaths.end(), std::back_inserter(actual_toolpaths), std::back_inserter(contour_paths),
[](const VariableWidthLines& path)
{
for(const ExtrusionLine& line : path)
{
for(const ExtrusionJunction& junction : line.junctions)
{
return junction.w != 0; //On the first actual junction, decide: If it's got 0 width, this is a contour. Otherwise it is an actual toolpath.
}
}
return true; //No junctions with any vertices? Classify it as a toolpath then.
});
if (! actual_toolpaths.empty())
{
toolpaths = std::move(actual_toolpaths); //Filtered out the 0-width paths.
}
else
{
toolpaths.clear();
}
//Now convert the contour_paths to Polygons to denote the inner contour of the walled areas.
inner_contour.clear();
//We're going to have to stitch these paths since not all walls may be closed contours.
//Since these walls have 0 width they should theoretically be closed. But there may be rounding errors.
const coord_t minimum_line_width = bead_width_0 / 2;
stitchContours(contour_paths, minimum_line_width, inner_contour);
//The output walls from the skeletal trapezoidation have no known winding order, especially if they are joined together from polylines.
//They can be in any direction, clockwise or counter-clockwise, regardless of whether the shapes are positive or negative.
//To get a correct shape, we need to make the outside contour positive and any holes inside negative.
//This can be done by applying the even-odd rule to the shape. This rule is not sensitive to the winding order of the polygon.
//The even-odd rule would be incorrect if the polygon self-intersects, but that should never be generated by the skeletal trapezoidation.
inner_contour = inner_contour.unionPolygons(Polygons(), ClipperLib::pftEvenOdd);
}
const Polygons& WallToolPaths::getInnerContour()
{
if (!toolpaths_generated && inset_count > 0)
{
generate();
}
else if(inset_count == 0)
{
return outline;
}
return inner_contour;
}
bool WallToolPaths::removeEmptyToolPaths(VariableWidthPaths& toolpaths)
{
toolpaths.erase(std::remove_if(toolpaths.begin(), toolpaths.end(), [](const VariableWidthLines& lines)
{
return lines.empty();
}), toolpaths.end());
return toolpaths.empty();
}
void WallToolPaths::stitchContours(const VariableWidthPaths& input, const coord_t stitch_distance, Polygons& output)
{
//Create a bucket grid to find endpoints that are close together.
struct ExtrusionLineStartLocator
{
Point operator()(const ExtrusionLine* line)
{
return Point(line->junctions.front().p);
}
};
struct ExtrusionLineEndLocator
{
Point operator()(const ExtrusionLine* line)
{
return Point(line->junctions.back().p);
}
};
SparsePointGrid<const ExtrusionLine*, ExtrusionLineStartLocator> line_starts(stitch_distance); //Only find endpoints closer than minimum_line_width, so we can't ever accidentally make crossing contours.
SparsePointGrid<const ExtrusionLine*, ExtrusionLineEndLocator> line_ends(stitch_distance);
for(const VariableWidthLines& path : input)
{
for(const ExtrusionLine& line : path)
{
line_starts.insert(&line);
line_ends.insert(&line);
}
}
//Then go through all lines and construct chains of polylines if the endpoints are nearby.
std::unordered_set<const ExtrusionLine*> processed_lines; //Track which lines were already processed to not process them twice.
for(const VariableWidthLines& path : input)
{
for(const ExtrusionLine& line : path)
{
if(processed_lines.find(&line) != processed_lines.end()) //We already added this line before. It got added as a nearby line.
{
continue;
}
//We'll create a chain of polylines that get joined together. We can add polylines on both ends!
std::deque<const ExtrusionLine*> chain;
std::deque<bool> is_reversed; //Lines could need to be inserted in reverse. Must coincide with the `chain` deque.
const ExtrusionLine* nearest = &line; //At every iteration, add the polyline that joins together most closely.
bool nearest_reverse = false; //Whether the next line to insert must be inserted in reverse.
bool nearest_before = false; //Whether the next line to insert must be inserted in the front of the chain.
while(nearest)
{
if(processed_lines.find(nearest) != processed_lines.end())
{
break; //Looping. This contour is already processed.
}
processed_lines.insert(nearest);
if(nearest_before)
{
chain.push_front(nearest);
is_reversed.push_front(nearest_reverse);
}
else
{
chain.push_back(nearest);
is_reversed.push_back(nearest_reverse);
}
//Find any nearby lines to attach. Look on both ends of our current chain and find both ends of polylines.
const Point chain_start = is_reversed.front() ? chain.front()->junctions.back().p : chain.front()->junctions.front().p;
const Point chain_end = is_reversed.back() ? chain.back()->junctions.front().p : chain.back()->junctions.back().p;
std::vector<const ExtrusionLine*> starts_near_start = line_starts.getNearby(chain_start, stitch_distance);
std::vector<const ExtrusionLine*> ends_near_start = line_ends.getNearby(chain_start, stitch_distance);
std::vector<const ExtrusionLine*> starts_near_end = line_starts.getNearby(chain_end, stitch_distance);
std::vector<const ExtrusionLine*> ends_near_end = line_ends.getNearby(chain_end, stitch_distance);
nearest = nullptr;
coord_t nearest_dist2 = std::numeric_limits<coord_t>::max();
for(const ExtrusionLine* candidate : starts_near_start)
{
if(processed_lines.find(candidate) != processed_lines.end())
{
continue; //Already processed this line before. It's linked to something else.
}
const coord_t dist2 = vSize2(candidate->junctions.front().p - chain_start);
if(dist2 < nearest_dist2)
{
nearest = candidate;
nearest_dist2 = dist2;
nearest_reverse = true;
nearest_before = true;
}
}
for(const ExtrusionLine* candidate : ends_near_start)
{
if(processed_lines.find(candidate) != processed_lines.end())
{
continue;
}
const coord_t dist2 = vSize2(candidate->junctions.back().p - chain_start);
if(dist2 < nearest_dist2)
{
nearest = candidate;
nearest_dist2 = dist2;
nearest_reverse = false;
nearest_before = true;
}
}
for(const ExtrusionLine* candidate : starts_near_end)
{
if(processed_lines.find(candidate) != processed_lines.end())
{
continue; //Already processed this line before. It's linked to something else.
}
const coord_t dist2 = vSize2(candidate->junctions.front().p - chain_start);
if(dist2 < nearest_dist2)
{
nearest = candidate;
nearest_dist2 = dist2;
nearest_reverse = false;
nearest_before = false;
}
}
for(const ExtrusionLine* candidate : ends_near_end)
{
if(processed_lines.find(candidate) != processed_lines.end())
{
continue;
}
const coord_t dist2 = vSize2(candidate->junctions.back().p - chain_start);
if(dist2 < nearest_dist2)
{
nearest = candidate;
nearest_dist2 = dist2;
nearest_reverse = true;
nearest_before = false;
}
}
}
//Now serialize the entire chain into one polygon.
output.emplace_back();
for(size_t i = 0; i < chain.size(); ++i)
{
if(!is_reversed[i])
{
for(const ExtrusionJunction& junction : chain[i]->junctions)
{
output.back().add(junction.p);
}
}
else
{
for(auto junction = chain[i]->junctions.rbegin(); junction != chain[i]->junctions.rend(); ++junction)
{
output.back().add(junction->p);
}
}
}
}
}
}
} // namespace cura
|
Fix other part of Mac crash.
|
Fix other part of Mac crash.
It turns out that 'actual toolpaths' can be empty, and then the move won't work on some systems. (Or maybe it quietly failed on others.) So check if empty first and clear toolpaths if necessary.
CURA-7914
|
C++
|
agpl-3.0
|
Ultimaker/CuraEngine,Ultimaker/CuraEngine
|
9dc824fd03ccb8b658495ab64619e0c7acad30bc
|
tensorflow/compiler/jit/xla_gpu_device.cc
|
tensorflow/compiler/jit/xla_gpu_device.cc
|
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// Registers the XLA_GPU device, which is an XlaDevice instantiation that runs
// operators using XLA via the XLA "CUDA" (GPU) backend.
#include <set>
#include "absl/memory/memory.h"
#include "absl/strings/numbers.h"
#include "absl/strings/str_split.h"
#include "tensorflow/compiler/jit/kernels/xla_ops.h"
#include "tensorflow/compiler/jit/xla_device.h"
#include "tensorflow/compiler/jit/xla_device_ops.h"
#include "tensorflow/compiler/tf2xla/xla_op_registry.h"
#include "tensorflow/core/common_runtime/device_factory.h"
#include "tensorflow/core/lib/core/status.h"
namespace tensorflow {
// Returns a set containing the device ids contained in visible_device_list or
// nullopt if it is empty. It returns error in case of malformed configuration
// string.
static xla::StatusOr<absl::optional<std::set<int>>> ParseVisibleDeviceList(
const string& visible_device_list) {
std::set<int> gpu_ids;
if (visible_device_list.empty()) {
return {{absl::nullopt}};
}
const std::vector<string> visible_devices =
absl::StrSplit(visible_device_list, ',');
for (const string& platform_gpu_id_str : visible_devices) {
int32 platform_gpu_id;
if (!absl::SimpleAtoi(platform_gpu_id_str, &platform_gpu_id)) {
return errors::InvalidArgument(
"Could not parse entry in 'visible_device_list': '",
platform_gpu_id_str, "'. visible_device_list = ",
visible_device_list);
}
gpu_ids.insert(platform_gpu_id);
}
return {{gpu_ids}};
}
class XlaGpuDeviceFactory : public DeviceFactory {
public:
Status CreateDevices(const SessionOptions& options, const string& name_prefix,
std::vector<std::unique_ptr<Device>>* devices) override;
};
Status XlaGpuDeviceFactory::CreateDevices(
const SessionOptions& session_options, const string& name_prefix,
std::vector<std::unique_ptr<Device>>* devices) {
XlaOpRegistry::DeviceRegistration registration;
registration.compilation_device_name = DEVICE_GPU_XLA_JIT;
registration.autoclustering_policy =
XlaOpRegistry::AutoclusteringPolicy::kAlways;
registration.compile_resource_ops = true;
XlaOpRegistry::RegisterCompilationDevice(DEVICE_XLA_GPU, registration);
static XlaDeviceOpRegistrations* registrations =
RegisterXlaDeviceKernels(DEVICE_XLA_GPU, DEVICE_GPU_XLA_JIT);
(void)registrations;
auto platform = se::MultiPlatformManager::PlatformWithName("CUDA");
if (!platform.ok()) {
// Treat failures as non-fatal; there might not be a GPU in the machine.
VLOG(1) << "Failed to create XLA_GPU device: " << platform.status();
return Status::OK();
}
string allowed_gpus =
session_options.config.gpu_options().visible_device_list();
absl::optional<std::set<int>> gpu_ids = ParseVisibleDeviceList(allowed_gpus).ValueOrDie();
if (!gpu_ids) {
gpu_ids.emplace();
// Fill the gpu_ids set with all devices if config string is empty.
for (int i = 0; i < platform.ValueOrDie()->VisibleDeviceCount(); ++i) {
gpu_ids->insert(i);
}
}
for (int i : *gpu_ids) {
XlaDevice::Options options;
options.platform = platform.ValueOrDie();
options.device_name_prefix = name_prefix;
options.device_name = DEVICE_XLA_GPU;
options.device_ordinal = i;
options.compilation_device_name = DEVICE_GPU_XLA_JIT;
options.use_multiple_streams = true;
options.allowed_devices = gpu_ids;
auto device = absl::make_unique<XlaDevice>(session_options, options);
Status status = device->UseGpuDeviceInfo();
if (!status.ok()) {
errors::AppendToMessage(&status, "while setting up ", DEVICE_GPU_XLA_JIT,
" device number ", i);
return status;
}
devices->push_back(std::move(device));
}
return Status::OK();
}
REGISTER_LOCAL_DEVICE_FACTORY(DEVICE_XLA_GPU, XlaGpuDeviceFactory);
// Kernel registrations
constexpr std::array<DataType, 13> kAllXlaGpuTypes = {
{DT_UINT8, DT_QUINT8, DT_INT8, DT_QINT8, DT_INT32, DT_QINT32, DT_INT64,
DT_HALF, DT_FLOAT, DT_DOUBLE, DT_COMPLEX64, DT_BOOL, DT_BFLOAT16}};
REGISTER_XLA_LAUNCH_KERNEL(DEVICE_XLA_GPU, XlaLocalLaunchOp, kAllXlaGpuTypes);
REGISTER_XLA_COMPILE_KERNEL(DEVICE_XLA_GPU, XlaCompileOp, kAllXlaGpuTypes);
REGISTER_XLA_RUN_KERNEL(DEVICE_XLA_GPU, XlaRunOp, kAllXlaGpuTypes);
REGISTER_XLA_DEVICE_KERNELS(DEVICE_XLA_GPU, kAllXlaGpuTypes);
} // namespace tensorflow
|
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// Registers the XLA_GPU device, which is an XlaDevice instantiation that runs
// operators using XLA via the XLA "CUDA" (GPU) backend.
#include <set>
#include "absl/memory/memory.h"
#include "absl/strings/numbers.h"
#include "absl/strings/str_split.h"
#include "tensorflow/compiler/jit/kernels/xla_ops.h"
#include "tensorflow/compiler/jit/xla_device.h"
#include "tensorflow/compiler/jit/xla_device_ops.h"
#include "tensorflow/compiler/tf2xla/xla_op_registry.h"
#include "tensorflow/core/common_runtime/device_factory.h"
#include "tensorflow/core/lib/core/status.h"
namespace tensorflow {
// Returns a set containing the device ids contained in visible_device_list or
// nullopt if it is empty. It returns error in case of malformed configuration
// string.
static xla::StatusOr<absl::optional<std::set<int>>> ParseVisibleDeviceList(
const string& visible_device_list) {
std::set<int> gpu_ids;
if (visible_device_list.empty()) {
return {{absl::nullopt}};
}
const std::vector<string> visible_devices =
absl::StrSplit(visible_device_list, ',');
for (const string& platform_gpu_id_str : visible_devices) {
int32 platform_gpu_id;
if (!absl::SimpleAtoi(platform_gpu_id_str, &platform_gpu_id)) {
return errors::InvalidArgument(
"Could not parse entry in 'visible_device_list': '",
platform_gpu_id_str, "'. visible_device_list = ",
visible_device_list);
}
gpu_ids.insert(platform_gpu_id);
}
return {{gpu_ids}};
}
class XlaGpuDeviceFactory : public DeviceFactory {
public:
Status CreateDevices(const SessionOptions& options, const string& name_prefix,
std::vector<std::unique_ptr<Device>>* devices) override;
};
Status XlaGpuDeviceFactory::CreateDevices(
const SessionOptions& session_options, const string& name_prefix,
std::vector<std::unique_ptr<Device>>* devices) {
XlaOpRegistry::DeviceRegistration registration;
registration.compilation_device_name = DEVICE_GPU_XLA_JIT;
registration.autoclustering_policy =
XlaOpRegistry::AutoclusteringPolicy::kAlways;
registration.compile_resource_ops = true;
XlaOpRegistry::RegisterCompilationDevice(DEVICE_XLA_GPU, registration);
static XlaDeviceOpRegistrations* registrations =
RegisterXlaDeviceKernels(DEVICE_XLA_GPU, DEVICE_GPU_XLA_JIT);
(void)registrations;
auto platform = se::MultiPlatformManager::PlatformWithName("CUDA");
if (!platform.ok()) {
// Treat failures as non-fatal; there might not be a GPU in the machine.
VLOG(1) << "Failed to create XLA_GPU device: " << platform.status();
return Status::OK();
}
string allowed_gpus =
session_options.config.gpu_options().visible_device_list();
absl::optional<std::set<int>> gpu_ids =
ParseVisibleDeviceList(allowed_gpus).ValueOrDie();
if (!gpu_ids) {
gpu_ids.emplace();
// Fill the gpu_ids set with all devices if config string is empty.
for (int i = 0; i < platform.ValueOrDie()->VisibleDeviceCount(); ++i) {
gpu_ids->insert(i);
}
}
for (int i : *gpu_ids) {
XlaDevice::Options options;
options.platform = platform.ValueOrDie();
options.device_name_prefix = name_prefix;
options.device_name = DEVICE_XLA_GPU;
options.device_ordinal = i;
options.compilation_device_name = DEVICE_GPU_XLA_JIT;
options.use_multiple_streams = true;
options.allowed_devices = gpu_ids;
auto device = absl::make_unique<XlaDevice>(session_options, options);
Status status = device->UseGpuDeviceInfo();
if (!status.ok()) {
errors::AppendToMessage(&status, "while setting up ", DEVICE_GPU_XLA_JIT,
" device number ", i);
return status;
}
devices->push_back(std::move(device));
}
return Status::OK();
}
REGISTER_LOCAL_DEVICE_FACTORY(DEVICE_XLA_GPU, XlaGpuDeviceFactory);
// Kernel registrations
constexpr std::array<DataType, 13> kAllXlaGpuTypes = {
{DT_UINT8, DT_QUINT8, DT_INT8, DT_QINT8, DT_INT32, DT_QINT32, DT_INT64,
DT_HALF, DT_FLOAT, DT_DOUBLE, DT_COMPLEX64, DT_BOOL, DT_BFLOAT16}};
REGISTER_XLA_LAUNCH_KERNEL(DEVICE_XLA_GPU, XlaLocalLaunchOp, kAllXlaGpuTypes);
REGISTER_XLA_COMPILE_KERNEL(DEVICE_XLA_GPU, XlaCompileOp, kAllXlaGpuTypes);
REGISTER_XLA_RUN_KERNEL(DEVICE_XLA_GPU, XlaRunOp, kAllXlaGpuTypes);
REGISTER_XLA_DEVICE_KERNELS(DEVICE_XLA_GPU, kAllXlaGpuTypes);
} // namespace tensorflow
|
Fix clang-format check. Somehow clang-format used in the CI produces a different output than clang-format-5
|
Fix clang-format check. Somehow clang-format used in the CI produces a different output than clang-format-5
|
C++
|
apache-2.0
|
gautam1858/tensorflow,tensorflow/tensorflow,Intel-tensorflow/tensorflow,arborh/tensorflow,ageron/tensorflow,gautam1858/tensorflow,xzturn/tensorflow,karllessard/tensorflow,ageron/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,davidzchen/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,Intel-Corporation/tensorflow,tensorflow/tensorflow-pywrap_saved_model,Bismarrck/tensorflow,alsrgv/tensorflow,jbedorf/tensorflow,Intel-Corporation/tensorflow,aam-at/tensorflow,jendap/tensorflow,jendap/tensorflow,theflofly/tensorflow,gunan/tensorflow,ageron/tensorflow,kevin-coder/tensorflow-fork,jendap/tensorflow,arborh/tensorflow,DavidNorman/tensorflow,theflofly/tensorflow,gunan/tensorflow,kevin-coder/tensorflow-fork,hfp/tensorflow-xsmm,tensorflow/tensorflow,alsrgv/tensorflow,Intel-tensorflow/tensorflow,xzturn/tensorflow,jhseu/tensorflow,aldian/tensorflow,DavidNorman/tensorflow,Intel-Corporation/tensorflow,aam-at/tensorflow,ppwwyyxx/tensorflow,renyi533/tensorflow,Bismarrck/tensorflow,jbedorf/tensorflow,arborh/tensorflow,arborh/tensorflow,chemelnucfin/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,ghchinoy/tensorflow,xzturn/tensorflow,Bismarrck/tensorflow,DavidNorman/tensorflow,renyi533/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,apark263/tensorflow,davidzchen/tensorflow,tensorflow/tensorflow-pywrap_saved_model,karllessard/tensorflow,jbedorf/tensorflow,ppwwyyxx/tensorflow,annarev/tensorflow,sarvex/tensorflow,tensorflow/tensorflow-pywrap_saved_model,jendap/tensorflow,gunan/tensorflow,xzturn/tensorflow,renyi533/tensorflow,theflofly/tensorflow,kevin-coder/tensorflow-fork,Bismarrck/tensorflow,gautam1858/tensorflow,Intel-tensorflow/tensorflow,jhseu/tensorflow,kevin-coder/tensorflow-fork,petewarden/tensorflow,karllessard/tensorflow,Intel-Corporation/tensorflow,frreiss/tensorflow-fred,Intel-tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,adit-chandra/tensorflow,renyi533/tensorflow,jhseu/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,ghchinoy/tensorflow,ghchinoy/tensorflow,paolodedios/tensorflow,Intel-tensorflow/tensorflow,jendap/tensorflow,sarvex/tensorflow,jbedorf/tensorflow,gunan/tensorflow,arborh/tensorflow,chemelnucfin/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,paolodedios/tensorflow,ageron/tensorflow,petewarden/tensorflow,karllessard/tensorflow,jhseu/tensorflow,gunan/tensorflow,arborh/tensorflow,arborh/tensorflow,frreiss/tensorflow-fred,yongtang/tensorflow,petewarden/tensorflow,frreiss/tensorflow-fred,alsrgv/tensorflow,ageron/tensorflow,DavidNorman/tensorflow,aam-at/tensorflow,davidzchen/tensorflow,annarev/tensorflow,Intel-tensorflow/tensorflow,DavidNorman/tensorflow,jbedorf/tensorflow,theflofly/tensorflow,aam-at/tensorflow,cxxgtxy/tensorflow,cxxgtxy/tensorflow,apark263/tensorflow,yongtang/tensorflow,aldian/tensorflow,jbedorf/tensorflow,Bismarrck/tensorflow,sarvex/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,annarev/tensorflow,freedomtan/tensorflow,DavidNorman/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,theflofly/tensorflow,DavidNorman/tensorflow,tensorflow/tensorflow-pywrap_saved_model,aam-at/tensorflow,alsrgv/tensorflow,adit-chandra/tensorflow,ppwwyyxx/tensorflow,ppwwyyxx/tensorflow,gautam1858/tensorflow,annarev/tensorflow,karllessard/tensorflow,paolodedios/tensorflow,davidzchen/tensorflow,karllessard/tensorflow,hfp/tensorflow-xsmm,tensorflow/tensorflow-experimental_link_static_libraries_once,petewarden/tensorflow,cxxgtxy/tensorflow,alsrgv/tensorflow,gunan/tensorflow,DavidNorman/tensorflow,renyi533/tensorflow,paolodedios/tensorflow,annarev/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,Bismarrck/tensorflow,jhseu/tensorflow,sarvex/tensorflow,jbedorf/tensorflow,ppwwyyxx/tensorflow,karllessard/tensorflow,xzturn/tensorflow,petewarden/tensorflow,chemelnucfin/tensorflow,apark263/tensorflow,gautam1858/tensorflow,theflofly/tensorflow,davidzchen/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,freedomtan/tensorflow,ageron/tensorflow,renyi533/tensorflow,renyi533/tensorflow,Bismarrck/tensorflow,adit-chandra/tensorflow,tensorflow/tensorflow-pywrap_saved_model,cxxgtxy/tensorflow,jendap/tensorflow,Intel-Corporation/tensorflow,tensorflow/tensorflow-pywrap_saved_model,freedomtan/tensorflow,yongtang/tensorflow,jbedorf/tensorflow,Intel-Corporation/tensorflow,freedomtan/tensorflow,ageron/tensorflow,Intel-Corporation/tensorflow,yongtang/tensorflow,karllessard/tensorflow,yongtang/tensorflow,sarvex/tensorflow,ppwwyyxx/tensorflow,tensorflow/tensorflow-pywrap_saved_model,renyi533/tensorflow,hfp/tensorflow-xsmm,gautam1858/tensorflow,alsrgv/tensorflow,paolodedios/tensorflow,aam-at/tensorflow,gautam1858/tensorflow,arborh/tensorflow,jendap/tensorflow,yongtang/tensorflow,kevin-coder/tensorflow-fork,jhseu/tensorflow,alsrgv/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,ppwwyyxx/tensorflow,frreiss/tensorflow-fred,adit-chandra/tensorflow,Intel-tensorflow/tensorflow,paolodedios/tensorflow,annarev/tensorflow,tensorflow/tensorflow,ghchinoy/tensorflow,adit-chandra/tensorflow,apark263/tensorflow,petewarden/tensorflow,davidzchen/tensorflow,aam-at/tensorflow,tensorflow/tensorflow,apark263/tensorflow,alsrgv/tensorflow,tensorflow/tensorflow,jhseu/tensorflow,xzturn/tensorflow,xzturn/tensorflow,aldian/tensorflow,apark263/tensorflow,ghchinoy/tensorflow,chemelnucfin/tensorflow,ageron/tensorflow,adit-chandra/tensorflow,aldian/tensorflow,jbedorf/tensorflow,petewarden/tensorflow,cxxgtxy/tensorflow,aldian/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,gautam1858/tensorflow,ppwwyyxx/tensorflow,aldian/tensorflow,ageron/tensorflow,chemelnucfin/tensorflow,ppwwyyxx/tensorflow,jbedorf/tensorflow,ageron/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-experimental_link_static_libraries_once,freedomtan/tensorflow,kevin-coder/tensorflow-fork,freedomtan/tensorflow,arborh/tensorflow,freedomtan/tensorflow,Bismarrck/tensorflow,freedomtan/tensorflow,gautam1858/tensorflow,paolodedios/tensorflow,davidzchen/tensorflow,aam-at/tensorflow,hfp/tensorflow-xsmm,frreiss/tensorflow-fred,kevin-coder/tensorflow-fork,paolodedios/tensorflow,aam-at/tensorflow,tensorflow/tensorflow,renyi533/tensorflow,hfp/tensorflow-xsmm,xzturn/tensorflow,Bismarrck/tensorflow,gautam1858/tensorflow,sarvex/tensorflow,ghchinoy/tensorflow,ppwwyyxx/tensorflow,adit-chandra/tensorflow,renyi533/tensorflow,ghchinoy/tensorflow,tensorflow/tensorflow-pywrap_saved_model,theflofly/tensorflow,petewarden/tensorflow,jhseu/tensorflow,Bismarrck/tensorflow,DavidNorman/tensorflow,renyi533/tensorflow,gunan/tensorflow,chemelnucfin/tensorflow,hfp/tensorflow-xsmm,DavidNorman/tensorflow,aam-at/tensorflow,aam-at/tensorflow,apark263/tensorflow,gunan/tensorflow,aldian/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow-experimental_link_static_libraries_once,freedomtan/tensorflow,chemelnucfin/tensorflow,frreiss/tensorflow-fred,cxxgtxy/tensorflow,ghchinoy/tensorflow,Intel-tensorflow/tensorflow,gunan/tensorflow,chemelnucfin/tensorflow,gunan/tensorflow,karllessard/tensorflow,alsrgv/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,annarev/tensorflow,theflofly/tensorflow,ghchinoy/tensorflow,yongtang/tensorflow,sarvex/tensorflow,tensorflow/tensorflow,xzturn/tensorflow,hfp/tensorflow-xsmm,frreiss/tensorflow-fred,theflofly/tensorflow,paolodedios/tensorflow,theflofly/tensorflow,adit-chandra/tensorflow,Intel-tensorflow/tensorflow,kevin-coder/tensorflow-fork,yongtang/tensorflow,cxxgtxy/tensorflow,Bismarrck/tensorflow,theflofly/tensorflow,paolodedios/tensorflow,hfp/tensorflow-xsmm,ppwwyyxx/tensorflow,frreiss/tensorflow-fred,alsrgv/tensorflow,apark263/tensorflow,petewarden/tensorflow,davidzchen/tensorflow,adit-chandra/tensorflow,ageron/tensorflow,jhseu/tensorflow,jhseu/tensorflow,cxxgtxy/tensorflow,davidzchen/tensorflow,gautam1858/tensorflow,renyi533/tensorflow,yongtang/tensorflow,adit-chandra/tensorflow,aldian/tensorflow,ghchinoy/tensorflow,aam-at/tensorflow,apark263/tensorflow,annarev/tensorflow,freedomtan/tensorflow,hfp/tensorflow-xsmm,DavidNorman/tensorflow,jendap/tensorflow,jhseu/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-experimental_link_static_libraries_once,apark263/tensorflow,jendap/tensorflow,freedomtan/tensorflow,arborh/tensorflow,chemelnucfin/tensorflow,jendap/tensorflow,adit-chandra/tensorflow,paolodedios/tensorflow,kevin-coder/tensorflow-fork,xzturn/tensorflow,petewarden/tensorflow,adit-chandra/tensorflow,jendap/tensorflow,sarvex/tensorflow,karllessard/tensorflow,hfp/tensorflow-xsmm,petewarden/tensorflow,freedomtan/tensorflow,arborh/tensorflow,DavidNorman/tensorflow,alsrgv/tensorflow,alsrgv/tensorflow,frreiss/tensorflow-fred,hfp/tensorflow-xsmm,jhseu/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,davidzchen/tensorflow,ppwwyyxx/tensorflow,tensorflow/tensorflow,annarev/tensorflow,jbedorf/tensorflow,chemelnucfin/tensorflow,jbedorf/tensorflow,ghchinoy/tensorflow,kevin-coder/tensorflow-fork,chemelnucfin/tensorflow,yongtang/tensorflow,kevin-coder/tensorflow-fork,davidzchen/tensorflow,Intel-tensorflow/tensorflow,frreiss/tensorflow-fred,xzturn/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,davidzchen/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-experimental_link_static_libraries_once,yongtang/tensorflow,apark263/tensorflow,karllessard/tensorflow,annarev/tensorflow,Intel-Corporation/tensorflow,tensorflow/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-pywrap_saved_model,xzturn/tensorflow,petewarden/tensorflow,ageron/tensorflow,gunan/tensorflow,arborh/tensorflow,gunan/tensorflow,annarev/tensorflow,ghchinoy/tensorflow,tensorflow/tensorflow,theflofly/tensorflow,chemelnucfin/tensorflow
|
df5b76bc9646ba9d68cc87bcdd9abfe7851911d4
|
tensorflow/lite/toco/tflite/op_version.cc
|
tensorflow/lite/toco/tflite/op_version.cc
|
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/lite/toco/tflite/op_version.h"
#include <cstring>
#include "tensorflow/lite/toco/model.h"
#include "tensorflow/lite/toco/tflite/operator.h"
#include "tensorflow/lite/toco/tooling_util.h"
namespace toco {
namespace tflite {
string GetMinimumRuntimeVersionForModel(const Model& model) {
static constexpr char kPendingReleaseOpVersion[] = "UNKNOWN";
// A map from the version key of an op to its minimum runtime version.
// For example, {{kAveragePool, 1}, "1.5.0"}, means the 1st version of
// AveragePool requires a minimum TF Lite runtime version '1.5.0`.
static const std::map<std::pair<OperatorType, int>, string>* op_version_map =
new std::map<std::pair<OperatorType, int>, string>(
{{{OperatorType::kAveragePool, 1}, "1.5.0"},
{{OperatorType::kAveragePool, 2}, kPendingReleaseOpVersion},
{{OperatorType::kConv, 1}, "1.5.0"},
{{OperatorType::kConv, 2}, kPendingReleaseOpVersion},
{{OperatorType::kConv, 3}, kPendingReleaseOpVersion},
{{OperatorType::kDepthwiseConv, 1}, "1.5.0"},
{{OperatorType::kDepthwiseConv, 2}, "1.12.0"},
{{OperatorType::kDepthwiseConv, 3}, kPendingReleaseOpVersion},
{{OperatorType::kAdd, 1}, "1.5.0"},
{{OperatorType::kAdd, 2}, kPendingReleaseOpVersion},
{{OperatorType::kAddN, 1}, kPendingReleaseOpVersion},
{{OperatorType::kSpaceToBatchND, 1}, "1.6.0"},
{{OperatorType::kSpaceToBatchND, 2}, kPendingReleaseOpVersion},
{{OperatorType::kSub, 1}, "1.6.0"},
{{OperatorType::kSub, 2}, kPendingReleaseOpVersion},
{{OperatorType::kDiv, 1}, "1.6.0"},
{{OperatorType::kBatchToSpaceND, 1}, "1.6.0"},
{{OperatorType::kBatchToSpaceND, 2}, kPendingReleaseOpVersion},
{{OperatorType::kCast, 1}, "1.5.0"},
{{OperatorType::kConcatenation, 1}, "1.5.0"},
{{OperatorType::kConcatenation, 2}, kPendingReleaseOpVersion},
{{OperatorType::kDepthToSpace, 1}, "1.5.0"},
{{OperatorType::kFakeQuant, 1}, "1.5.0"},
{{OperatorType::kFakeQuant, 2}, "1.10.0"},
{{OperatorType::kFullyConnected, 1}, "1.5.0"},
{{OperatorType::kFullyConnected, 2}, "1.10.0"},
{{OperatorType::kFullyConnected, 3}, kPendingReleaseOpVersion},
{{OperatorType::kFullyConnected, 4}, kPendingReleaseOpVersion},
{{OperatorType::kGather, 1}, "1.6.0"},
{{OperatorType::kGather, 2}, kPendingReleaseOpVersion},
{{OperatorType::kGatherNd, 1}, kPendingReleaseOpVersion},
{{OperatorType::kSvdf, 1}, "1.5.0"},
{{OperatorType::kSvdf, 2}, kPendingReleaseOpVersion},
{{OperatorType::kL2Normalization, 1}, "1.5.0"},
{{OperatorType::kL2Normalization, 2}, kPendingReleaseOpVersion},
{{OperatorType::kL2Pool, 1}, "1.5.0"},
{{OperatorType::kLocalResponseNormalization, 1}, "1.5.0"},
{{OperatorType::kMaxPool, 1}, "1.5.0"},
{{OperatorType::kMaxPool, 2}, kPendingReleaseOpVersion},
{{OperatorType::kMaximum, 1}, kPendingReleaseOpVersion},
{{OperatorType::kMaximum, 2}, kPendingReleaseOpVersion},
{{OperatorType::kMinimum, 1}, kPendingReleaseOpVersion},
{{OperatorType::kMinimum, 2}, kPendingReleaseOpVersion},
{{OperatorType::kMul, 1}, "1.5.0"},
{{OperatorType::kMul, 2}, kPendingReleaseOpVersion},
{{OperatorType::kPad, 1}, "1.5.0"},
{{OperatorType::kPad, 2}, kPendingReleaseOpVersion},
{{OperatorType::kTile, 1}, "1.10.1"},
{{OperatorType::kPadV2, 1}, "1.9.0"},
{{OperatorType::kPadV2, 2}, kPendingReleaseOpVersion},
{{OperatorType::kReshape, 1}, "1.5.0"},
{{OperatorType::kSoftmax, 1}, "1.5.0"},
{{OperatorType::kSoftmax, 2}, kPendingReleaseOpVersion},
{{OperatorType::kSpaceToDepth, 1}, "1.5.0"},
{{OperatorType::kSpaceToDepth, 2}, kPendingReleaseOpVersion},
{{OperatorType::kTranspose, 1}, "1.6.0"},
{{OperatorType::kTranspose, 2}, kPendingReleaseOpVersion},
{{OperatorType::kLstmCell, 1}, "1.7.0"},
{{OperatorType::kLstmCell, 2}, "1.10.0"},
{{OperatorType::kLstmCell, 3}, kPendingReleaseOpVersion},
{{OperatorType::kUnidirectionalSequenceLstm, 1}, "1.13.1"},
{{OperatorType::kUnidirectionalSequenceLstm, 1},
kPendingReleaseOpVersion},
{{OperatorType::kBidirectionalSequenceLstm, 1},
kPendingReleaseOpVersion},
{{OperatorType::kBidirectionalSequenceRnn, 1},
kPendingReleaseOpVersion},
{{OperatorType::kMean, 1}, "1.6.0"},
{{OperatorType::kMean, 2}, kPendingReleaseOpVersion},
{{OperatorType::kSum, 1}, "1.10.0"},
{{OperatorType::kReduceMax, 1}, "1.11.0"},
{{OperatorType::kReduceMax, 2}, kPendingReleaseOpVersion},
{{OperatorType::kReduceMin, 1}, "1.11.0"},
{{OperatorType::kReduceMin, 2}, kPendingReleaseOpVersion},
{{OperatorType::kReduceProd, 1}, "1.11.0"},
{{OperatorType::kAny, 1}, "1.11.0"},
{{OperatorType::kRelu6, 1}, kPendingReleaseOpVersion},
{{OperatorType::kRelu6, 2}, kPendingReleaseOpVersion},
{{OperatorType::kResizeBilinear, 1}, "1.7.0"},
{{OperatorType::kResizeBilinear, 2}, kPendingReleaseOpVersion},
{{OperatorType::kResizeNearestNeighbor, 1}, "1.13.1"},
{{OperatorType::kResizeNearestNeighbor, 2},
kPendingReleaseOpVersion},
{{OperatorType::kSqueeze, 1}, "1.6.0"},
{{OperatorType::kSplit, 1}, "1.5.0"},
{{OperatorType::kSplit, 2}, kPendingReleaseOpVersion},
{{OperatorType::kSplit, 3}, kPendingReleaseOpVersion},
{{OperatorType::kSplitV, 1}, "1.13.1"},
{{OperatorType::kStridedSlice, 1}, "1.6.0"},
{{OperatorType::kStridedSlice, 2}, kPendingReleaseOpVersion},
{{OperatorType::kTopK_V2, 1}, "1.7.0"},
{{OperatorType::kTopK_V2, 2}, kPendingReleaseOpVersion},
{{OperatorType::kArgMax, 1}, "1.9.0"},
{{OperatorType::kArgMax, 2}, kPendingReleaseOpVersion},
{{OperatorType::kArgMin, 1}, "1.9.0"},
{{OperatorType::kArgMin, 2}, kPendingReleaseOpVersion},
{{OperatorType::kTransposeConv, 1}, "1.9.0"},
{{OperatorType::kSparseToDense, 1}, "1.9.0"},
{{OperatorType::kSparseToDense, 2}, kPendingReleaseOpVersion},
{{OperatorType::kExpandDims, 1}, "1.10.0"},
{{OperatorType::kPack, 1}, "1.11.0"},
{{OperatorType::kPack, 2}, kPendingReleaseOpVersion},
{{OperatorType::kShape, 1}, "1.10.0"},
{{OperatorType::kSlice, 1}, kPendingReleaseOpVersion},
{{OperatorType::kSlice, 2}, kPendingReleaseOpVersion},
{{OperatorType::kSlice, 3}, kPendingReleaseOpVersion},
{{OperatorType::kTanh, 1}, kPendingReleaseOpVersion},
{{OperatorType::kTanh, 2}, kPendingReleaseOpVersion},
{{OperatorType::kOneHot, 1}, "1.11.0"},
{{OperatorType::kCTCBeamSearchDecoder, 1}, "1.11.0"},
{{OperatorType::kUnpack, 1}, "1.11.0"},
{{OperatorType::kLeakyRelu, 1}, "1.13.1"},
{{OperatorType::kLogistic, 1}, kPendingReleaseOpVersion},
{{OperatorType::kLogistic, 2}, kPendingReleaseOpVersion},
{{OperatorType::kLogSoftmax, 1}, kPendingReleaseOpVersion},
{{OperatorType::kLogSoftmax, 2}, kPendingReleaseOpVersion},
{{OperatorType::kSquaredDifference, 1}, "1.13.1"},
{{OperatorType::kMirrorPad, 1}, "1.13.1"},
{{OperatorType::kUnique, 1}, kPendingReleaseOpVersion},
{{OperatorType::kUnidirectionalSequenceRnn, 1},
kPendingReleaseOpVersion},
{{OperatorType::kWhere, 1}, kPendingReleaseOpVersion},
{{OperatorType::kDequantize, 1}, "1.13.1"},
{{OperatorType::kDequantize, 2}, kPendingReleaseOpVersion},
{{OperatorType::kReverseSequence, 1}, kPendingReleaseOpVersion},
{{OperatorType::kReverseSequence, 2}, kPendingReleaseOpVersion},
{{OperatorType::kEqual, 1}, kPendingReleaseOpVersion},
{{OperatorType::kEqual, 2}, kPendingReleaseOpVersion},
{{OperatorType::kNotEqual, 1}, kPendingReleaseOpVersion},
{{OperatorType::kNotEqual, 2}, kPendingReleaseOpVersion},
{{OperatorType::kGreater, 1}, kPendingReleaseOpVersion},
{{OperatorType::kGreater, 2}, kPendingReleaseOpVersion},
{{OperatorType::kGreaterEqual, 1}, kPendingReleaseOpVersion},
{{OperatorType::kGreaterEqual, 2}, kPendingReleaseOpVersion},
{{OperatorType::kLess, 1}, kPendingReleaseOpVersion},
{{OperatorType::kLess, 2}, kPendingReleaseOpVersion},
{{OperatorType::kLessEqual, 1}, kPendingReleaseOpVersion},
{{OperatorType::kLessEqual, 2}, kPendingReleaseOpVersion},
{{OperatorType::kSelect, 1}, kPendingReleaseOpVersion},
{{OperatorType::kSelect, 2}, kPendingReleaseOpVersion}});
const auto& op_types_map =
tflite::BuildOperatorByTypeMap(false /*enable_select_tf_ops=*/);
OperatorSignature op_signature;
op_signature.model = &model;
string model_min_version;
for (const auto& op : model.operators) {
op_signature.op = op.get();
const int version = op_types_map.at(op->type)->GetVersion(op_signature);
std::pair<OperatorType, int> version_key = {op->type, version};
auto it = op_version_map->find(version_key);
if (it == op_version_map->end() || it->second == kPendingReleaseOpVersion) {
// In case we didn't find the current op in the map, or the operator
// doesn't have a minimum runtime version associated, continue.
continue;
}
if (strcmp(model_min_version.c_str(), it->second.c_str()) < 0) {
// Current min model runtime version should be bumped if we see a higher
// op version.
model_min_version = it->second;
}
}
return model_min_version;
}
} // namespace tflite
} // namespace toco
|
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/lite/toco/tflite/op_version.h"
#include <cstring>
#include "tensorflow/lite/toco/model.h"
#include "tensorflow/lite/toco/tflite/operator.h"
#include "tensorflow/lite/toco/tooling_util.h"
namespace toco {
namespace tflite {
string GetMinimumRuntimeVersionForModel(const Model& model) {
// Use this as the placeholder string if a particular op is not yet included
// in any Tensorflow's RC/Final release source package. Once that op is
// included in the release, please update this with the real version string.
static constexpr char kPendingReleaseOpVersion[] = "UNKNOWN";
// A map from the version key of an op to its minimum runtime version.
// For example, {{kAveragePool, 1}, "1.5.0"}, means the 1st version of
// AveragePool requires a minimum TF Lite runtime version '1.5.0`.
static const std::map<std::pair<OperatorType, int>, string>* op_version_map =
new std::map<std::pair<OperatorType, int>, string>({
{{OperatorType::kAveragePool, 1}, "1.5.0"},
{{OperatorType::kAveragePool, 2}, "1.14.0"},
{{OperatorType::kConv, 1}, "1.5.0"},
{{OperatorType::kConv, 2}, "1.14.0"},
{{OperatorType::kConv, 3}, "1.14.0"},
{{OperatorType::kDepthwiseConv, 1}, "1.5.0"},
{{OperatorType::kDepthwiseConv, 2}, "1.12.0"},
{{OperatorType::kDepthwiseConv, 3}, "1.14.0"},
{{OperatorType::kAdd, 1}, "1.5.0"},
{{OperatorType::kAdd, 2}, "1.14.0"},
{{OperatorType::kAddN, 1}, "1.14.0"},
{{OperatorType::kSpaceToBatchND, 1}, "1.6.0"},
{{OperatorType::kSpaceToBatchND, 2}, "1.14.0"},
{{OperatorType::kSub, 1}, "1.6.0"},
{{OperatorType::kSub, 2}, "1.14.0"},
{{OperatorType::kDiv, 1}, "1.6.0"},
{{OperatorType::kBatchToSpaceND, 1}, "1.6.0"},
{{OperatorType::kBatchToSpaceND, 2}, "1.14.0"},
{{OperatorType::kCast, 1}, "1.5.0"},
{{OperatorType::kConcatenation, 1}, "1.5.0"},
{{OperatorType::kConcatenation, 2}, "1.14.0"},
{{OperatorType::kDepthToSpace, 1}, "1.5.0"},
{{OperatorType::kFakeQuant, 1}, "1.5.0"},
{{OperatorType::kFakeQuant, 2}, "1.10.0"},
{{OperatorType::kFullyConnected, 1}, "1.5.0"},
{{OperatorType::kFullyConnected, 2}, "1.10.0"},
{{OperatorType::kFullyConnected, 3}, "1.14.0"},
{{OperatorType::kFullyConnected, 4}, "1.14.0"},
{{OperatorType::kGather, 1}, "1.6.0"},
{{OperatorType::kGather, 2}, "1.14.0"},
{{OperatorType::kGatherNd, 1}, "1.14.0"},
{{OperatorType::kSvdf, 1}, "1.5.0"},
{{OperatorType::kSvdf, 2}, "1.14.0"},
{{OperatorType::kL2Normalization, 1}, "1.5.0"},
{{OperatorType::kL2Normalization, 2}, "1.14.0"},
{{OperatorType::kL2Pool, 1}, "1.5.0"},
{{OperatorType::kLocalResponseNormalization, 1}, "1.5.0"},
{{OperatorType::kMaxPool, 1}, "1.5.0"},
{{OperatorType::kMaxPool, 2}, "1.14.0"},
{{OperatorType::kMaximum, 1}, "1.14.0"},
{{OperatorType::kMaximum, 2}, "1.14.0"},
{{OperatorType::kMinimum, 1}, "1.14.0"},
{{OperatorType::kMinimum, 2}, "1.14.0"},
{{OperatorType::kMul, 1}, "1.5.0"},
{{OperatorType::kMul, 2}, "1.14.0"},
{{OperatorType::kPad, 1}, "1.5.0"},
{{OperatorType::kPad, 2}, "1.14.0"},
{{OperatorType::kTile, 1}, "1.10.1"},
{{OperatorType::kPadV2, 1}, "1.9.0"},
{{OperatorType::kPadV2, 2}, "1.14.0"},
{{OperatorType::kReshape, 1}, "1.5.0"},
{{OperatorType::kSoftmax, 1}, "1.5.0"},
{{OperatorType::kSoftmax, 2}, "1.14.0"},
{{OperatorType::kSpaceToDepth, 1}, "1.5.0"},
{{OperatorType::kSpaceToDepth, 2}, "1.14.0"},
{{OperatorType::kTranspose, 1}, "1.6.0"},
{{OperatorType::kTranspose, 2}, "1.14.0"},
{{OperatorType::kLstmCell, 1}, "1.7.0"},
{{OperatorType::kLstmCell, 2}, "1.10.0"},
{{OperatorType::kLstmCell, 3}, "1.14.0"},
{{OperatorType::kUnidirectionalSequenceLstm, 1}, "1.13.1"},
{{OperatorType::kUnidirectionalSequenceLstm, 1}, "1.14.0"},
{{OperatorType::kBidirectionalSequenceLstm, 1}, "1.14.0"},
{{OperatorType::kBidirectionalSequenceRnn, 1}, "1.14.0"},
{{OperatorType::kMean, 1}, "1.6.0"},
{{OperatorType::kMean, 2}, "1.14.0"},
{{OperatorType::kSum, 1}, "1.10.0"},
{{OperatorType::kReduceMax, 1}, "1.11.0"},
{{OperatorType::kReduceMax, 2}, "1.14.0"},
{{OperatorType::kReduceMin, 1}, "1.11.0"},
{{OperatorType::kReduceMin, 2}, "1.14.0"},
{{OperatorType::kReduceProd, 1}, "1.11.0"},
{{OperatorType::kAny, 1}, "1.11.0"},
{{OperatorType::kRelu6, 1}, "1.14.0"},
{{OperatorType::kRelu6, 2}, "1.14.0"},
{{OperatorType::kResizeBilinear, 1}, "1.7.0"},
{{OperatorType::kResizeBilinear, 2}, "1.14.0"},
{{OperatorType::kResizeNearestNeighbor, 1}, "1.13.1"},
{{OperatorType::kResizeNearestNeighbor, 2}, "1.14.0"},
{{OperatorType::kSqueeze, 1}, "1.6.0"},
{{OperatorType::kSplit, 1}, "1.5.0"},
{{OperatorType::kSplit, 2}, "1.14.0"},
{{OperatorType::kSplit, 3}, "1.14.0"},
{{OperatorType::kSplitV, 1}, "1.13.1"},
{{OperatorType::kStridedSlice, 1}, "1.6.0"},
{{OperatorType::kStridedSlice, 2}, "1.14.0"},
{{OperatorType::kTopK_V2, 1}, "1.7.0"},
{{OperatorType::kTopK_V2, 2}, "1.14.0"},
{{OperatorType::kArgMax, 1}, "1.9.0"},
{{OperatorType::kArgMax, 2}, "1.14.0"},
{{OperatorType::kArgMin, 1}, "1.9.0"},
{{OperatorType::kArgMin, 2}, "1.14.0"},
{{OperatorType::kTransposeConv, 1}, "1.9.0"},
{{OperatorType::kSparseToDense, 1}, "1.9.0"},
{{OperatorType::kSparseToDense, 2}, "1.14.0"},
{{OperatorType::kExpandDims, 1}, "1.10.0"},
{{OperatorType::kPack, 1}, "1.11.0"},
{{OperatorType::kPack, 2}, "1.14.0"},
{{OperatorType::kShape, 1}, "1.10.0"},
{{OperatorType::kSlice, 1}, "1.14.0"},
{{OperatorType::kSlice, 2}, "1.14.0"},
{{OperatorType::kSlice, 3}, "1.14.0"},
{{OperatorType::kTanh, 1}, "1.14.0"},
{{OperatorType::kTanh, 2}, "1.14.0"},
{{OperatorType::kOneHot, 1}, "1.11.0"},
{{OperatorType::kCTCBeamSearchDecoder, 1}, "1.11.0"},
{{OperatorType::kUnpack, 1}, "1.11.0"},
{{OperatorType::kLeakyRelu, 1}, "1.13.1"},
{{OperatorType::kLogistic, 1}, "1.14.0"},
{{OperatorType::kLogistic, 2}, "1.14.0"},
{{OperatorType::kLogSoftmax, 1}, "1.14.0"},
{{OperatorType::kLogSoftmax, 2}, "1.14.0"},
{{OperatorType::kSquaredDifference, 1}, "1.13.1"},
{{OperatorType::kMirrorPad, 1}, "1.13.1"},
{{OperatorType::kUnique, 1}, "1.14.0"},
{{OperatorType::kUnidirectionalSequenceRnn, 1}, "1.14.0"},
{{OperatorType::kWhere, 1}, "1.14.0"},
{{OperatorType::kDequantize, 1}, "1.13.1"},
{{OperatorType::kDequantize, 2}, "1.14.0"},
{{OperatorType::kReverseSequence, 1}, "1.14.0"},
{{OperatorType::kEqual, 1}, "1.14.0"},
{{OperatorType::kEqual, 2}, "1.14.0"},
{{OperatorType::kNotEqual, 1}, "1.14.0"},
{{OperatorType::kNotEqual, 2}, "1.14.0"},
{{OperatorType::kGreater, 1}, "1.14.0"},
{{OperatorType::kGreater, 2}, "1.14.0"},
{{OperatorType::kGreaterEqual, 1}, "1.14.0"},
{{OperatorType::kGreaterEqual, 2}, "1.14.0"},
{{OperatorType::kLess, 1}, "1.14.0"},
{{OperatorType::kLess, 2}, "1.14.0"},
{{OperatorType::kLessEqual, 1}, "1.14.0"},
{{OperatorType::kLessEqual, 2}, "1.14.0"},
{{OperatorType::kSelect, 1}, "1.14.0"},
{{OperatorType::kSelect, 2}, "1.14.0"},
{{OperatorType::kFloorDiv, 1}, "1.14.0"},
{{OperatorType::kFloorDiv, 2}, "1.14.0"},
});
const auto& op_types_map =
tflite::BuildOperatorByTypeMap(false /*enable_select_tf_ops=*/);
OperatorSignature op_signature;
op_signature.model = &model;
string model_min_version;
for (const auto& op : model.operators) {
op_signature.op = op.get();
const int version = op_types_map.at(op->type)->GetVersion(op_signature);
std::pair<OperatorType, int> version_key = {op->type, version};
auto it = op_version_map->find(version_key);
if (it == op_version_map->end() || it->second == kPendingReleaseOpVersion) {
// In case we didn't find the current op in the map, or the operator
// doesn't have a minimum runtime version associated, continue.
continue;
}
if (strcmp(model_min_version.c_str(), it->second.c_str()) < 0) {
// Current min model runtime version should be bumped if we see a higher
// op version.
model_min_version = it->second;
}
}
return model_min_version;
}
} // namespace tflite
} // namespace toco
|
Update op version map as 1.14.0 first RC comes out.
|
Update op version map as 1.14.0 first RC comes out.
PiperOrigin-RevId: 250941161
|
C++
|
apache-2.0
|
ppwwyyxx/tensorflow,ppwwyyxx/tensorflow,petewarden/tensorflow,davidzchen/tensorflow,adit-chandra/tensorflow,freedomtan/tensorflow,arborh/tensorflow,jhseu/tensorflow,ppwwyyxx/tensorflow,davidzchen/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-pywrap_tf_optimizer,renyi533/tensorflow,chemelnucfin/tensorflow,gunan/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,sarvex/tensorflow,ppwwyyxx/tensorflow,tensorflow/tensorflow-pywrap_saved_model,yongtang/tensorflow,frreiss/tensorflow-fred,adit-chandra/tensorflow,renyi533/tensorflow,davidzchen/tensorflow,xzturn/tensorflow,davidzchen/tensorflow,xzturn/tensorflow,frreiss/tensorflow-fred,DavidNorman/tensorflow,freedomtan/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-experimental_link_static_libraries_once,ppwwyyxx/tensorflow,arborh/tensorflow,sarvex/tensorflow,tensorflow/tensorflow,paolodedios/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,frreiss/tensorflow-fred,ppwwyyxx/tensorflow,adit-chandra/tensorflow,xzturn/tensorflow,paolodedios/tensorflow,chemelnucfin/tensorflow,arborh/tensorflow,jhseu/tensorflow,paolodedios/tensorflow,paolodedios/tensorflow,gunan/tensorflow,alsrgv/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow,karllessard/tensorflow,annarev/tensorflow,adit-chandra/tensorflow,tensorflow/tensorflow,freedomtan/tensorflow,xzturn/tensorflow,renyi533/tensorflow,cxxgtxy/tensorflow,alsrgv/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,karllessard/tensorflow,ppwwyyxx/tensorflow,ghchinoy/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,yongtang/tensorflow,ppwwyyxx/tensorflow,gunan/tensorflow,davidzchen/tensorflow,xzturn/tensorflow,jhseu/tensorflow,xzturn/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,aldian/tensorflow,petewarden/tensorflow,alsrgv/tensorflow,DavidNorman/tensorflow,frreiss/tensorflow-fred,gunan/tensorflow,ppwwyyxx/tensorflow,renyi533/tensorflow,yongtang/tensorflow,ghchinoy/tensorflow,Intel-Corporation/tensorflow,annarev/tensorflow,tensorflow/tensorflow,yongtang/tensorflow,cxxgtxy/tensorflow,Intel-tensorflow/tensorflow,gautam1858/tensorflow,alsrgv/tensorflow,adit-chandra/tensorflow,alsrgv/tensorflow,chemelnucfin/tensorflow,frreiss/tensorflow-fred,adit-chandra/tensorflow,jhseu/tensorflow,annarev/tensorflow,frreiss/tensorflow-fred,petewarden/tensorflow,freedomtan/tensorflow,aam-at/tensorflow,renyi533/tensorflow,yongtang/tensorflow,DavidNorman/tensorflow,frreiss/tensorflow-fred,DavidNorman/tensorflow,adit-chandra/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,Intel-Corporation/tensorflow,karllessard/tensorflow,annarev/tensorflow,annarev/tensorflow,ppwwyyxx/tensorflow,aam-at/tensorflow,freedomtan/tensorflow,tensorflow/tensorflow,adit-chandra/tensorflow,davidzchen/tensorflow,renyi533/tensorflow,aam-at/tensorflow,jhseu/tensorflow,chemelnucfin/tensorflow,davidzchen/tensorflow,ghchinoy/tensorflow,sarvex/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-pywrap_saved_model,petewarden/tensorflow,arborh/tensorflow,karllessard/tensorflow,DavidNorman/tensorflow,cxxgtxy/tensorflow,paolodedios/tensorflow,paolodedios/tensorflow,chemelnucfin/tensorflow,cxxgtxy/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,petewarden/tensorflow,aam-at/tensorflow,arborh/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_saved_model,ghchinoy/tensorflow,aam-at/tensorflow,Intel-Corporation/tensorflow,petewarden/tensorflow,arborh/tensorflow,alsrgv/tensorflow,davidzchen/tensorflow,renyi533/tensorflow,aldian/tensorflow,gautam1858/tensorflow,petewarden/tensorflow,alsrgv/tensorflow,cxxgtxy/tensorflow,Intel-tensorflow/tensorflow,DavidNorman/tensorflow,ppwwyyxx/tensorflow,karllessard/tensorflow,yongtang/tensorflow,paolodedios/tensorflow,petewarden/tensorflow,petewarden/tensorflow,gunan/tensorflow,gautam1858/tensorflow,adit-chandra/tensorflow,tensorflow/tensorflow-pywrap_saved_model,karllessard/tensorflow,tensorflow/tensorflow,davidzchen/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,alsrgv/tensorflow,aldian/tensorflow,Intel-Corporation/tensorflow,xzturn/tensorflow,gunan/tensorflow,gautam1858/tensorflow,jhseu/tensorflow,arborh/tensorflow,sarvex/tensorflow,Intel-Corporation/tensorflow,jhseu/tensorflow,freedomtan/tensorflow,annarev/tensorflow,karllessard/tensorflow,jhseu/tensorflow,gautam1858/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-pywrap_tf_optimizer,aldian/tensorflow,ghchinoy/tensorflow,Intel-tensorflow/tensorflow,DavidNorman/tensorflow,petewarden/tensorflow,sarvex/tensorflow,aldian/tensorflow,paolodedios/tensorflow,yongtang/tensorflow,annarev/tensorflow,DavidNorman/tensorflow,gautam1858/tensorflow,gunan/tensorflow,tensorflow/tensorflow-pywrap_saved_model,gautam1858/tensorflow,frreiss/tensorflow-fred,yongtang/tensorflow,alsrgv/tensorflow,adit-chandra/tensorflow,davidzchen/tensorflow,arborh/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-pywrap_tf_optimizer,davidzchen/tensorflow,aam-at/tensorflow,Intel-tensorflow/tensorflow,adit-chandra/tensorflow,annarev/tensorflow,gautam1858/tensorflow,freedomtan/tensorflow,xzturn/tensorflow,adit-chandra/tensorflow,gautam1858/tensorflow,frreiss/tensorflow-fred,renyi533/tensorflow,ghchinoy/tensorflow,tensorflow/tensorflow-pywrap_saved_model,gunan/tensorflow,freedomtan/tensorflow,renyi533/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,ghchinoy/tensorflow,aam-at/tensorflow,chemelnucfin/tensorflow,cxxgtxy/tensorflow,aam-at/tensorflow,ghchinoy/tensorflow,tensorflow/tensorflow,annarev/tensorflow,aldian/tensorflow,jhseu/tensorflow,frreiss/tensorflow-fred,cxxgtxy/tensorflow,gautam1858/tensorflow,gautam1858/tensorflow,paolodedios/tensorflow,DavidNorman/tensorflow,alsrgv/tensorflow,aam-at/tensorflow,gunan/tensorflow,freedomtan/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,arborh/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,sarvex/tensorflow,petewarden/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,Intel-Corporation/tensorflow,yongtang/tensorflow,frreiss/tensorflow-fred,chemelnucfin/tensorflow,aldian/tensorflow,freedomtan/tensorflow,xzturn/tensorflow,frreiss/tensorflow-fred,karllessard/tensorflow,annarev/tensorflow,ghchinoy/tensorflow,gautam1858/tensorflow,ppwwyyxx/tensorflow,aam-at/tensorflow,ghchinoy/tensorflow,sarvex/tensorflow,gunan/tensorflow,karllessard/tensorflow,DavidNorman/tensorflow,tensorflow/tensorflow,chemelnucfin/tensorflow,sarvex/tensorflow,karllessard/tensorflow,aam-at/tensorflow,arborh/tensorflow,jhseu/tensorflow,aam-at/tensorflow,freedomtan/tensorflow,arborh/tensorflow,paolodedios/tensorflow,karllessard/tensorflow,tensorflow/tensorflow,DavidNorman/tensorflow,chemelnucfin/tensorflow,chemelnucfin/tensorflow,chemelnucfin/tensorflow,Intel-tensorflow/tensorflow,renyi533/tensorflow,xzturn/tensorflow,renyi533/tensorflow,arborh/tensorflow,davidzchen/tensorflow,Intel-Corporation/tensorflow,cxxgtxy/tensorflow,aldian/tensorflow,gunan/tensorflow,Intel-Corporation/tensorflow,xzturn/tensorflow,Intel-tensorflow/tensorflow,ghchinoy/tensorflow,renyi533/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,Intel-tensorflow/tensorflow,annarev/tensorflow,gunan/tensorflow,alsrgv/tensorflow,freedomtan/tensorflow,chemelnucfin/tensorflow,jhseu/tensorflow,petewarden/tensorflow,jhseu/tensorflow,alsrgv/tensorflow,xzturn/tensorflow,ghchinoy/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-experimental_link_static_libraries_once,DavidNorman/tensorflow,Intel-tensorflow/tensorflow
|
549fa59a5d3e13b9cf18249655462ebd35aecda2
|
tests/input/kbd.cpp
|
tests/input/kbd.cpp
|
/*
* Copyright © 2012-2013 Red Hat, Inc.
*
* 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 (including the next
* paragraph) 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.
*
*/
#if HAVE_CONFIG_H
#include <config.h>
#endif
#include <stdexcept>
#include <map>
#include <xorg/gtest/xorg-gtest.h>
#include <linux/input.h>
#include <X11/Xlib.h>
#define XK_LATIN1
#include <X11/keysymdef.h>
#include <X11/XF86keysym.h>
#include <X11/Xutil.h>
#include <X11/extensions/XInput.h>
#include <X11/extensions/XInput2.h>
#include "xit-server-input-test.h"
#include "device-interface.h"
#include "helpers.h"
typedef std::pair <int, KeySym> Key_Pair;
typedef std::multimap<std::string, Key_Pair> Keys_Map;
typedef Keys_Map::iterator keys_mapIter;
typedef std::vector<Key_Pair> MultiMedia_Keys_Map;
typedef MultiMedia_Keys_Map::iterator multimediakeys_mapIter;
/**
* Keyboard driver test. This class takes a string as parameter that is used
* for the XkbLayout option.
*/
class KeyboardTest : public XITServerInputTest,
public DeviceInterface,
public ::testing::WithParamInterface<std::string> {
/**
* Initializes a standard keyboard device.
*/
virtual void SetUp() {
SetDevice("keyboards/AT-Translated-Set-2-Keyboard.desc");
// Define a map of pair to hold each key/keysym per layout
// US, QWERTY => qwerty
Keys.insert (std::pair<std::string, Key_Pair> ("us", Key_Pair (KEY_Q, XK_q)));
Keys.insert (std::pair<std::string, Key_Pair> ("us", Key_Pair (KEY_W, XK_w)));
Keys.insert (std::pair<std::string, Key_Pair> ("us", Key_Pair (KEY_E, XK_e)));
Keys.insert (std::pair<std::string, Key_Pair> ("us", Key_Pair (KEY_R, XK_r)));
Keys.insert (std::pair<std::string, Key_Pair> ("us", Key_Pair (KEY_T, XK_t)));
Keys.insert (std::pair<std::string, Key_Pair> ("us", Key_Pair (KEY_Y, XK_y)));
// German, QWERTY => qwertz
Keys.insert (std::pair<std::string, Key_Pair> ("de", Key_Pair (KEY_Q, XK_q)));
Keys.insert (std::pair<std::string, Key_Pair> ("de", Key_Pair (KEY_W, XK_w)));
Keys.insert (std::pair<std::string, Key_Pair> ("de", Key_Pair (KEY_E, XK_e)));
Keys.insert (std::pair<std::string, Key_Pair> ("de", Key_Pair (KEY_R, XK_r)));
Keys.insert (std::pair<std::string, Key_Pair> ("de", Key_Pair (KEY_T, XK_t)));
Keys.insert (std::pair<std::string, Key_Pair> ("de", Key_Pair (KEY_Y, XK_z)));
// French, QWERTY => azerty
Keys.insert (std::pair<std::string, Key_Pair> ("fr", Key_Pair (KEY_Q, XK_a)));
Keys.insert (std::pair<std::string, Key_Pair> ("fr", Key_Pair (KEY_W, XK_z)));
Keys.insert (std::pair<std::string, Key_Pair> ("fr", Key_Pair (KEY_E, XK_e)));
Keys.insert (std::pair<std::string, Key_Pair> ("fr", Key_Pair (KEY_R, XK_r)));
Keys.insert (std::pair<std::string, Key_Pair> ("fr", Key_Pair (KEY_T, XK_t)));
Keys.insert (std::pair<std::string, Key_Pair> ("fr", Key_Pair (KEY_Y, XK_y)));
// Define a vector of pair to hold each key/keysym for multimedia
Multimedia_Keys.push_back (Key_Pair (KEY_MUTE, XF86XK_AudioMute));
Multimedia_Keys.push_back (Key_Pair (KEY_VOLUMEUP, XF86XK_AudioRaiseVolume));
Multimedia_Keys.push_back (Key_Pair (KEY_VOLUMEDOWN, XF86XK_AudioLowerVolume));
Multimedia_Keys.push_back (Key_Pair (KEY_PLAYPAUSE, XF86XK_AudioPlay));
Multimedia_Keys.push_back (Key_Pair (KEY_NEXTSONG, XF86XK_AudioNext));
Multimedia_Keys.push_back (Key_Pair (KEY_PREVIOUSSONG, XF86XK_AudioPrev));
XITServerInputTest::SetUp();
}
/**
* Sets up an xorg.conf for a single kbd CoreKeyboard device.
* The input from GetParam() is used as XkbLayout.
*/
virtual void SetUpConfigAndLog() {
/* we don't use the dummy driver here, for some reason we won't get
* key events with it */
config.AddInputSection("kbd", "--device--",
"Option \"CoreKeyboard\" \"on\"\n"
"Option \"XkbRules\" \"xorg\"\n"
"Option \"XkbModel\" \"dellusbmm\"\n"
"Option \"XkbLayout\" \""+ GetParam() + "\"\n");
config.WriteConfig();
}
protected:
/**
* List of evdev keysyms to X11 keysyms for each layout.
*/
Keys_Map Keys;
/**
* List of evdev keysyms to X11 keysyms for multimedia keys
*/
MultiMedia_Keys_Map Multimedia_Keys;
};
TEST_P(KeyboardTest, DeviceExists)
{
std::string param;
int ndevices;
XIDeviceInfo *info;
info = XIQueryDevice(Display(), XIAllDevices, &ndevices);
bool found = false;
while(ndevices--) {
if (strcmp(info[ndevices].name, "--device--") == 0) {
ASSERT_EQ(found, false) << "Duplicate device" << std::endl;
found = true;
}
}
ASSERT_EQ(found, true);
XIFreeDeviceInfo(info);
}
void play_key_pair (::Display *display, xorg::testing::evemu::Device *dev, Key_Pair pair)
{
dev->PlayOne(EV_KEY, pair.first, 1, true);
dev->PlayOne(EV_KEY, pair.first, 0, true);
XSync(display, False);
ASSERT_NE(XPending(display), 0) << "No event pending" << std::endl;
XEvent press;
XNextEvent(display, &press);
KeySym sym = XKeycodeToKeysym(display, press.xkey.keycode, 0);
ASSERT_NE((KeySym)NoSymbol, sym) << "No keysym for keycode " << press.xkey.keycode << std::endl;
ASSERT_EQ(pair.second, sym) << "Keysym not matching for keycode " << press.xkey.keycode << std::endl;
XSync(display, False);
while (XPending(display))
XNextEvent(display, &press);
}
TEST_P(KeyboardTest, KeyboardLayout)
{
std::string layout = GetParam();
ASSERT_TRUE(xorg::testing::XServer::WaitForDevice(Display(), "--device--"));
XSelectInput(Display(), DefaultRootWindow(Display()), KeyPressMask | KeyReleaseMask);
keys_mapIter it;
std::pair<keys_mapIter, keys_mapIter> keyRange = Keys.equal_range(layout);
for (it = keyRange.first; it != keyRange.second; ++it)
play_key_pair (Display(), dev.get(), (*it).second);
// Now test multimedia keys
multimediakeys_mapIter m_it;
for (m_it = Multimedia_Keys.begin(); m_it != Multimedia_Keys.end(); m_it++)
play_key_pair (Display(), dev.get(), (*m_it));
}
INSTANTIATE_TEST_CASE_P(, KeyboardTest, ::testing::Values("us", "de", "fr"));
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
/*
* Copyright © 2012-2013 Red Hat, Inc.
*
* 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 (including the next
* paragraph) 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.
*
*/
#if HAVE_CONFIG_H
#include <config.h>
#endif
#include <stdexcept>
#include <map>
#include <xorg/gtest/xorg-gtest.h>
#include <linux/input.h>
#include <X11/Xlib.h>
#define XK_LATIN1
#include <X11/keysymdef.h>
#include <X11/XF86keysym.h>
#include <X11/Xutil.h>
#include <X11/extensions/XInput.h>
#include <X11/extensions/XInput2.h>
#include "xit-server-input-test.h"
#include "xit-event.h"
#include "device-interface.h"
#include "helpers.h"
typedef std::pair <int, KeySym> Key_Pair;
typedef std::multimap<std::string, Key_Pair> Keys_Map;
typedef Keys_Map::iterator keys_mapIter;
typedef std::vector<Key_Pair> MultiMedia_Keys_Map;
typedef MultiMedia_Keys_Map::iterator multimediakeys_mapIter;
/**
* Keyboard driver test. This class takes a string as parameter that is used
* for the XkbLayout option.
*/
class KeyboardTest : public XITServerInputTest,
public DeviceInterface,
public ::testing::WithParamInterface<std::string> {
/**
* Initializes a standard keyboard device.
*/
virtual void SetUp() {
SetDevice("keyboards/AT-Translated-Set-2-Keyboard.desc");
// Define a map of pair to hold each key/keysym per layout
// US, QWERTY => qwerty
Keys.insert (std::pair<std::string, Key_Pair> ("us", Key_Pair (KEY_Q, XK_q)));
Keys.insert (std::pair<std::string, Key_Pair> ("us", Key_Pair (KEY_W, XK_w)));
Keys.insert (std::pair<std::string, Key_Pair> ("us", Key_Pair (KEY_E, XK_e)));
Keys.insert (std::pair<std::string, Key_Pair> ("us", Key_Pair (KEY_R, XK_r)));
Keys.insert (std::pair<std::string, Key_Pair> ("us", Key_Pair (KEY_T, XK_t)));
Keys.insert (std::pair<std::string, Key_Pair> ("us", Key_Pair (KEY_Y, XK_y)));
// German, QWERTY => qwertz
Keys.insert (std::pair<std::string, Key_Pair> ("de", Key_Pair (KEY_Q, XK_q)));
Keys.insert (std::pair<std::string, Key_Pair> ("de", Key_Pair (KEY_W, XK_w)));
Keys.insert (std::pair<std::string, Key_Pair> ("de", Key_Pair (KEY_E, XK_e)));
Keys.insert (std::pair<std::string, Key_Pair> ("de", Key_Pair (KEY_R, XK_r)));
Keys.insert (std::pair<std::string, Key_Pair> ("de", Key_Pair (KEY_T, XK_t)));
Keys.insert (std::pair<std::string, Key_Pair> ("de", Key_Pair (KEY_Y, XK_z)));
// French, QWERTY => azerty
Keys.insert (std::pair<std::string, Key_Pair> ("fr", Key_Pair (KEY_Q, XK_a)));
Keys.insert (std::pair<std::string, Key_Pair> ("fr", Key_Pair (KEY_W, XK_z)));
Keys.insert (std::pair<std::string, Key_Pair> ("fr", Key_Pair (KEY_E, XK_e)));
Keys.insert (std::pair<std::string, Key_Pair> ("fr", Key_Pair (KEY_R, XK_r)));
Keys.insert (std::pair<std::string, Key_Pair> ("fr", Key_Pair (KEY_T, XK_t)));
Keys.insert (std::pair<std::string, Key_Pair> ("fr", Key_Pair (KEY_Y, XK_y)));
// Define a vector of pair to hold each key/keysym for multimedia
Multimedia_Keys.push_back (Key_Pair (KEY_MUTE, XF86XK_AudioMute));
Multimedia_Keys.push_back (Key_Pair (KEY_VOLUMEUP, XF86XK_AudioRaiseVolume));
Multimedia_Keys.push_back (Key_Pair (KEY_VOLUMEDOWN, XF86XK_AudioLowerVolume));
Multimedia_Keys.push_back (Key_Pair (KEY_PLAYPAUSE, XF86XK_AudioPlay));
Multimedia_Keys.push_back (Key_Pair (KEY_NEXTSONG, XF86XK_AudioNext));
Multimedia_Keys.push_back (Key_Pair (KEY_PREVIOUSSONG, XF86XK_AudioPrev));
XITServerInputTest::SetUp();
}
/**
* Sets up an xorg.conf for a single kbd CoreKeyboard device.
* The input from GetParam() is used as XkbLayout.
*/
virtual void SetUpConfigAndLog() {
/* we don't use the dummy driver here, for some reason we won't get
* key events with it */
config.AddInputSection("kbd", "--device--",
"Option \"CoreKeyboard\" \"on\"\n"
"Option \"XkbRules\" \"xorg\"\n"
"Option \"XkbModel\" \"dellusbmm\"\n"
"Option \"XkbLayout\" \""+ GetParam() + "\"\n");
config.WriteConfig();
}
protected:
/**
* List of evdev keysyms to X11 keysyms for each layout.
*/
Keys_Map Keys;
/**
* List of evdev keysyms to X11 keysyms for multimedia keys
*/
MultiMedia_Keys_Map Multimedia_Keys;
};
TEST_P(KeyboardTest, DeviceExists)
{
std::string param;
int ndevices;
XIDeviceInfo *info;
info = XIQueryDevice(Display(), XIAllDevices, &ndevices);
bool found = false;
while(ndevices--) {
if (strcmp(info[ndevices].name, "--device--") == 0) {
ASSERT_EQ(found, false) << "Duplicate device" << std::endl;
found = true;
}
}
ASSERT_EQ(found, true);
XIFreeDeviceInfo(info);
}
void play_key_pair (::Display *display, xorg::testing::evemu::Device *dev, Key_Pair pair)
{
dev->PlayOne(EV_KEY, pair.first, 1, true);
dev->PlayOne(EV_KEY, pair.first, 0, true);
ASSERT_EVENT(XEvent, press, display, KeyPress);
KeySym sym = XKeycodeToKeysym(display, press->xkey.keycode, 0);
ASSERT_NE((KeySym)NoSymbol, sym) << "No keysym for keycode " << press->xkey.keycode << std::endl;
ASSERT_EQ(pair.second, sym) << "Keysym not matching for keycode " << press->xkey.keycode << std::endl;
XSync(display, False);
while (XPending(display))
XSync(display, True);
}
TEST_P(KeyboardTest, KeyboardLayout)
{
std::string layout = GetParam();
ASSERT_TRUE(xorg::testing::XServer::WaitForDevice(Display(), "--device--"));
XSelectInput(Display(), DefaultRootWindow(Display()), KeyPressMask | KeyReleaseMask);
keys_mapIter it;
std::pair<keys_mapIter, keys_mapIter> keyRange = Keys.equal_range(layout);
for (it = keyRange.first; it != keyRange.second; ++it)
play_key_pair (Display(), dev.get(), (*it).second);
// Now test multimedia keys
multimediakeys_mapIter m_it;
for (m_it = Multimedia_Keys.begin(); m_it != Multimedia_Keys.end(); m_it++)
play_key_pair (Display(), dev.get(), (*m_it));
}
INSTANTIATE_TEST_CASE_P(, KeyboardTest, ::testing::Values("us", "de", "fr"));
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
use some of the newer wrappers to handle key events
|
kbd: use some of the newer wrappers to handle key events
This makes the test less flaky too, since slow VT switching could previously
fail the tests
Signed-off-by: Peter Hutterer <[email protected]>
|
C++
|
mit
|
freedesktop-unofficial-mirror/xorg__test__xorg-integration-tests,freedesktop-unofficial-mirror/xorg__test__xorg-integration-tests,freedesktop-unofficial-mirror/xorg__test__xorg-integration-tests
|
4311e26cf6abf6a6cc18b9562ab9f7db89be3d1a
|
tests/model_test.cc
|
tests/model_test.cc
|
// Nodebase test
#include <limits>
#include <memory>
#include "catch.hpp"
#include "model.h"
#include "settings.h"
//! \brief Check 3D model D3Q19 case
TEST_CASE("Model weights are checked", "[LBM][Model]") {
const lbmdem::Real Tolerance = 1.E-16;
SECTION("D2Q9 model weights are checked") {
const auto d2q9 = lbmdem::Model<2, 9>();
REQUIRE(d2q9.weight( 0, 0) == Approx(4.0/9.0));
REQUIRE(d2q9.weight( 1, 0) == Approx(1.0/9.0));
REQUIRE(d2q9.weight( 0, 1) == Approx(1.0/9.0));
REQUIRE(d2q9.weight(-1, 0) == Approx(1.0/9.0));
REQUIRE(d2q9.weight( 0,-1) == Approx(1.0/9.0));
REQUIRE(d2q9.weight( 1, 1) == Approx(1.0/36.0));
REQUIRE(d2q9.weight( 1,-1) == Approx(1.0/36.0));
REQUIRE(d2q9.weight(-1, 1) == Approx(1.0/36.0));
REQUIRE(d2q9.weight(-1,-1) == Approx(1.0/36.0));
}
SECTION("D2Q9 model weights sum to 1") {
const auto d2q9 = lbmdem::Model<2, 9>();
lbmdem::Real sum = 0;
for (int i = -1; i <= 1; ++i)
for (int j = -1; j <= 1; ++j)
sum += d2q9.weight(i,j);
REQUIRE(sum == Approx(1.0));
}
SECTION("D3Q27 model weights are checked") {
const auto d3q27 = lbmdem::Model<3, 27>();
REQUIRE(d3q27.weight( 0, 0, 0) == Approx(8.0/27.0));
REQUIRE(d3q27.weight( 1, 0, 0) == Approx(2.0/27.0));
REQUIRE(d3q27.weight( 0, 1, 0) == Approx(2.0/27.0));
REQUIRE(d3q27.weight( 0, 0, 1) == Approx(2.0/27.0));
REQUIRE(d3q27.weight(-1, 0, 0) == Approx(2.0/27.0));
REQUIRE(d3q27.weight( 0,-1, 0) == Approx(2.0/27.0));
REQUIRE(d3q27.weight( 0, 0,-1) == Approx(2.0/27.0));
REQUIRE(d3q27.weight( 1, 1, 0) == Approx(1.0/54.0));
REQUIRE(d3q27.weight( 1, 0, 1) == Approx(1.0/54.0));
REQUIRE(d3q27.weight( 0, 1, 1) == Approx(1.0/54.0));
REQUIRE(d3q27.weight(-1, 1, 0) == Approx(1.0/54.0));
REQUIRE(d3q27.weight(-1, 0, 1) == Approx(1.0/54.0));
REQUIRE(d3q27.weight( 0,-1, 1) == Approx(1.0/54.0));
REQUIRE(d3q27.weight( 1,-1, 0) == Approx(1.0/54.0));
REQUIRE(d3q27.weight( 1, 0,-1) == Approx(1.0/54.0));
REQUIRE(d3q27.weight( 0, 1,-1) == Approx(1.0/54.0));
REQUIRE(d3q27.weight(-1,-1, 0) == Approx(1.0/54.0));
REQUIRE(d3q27.weight(-1, 0,-1) == Approx(1.0/54.0));
REQUIRE(d3q27.weight( 0,-1,-1) == Approx(1.0/54.0));
REQUIRE(d3q27.weight( 1, 1, 1) == Approx(1.0/216.0));
REQUIRE(d3q27.weight( 1, 1, 1) == Approx(1.0/216.0));
REQUIRE(d3q27.weight( 1, 1, 1) == Approx(1.0/216.0));
REQUIRE(d3q27.weight(-1,-1,-1) == Approx(1.0/216.0));
REQUIRE(d3q27.weight(-1,-1,-1) == Approx(1.0/216.0));
REQUIRE(d3q27.weight(-1,-1,-1) == Approx(1.0/216.0));
}
SECTION("D3Q27 model weights sum to 1") {
const auto d3q27 = lbmdem::Model<3, 27>();
lbmdem::Real sum = 0;
for (int i = -1; i <= 1; ++i)
for (int j = -1; j <= 1; ++j)
for (int k = -1; k <= 1; ++k)
sum += d3q27.weight(i,j,k);
REQUIRE(sum == Approx(1.0));
}
}
|
// Nodebase test
#include <limits>
#include <memory>
#include "catch.hpp"
#include "model.h"
#include "settings.h"
//! \brief Check 3D model D3Q19 case
TEST_CASE("Model weights are checked", "[LBM][Model]") {
const lbmdem::Real Tolerance = 1.E-16;
SECTION("D2Q9 model weights are checked") {
const auto d2q9 = lbmdem::Model<2, 9>();
REQUIRE(d2q9.weight( 0, 0) == Approx(4.0/9.0));
REQUIRE(d2q9.weight( 1, 0) == Approx(1.0/9.0));
REQUIRE(d2q9.weight( 0, 1) == Approx(1.0/9.0));
REQUIRE(d2q9.weight(-1, 0) == Approx(1.0/9.0));
REQUIRE(d2q9.weight( 0,-1) == Approx(1.0/9.0));
REQUIRE(d2q9.weight( 1, 1) == Approx(1.0/36.0));
REQUIRE(d2q9.weight( 1,-1) == Approx(1.0/36.0));
REQUIRE(d2q9.weight(-1, 1) == Approx(1.0/36.0));
REQUIRE(d2q9.weight(-1,-1) == Approx(1.0/36.0));
}
SECTION("D2Q9 model weights sum to 1") {
const auto d2q9 = lbmdem::Model<2, 9>();
lbmdem::Real sum = 0;
for (int i = -1; i <= 1; ++i)
for (int j = -1; j <= 1; ++j)
sum += d2q9.weight(i,j);
REQUIRE(sum == Approx(1.0));
}
SECTION("D2Q9 model weights are zero outside the stencil") {
const auto d2q9 = lbmdem::Model<2, 9>();
lbmdem::Real sum = 0;
for (int i = -100; i <= 100; ++i)
for (int j = -100; j <= 100; ++j)
sum += d2q9.weight(i,j);
REQUIRE(sum == Approx(1.0));
}
SECTION("D3Q27 model weights are checked") {
const auto d3q27 = lbmdem::Model<3, 27>();
REQUIRE(d3q27.weight( 0, 0, 0) == Approx(8.0/27.0));
REQUIRE(d3q27.weight( 1, 0, 0) == Approx(2.0/27.0));
REQUIRE(d3q27.weight( 0, 1, 0) == Approx(2.0/27.0));
REQUIRE(d3q27.weight( 0, 0, 1) == Approx(2.0/27.0));
REQUIRE(d3q27.weight(-1, 0, 0) == Approx(2.0/27.0));
REQUIRE(d3q27.weight( 0,-1, 0) == Approx(2.0/27.0));
REQUIRE(d3q27.weight( 0, 0,-1) == Approx(2.0/27.0));
REQUIRE(d3q27.weight( 1, 1, 0) == Approx(1.0/54.0));
REQUIRE(d3q27.weight( 1, 0, 1) == Approx(1.0/54.0));
REQUIRE(d3q27.weight( 0, 1, 1) == Approx(1.0/54.0));
REQUIRE(d3q27.weight(-1, 1, 0) == Approx(1.0/54.0));
REQUIRE(d3q27.weight(-1, 0, 1) == Approx(1.0/54.0));
REQUIRE(d3q27.weight( 0,-1, 1) == Approx(1.0/54.0));
REQUIRE(d3q27.weight( 1,-1, 0) == Approx(1.0/54.0));
REQUIRE(d3q27.weight( 1, 0,-1) == Approx(1.0/54.0));
REQUIRE(d3q27.weight( 0, 1,-1) == Approx(1.0/54.0));
REQUIRE(d3q27.weight(-1,-1, 0) == Approx(1.0/54.0));
REQUIRE(d3q27.weight(-1, 0,-1) == Approx(1.0/54.0));
REQUIRE(d3q27.weight( 0,-1,-1) == Approx(1.0/54.0));
REQUIRE(d3q27.weight( 1, 1, 1) == Approx(1.0/216.0));
REQUIRE(d3q27.weight( 1, 1, 1) == Approx(1.0/216.0));
REQUIRE(d3q27.weight( 1, 1, 1) == Approx(1.0/216.0));
REQUIRE(d3q27.weight(-1,-1,-1) == Approx(1.0/216.0));
REQUIRE(d3q27.weight(-1,-1,-1) == Approx(1.0/216.0));
REQUIRE(d3q27.weight(-1,-1,-1) == Approx(1.0/216.0));
}
SECTION("D3Q27 model weights sum to 1") {
const auto d3q27 = lbmdem::Model<3, 27>();
lbmdem::Real sum = 0;
for (int i = -1; i <= 1; ++i)
for (int j = -1; j <= 1; ++j)
for (int k = -1; k <= 1; ++k)
sum += d3q27.weight(i,j,k);
REQUIRE(sum == Approx(1.0));
}
SECTION("D3Q27 model weights are zero outside the stencil") {
const auto d3q27 = lbmdem::Model<3, 27>();
lbmdem::Real sum = 0;
for (int i = -100; i <= 100; ++i)
for (int j = -100; j <= 100; ++j)
for (int k = -100; k <= 100; ++k)
sum += d3q27.weight(i,j,k);
REQUIRE(sum == Approx(1.0));
}
}
|
add tests for zero weights outside the stencil
|
add tests for zero weights outside the stencil
|
C++
|
mit
|
cb-geo/lbm-dem,cb-geo/lbm-dem,cb-geo/lbmdem,cb-geo/lbmdem
|
9af97140b8f7b7fd776fd1c261531bf5340cd29b
|
cont/src/TCollection.cxx
|
cont/src/TCollection.cxx
|
// @(#)root/cont:$Name: $:$Id: TCollection.cxx,v 1.16 2002/02/23 16:01:44 rdm Exp $
// Author: Fons Rademakers 13/08/95
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// Collection abstract base class. This class describes the base //
// protocol all collection classes have to implement. The ROOT //
// collection classes always store pointers to objects that inherit //
// from TObject. They never adopt the objects. Therefore, it is the //
// user's responsability to take care of deleting the actual objects //
// once they are not needed anymore. In exceptional cases, when the //
// user is 100% sure nothing else is referencing the objects in the //
// collection, one can delete all objects and the collection at the //
// same time using the Delete() function. //
// //
// Collections can be iterated using an iterator object (see //
// TIterator). Depending on the concrete collection class there may be //
// some additional methods of iterating. See the repective classes. //
// //
// TCollection inherits from TObject since we want to be able to have //
// collections of collections. //
// //
// In a later release the collections may become templatized. //
// //
//Begin_Html
/*
<img src="gif/tcollection_classtree.gif">
*/
//End_Html
//////////////////////////////////////////////////////////////////////////
#include "TCollection.h"
#include "TClass.h"
#include "TROOT.h"
#include "TBrowser.h"
#include "TObjectTable.h"
#include "TRegexp.h"
#include "TVirtualMutex.h"
TCollection *TCollection::fgCurrentCollection = 0;
TObjectTable *TCollection::fgGarbageCollection = 0;
Bool_t TCollection::fgEmptyingGarbage = kFALSE;
Int_t TCollection::fgGarbageStack = 0;
ClassImp(TCollection)
ClassImp(TIter)
//______________________________________________________________________________
void TCollection::AddAll(TCollection *col)
{
// Add all objects from collection col to this collection.
TIter next(col);
TObject *obj;
while ((obj = next()))
Add(obj);
}
//______________________________________________________________________________
void TCollection::AddVector(TObject *va_(obj1), ...)
{
// Add all arguments to this collection.
va_list ap;
va_start(ap, va_(obj1));
TObject *obj;
Add(va_(obj1));
while ((obj = va_arg(ap, TObject *)))
Add(obj);
va_end(ap);
}
//______________________________________________________________________________
Bool_t TCollection::AssertClass(TClass *cl) const
{
// Make sure all objects in this collection inherit from class cl.
TObject *obj;
TIter next(this);
Bool_t error = kFALSE;
if (!cl) {
Error("AssertClass", "class == 0");
return kTRUE;
}
for (int i = 0; (obj = next()); i++)
if (!obj->InheritsFrom(cl)) {
Error("AssertClass", "element %d is not an instance of class %s (%s)",
i, cl->GetName(), obj->ClassName());
error = kTRUE;
}
return error;
}
//______________________________________________________________________________
void TCollection::Browse(TBrowser *b)
{
// Browse this collection (called by TBrowser).
// If b=0, there is no Browse call TObject::Browse(0) instead.
// This means TObject::Inspect() will be invoked indirectly
TIter next(this);
TObject *obj;
if (b)
while ((obj = next())) b->Add(obj);
else
TObject::Browse(b);
}
//______________________________________________________________________________
void TCollection::Draw(Option_t *option)
{
// Draw all objects in this collection.
// wildcarding supported, eg option="xxx*" draws only objects
// with names xxx*
TRegexp re(option,kTRUE);
TIter next(this);
TObject *object;
Int_t nch = strlen(option);
while ((object = next())) {
TString s = object->GetName();
if (nch && strcmp(option,object->GetName()) && s.Index(re) == kNPOS) continue;
object->Draw(option);
}
}
//______________________________________________________________________________
void TCollection::Dump() const
{
// Dump all objects in this collection.
TIter next(this);
TObject *object;
while ((object = next())) {
object->Dump();
}
}
//______________________________________________________________________________
TObject *TCollection::FindObject(const char *name) const
{
// Find an object in this collection using its name. Requires a sequential
// scan till the object has been found. Returns 0 if object with specified
// name is not found.
TIter next(this);
TObject *obj;
while ((obj = next()))
if (!strcmp(name, obj->GetName())) return obj;
return 0;
}
//______________________________________________________________________________
TObject *TCollection::operator()(const char *name) const
{
// Find an object in this collection by name.
return FindObject(name);
}
//______________________________________________________________________________
TObject *TCollection::FindObject(const TObject *obj) const
{
// Find an object in this collection using the object's IsEqual()
// member function. Requires a sequential scan till the object has
// been found. Returns 0 if object is not found.
// Typically this function is overridden by a more efficient version
// in concrete collection classes (e.g. THashTable).
TIter next(this);
TObject *ob;
while ((ob = next()))
if (ob->IsEqual(obj)) return ob;
return 0;
}
//______________________________________________________________________________
const char *TCollection::GetName() const
{
// Return name of this collection.
// if no name, return the collection class name.
if (fName.Length() > 0) return fName.Data();
return ClassName();
}
//______________________________________________________________________________
Int_t TCollection::GrowBy(Int_t delta) const
{
// Increase the collection's capacity by delta slots.
if (delta < 0) {
Error("GrowBy", "delta < 0");
delta = Capacity();
}
return Capacity() + TMath::Range(2, kMaxInt - Capacity(), delta);
}
//______________________________________________________________________________
Bool_t TCollection::IsArgNull(const char *where, const TObject *obj) const
{
// Returns true if object is a null pointer.
return obj ? kFALSE : (Error(where, "argument is a null pointer"), kTRUE);
}
//______________________________________________________________________________
void TCollection::ls(Option_t *option) const
{
// List (ls) all objects in this collection.
// wildcarding supported, eg option="xxx*" lists only objects
// with names xxx*
TRegexp re(option,kTRUE);
TIter next(this);
TObject *object;
char *star = 0;
if (option) star = (char*)strchr(option,'*');
while ((object = next())) {
if (star) {
TString s = object->GetName();
if (strcmp(option,object->GetName()) && s.Index(re) == kNPOS) continue;
}
object->ls(option);
}
}
//______________________________________________________________________________
void TCollection::Paint(Option_t *option)
{
// Paint all objects in this collection.
// this->ForEach(TObject,Paint)((Option_t *)TObjectPaint_nxt.GetOption());
this->ForEach(TObject,Paint)(option);
}
//______________________________________________________________________________
void TCollection::Print(Option_t *option) const
{
// Print all objects in this collection.
// wildcarding supported, eg option="xxx*" prints only objects
// with names xxx*
TRegexp re(option,kTRUE);
TIter next(this);
TObject *object;
Int_t nch = strlen(option);
while ((object = next())) {
TString s = object->GetName();
if (nch && strcmp(option,object->GetName()) && s.Index(re) == kNPOS) continue;
object->Print(option);
}
}
//______________________________________________________________________________
void TCollection::RecursiveRemove(TObject *obj)
{
// Remove object from this collection and recursively remove the object
// from all other objects (and collections).
if (!obj) return;
// Scan list and remove obj in the list itself
while (Remove(obj))
;
// Scan again the list and invoke RecursiveRemove for all objects
TIter next(this);
TObject *object;
while ((object = next())) {
if (object->TestBit(kNotDeleted)) object->RecursiveRemove(obj);
}
}
//______________________________________________________________________________
void TCollection::RemoveAll(TCollection *col)
{
// Remove all objects in collection col from this collection.
TIter next(col);
TObject *obj;
while ((obj = next()))
Remove(obj);
}
//_______________________________________________________________________
void TCollection::Streamer(TBuffer &b)
{
// Stream all objects in the collection to or from the I/O buffer.
Int_t nobjects;
TObject *obj;
UInt_t R__s, R__c;
if (b.IsReading()) {
Version_t v = b.ReadVersion(&R__s, &R__c);
if (v > 2)
TObject::Streamer(b);
if (v > 1)
fName.Streamer(b);
b >> nobjects;
for (Int_t i = 0; i < nobjects; i++) {
b >> obj;
Add(obj);
}
b.CheckByteCount(R__s, R__c,TCollection::IsA());
} else {
R__c = b.WriteVersion(TCollection::IsA(), kTRUE);
TObject::Streamer(b);
fName.Streamer(b);
nobjects = GetSize();
b << nobjects;
TIter next(this);
while ((obj = next())) {
b << obj;
}
b.SetByteCount(R__c, kTRUE);
}
}
//______________________________________________________________________________
Int_t TCollection::Write(const char *name, Int_t option, Int_t bsize)
{
// Write all objects in this collection. By default all objects in
// the collection are written individually (each object gets its
// own key). Note, this is not recursive, collections in the collection
// are written with a single key. To write all objects using a single
// key specify a name and set option to TObject::kSingleKey (i.e. 1).
if ((option & kSingleKey)) {
return TObject::Write(name, option, bsize);
} else {
option &= ~kSingleKey;
Int_t nbytes = 0;
TIter next(this);
TObject *obj;
while ((obj = next())) {
nbytes += obj->Write(name, option, bsize);
}
return nbytes;
}
}
// -------------------- Static data members access -----------------------------
//______________________________________________________________________________
TCollection *TCollection::GetCurrentCollection()
{
return fgCurrentCollection;
}
//______________________________________________________________________________
void TCollection::SetCurrentCollection()
{
fgCurrentCollection = this;
}
//______________________________________________________________________________
void TCollection::StartGarbageCollection()
{
R__LOCKGUARD(gContainerMutex);
if (!fgGarbageCollection) {
fgGarbageCollection = new TObjectTable;
fgEmptyingGarbage = kFALSE;
fgGarbageStack = 0;
}
fgGarbageStack++;
}
//______________________________________________________________________________
void TCollection::EmptyGarbageCollection()
{
R__LOCKGUARD(gContainerMutex);
if (fgGarbageStack > 0) fgGarbageStack--;
if (fgGarbageCollection && fgGarbageStack == 0 && fgEmptyingGarbage == kFALSE) {
fgEmptyingGarbage = kTRUE;
fgGarbageCollection->Delete();
fgEmptyingGarbage = kFALSE;
SafeDelete(fgGarbageCollection);
}
}
//______________________________________________________________________________
void TCollection::GarbageCollect(TObject *obj)
{
R__LOCKGUARD(gContainerMutex);
if (fgGarbageCollection) {
if (!fgEmptyingGarbage) {
fgGarbageCollection->Add(obj);
} else
delete obj;
} else
delete obj;
}
//______________________________________________________________________________
TIter::TIter(const TIter &iter)
{
// Copy a TIter. This involves allocating a new TIterator of the right
// sub class and assigning it with the original.
if (iter.fIterator) {
fIterator = iter.GetCollection()->MakeIterator();
fIterator->operator=(*iter.fIterator);
} else
fIterator = 0;
}
//______________________________________________________________________________
TIter &TIter::operator=(const TIter &rhs)
{
// Assigning an TIter to another. This involves allocatiing a new TIterator
// of the right sub class and assigning it with the original.
if (this != &rhs) {
if (rhs.fIterator) {
delete fIterator;
fIterator = rhs.GetCollection()->MakeIterator();
fIterator->operator=(*rhs.fIterator);
}
}
return *this;
}
|
// @(#)root/cont:$Name: $:$Id: TCollection.cxx,v 1.17 2002/05/30 19:43:06 brun Exp $
// Author: Fons Rademakers 13/08/95
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// Collection abstract base class. This class describes the base //
// protocol all collection classes have to implement. The ROOT //
// collection classes always store pointers to objects that inherit //
// from TObject. They never adopt the objects. Therefore, it is the //
// user's responsability to take care of deleting the actual objects //
// once they are not needed anymore. In exceptional cases, when the //
// user is 100% sure nothing else is referencing the objects in the //
// collection, one can delete all objects and the collection at the //
// same time using the Delete() function. //
// //
// Collections can be iterated using an iterator object (see //
// TIterator). Depending on the concrete collection class there may be //
// some additional methods of iterating. See the repective classes. //
// //
// TCollection inherits from TObject since we want to be able to have //
// collections of collections. //
// //
// In a later release the collections may become templatized. //
// //
//Begin_Html
/*
<img src="gif/tcollection_classtree.gif">
*/
//End_Html
//////////////////////////////////////////////////////////////////////////
#include "TCollection.h"
#include "TClass.h"
#include "TROOT.h"
#include "TBrowser.h"
#include "TObjectTable.h"
#include "TRegexp.h"
#include "TVirtualMutex.h"
TCollection *TCollection::fgCurrentCollection = 0;
TObjectTable *TCollection::fgGarbageCollection = 0;
Bool_t TCollection::fgEmptyingGarbage = kFALSE;
Int_t TCollection::fgGarbageStack = 0;
ClassImp(TCollection)
ClassImp(TIter)
//______________________________________________________________________________
void TCollection::AddAll(TCollection *col)
{
// Add all objects from collection col to this collection.
TIter next(col);
TObject *obj;
while ((obj = next()))
Add(obj);
}
//______________________________________________________________________________
void TCollection::AddVector(TObject *va_(obj1), ...)
{
// Add all arguments to this collection.
va_list ap;
va_start(ap, va_(obj1));
TObject *obj;
Add(va_(obj1));
while ((obj = va_arg(ap, TObject *)))
Add(obj);
va_end(ap);
}
//______________________________________________________________________________
Bool_t TCollection::AssertClass(TClass *cl) const
{
// Make sure all objects in this collection inherit from class cl.
TObject *obj;
TIter next(this);
Bool_t error = kFALSE;
if (!cl) {
Error("AssertClass", "class == 0");
return kTRUE;
}
for (int i = 0; (obj = next()); i++)
if (!obj->InheritsFrom(cl)) {
Error("AssertClass", "element %d is not an instance of class %s (%s)",
i, cl->GetName(), obj->ClassName());
error = kTRUE;
}
return error;
}
//______________________________________________________________________________
void TCollection::Browse(TBrowser *b)
{
// Browse this collection (called by TBrowser).
// If b=0, there is no Browse call TObject::Browse(0) instead.
// This means TObject::Inspect() will be invoked indirectly
TIter next(this);
TObject *obj;
if (b)
while ((obj = next())) b->Add(obj);
else
TObject::Browse(b);
}
//______________________________________________________________________________
void TCollection::Draw(Option_t *option)
{
// Draw all objects in this collection.
// wildcarding supported, eg option="xxx*" draws only objects
// with names xxx*
TRegexp re(option,kTRUE);
TIter next(this);
TObject *object;
Int_t nch = strlen(option);
while ((object = next())) {
TString s = object->GetName();
if (nch && strcmp(option,object->GetName()) && s.Index(re) == kNPOS) continue;
object->Draw(option);
}
}
//______________________________________________________________________________
void TCollection::Dump() const
{
// Dump all objects in this collection.
TIter next(this);
TObject *object;
while ((object = next())) {
object->Dump();
}
}
//______________________________________________________________________________
TObject *TCollection::FindObject(const char *name) const
{
// Find an object in this collection using its name. Requires a sequential
// scan till the object has been found. Returns 0 if object with specified
// name is not found.
TIter next(this);
TObject *obj;
while ((obj = next()))
if (!strcmp(name, obj->GetName())) return obj;
return 0;
}
//______________________________________________________________________________
TObject *TCollection::operator()(const char *name) const
{
// Find an object in this collection by name.
return FindObject(name);
}
//______________________________________________________________________________
TObject *TCollection::FindObject(const TObject *obj) const
{
// Find an object in this collection using the object's IsEqual()
// member function. Requires a sequential scan till the object has
// been found. Returns 0 if object is not found.
// Typically this function is overridden by a more efficient version
// in concrete collection classes (e.g. THashTable).
TIter next(this);
TObject *ob;
while ((ob = next()))
if (ob->IsEqual(obj)) return ob;
return 0;
}
//______________________________________________________________________________
const char *TCollection::GetName() const
{
// Return name of this collection.
// if no name, return the collection class name.
if (fName.Length() > 0) return fName.Data();
return ClassName();
}
//______________________________________________________________________________
Int_t TCollection::GrowBy(Int_t delta) const
{
// Increase the collection's capacity by delta slots.
if (delta < 0) {
Error("GrowBy", "delta < 0");
delta = Capacity();
}
return Capacity() + TMath::Range(2, kMaxInt - Capacity(), delta);
}
//______________________________________________________________________________
Bool_t TCollection::IsArgNull(const char *where, const TObject *obj) const
{
// Returns true if object is a null pointer.
return obj ? kFALSE : (Error(where, "argument is a null pointer"), kTRUE);
}
//______________________________________________________________________________
void TCollection::ls(Option_t *option) const
{
// List (ls) all objects in this collection.
// Wildcarding supported, eg option="xxx*" lists only objects
// with names xxx*.
TRegexp re(option,kTRUE);
TIter next(this);
TObject *object;
char *star = 0;
if (option) star = (char*)strchr(option,'*');
while ((object = next())) {
if (star) {
TString s = object->GetName();
if (s != option && s.Index(re) == kNPOS) continue;
}
object->ls(option);
}
}
//______________________________________________________________________________
void TCollection::Paint(Option_t *option)
{
// Paint all objects in this collection.
// this->ForEach(TObject,Paint)((Option_t *)TObjectPaint_nxt.GetOption());
this->ForEach(TObject,Paint)(option);
}
//______________________________________________________________________________
void TCollection::Print(Option_t *option) const
{
// Print all objects in this collection.
// Wildcarding supported, eg option="xxx*" prints only objects
// with names xxx*.
TRegexp re(option,kTRUE);
Int_t nch = strlen(option);
TIter next(this);
TObject *object;
while ((object = next())) {
TString s = object->GetName();
if (nch && s != option && s.Index(re) == kNPOS) continue;
object->Print(option);
}
}
//______________________________________________________________________________
void TCollection::RecursiveRemove(TObject *obj)
{
// Remove object from this collection and recursively remove the object
// from all other objects (and collections).
if (!obj) return;
// Scan list and remove obj in the list itself
while (Remove(obj))
;
// Scan again the list and invoke RecursiveRemove for all objects
TIter next(this);
TObject *object;
while ((object = next())) {
if (object->TestBit(kNotDeleted)) object->RecursiveRemove(obj);
}
}
//______________________________________________________________________________
void TCollection::RemoveAll(TCollection *col)
{
// Remove all objects in collection col from this collection.
TIter next(col);
TObject *obj;
while ((obj = next()))
Remove(obj);
}
//_______________________________________________________________________
void TCollection::Streamer(TBuffer &b)
{
// Stream all objects in the collection to or from the I/O buffer.
Int_t nobjects;
TObject *obj;
UInt_t R__s, R__c;
if (b.IsReading()) {
Version_t v = b.ReadVersion(&R__s, &R__c);
if (v > 2)
TObject::Streamer(b);
if (v > 1)
fName.Streamer(b);
b >> nobjects;
for (Int_t i = 0; i < nobjects; i++) {
b >> obj;
Add(obj);
}
b.CheckByteCount(R__s, R__c,TCollection::IsA());
} else {
R__c = b.WriteVersion(TCollection::IsA(), kTRUE);
TObject::Streamer(b);
fName.Streamer(b);
nobjects = GetSize();
b << nobjects;
TIter next(this);
while ((obj = next())) {
b << obj;
}
b.SetByteCount(R__c, kTRUE);
}
}
//______________________________________________________________________________
Int_t TCollection::Write(const char *name, Int_t option, Int_t bsize)
{
// Write all objects in this collection. By default all objects in
// the collection are written individually (each object gets its
// own key). Note, this is not recursive, collections in the collection
// are written with a single key. To write all objects using a single
// key specify a name and set option to TObject::kSingleKey (i.e. 1).
if ((option & kSingleKey)) {
return TObject::Write(name, option, bsize);
} else {
option &= ~kSingleKey;
Int_t nbytes = 0;
TIter next(this);
TObject *obj;
while ((obj = next())) {
nbytes += obj->Write(name, option, bsize);
}
return nbytes;
}
}
// -------------------- Static data members access -----------------------------
//______________________________________________________________________________
TCollection *TCollection::GetCurrentCollection()
{
return fgCurrentCollection;
}
//______________________________________________________________________________
void TCollection::SetCurrentCollection()
{
fgCurrentCollection = this;
}
//______________________________________________________________________________
void TCollection::StartGarbageCollection()
{
R__LOCKGUARD(gContainerMutex);
if (!fgGarbageCollection) {
fgGarbageCollection = new TObjectTable;
fgEmptyingGarbage = kFALSE;
fgGarbageStack = 0;
}
fgGarbageStack++;
}
//______________________________________________________________________________
void TCollection::EmptyGarbageCollection()
{
R__LOCKGUARD(gContainerMutex);
if (fgGarbageStack > 0) fgGarbageStack--;
if (fgGarbageCollection && fgGarbageStack == 0 && fgEmptyingGarbage == kFALSE) {
fgEmptyingGarbage = kTRUE;
fgGarbageCollection->Delete();
fgEmptyingGarbage = kFALSE;
SafeDelete(fgGarbageCollection);
}
}
//______________________________________________________________________________
void TCollection::GarbageCollect(TObject *obj)
{
R__LOCKGUARD(gContainerMutex);
if (fgGarbageCollection) {
if (!fgEmptyingGarbage) {
fgGarbageCollection->Add(obj);
} else
delete obj;
} else
delete obj;
}
//______________________________________________________________________________
TIter::TIter(const TIter &iter)
{
// Copy a TIter. This involves allocating a new TIterator of the right
// sub class and assigning it with the original.
if (iter.fIterator) {
fIterator = iter.GetCollection()->MakeIterator();
fIterator->operator=(*iter.fIterator);
} else
fIterator = 0;
}
//______________________________________________________________________________
TIter &TIter::operator=(const TIter &rhs)
{
// Assigning an TIter to another. This involves allocatiing a new TIterator
// of the right sub class and assigning it with the original.
if (this != &rhs) {
if (rhs.fIterator) {
delete fIterator;
fIterator = rhs.GetCollection()->MakeIterator();
fIterator->operator=(*rhs.fIterator);
}
}
return *this;
}
|
use TString== instead of strcmp().
|
use TString== instead of strcmp().
git-svn-id: acec3fd5b7ea1eb9e79d6329d318e8118ee2e14f@5014 27541ba8-7e3a-0410-8455-c3a389f83636
|
C++
|
lgpl-2.1
|
jrtomps/root,buuck/root,veprbl/root,0x0all/ROOT,thomaskeck/root,nilqed/root,Y--/root,mhuwiler/rootauto,Duraznos/root,omazapa/root-old,mattkretz/root,bbockelm/root,olifre/root,simonpf/root,Dr15Jones/root,davidlt/root,agarciamontoro/root,alexschlueter/cern-root,nilqed/root,abhinavmoudgil95/root,BerserkerTroll/root,simonpf/root,krafczyk/root,satyarth934/root,root-mirror/root,veprbl/root,perovic/root,0x0all/ROOT,sawenzel/root,veprbl/root,tc3t/qoot,omazapa/root,ffurano/root5,bbockelm/root,mkret2/root,pspe/root,karies/root,jrtomps/root,olifre/root,sbinet/cxx-root,zzxuanyuan/root,agarciamontoro/root,sawenzel/root,gganis/root,kirbyherm/root-r-tools,mhuwiler/rootauto,veprbl/root,thomaskeck/root,CristinaCristescu/root,vukasinmilosevic/root,beniz/root,Y--/root,mattkretz/root,mkret2/root,gbitzes/root,esakellari/my_root_for_test,omazapa/root-old,kirbyherm/root-r-tools,jrtomps/root,mattkretz/root,mhuwiler/rootauto,jrtomps/root,beniz/root,davidlt/root,pspe/root,Dr15Jones/root,simonpf/root,mkret2/root,lgiommi/root,alexschlueter/cern-root,Duraznos/root,BerserkerTroll/root,georgtroska/root,evgeny-boger/root,agarciamontoro/root,zzxuanyuan/root,root-mirror/root,karies/root,nilqed/root,veprbl/root,davidlt/root,sirinath/root,pspe/root,sirinath/root,zzxuanyuan/root,tc3t/qoot,karies/root,esakellari/root,sawenzel/root,pspe/root,sawenzel/root,BerserkerTroll/root,esakellari/my_root_for_test,mkret2/root,buuck/root,strykejern/TTreeReader,gbitzes/root,mhuwiler/rootauto,zzxuanyuan/root,gbitzes/root,mkret2/root,abhinavmoudgil95/root,esakellari/my_root_for_test,cxx-hep/root-cern,georgtroska/root,lgiommi/root,georgtroska/root,mattkretz/root,dfunke/root,root-mirror/root,sbinet/cxx-root,gbitzes/root,krafczyk/root,zzxuanyuan/root-compressor-dummy,smarinac/root,lgiommi/root,Y--/root,olifre/root,nilqed/root,Duraznos/root,simonpf/root,beniz/root,alexschlueter/cern-root,gbitzes/root,karies/root,Y--/root,beniz/root,0x0all/ROOT,evgeny-boger/root,karies/root,sawenzel/root,zzxuanyuan/root,root-mirror/root,strykejern/TTreeReader,perovic/root,smarinac/root,ffurano/root5,mhuwiler/rootauto,omazapa/root,BerserkerTroll/root,tc3t/qoot,esakellari/my_root_for_test,zzxuanyuan/root-compressor-dummy,omazapa/root,karies/root,nilqed/root,veprbl/root,alexschlueter/cern-root,Y--/root,0x0all/ROOT,Dr15Jones/root,karies/root,zzxuanyuan/root,ffurano/root5,vukasinmilosevic/root,gganis/root,esakellari/root,vukasinmilosevic/root,olifre/root,pspe/root,sbinet/cxx-root,arch1tect0r/root,gganis/root,root-mirror/root,CristinaCristescu/root,cxx-hep/root-cern,beniz/root,kirbyherm/root-r-tools,buuck/root,buuck/root,kirbyherm/root-r-tools,omazapa/root,Dr15Jones/root,abhinavmoudgil95/root,alexschlueter/cern-root,lgiommi/root,Y--/root,abhinavmoudgil95/root,strykejern/TTreeReader,olifre/root,sirinath/root,dfunke/root,omazapa/root,BerserkerTroll/root,Y--/root,root-mirror/root,nilqed/root,georgtroska/root,arch1tect0r/root,perovic/root,georgtroska/root,abhinavmoudgil95/root,jrtomps/root,bbockelm/root,agarciamontoro/root,perovic/root,davidlt/root,esakellari/my_root_for_test,vukasinmilosevic/root,krafczyk/root,zzxuanyuan/root-compressor-dummy,georgtroska/root,sawenzel/root,sirinath/root,root-mirror/root,thomaskeck/root,esakellari/root,mkret2/root,gbitzes/root,sawenzel/root,beniz/root,zzxuanyuan/root,gganis/root,smarinac/root,zzxuanyuan/root,zzxuanyuan/root-compressor-dummy,sbinet/cxx-root,gganis/root,dfunke/root,georgtroska/root,bbockelm/root,krafczyk/root,lgiommi/root,jrtomps/root,vukasinmilosevic/root,sirinath/root,karies/root,sbinet/cxx-root,veprbl/root,sawenzel/root,olifre/root,arch1tect0r/root,vukasinmilosevic/root,CristinaCristescu/root,satyarth934/root,mattkretz/root,Dr15Jones/root,cxx-hep/root-cern,BerserkerTroll/root,krafczyk/root,mkret2/root,satyarth934/root,strykejern/TTreeReader,0x0all/ROOT,satyarth934/root,simonpf/root,pspe/root,evgeny-boger/root,buuck/root,olifre/root,dfunke/root,Duraznos/root,krafczyk/root,esakellari/root,dfunke/root,veprbl/root,abhinavmoudgil95/root,smarinac/root,sawenzel/root,omazapa/root-old,Dr15Jones/root,evgeny-boger/root,zzxuanyuan/root,cxx-hep/root-cern,bbockelm/root,veprbl/root,tc3t/qoot,beniz/root,BerserkerTroll/root,Y--/root,olifre/root,BerserkerTroll/root,thomaskeck/root,dfunke/root,esakellari/my_root_for_test,zzxuanyuan/root,simonpf/root,georgtroska/root,esakellari/my_root_for_test,mhuwiler/rootauto,arch1tect0r/root,krafczyk/root,cxx-hep/root-cern,agarciamontoro/root,simonpf/root,sirinath/root,thomaskeck/root,CristinaCristescu/root,sawenzel/root,smarinac/root,Duraznos/root,mattkretz/root,abhinavmoudgil95/root,dfunke/root,CristinaCristescu/root,davidlt/root,gbitzes/root,esakellari/my_root_for_test,lgiommi/root,esakellari/my_root_for_test,perovic/root,esakellari/root,sirinath/root,cxx-hep/root-cern,evgeny-boger/root,tc3t/qoot,strykejern/TTreeReader,esakellari/root,sbinet/cxx-root,CristinaCristescu/root,omazapa/root-old,simonpf/root,gbitzes/root,omazapa/root,Duraznos/root,cxx-hep/root-cern,sbinet/cxx-root,sbinet/cxx-root,zzxuanyuan/root-compressor-dummy,buuck/root,sbinet/cxx-root,kirbyherm/root-r-tools,omazapa/root-old,0x0all/ROOT,esakellari/root,olifre/root,CristinaCristescu/root,lgiommi/root,arch1tect0r/root,gbitzes/root,beniz/root,lgiommi/root,Duraznos/root,beniz/root,vukasinmilosevic/root,cxx-hep/root-cern,arch1tect0r/root,satyarth934/root,lgiommi/root,olifre/root,tc3t/qoot,veprbl/root,buuck/root,evgeny-boger/root,bbockelm/root,omazapa/root,agarciamontoro/root,krafczyk/root,nilqed/root,davidlt/root,satyarth934/root,omazapa/root,gganis/root,alexschlueter/cern-root,dfunke/root,sawenzel/root,CristinaCristescu/root,perovic/root,vukasinmilosevic/root,abhinavmoudgil95/root,nilqed/root,nilqed/root,jrtomps/root,karies/root,zzxuanyuan/root-compressor-dummy,omazapa/root-old,dfunke/root,zzxuanyuan/root-compressor-dummy,esakellari/root,pspe/root,nilqed/root,buuck/root,pspe/root,satyarth934/root,root-mirror/root,CristinaCristescu/root,buuck/root,mattkretz/root,perovic/root,simonpf/root,lgiommi/root,satyarth934/root,mattkretz/root,mhuwiler/rootauto,omazapa/root-old,esakellari/my_root_for_test,georgtroska/root,0x0all/ROOT,smarinac/root,strykejern/TTreeReader,davidlt/root,beniz/root,ffurano/root5,bbockelm/root,mkret2/root,evgeny-boger/root,vukasinmilosevic/root,olifre/root,sbinet/cxx-root,mhuwiler/rootauto,gbitzes/root,agarciamontoro/root,BerserkerTroll/root,arch1tect0r/root,georgtroska/root,mhuwiler/rootauto,evgeny-boger/root,0x0all/ROOT,Duraznos/root,Duraznos/root,sirinath/root,abhinavmoudgil95/root,krafczyk/root,simonpf/root,georgtroska/root,perovic/root,esakellari/root,CristinaCristescu/root,0x0all/ROOT,arch1tect0r/root,BerserkerTroll/root,agarciamontoro/root,Y--/root,dfunke/root,Dr15Jones/root,root-mirror/root,sirinath/root,sirinath/root,karies/root,jrtomps/root,agarciamontoro/root,evgeny-boger/root,BerserkerTroll/root,zzxuanyuan/root,CristinaCristescu/root,strykejern/TTreeReader,root-mirror/root,smarinac/root,ffurano/root5,tc3t/qoot,root-mirror/root,satyarth934/root,arch1tect0r/root,gganis/root,buuck/root,zzxuanyuan/root,gganis/root,davidlt/root,simonpf/root,perovic/root,kirbyherm/root-r-tools,krafczyk/root,smarinac/root,pspe/root,omazapa/root-old,abhinavmoudgil95/root,krafczyk/root,davidlt/root,tc3t/qoot,satyarth934/root,lgiommi/root,smarinac/root,kirbyherm/root-r-tools,ffurano/root5,thomaskeck/root,agarciamontoro/root,evgeny-boger/root,omazapa/root,omazapa/root-old,omazapa/root,veprbl/root,thomaskeck/root,thomaskeck/root,esakellari/root,alexschlueter/cern-root,gganis/root,gganis/root,tc3t/qoot,jrtomps/root,mkret2/root,davidlt/root,Duraznos/root,sirinath/root,nilqed/root,jrtomps/root,gbitzes/root,jrtomps/root,mkret2/root,mattkretz/root,vukasinmilosevic/root,beniz/root,ffurano/root5,pspe/root,esakellari/root,Y--/root,zzxuanyuan/root-compressor-dummy,perovic/root,bbockelm/root,davidlt/root,buuck/root,mhuwiler/rootauto,omazapa/root,gganis/root,pspe/root,zzxuanyuan/root-compressor-dummy,satyarth934/root,mattkretz/root,tc3t/qoot,arch1tect0r/root,karies/root,omazapa/root-old,evgeny-boger/root,Duraznos/root,vukasinmilosevic/root,mattkretz/root,bbockelm/root,abhinavmoudgil95/root,thomaskeck/root,zzxuanyuan/root-compressor-dummy,perovic/root,agarciamontoro/root,sbinet/cxx-root,dfunke/root,zzxuanyuan/root-compressor-dummy,bbockelm/root,bbockelm/root,mhuwiler/rootauto,mkret2/root,smarinac/root,arch1tect0r/root,omazapa/root-old,Y--/root,thomaskeck/root
|
9b1bcbd58e387c128ef5eceef835de8fe7191e0f
|
Base/Analysis/voPLSStatistics.cpp
|
Base/Analysis/voPLSStatistics.cpp
|
// Qt includes
#include <QDebug>
// QtPropertyBrowser includes
#include <QtVariantPropertyManager>
// Visomics includes
#include "voPLSStatistics.h"
#include "voTableDataObject.h"
#include "voUtils.h"
#include "vtkExtendedTable.h"
// VTK includes
#include <vtkArrayData.h>
#include <vtkDoubleArray.h>
#include <vtkRCalculatorFilter.h>
#include <vtkSmartPointer.h>
#include <vtkStringArray.h>
#include <vtkNew.h>
#include <vtkTable.h>
// --------------------------------------------------------------------------
// voPLSStatisticsPrivate methods
// --------------------------------------------------------------------------
class voPLSStatisticsPrivate
{
public:
vtkSmartPointer<vtkRCalculatorFilter> RCalc;
};
// --------------------------------------------------------------------------
// voPLSStatistics methods
// --------------------------------------------------------------------------
voPLSStatistics::voPLSStatistics():
Superclass(), d_ptr(new voPLSStatisticsPrivate)
{
Q_D(voPLSStatistics);
d->RCalc = vtkSmartPointer<vtkRCalculatorFilter>::New();
}
// --------------------------------------------------------------------------
voPLSStatistics::~voPLSStatistics()
{
}
// --------------------------------------------------------------------------
void voPLSStatistics::setInputInformation()
{
this->addInputType("input", "vtkExtendedTable");
}
// --------------------------------------------------------------------------
void voPLSStatistics::setOutputInformation()
{
this->addOutputType("scores", "vtkTable" ,
"", "",
"voTableView", "Table (Scores)");
this->addOutputType("yScores", "vtkTable" ,
"", "",
"voTableView", "Table (Y-Scores)");
this->addOutputType("loadings", "vtkTable" ,
"", "",
"voTableView", "Table (Loadings)");
this->addOutputType("loadingWeights", "vtkTable" ,
"", "",
"voTableView", "Table (Loading Weights)");
this->addOutputType("yLoadings", "vtkTable" ,
"", "",
"voTableView", "Table (Y-Loadings)");
}
// --------------------------------------------------------------------------
void voPLSStatistics::setParameterInformation()
{
QList<QtProperty*> pls_parameters;
pls_parameters << this->addStringParameter("predictor_range", QObject::tr("Predictor Analyte(s)"), "1-3,6");
pls_parameters << this->addStringParameter("response_range", QObject::tr("Response Analyte(s)"), "4,5,7-10");
pls_parameters << this->addEnumParameter("algorithm", tr("Algorithm"),
(QStringList() << "Kernel" << "Wide Kernel" << "SIMPLS" << "Orthogonal Scores"),
"Kernel");
this->addParameterGroup("PLS parameters", pls_parameters);
}
// --------------------------------------------------------------------------
bool voPLSStatistics::execute()
{
Q_D(voPLSStatistics);
// Get and parse parameters
QString algorithmString;
if (this->enumParameter("algorithm") == QLatin1String("Kernel"))
{
algorithmString = "kernelpls";
}
else if (this->enumParameter("algorithm") == QLatin1String("Wide Kernel"))
{
algorithmString = "widekernelpls";
}
else if (this->enumParameter("algorithm") == QLatin1String("SIMPLS"))
{
algorithmString = "simpls";
}
else //if (this->enumParameter("algorithm") == QString("Orthogonal Scores"))
{
algorithmString = "oscorespls";
}
bool result;
QList<int> predictorRangeList;
result = voUtils::parseRangeString(this->stringParameter("predictor_range"), predictorRangeList, false);
if(!result || predictorRangeList.empty())
{
qWarning() << QObject::tr("Invalid paramater, could not parse Predictor Measure(s)");
return false;
}
QList<int> responseRangeList;
result= voUtils::parseRangeString(this->stringParameter("response_range"), responseRangeList, false);
if(!result || responseRangeList.empty())
{
qWarning() << QObject::tr("Invalid paramater, could not parse Response Measure(s)");
return false;
}
// Import data table locally
vtkExtendedTable* extendedTable = vtkExtendedTable::SafeDownCast(this->input()->dataAsVTKDataObject());
if (!extendedTable)
{
qWarning() << "Input is Null";
return false;
}
vtkSmartPointer<vtkTable> inputDataTable = extendedTable->GetData();
// PLS expects each measure (analyte) as a column, and each sample (experiment) as a row, so we must transpose
vtkNew<vtkTable> inputDataTableTransposed;
bool transposeResult = voUtils::transposeTable(inputDataTable.GetPointer(), inputDataTableTransposed.GetPointer());
if (!transposeResult)
{
qWarning() << QObject::tr("Error: could not transpose input table");
return false;
}
// Build array for predictor measure range
vtkSmartPointer<vtkArray> predictorArray;
bool tabToArrResult = voUtils::tableToArray(inputDataTableTransposed.GetPointer(), predictorArray, predictorRangeList);
if (!tabToArrResult)
{
qWarning() << QObject::tr("Invalid paramater, out of range: Predictor Measure(s)");
return false;
}
// Build array for response measure
vtkSmartPointer<vtkArray> responseArray;
tabToArrResult = voUtils::tableToArray(inputDataTableTransposed.GetPointer(), responseArray, responseRangeList);
if (!tabToArrResult)
{
qWarning() << QObject::tr("Invalid paramater, out of range: Response Measure(s)");
return false;
}
// Combine sample 1 and 2 array groups
vtkNew<vtkArrayData> RInputArrayData;
RInputArrayData->AddArray(predictorArray.GetPointer());
RInputArrayData->AddArray(responseArray.GetPointer());
// Run R code
d->RCalc->SetRoutput(0);
d->RCalc->SetInputConnection(RInputArrayData->GetProducerPort());
d->RCalc->PutArray("0", "predictorArray");
d->RCalc->PutArray("1", "responseArray");
d->RCalc->GetArray("scoresArray","scoresArray");
d->RCalc->GetArray("yScoresArray","yScoresArray");
d->RCalc->GetArray("loadingsArray","loadingsArray");
d->RCalc->GetArray("loadingWeightsArray","loadingWeightsArray");
d->RCalc->GetArray("yLoadingsArray","yLoadingsArray");
d->RCalc->GetArray("RerrValue","RerrValue");
d->RCalc->SetRscript(QString(
"library(\"pls\", warn.conflicts=FALSE)\n"
"PLSdata <- data.frame(response=I(responseArray), predictor=I(predictorArray) )\n"
"PLSresult <- plsr(response ~ predictor, data = PLSdata, method = \"%1\")\n"
"if(exists(\"PLSresult\")) {"
"RerrValue<-1"
"}else{"
"RerrValue<-0"
"}\n"
"scoresArray <- t(PLSresult$scores)\n"
"yScoresArray <- t(PLSresult$Yscores)\n"
"loadingsArray <- PLSresult$loadings[,]\n"
"loadingWeightsArray <- PLSresult$loading.weights[,]\n"
"yLoadingsArray <- PLSresult$Yloadings[,]\n"
).arg(algorithmString).toLatin1());
d->RCalc->Update();
vtkSmartPointer<vtkArrayData> outputArrayData = vtkArrayData::SafeDownCast(d->RCalc->GetOutput());
// Check for errors "thrown" by R script
if(outputArrayData->GetArrayByName("RerrValue")->GetVariantValue(0).ToInt() > 1)
{
qWarning() << QObject::tr("Error: R could not calculate PLS");
return false;
}
// ------------------------------------------------
// Extract table for scores and Y-scores
// No need to transpose scoresArray, it was done within the R code
vtkNew<vtkTable> scoresTable;
vtkNew<vtkTable> yScoresTable;
{
voUtils::arrayToTable(outputArrayData->GetArrayByName("scoresArray"), scoresTable.GetPointer());
voUtils::arrayToTable(outputArrayData->GetArrayByName("yScoresArray"), yScoresTable.GetPointer());
// Add column labels (experiment names)
voUtils::setTableColumnNames(scoresTable.GetPointer(), extendedTable->GetColumnMetaDataOfInterestAsString());
voUtils::setTableColumnNames(yScoresTable.GetPointer(), extendedTable->GetColumnMetaDataOfInterestAsString());
// Add row labels (components)
vtkNew<vtkStringArray> headerArr;
for (vtkIdType r = 0;r < scoresTable->GetNumberOfRows(); ++r)
{
headerArr->InsertNextValue(QString("Comp %1").arg(r + 1).toLatin1());
}
voUtils::insertColumnIntoTable(scoresTable.GetPointer(), 0, headerArr.GetPointer());
voUtils::insertColumnIntoTable(yScoresTable.GetPointer(), 0, headerArr.GetPointer());
}
this->setOutput("scores", new voTableDataObject("scores", scoresTable.GetPointer()));
this->setOutput("yScores", new voTableDataObject("yScores", yScoresTable.GetPointer()));
// ------------------------------------------------
// Extract table for loadings and loading weights
vtkNew<vtkTable> loadingsTable;
vtkNew<vtkTable> loadingWeightsTable;
{
voUtils::arrayToTable(outputArrayData->GetArrayByName("loadingsArray"), loadingsTable.GetPointer());
voUtils::arrayToTable(outputArrayData->GetArrayByName("loadingWeightsArray"), loadingWeightsTable.GetPointer());
// Add column labels (components)
for(vtkIdType c = 0; c < loadingsTable->GetNumberOfColumns(); ++c)
{
QByteArray colName = QString("Comp %1").arg(c + 1).toLatin1();
loadingsTable->GetColumn(c)->SetName(colName);
loadingWeightsTable->GetColumn(c)->SetName(colName);
}
// Add row labels (predictor analytes)
vtkNew<vtkStringArray> headerArr;
vtkStringArray* analyteNames = extendedTable->GetRowMetaDataOfInterestAsString();
foreach(int r, predictorRangeList)
{
headerArr->InsertNextValue(analyteNames->GetValue(r));
}
voUtils::insertColumnIntoTable(loadingsTable.GetPointer(), 0, headerArr.GetPointer());
voUtils::insertColumnIntoTable(loadingWeightsTable.GetPointer(), 0, headerArr.GetPointer());
}
this->setOutput("loadings", new voTableDataObject("loadings", loadingsTable.GetPointer()));
this->setOutput("loadingWeights", new voTableDataObject("loadingWeights", loadingWeightsTable.GetPointer()));
// ------------------------------------------------
// Extract table for Y-loadings
vtkNew<vtkTable> yLoadingsTable;
{
voUtils::arrayToTable(outputArrayData->GetArrayByName("yLoadingsArray"), yLoadingsTable.GetPointer());
// Add column labels (components)
for(vtkIdType c = 0; c < yLoadingsTable->GetNumberOfColumns(); ++c)
{
yLoadingsTable->GetColumn(c)->SetName(QString("Comp %1").arg(c + 1).toLatin1());
}
// Add row labels (response analytes)
vtkNew<vtkStringArray> headerArr;
vtkStringArray* analyteNames = extendedTable->GetRowMetaDataOfInterestAsString();
foreach(int r, responseRangeList)
{
headerArr->InsertNextValue(analyteNames->GetValue(r));
}
voUtils::insertColumnIntoTable(yLoadingsTable.GetPointer(), 0, headerArr.GetPointer());
}
this->setOutput("yLoadings", new voTableDataObject("yLoadings", yLoadingsTable.GetPointer()));
return true;
}
|
// Qt includes
#include <QDebug>
// QtPropertyBrowser includes
#include <QtVariantPropertyManager>
// Visomics includes
#include "voPLSStatistics.h"
#include "voTableDataObject.h"
#include "voUtils.h"
#include "vtkExtendedTable.h"
// VTK includes
#include <vtkArrayData.h>
#include <vtkDoubleArray.h>
#include <vtkRCalculatorFilter.h>
#include <vtkSmartPointer.h>
#include <vtkStringArray.h>
#include <vtkNew.h>
#include <vtkTable.h>
// --------------------------------------------------------------------------
// voPLSStatisticsPrivate methods
// --------------------------------------------------------------------------
class voPLSStatisticsPrivate
{
public:
vtkSmartPointer<vtkRCalculatorFilter> RCalc;
};
// --------------------------------------------------------------------------
// voPLSStatistics methods
// --------------------------------------------------------------------------
voPLSStatistics::voPLSStatistics():
Superclass(), d_ptr(new voPLSStatisticsPrivate)
{
Q_D(voPLSStatistics);
d->RCalc = vtkSmartPointer<vtkRCalculatorFilter>::New();
}
// --------------------------------------------------------------------------
voPLSStatistics::~voPLSStatistics()
{
}
// --------------------------------------------------------------------------
void voPLSStatistics::setInputInformation()
{
this->addInputType("input", "vtkExtendedTable");
}
// --------------------------------------------------------------------------
void voPLSStatistics::setOutputInformation()
{
this->addOutputType("scores", "vtkTable" ,
"", "",
"voTableView", "Table (Scores)");
this->addOutputType("yScores", "vtkTable" ,
"", "",
"voTableView", "Table (Y-Scores)");
this->addOutputType("loadings", "vtkTable" ,
"", "",
"voTableView", "Table (Loadings)");
this->addOutputType("loadingWeights", "vtkTable" ,
"", "",
"voTableView", "Table (Loading Weights)");
this->addOutputType("yLoadings", "vtkTable" ,
"", "",
"voTableView", "Table (Y-Loadings)");
}
// --------------------------------------------------------------------------
void voPLSStatistics::setParameterInformation()
{
QList<QtProperty*> pls_parameters;
pls_parameters << this->addStringParameter("predictor_range", QObject::tr("Predictor Analyte(s)"), "1-3,6");
pls_parameters << this->addStringParameter("response_range", QObject::tr("Response Analyte(s)"), "4,5,7-10");
pls_parameters << this->addEnumParameter("algorithm", tr("Algorithm"),
(QStringList() << "Kernel" << "Wide Kernel" << "SIMPLS" << "Orthogonal Scores"),
"Kernel");
this->addParameterGroup("PLS parameters", pls_parameters);
}
// --------------------------------------------------------------------------
bool voPLSStatistics::execute()
{
Q_D(voPLSStatistics);
// Get and parse parameters
QString algorithmString;
if (this->enumParameter("algorithm") == QLatin1String("Kernel"))
{
algorithmString = "kernelpls";
}
else if (this->enumParameter("algorithm") == QLatin1String("Wide Kernel"))
{
algorithmString = "widekernelpls";
}
else if (this->enumParameter("algorithm") == QLatin1String("SIMPLS"))
{
algorithmString = "simpls";
}
else //if (this->enumParameter("algorithm") == QString("Orthogonal Scores"))
{
algorithmString = "oscorespls";
}
bool result;
QList<int> predictorRangeList;
result = voUtils::parseRangeString(this->stringParameter("predictor_range"), predictorRangeList, false);
if(!result || predictorRangeList.empty())
{
qWarning() << QObject::tr("Invalid paramater, could not parse Predictor Measure(s)");
return false;
}
QList<int> responseRangeList;
result= voUtils::parseRangeString(this->stringParameter("response_range"), responseRangeList, false);
if(!result || responseRangeList.empty())
{
qWarning() << QObject::tr("Invalid paramater, could not parse Response Measure(s)");
return false;
}
// Import data table locally
vtkExtendedTable* extendedTable = vtkExtendedTable::SafeDownCast(this->input()->dataAsVTKDataObject());
if (!extendedTable)
{
qWarning() << "Input is Null";
return false;
}
vtkSmartPointer<vtkTable> inputDataTable = extendedTable->GetData();
// PLS expects each measure (analyte) as a column, and each sample (experiment) as a row, so we must transpose
vtkNew<vtkTable> inputDataTableTransposed;
bool transposeResult = voUtils::transposeTable(inputDataTable.GetPointer(), inputDataTableTransposed.GetPointer());
if (!transposeResult)
{
qWarning() << QObject::tr("Error: could not transpose input table");
return false;
}
// Build array for predictor measure range
vtkSmartPointer<vtkArray> predictorArray;
bool tabToArrResult = voUtils::tableToArray(inputDataTableTransposed.GetPointer(), predictorArray, predictorRangeList);
if (!tabToArrResult)
{
qWarning() << QObject::tr("Invalid paramater, out of range: Predictor Measure(s)");
return false;
}
// Build array for response measure
vtkSmartPointer<vtkArray> responseArray;
tabToArrResult = voUtils::tableToArray(inputDataTableTransposed.GetPointer(), responseArray, responseRangeList);
if (!tabToArrResult)
{
qWarning() << QObject::tr("Invalid paramater, out of range: Response Measure(s)");
return false;
}
// Combine sample 1 and 2 array groups
vtkNew<vtkArrayData> RInputArrayData;
RInputArrayData->AddArray(predictorArray.GetPointer());
RInputArrayData->AddArray(responseArray.GetPointer());
// Run R code
d->RCalc->SetRoutput(0);
d->RCalc->SetInputConnection(RInputArrayData->GetProducerPort());
d->RCalc->PutArray("0", "predictorArray");
d->RCalc->PutArray("1", "responseArray");
d->RCalc->GetArray("scoresArray","scoresArray");
d->RCalc->GetArray("yScoresArray","yScoresArray");
d->RCalc->GetArray("loadingsArray","loadingsArray");
d->RCalc->GetArray("loadingWeightsArray","loadingWeightsArray");
d->RCalc->GetArray("yLoadingsArray","yLoadingsArray");
d->RCalc->GetArray("RerrValue","RerrValue");
d->RCalc->SetRscript(QString(
"library(\"pls\", warn.conflicts=FALSE)\n"
"PLSdata <- data.frame(response=I(responseArray), predictor=I(predictorArray) )\n"
"PLSresult <- plsr(response ~ predictor, data = PLSdata, method = \"%1\")\n"
"if(exists(\"PLSresult\")) {"
"RerrValue<-1"
"}else{"
"RerrValue<-0"
"}\n"
"scoresArray <- t(PLSresult$scores)\n"
"yScoresArray <- t(PLSresult$Yscores)\n"
"loadingsArray <- PLSresult$loadings[,]\n"
"loadingWeightsArray <- PLSresult$loading.weights[,]\n"
"yLoadingsArray <- PLSresult$Yloadings[,]\n"
).arg(algorithmString).toLatin1());
d->RCalc->Update();
vtkSmartPointer<vtkArrayData> outputArrayData = vtkArrayData::SafeDownCast(d->RCalc->GetOutput());
// Check for errors "thrown" by R script
if(outputArrayData->GetArrayByName("RerrValue")->GetVariantValue(0).ToInt() > 1)
{
qWarning() << QObject::tr("Error: R could not calculate PLS");
return false;
}
// ------------------------------------------------
// Extract table for scores and Y-scores
// No need to transpose scoresArray, it was done within the R code
vtkNew<vtkTable> scoresTable;
vtkNew<vtkTable> yScoresTable;
{
voUtils::arrayToTable(outputArrayData->GetArrayByName("scoresArray"), scoresTable.GetPointer());
voUtils::arrayToTable(outputArrayData->GetArrayByName("yScoresArray"), yScoresTable.GetPointer());
// Add column labels (experiment names)
voUtils::setTableColumnNames(scoresTable.GetPointer(), extendedTable->GetColumnMetaDataOfInterestAsString());
voUtils::setTableColumnNames(yScoresTable.GetPointer(), extendedTable->GetColumnMetaDataOfInterestAsString());
// Add row labels (components)
vtkNew<vtkStringArray> headerArr;
for (vtkIdType r = 0;r < scoresTable->GetNumberOfRows(); ++r)
{
headerArr->InsertNextValue(QString("Comp %1").arg(r + 1).toLatin1());
}
voUtils::insertColumnIntoTable(scoresTable.GetPointer(), 0, headerArr.GetPointer());
voUtils::insertColumnIntoTable(yScoresTable.GetPointer(), 0, headerArr.GetPointer());
}
this->setOutput("scores", new voTableDataObject("scores", scoresTable.GetPointer()));
this->setOutput("yScores", new voTableDataObject("yScores", yScoresTable.GetPointer()));
// ------------------------------------------------
// Extract table for loadings and loading weights
vtkNew<vtkTable> loadingsTable;
vtkNew<vtkTable> loadingWeightsTable;
{
voUtils::arrayToTable(outputArrayData->GetArrayByName("loadingsArray"), loadingsTable.GetPointer());
voUtils::arrayToTable(outputArrayData->GetArrayByName("loadingWeightsArray"), loadingWeightsTable.GetPointer());
// Add column labels (components)
for(vtkIdType c = 0; c < loadingsTable->GetNumberOfColumns(); ++c)
{
QByteArray colName = QString("Comp %1").arg(c + 1).toLatin1();
loadingsTable->GetColumn(c)->SetName(colName);
loadingWeightsTable->GetColumn(c)->SetName(colName);
}
// Add row labels (predictor analytes)
vtkNew<vtkStringArray> headerArr;
vtkStringArray* analyteNames = extendedTable->GetRowMetaDataOfInterestAsString();
foreach(int r, predictorRangeList)
{
headerArr->InsertNextValue(analyteNames->GetValue(r));
}
voUtils::insertColumnIntoTable(loadingsTable.GetPointer(), 0, headerArr.GetPointer());
voUtils::insertColumnIntoTable(loadingWeightsTable.GetPointer(), 0, headerArr.GetPointer());
}
this->setOutput("loadings", new voTableDataObject("loadings", loadingsTable.GetPointer()));
this->setOutput("loadingWeights", new voTableDataObject("loadingWeights", loadingWeightsTable.GetPointer()));
// ------------------------------------------------
// Extract table for Y-loadings
vtkNew<vtkTable> yLoadingsTable;
{
voUtils::arrayToTable(outputArrayData->GetArrayByName("yLoadingsArray"), yLoadingsTable.GetPointer());
// Add column labels (components)
for(vtkIdType c = 0; c < yLoadingsTable->GetNumberOfColumns(); ++c)
{
yLoadingsTable->GetColumn(c)->SetName(QString("Comp %1").arg(c + 1).toLatin1());
}
// Add row labels (response analytes)
vtkNew<vtkStringArray> headerArr;
vtkStringArray* analyteNames = extendedTable->GetRowMetaDataOfInterestAsString();
foreach(int r, responseRangeList)
{
headerArr->InsertNextValue(analyteNames->GetValue(r));
}
voUtils::insertColumnIntoTable(yLoadingsTable.GetPointer(), 0, headerArr.GetPointer());
}
this->setOutput("yLoadings", new voTableDataObject("yLoadings", yLoadingsTable.GetPointer()));
return true;
}
|
Change newlines in voPLSStatistics.cpp to unix-style
|
Change newlines in voPLSStatistics.cpp to unix-style
|
C++
|
apache-2.0
|
arborworkflows/Visomics,arborworkflows/Visomics,Visomics/Visomics,Visomics/Visomics,arborworkflows/Visomics,Visomics/Visomics,Visomics/Visomics,Visomics/Visomics,Visomics/Visomics,arborworkflows/Visomics,arborworkflows/Visomics,arborworkflows/Visomics
|
e766c19e0faedcf661870f9b6464f3459214ce63
|
hecl-gui/DownloadManager.cpp
|
hecl-gui/DownloadManager.cpp
|
#include "DownloadManager.hpp"
#include "Common.hpp"
#include <QBuffer>
#include <quazip.h>
static const char AxioDLPublicKeyPEM[] =
"-----BEGIN PUBLIC KEY-----\n"
"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvtshImzoP1a++9P5RK0k\n"
"btTOpwie7O7S/wWFZxwwbMezEPhjw2uu86TPqJe3P/1v+6xRKrEf9zFn/sKNygvD\n"
"bO64ZkJre4M46IYd0XxwIhiu7PBR+13CD+fqbrbYwPkoG090CP4MtZZN6mt5NAKB\n"
"QHoIj0wV5K/jJE9cBQxViwOqrxK05Cl/ivy0gRtpL7Ot6S+QHL3++rb6U2hWydIQ\n"
"kS+ucufKCIL77RcDwAc9vwNvzxf9EUU2pmq+EsEtLgRw3fR6BInoltOI8P9X5Wo6\n"
"/skeg92xZA++vv0neq5gjjDfa2A1zDgJRysz3Xps/AMlLOe55XCzXse9BpvChT+Z\n"
"pwIDAQAB\n"
"-----END PUBLIC KEY-----\n";
static const QSslKey AxioDLPublicKey =
QSslKey({AxioDLPublicKeyPEM}, QSsl::Rsa, QSsl::Pem, QSsl::PublicKey);
void DownloadManager::_validateCert(QNetworkReply* reply)
{
QSslCertificate peerCert = reply->sslConfiguration().peerCertificate();
if (peerCert.publicKey() != AxioDLPublicKey)
{
auto cn = peerCert.subjectInfo(QSslCertificate::CommonName);
if (!cn.empty())
setError(QNetworkReply::SslHandshakeFailedError,
QStringLiteral("Certificate pinning mismatch \"") + cn.first() + "\"");
else
setError(QNetworkReply::SslHandshakeFailedError,
QStringLiteral("Certificate pinning mismatch"));
reply->abort();
}
}
static const QString Domain = QStringLiteral("https://releases.axiodl.com/");
static const QString Index = QStringLiteral("index.txt");
void DownloadManager::fetchIndex()
{
if (m_indexInProgress)
return;
resetError();
QString url = Domain + CurPlatformString + '/' + Index;
m_indexInProgress = m_netManager.get(QNetworkRequest(url));
connect(m_indexInProgress, SIGNAL(finished()),
this, SLOT(indexFinished()));
connect(m_indexInProgress, SIGNAL(error(QNetworkReply::NetworkError)),
this, SLOT(indexError(QNetworkReply::NetworkError)));
connect(m_indexInProgress, SIGNAL(encrypted()),
this, SLOT(indexValidateCert()));
}
void DownloadManager::fetchBinary(const QString& str, const QString& outPath)
{
if (m_binaryInProgress)
return;
resetError();
m_outPath = outPath;
QString url = Domain + CurPlatformString + '/' + str;
m_binaryInProgress = m_netManager.get(QNetworkRequest(url));
connect(m_binaryInProgress, SIGNAL(finished()),
this, SLOT(binaryFinished()));
connect(m_binaryInProgress, SIGNAL(error(QNetworkReply::NetworkError)),
this, SLOT(binaryError(QNetworkReply::NetworkError)));
connect(m_binaryInProgress, SIGNAL(encrypted()),
this, SLOT(binaryValidateCert()));
connect(m_binaryInProgress, SIGNAL(downloadProgress(qint64, qint64)),
this, SLOT(binaryDownloadProgress(qint64, qint64)));
if (m_progBar)
{
m_progBar->setEnabled(true);
m_progBar->setValue(0);
}
}
void DownloadManager::indexFinished()
{
if (m_hasError)
return;
QStringList files;
while (!m_indexInProgress->atEnd())
{
QString line = QString::fromUtf8(m_indexInProgress->readLine()).trimmed();
if (line.isEmpty())
continue;
files.push_back(line);
}
if (m_indexCompletionHandler)
m_indexCompletionHandler(files);
m_indexInProgress->deleteLater();
m_indexInProgress = nullptr;
}
void DownloadManager::indexError(QNetworkReply::NetworkError error)
{
setError(error, m_indexInProgress->errorString());
m_indexInProgress->deleteLater();
m_indexInProgress = nullptr;
}
void DownloadManager::indexValidateCert()
{
_validateCert(m_indexInProgress);
}
void DownloadManager::binaryFinished()
{
if (m_hasError)
return;
if (m_progBar)
m_progBar->setValue(100);
QByteArray all = m_binaryInProgress->readAll();
QBuffer buff(&all);
QuaZip zip(&buff);
if (!zip.open(QuaZip::mdUnzip))
{
setError(QNetworkReply::UnknownContentError, "Unable to open zip archive.");
m_binaryInProgress->deleteLater();
m_binaryInProgress = nullptr;
return;
}
if (m_completionHandler)
m_completionHandler(zip);
m_binaryInProgress->deleteLater();
m_binaryInProgress = nullptr;
}
void DownloadManager::binaryError(QNetworkReply::NetworkError error)
{
setError(error, m_binaryInProgress->errorString());
m_binaryInProgress->deleteLater();
m_binaryInProgress = nullptr;
if (m_progBar)
m_progBar->setEnabled(false);
if (m_failedHandler)
m_failedHandler();
}
void DownloadManager::binaryValidateCert()
{
_validateCert(m_binaryInProgress);
}
void DownloadManager::binaryDownloadProgress(qint64 bytesReceived, qint64 bytesTotal)
{
if (m_progBar)
{
if (bytesReceived == bytesTotal)
m_progBar->setValue(100);
else
m_progBar->setValue(int(bytesReceived * 100 / bytesTotal));
}
}
|
#include "DownloadManager.hpp"
#include "Common.hpp"
#include <QBuffer>
#include <quazip.h>
static const char AxioDLPublicKeyPEM[] =
"-----BEGIN PUBLIC KEY-----\n"
"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvtshImzoP1a++9P5RK0k\n"
"btTOpwie7O7S/wWFZxwwbMezEPhjw2uu86TPqJe3P/1v+6xRKrEf9zFn/sKNygvD\n"
"bO64ZkJre4M46IYd0XxwIhiu7PBR+13CD+fqbrbYwPkoG090CP4MtZZN6mt5NAKB\n"
"QHoIj0wV5K/jJE9cBQxViwOqrxK05Cl/ivy0gRtpL7Ot6S+QHL3++rb6U2hWydIQ\n"
"kS+ucufKCIL77RcDwAc9vwNvzxf9EUU2pmq+EsEtLgRw3fR6BInoltOI8P9X5Wo6\n"
"/skeg92xZA++vv0neq5gjjDfa2A1zDgJRysz3Xps/AMlLOe55XCzXse9BpvChT+Z\n"
"pwIDAQAB\n"
"-----END PUBLIC KEY-----\n";
static const QSslKey AxioDLPublicKey =
QSslKey({AxioDLPublicKeyPEM}, QSsl::Rsa, QSsl::Pem, QSsl::PublicKey);
static const char AxioDLEdgePublicKeyPEM[] =
"-----BEGIN PUBLIC KEY-----\n"
"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE4a8ZLg3LRU0FiK6m8g2pT3qVBTMA\n"
"K2Uu5VGl7iamdGpUjynQ4uYWMx+WXf2Qkh7UZZgYvA6UeWHEs3M6ME8T6g==\n"
"-----END PUBLIC KEY-----\n";
static const QSslKey AxioDLEdgePublicKey =
QSslKey({AxioDLEdgePublicKeyPEM}, QSsl::Ec, QSsl::Pem, QSsl::PublicKey);
void DownloadManager::_validateCert(QNetworkReply* reply)
{
QSslCertificate peerCert = reply->sslConfiguration().peerCertificate();
QSslKey peerKey = peerCert.publicKey();
if (peerKey != AxioDLPublicKey && peerKey != AxioDLEdgePublicKey)
{
auto cn = peerCert.subjectInfo(QSslCertificate::CommonName);
if (!cn.empty())
setError(QNetworkReply::SslHandshakeFailedError,
QStringLiteral("Certificate pinning mismatch \"") + cn.first() + "\"");
else
setError(QNetworkReply::SslHandshakeFailedError,
QStringLiteral("Certificate pinning mismatch"));
reply->abort();
}
}
static const QString Domain = QStringLiteral("https://releases.axiodl.com/");
static const QString Index = QStringLiteral("index.txt");
void DownloadManager::fetchIndex()
{
if (m_indexInProgress)
return;
resetError();
QString url = Domain + CurPlatformString + '/' + Index;
m_indexInProgress = m_netManager.get(QNetworkRequest(url));
connect(m_indexInProgress, SIGNAL(finished()),
this, SLOT(indexFinished()));
connect(m_indexInProgress, SIGNAL(error(QNetworkReply::NetworkError)),
this, SLOT(indexError(QNetworkReply::NetworkError)));
connect(m_indexInProgress, SIGNAL(encrypted()),
this, SLOT(indexValidateCert()));
}
void DownloadManager::fetchBinary(const QString& str, const QString& outPath)
{
if (m_binaryInProgress)
return;
resetError();
m_outPath = outPath;
QString url = Domain + CurPlatformString + '/' + str;
m_binaryInProgress = m_netManager.get(QNetworkRequest(url));
connect(m_binaryInProgress, SIGNAL(finished()),
this, SLOT(binaryFinished()));
connect(m_binaryInProgress, SIGNAL(error(QNetworkReply::NetworkError)),
this, SLOT(binaryError(QNetworkReply::NetworkError)));
connect(m_binaryInProgress, SIGNAL(encrypted()),
this, SLOT(binaryValidateCert()));
connect(m_binaryInProgress, SIGNAL(downloadProgress(qint64, qint64)),
this, SLOT(binaryDownloadProgress(qint64, qint64)));
if (m_progBar)
{
m_progBar->setEnabled(true);
m_progBar->setValue(0);
}
}
void DownloadManager::indexFinished()
{
if (m_hasError)
return;
QStringList files;
while (!m_indexInProgress->atEnd())
{
QString line = QString::fromUtf8(m_indexInProgress->readLine()).trimmed();
if (line.isEmpty())
continue;
files.push_back(line);
}
if (m_indexCompletionHandler)
m_indexCompletionHandler(files);
m_indexInProgress->deleteLater();
m_indexInProgress = nullptr;
}
void DownloadManager::indexError(QNetworkReply::NetworkError error)
{
setError(error, m_indexInProgress->errorString());
m_indexInProgress->deleteLater();
m_indexInProgress = nullptr;
}
void DownloadManager::indexValidateCert()
{
_validateCert(m_indexInProgress);
}
void DownloadManager::binaryFinished()
{
if (m_hasError)
return;
if (m_progBar)
m_progBar->setValue(100);
QByteArray all = m_binaryInProgress->readAll();
QBuffer buff(&all);
QuaZip zip(&buff);
if (!zip.open(QuaZip::mdUnzip))
{
setError(QNetworkReply::UnknownContentError, "Unable to open zip archive.");
m_binaryInProgress->deleteLater();
m_binaryInProgress = nullptr;
return;
}
if (m_completionHandler)
m_completionHandler(zip);
m_binaryInProgress->deleteLater();
m_binaryInProgress = nullptr;
}
void DownloadManager::binaryError(QNetworkReply::NetworkError error)
{
setError(error, m_binaryInProgress->errorString());
m_binaryInProgress->deleteLater();
m_binaryInProgress = nullptr;
if (m_progBar)
m_progBar->setEnabled(false);
if (m_failedHandler)
m_failedHandler();
}
void DownloadManager::binaryValidateCert()
{
_validateCert(m_binaryInProgress);
}
void DownloadManager::binaryDownloadProgress(qint64 bytesReceived, qint64 bytesTotal)
{
if (m_progBar)
{
if (bytesReceived == bytesTotal)
m_progBar->setValue(100);
else
m_progBar->setValue(int(bytesReceived * 100 / bytesTotal));
}
}
|
Add edge certificate for pinning check
|
Add edge certificate for pinning check
|
C++
|
mit
|
AxioDL/PathShagged,AxioDL/PathShagged,AxioDL/PathShagged
|
096172d5135001dd426fde111da66dcf19644364
|
test/cxx/ApplicationPool2/ProcessTest.cpp
|
test/cxx/ApplicationPool2/ProcessTest.cpp
|
#include <TestSupport.h>
#include <ApplicationPool2/Process.h>
#include <Utils/IOUtils.h>
using namespace Passenger;
using namespace Passenger::ApplicationPool2;
using namespace std;
namespace tut {
struct ApplicationPool2_ProcessTest {
BackgroundEventLoop bg;
SocketList sockets;
SocketPair adminSocket;
Pipe errorPipe;
FileDescriptor server1, server2, server3;
ApplicationPool2_ProcessTest() {
bg.start();
struct sockaddr_in addr;
socklen_t len = sizeof(addr);
server1 = createTcpServer("127.0.0.1", 0);
getsockname(server1, (struct sockaddr *) &addr, &len);
sockets.add("main1",
"tcp://127.0.0.1:" + toString(addr.sin_port),
"session", 3);
server2 = createTcpServer("127.0.0.1", 0);
getsockname(server2, (struct sockaddr *) &addr, &len);
sockets.add("main2",
"tcp://127.0.0.1:" + toString(addr.sin_port),
"session", 3);
server3 = createTcpServer("127.0.0.1", 0);
getsockname(server3, (struct sockaddr *) &addr, &len);
sockets.add("main3",
"tcp://127.0.0.1:" + toString(addr.sin_port),
"session", 3);
adminSocket = createUnixSocketPair();
errorPipe = createPipe();
}
ProcessPtr createProcess() {
ProcessPtr process = boost::make_shared<Process>(123,
"123", adminSocket[0], errorPipe[0], sockets, 0, 0);
process->dummy = true;
process->requiresShutdown = false;
return process;
}
};
DEFINE_TEST_GROUP(ApplicationPool2_ProcessTest);
TEST_METHOD(1) {
// Test initial state.
ProcessPtr process = createProcess();
ensure_equals(process->busyness(), 0);
ensure(!process->isTotallyBusy());
}
TEST_METHOD(2) {
// Test opening and closing sessions.
ProcessPtr process = createProcess();
SessionPtr session = process->newSession();
SessionPtr session2 = process->newSession();
ensure_equals(process->sessions, 2);
process->sessionClosed(session.get());
ensure_equals(process->sessions, 1);
process->sessionClosed(session2.get());
ensure_equals(process->sessions, 0);
}
TEST_METHOD(3) {
// newSession() checks out the socket with the smallest busyness number
// and sessionClosed() restores the session busyness statistics.
ProcessPtr process = createProcess();
// The first 3 newSession() commands check out an idle socket.
SessionPtr session1 = process->newSession();
SessionPtr session2 = process->newSession();
SessionPtr session3 = process->newSession();
ensure(session1->getSocket()->name != session2->getSocket()->name);
ensure(session1->getSocket()->name != session3->getSocket()->name);
ensure(session2->getSocket()->name != session3->getSocket()->name);
// The next 2 newSession() commands check out sockets with sessions == 1.
SessionPtr session4 = process->newSession();
SessionPtr session5 = process->newSession();
ensure(session4->getSocket()->name != session5->getSocket()->name);
// There should now be 1 process with 1 session
// and 2 processes with 2 sessions.
map<int, int> sessionCount;
SocketList::const_iterator it;
for (it = process->sockets.begin(); it != process->sockets.end(); it++) {
sessionCount[it->sessions]++;
}
ensure_equals(sessionCount.size(), 2u);
ensure_equals(sessionCount[1], 1);
ensure_equals(sessionCount[2], 2);
// Closing the first 3 sessions will result in no processes having 1 session
// and 1 process having 2 sessions.
process->sessionClosed(session1.get());
process->sessionClosed(session2.get());
process->sessionClosed(session3.get());
sessionCount.clear();
for (it = process->sockets.begin(); it != process->sockets.end(); it++) {
sessionCount[it->sessions]++;
}
ensure_equals(sessionCount[0], 1);
ensure_equals(sessionCount[1], 2);
}
TEST_METHOD(4) {
// If all sockets are at their full capacity then newSession() will fail.
ProcessPtr process = createProcess();
vector<SessionPtr> sessions;
for (int i = 0; i < 9; i++) {
ensure(!process->isTotallyBusy());
SessionPtr session = process->newSession();
ensure(session != NULL);
sessions.push_back(session);
}
ensure(process->isTotallyBusy());
ensure(process->newSession() == NULL);
}
}
|
#include <TestSupport.h>
#include <ApplicationPool2/Process.h>
#include <Utils/IOUtils.h>
using namespace Passenger;
using namespace Passenger::ApplicationPool2;
using namespace std;
namespace tut {
struct ApplicationPool2_ProcessTest {
SocketList sockets;
SocketPair adminSocket;
Pipe errorPipe;
FileDescriptor server1, server2, server3;
ApplicationPool2_ProcessTest() {
struct sockaddr_in addr;
socklen_t len = sizeof(addr);
server1 = createTcpServer("127.0.0.1", 0);
getsockname(server1, (struct sockaddr *) &addr, &len);
sockets.add("main1",
"tcp://127.0.0.1:" + toString(addr.sin_port),
"session", 3);
server2 = createTcpServer("127.0.0.1", 0);
getsockname(server2, (struct sockaddr *) &addr, &len);
sockets.add("main2",
"tcp://127.0.0.1:" + toString(addr.sin_port),
"session", 3);
server3 = createTcpServer("127.0.0.1", 0);
getsockname(server3, (struct sockaddr *) &addr, &len);
sockets.add("main3",
"tcp://127.0.0.1:" + toString(addr.sin_port),
"session", 3);
adminSocket = createUnixSocketPair();
errorPipe = createPipe();
}
ProcessPtr createProcess() {
ProcessPtr process = boost::make_shared<Process>(123,
"123", adminSocket[0], errorPipe[0], sockets, 0, 0);
process->dummy = true;
process->requiresShutdown = false;
return process;
}
};
DEFINE_TEST_GROUP(ApplicationPool2_ProcessTest);
TEST_METHOD(1) {
// Test initial state.
ProcessPtr process = createProcess();
ensure_equals(process->busyness(), 0);
ensure(!process->isTotallyBusy());
}
TEST_METHOD(2) {
// Test opening and closing sessions.
ProcessPtr process = createProcess();
SessionPtr session = process->newSession();
SessionPtr session2 = process->newSession();
ensure_equals(process->sessions, 2);
process->sessionClosed(session.get());
ensure_equals(process->sessions, 1);
process->sessionClosed(session2.get());
ensure_equals(process->sessions, 0);
}
TEST_METHOD(3) {
// newSession() checks out the socket with the smallest busyness number
// and sessionClosed() restores the session busyness statistics.
ProcessPtr process = createProcess();
// The first 3 newSession() commands check out an idle socket.
SessionPtr session1 = process->newSession();
SessionPtr session2 = process->newSession();
SessionPtr session3 = process->newSession();
ensure(session1->getSocket()->name != session2->getSocket()->name);
ensure(session1->getSocket()->name != session3->getSocket()->name);
ensure(session2->getSocket()->name != session3->getSocket()->name);
// The next 2 newSession() commands check out sockets with sessions == 1.
SessionPtr session4 = process->newSession();
SessionPtr session5 = process->newSession();
ensure(session4->getSocket()->name != session5->getSocket()->name);
// There should now be 1 process with 1 session
// and 2 processes with 2 sessions.
map<int, int> sessionCount;
SocketList::const_iterator it;
for (it = process->sockets.begin(); it != process->sockets.end(); it++) {
sessionCount[it->sessions]++;
}
ensure_equals(sessionCount.size(), 2u);
ensure_equals(sessionCount[1], 1);
ensure_equals(sessionCount[2], 2);
// Closing the first 3 sessions will result in no processes having 1 session
// and 1 process having 2 sessions.
process->sessionClosed(session1.get());
process->sessionClosed(session2.get());
process->sessionClosed(session3.get());
sessionCount.clear();
for (it = process->sockets.begin(); it != process->sockets.end(); it++) {
sessionCount[it->sessions]++;
}
ensure_equals(sessionCount[0], 1);
ensure_equals(sessionCount[1], 2);
}
TEST_METHOD(4) {
// If all sockets are at their full capacity then newSession() will fail.
ProcessPtr process = createProcess();
vector<SessionPtr> sessions;
for (int i = 0; i < 9; i++) {
ensure(!process->isTotallyBusy());
SessionPtr session = process->newSession();
ensure(session != NULL);
sessions.push_back(session);
}
ensure(process->isTotallyBusy());
ensure(process->newSession() == NULL);
}
}
|
Remove dependency on BackgroundEventLoop in ProcessTest
|
Remove dependency on BackgroundEventLoop in ProcessTest
|
C++
|
mit
|
kewaunited/passenger,phusion/passenger,phusion/passenger,phusion/passenger,clemensg/passenger,phusion/passenger,phusion/passenger,cgvarela/passenger,clemensg/passenger,antek-drzewiecki/passenger,antek-drzewiecki/passenger,antek-drzewiecki/passenger,cgvarela/passenger,cgvarela/passenger,kewaunited/passenger,clemensg/passenger,cgvarela/passenger,antek-drzewiecki/passenger,kewaunited/passenger,antek-drzewiecki/passenger,kewaunited/passenger,kewaunited/passenger,phusion/passenger,kewaunited/passenger,cgvarela/passenger,kewaunited/passenger,antek-drzewiecki/passenger,cgvarela/passenger,clemensg/passenger,kewaunited/passenger,clemensg/passenger,clemensg/passenger,cgvarela/passenger,phusion/passenger,cgvarela/passenger,phusion/passenger,clemensg/passenger,antek-drzewiecki/passenger,antek-drzewiecki/passenger,clemensg/passenger
|
b0a28a9a2491d464efffc91f470824bad7983cd3
|
apps/ELFLoader/elf_loader.cc
|
apps/ELFLoader/elf_loader.cc
|
#include "apps/ELFLoader/elf_loader.h"
#include "libs/base/filesystem.h"
#include "libs/base/tasks.h"
#include "libs/tasks/UsbDeviceTask/usb_device_task.h"
#include "libs/usb/descriptors.h"
#include "third_party/freertos_kernel/include/FreeRTOS.h"
#include "third_party/freertos_kernel/include/task.h"
#include "third_party/freertos_kernel/include/timers.h"
#include "third_party/nxp/rt1176-sdk/devices/MIMXRT1176/utilities/debug_console/fsl_debug_console.h"
#include <elf.h>
#include <memory>
/* Function definitions */
static void elfloader_main(void *param);
static void elfloader_recv(const uint8_t *buffer, uint32_t length);
static void usb_timer_callback(TimerHandle_t timer);
static bool elfloader_HandleEvent(uint32_t event, void *param);
static void elfloader_SetClassHandle(class_handle_t class_handle);
static usb_status_t elfloader_Handler(class_handle_t class_handle, uint32_t event, void *param);
void usb_device_task(void *param);
/* Static data definitions */
TimerHandle_t usb_timer;
static uint8_t* elfloader_recv_image = nullptr;
static uint8_t elfloader_data[64];
static class_handle_t elfloader_class_handle;
static void elfloader_recv(const uint8_t *buffer, uint32_t length) {
ElfloaderCommand cmd = static_cast<ElfloaderCommand>(buffer[0]);
const ElfloaderSetSize *set_size = reinterpret_cast<const ElfloaderSetSize*>(&buffer[1]);
const ElfloaderBytes *bytes = reinterpret_cast<const ElfloaderBytes*>(&buffer[1]);
switch (cmd) {
case ElfloaderCommand::SetSize:
assert(length == sizeof(ElfloaderSetSize) + 1);
xTimerStop(usb_timer, 0);
elfloader_recv_image = (uint8_t*)malloc(set_size->size);
break;
case ElfloaderCommand::Bytes:
assert(length >= sizeof(ElfloaderBytes) + 1);
memcpy(elfloader_recv_image + bytes->offset, &buffer[1] + sizeof(ElfloaderBytes), bytes->size);
break;
case ElfloaderCommand::Done:
xTaskCreate(elfloader_main, "elfloader_main", configMINIMAL_STACK_SIZE * 10, elfloader_recv_image, APP_TASK_PRIORITY, NULL);
break;
}
}
static bool elfloader_HandleEvent(uint32_t event, void *param) {
bool ret = true;
usb_device_get_hid_descriptor_struct_t* get_hid_descriptor =
static_cast<usb_device_get_hid_descriptor_struct_t*>(param);
switch (event) {
case kUSB_DeviceEventSetConfiguration:
USB_DeviceHidRecv(elfloader_class_handle, elfloader_hid_endpoints[kRxEndpoint].endpointAddress, elfloader_data, sizeof(elfloader_data));
break;
case kUSB_DeviceEventGetHidReportDescriptor:
get_hid_descriptor->buffer = elfloader_hid_report;
get_hid_descriptor->length = elfloader_hid_report_size;
get_hid_descriptor->interfaceNumber = elfloader_interfaces[0].interfaceNumber;
break;
default:
ret = false;
break;
}
return ret;
}
static void elfloader_SetClassHandle(class_handle_t class_handle) {
elfloader_class_handle = class_handle;
}
static usb_status_t elfloader_Handler(class_handle_t class_handle, uint32_t event, void *param) {
usb_status_t ret = kStatus_USB_Success;
usb_device_endpoint_callback_message_struct_t *message =
static_cast<usb_device_endpoint_callback_message_struct_t*>(param);
switch (event) {
case kUSB_DeviceHidEventRecvResponse:
if (message->length != USB_UNINITIALIZED_VAL_32) {
elfloader_recv(message->buffer, message->length);
}
USB_DeviceHidRecv(elfloader_class_handle, elfloader_hid_endpoints[kRxEndpoint].endpointAddress, elfloader_data, sizeof(elfloader_data));
break;
case kUSB_DeviceHidEventGetReport:
ret = kStatus_USB_InvalidRequest;
break;
case kUSB_DeviceHidEventSendResponse:
case kUSB_DeviceHidEventSetIdle:
break;
default:
ret = kStatus_USB_Error;
break;
}
return ret;
}
static usb_device_class_config_struct_t elfloader_config_data_ = {
elfloader_Handler, nullptr, &elfloader_class_struct,
};
typedef void (*entry_point)(void);
static void elfloader_main(void *param) {
size_t elf_size;
std::unique_ptr<uint8_t> application_elf;
if (!param) {
application_elf.reset(valiant::filesystem::ReadToMemory("/default.elf", &elf_size));
} else {
application_elf.reset(reinterpret_cast<uint8_t*>(param));
}
Elf32_Ehdr* elf_header = reinterpret_cast<Elf32_Ehdr*>(application_elf.get());
assert(EF_ARM_EABI_VERSION(elf_header->e_flags) == EF_ARM_EABI_VER5);
assert(elf_header->e_phentsize == sizeof(Elf32_Phdr));
for (int i = 0; i < elf_header->e_phnum; ++i) {
Elf32_Phdr *program_header = reinterpret_cast<Elf32_Phdr*>(application_elf.get() + elf_header->e_phoff + sizeof(Elf32_Phdr) * i);
if (program_header->p_type != PT_LOAD) {
continue;
}
if (program_header->p_filesz == 0) {
continue;
}
memcpy(reinterpret_cast<void*>(program_header->p_paddr), application_elf.get() + program_header->p_offset, program_header->p_filesz);
}
entry_point entry_point_fn = reinterpret_cast<entry_point>(elf_header->e_entry);
entry_point_fn();
vTaskSuspend(NULL);
}
void usb_device_task(void *param) {
while (true) {
valiant::UsbDeviceTask::GetSingleton()->UsbDeviceTaskFn();
taskYIELD();
}
}
static void usb_timer_callback(TimerHandle_t timer) {
vTaskSuspend(reinterpret_cast<TaskHandle_t>(pvTimerGetTimerID(timer)));
xTaskCreate(elfloader_main, "elfloader_main", configMINIMAL_STACK_SIZE * 10, nullptr, APP_TASK_PRIORITY, NULL);
}
extern "C" void BOARD_InitHardware();
extern "C" int main(int argc, char **argv) {
BOARD_InitHardware();
valiant::filesystem::Init();
TaskHandle_t usb_task;
xTaskCreate(usb_device_task, "usb_device_task", configMINIMAL_STACK_SIZE * 10, NULL, USB_DEVICE_TASK_PRIORITY, &usb_task);
usb_timer = xTimerCreate("usb_timer", pdMS_TO_TICKS(500), pdFALSE, usb_task, usb_timer_callback);
xTimerStart(usb_timer, 0);
elfloader_hid_endpoints[0].endpointAddress =
valiant::UsbDeviceTask::GetSingleton()->next_descriptor_value() | (USB_IN << 7);
elfloader_hid_endpoints[1].endpointAddress =
valiant::UsbDeviceTask::GetSingleton()->next_descriptor_value() | (USB_OUT << 7);
elfloader_descriptor_data.in_ep.endpoint_address = elfloader_hid_endpoints[0].endpointAddress;
elfloader_descriptor_data.out_ep.endpoint_address = elfloader_hid_endpoints[1].endpointAddress;
elfloader_interfaces[0].interfaceNumber =
valiant::UsbDeviceTask::GetSingleton()->next_interface_value();
valiant::UsbDeviceTask::GetSingleton()->AddDevice(
&elfloader_config_data_,
elfloader_SetClassHandle,
elfloader_HandleEvent,
&elfloader_descriptor_data,
sizeof(elfloader_descriptor_data)
);
valiant::UsbDeviceTask::GetSingleton()->Init();
vTaskStartScheduler();
return 0;
}
|
#include "apps/ELFLoader/elf_loader.h"
#include "libs/base/filesystem.h"
#include "libs/base/tasks.h"
#include "libs/tasks/UsbDeviceTask/usb_device_task.h"
#include "libs/usb/descriptors.h"
#include "third_party/freertos_kernel/include/FreeRTOS.h"
#include "third_party/freertos_kernel/include/task.h"
#include "third_party/freertos_kernel/include/timers.h"
#include "third_party/nxp/rt1176-sdk/devices/MIMXRT1176/utilities/debug_console/fsl_debug_console.h"
#include <elf.h>
#include <memory>
/* Function definitions */
static void elfloader_main(void *param);
static void elfloader_recv(const uint8_t *buffer, uint32_t length);
static void usb_timer_callback(TimerHandle_t timer);
static bool elfloader_HandleEvent(uint32_t event, void *param);
static void elfloader_SetClassHandle(class_handle_t class_handle);
static usb_status_t elfloader_Handler(class_handle_t class_handle, uint32_t event, void *param);
void usb_device_task(void *param);
/* Static data definitions */
TimerHandle_t usb_timer;
static uint8_t* elfloader_recv_image = nullptr;
static uint8_t elfloader_data[64];
static class_handle_t elfloader_class_handle;
static void elfloader_recv(const uint8_t *buffer, uint32_t length) {
ElfloaderCommand cmd = static_cast<ElfloaderCommand>(buffer[0]);
const ElfloaderSetSize *set_size = reinterpret_cast<const ElfloaderSetSize*>(&buffer[1]);
const ElfloaderBytes *bytes = reinterpret_cast<const ElfloaderBytes*>(&buffer[1]);
switch (cmd) {
case ElfloaderCommand::SetSize:
assert(length == sizeof(ElfloaderSetSize) + 1);
xTimerStop(usb_timer, 0);
elfloader_recv_image = (uint8_t*)malloc(set_size->size);
break;
case ElfloaderCommand::Bytes:
assert(length >= sizeof(ElfloaderBytes) + 1);
memcpy(elfloader_recv_image + bytes->offset, &buffer[1] + sizeof(ElfloaderBytes), bytes->size);
break;
case ElfloaderCommand::Done:
xTaskCreate(elfloader_main, "elfloader_main", configMINIMAL_STACK_SIZE * 10, elfloader_recv_image, APP_TASK_PRIORITY, NULL);
break;
}
}
static bool elfloader_HandleEvent(uint32_t event, void *param) {
bool ret = true;
usb_device_get_hid_descriptor_struct_t* get_hid_descriptor =
static_cast<usb_device_get_hid_descriptor_struct_t*>(param);
switch (event) {
case kUSB_DeviceEventSetConfiguration:
USB_DeviceHidRecv(elfloader_class_handle, elfloader_hid_endpoints[kRxEndpoint].endpointAddress, elfloader_data, sizeof(elfloader_data));
break;
case kUSB_DeviceEventGetHidReportDescriptor:
get_hid_descriptor->buffer = elfloader_hid_report;
get_hid_descriptor->length = elfloader_hid_report_size;
get_hid_descriptor->interfaceNumber = elfloader_interfaces[0].interfaceNumber;
break;
default:
ret = false;
break;
}
return ret;
}
static void elfloader_SetClassHandle(class_handle_t class_handle) {
elfloader_class_handle = class_handle;
}
static usb_status_t elfloader_Handler(class_handle_t class_handle, uint32_t event, void *param) {
usb_status_t ret = kStatus_USB_Success;
usb_device_endpoint_callback_message_struct_t *message =
static_cast<usb_device_endpoint_callback_message_struct_t*>(param);
switch (event) {
case kUSB_DeviceHidEventRecvResponse:
if (message->length != USB_UNINITIALIZED_VAL_32) {
elfloader_recv(message->buffer, message->length);
}
USB_DeviceHidRecv(elfloader_class_handle, elfloader_hid_endpoints[kRxEndpoint].endpointAddress, elfloader_data, sizeof(elfloader_data));
break;
case kUSB_DeviceHidEventGetReport:
ret = kStatus_USB_InvalidRequest;
break;
case kUSB_DeviceHidEventSendResponse:
case kUSB_DeviceHidEventSetIdle:
break;
default:
ret = kStatus_USB_Error;
break;
}
return ret;
}
static usb_device_class_config_struct_t elfloader_config_data_ = {
elfloader_Handler, nullptr, &elfloader_class_struct,
};
typedef void (*entry_point)(void);
static void elfloader_main(void *param) {
size_t elf_size;
std::unique_ptr<uint8_t> application_elf;
if (!param) {
application_elf.reset(valiant::filesystem::ReadToMemory("/default.elf", &elf_size));
} else {
application_elf.reset(reinterpret_cast<uint8_t*>(param));
}
Elf32_Ehdr* elf_header = reinterpret_cast<Elf32_Ehdr*>(application_elf.get());
assert(EF_ARM_EABI_VERSION(elf_header->e_flags) == EF_ARM_EABI_VER5);
assert(elf_header->e_phentsize == sizeof(Elf32_Phdr));
for (int i = 0; i < elf_header->e_phnum; ++i) {
Elf32_Phdr *program_header = reinterpret_cast<Elf32_Phdr*>(application_elf.get() + elf_header->e_phoff + sizeof(Elf32_Phdr) * i);
if (program_header->p_type != PT_LOAD) {
continue;
}
if (program_header->p_filesz == 0) {
continue;
}
memcpy(reinterpret_cast<void*>(program_header->p_paddr), application_elf.get() + program_header->p_offset, program_header->p_filesz);
}
entry_point entry_point_fn = reinterpret_cast<entry_point>(elf_header->e_entry);
entry_point_fn();
vTaskSuspend(NULL);
}
void usb_device_task(void *param) {
while (true) {
valiant::UsbDeviceTask::GetSingleton()->UsbDeviceTaskFn();
taskYIELD();
}
}
static void usb_timer_callback(TimerHandle_t timer) {
vTaskSuspend(reinterpret_cast<TaskHandle_t>(pvTimerGetTimerID(timer)));
xTaskCreate(elfloader_main, "elfloader_main", configMINIMAL_STACK_SIZE * 10, nullptr, APP_TASK_PRIORITY, NULL);
}
extern "C" void BOARD_InitHardware();
extern "C" int main(int argc, char **argv) {
BOARD_InitHardware();
valiant::filesystem::Init();
TaskHandle_t usb_task;
xTaskCreate(usb_device_task, "usb_device_task", configMINIMAL_STACK_SIZE * 10, NULL, USB_DEVICE_TASK_PRIORITY, &usb_task);
usb_timer = xTimerCreate("usb_timer", pdMS_TO_TICKS(1000), pdFALSE, usb_task, usb_timer_callback);
xTimerStart(usb_timer, 0);
elfloader_hid_endpoints[0].endpointAddress =
valiant::UsbDeviceTask::GetSingleton()->next_descriptor_value() | (USB_IN << 7);
elfloader_hid_endpoints[1].endpointAddress =
valiant::UsbDeviceTask::GetSingleton()->next_descriptor_value() | (USB_OUT << 7);
elfloader_descriptor_data.in_ep.endpoint_address = elfloader_hid_endpoints[0].endpointAddress;
elfloader_descriptor_data.out_ep.endpoint_address = elfloader_hid_endpoints[1].endpointAddress;
elfloader_interfaces[0].interfaceNumber =
valiant::UsbDeviceTask::GetSingleton()->next_interface_value();
valiant::UsbDeviceTask::GetSingleton()->AddDevice(
&elfloader_config_data_,
elfloader_SetClassHandle,
elfloader_HandleEvent,
&elfloader_descriptor_data,
sizeof(elfloader_descriptor_data)
);
valiant::UsbDeviceTask::GetSingleton()->Init();
vTaskStartScheduler();
return 0;
}
|
Increase ELFLoader timeout to 1s
|
Increase ELFLoader timeout to 1s
Change-Id: I41fec0a8a6e38be65b7acf0177a123e74fdeb129
GitOrigin-RevId: 5d82dcfd15bd16437d4a2d01e8d016a19708fdb8
|
C++
|
apache-2.0
|
google-coral/coralmicro,google-coral/coralmicro,google-coral/coralmicro,google-coral/coralmicro,google-coral/coralmicro
|
c3f8bfc06576be94e943ca969deee2cddc881293
|
memory_alignment/align_test.cpp
|
memory_alignment/align_test.cpp
|
#include <stdlib.h>
#include <iostream>
#include <type_traits>
#include <string>
#include <sstream>
template <typename T>
struct threepack {
T v1;
T v2;
T v3;
};
template <typename T>
struct fourpack {
T v1;
T v2;
T v3;
T v4;
};
template <typename T>
struct type_printer {
static std::string print () {
std::stringstream s;
s << "unknown(" << sizeof(T) << ")";
return s.str();
}
};
template <>
struct type_printer<char> {
static std::string print () {
return std::string("char");
}
};
template <>
struct type_printer<int> {
static std::string print () {
return std::string("int");
}
};
template <>
struct type_printer<float> {
static std::string print () {
return std::string("float");
}
};
template <>
struct type_printer<double> {
static std::string print () {
return std::string("double");
}
};
template <typename T>
struct type_printer<threepack<T>> {
static std::string print () {
std::stringstream s;
s << "threepack<" << type_printer<T>::print() << ">";
return s.str();
}
};
template <typename T>
struct type_printer<fourpack<T>> {
static std::string print () {
std::stringstream s;
s << "fourpack<" << type_printer<T>::print() << ">";
return s.str();
}
};
// meta function that returns true if x is a power of two (including 1)
template <size_t x>
struct is_power_of_two : std::integral_constant< bool, !(x&(x-1)) > {};
// meta function that returns the smallest power of two that is strictly greater than x
template <size_t x, unsigned char p=1>
struct next_power_of_two : std::integral_constant< size_t, next_power_of_two<x-(x&p), (p<<1) >::value> {};
template <unsigned char p>
struct next_power_of_two<0,p> : std::integral_constant<size_t, p> {};
// metafunction that returns the smallest power of two that is greater than or equal to x
template <size_t x>
struct round_up_power_of_two
: std::integral_constant< size_t, is_power_of_two<x>::value ? x : next_power_of_two<x>::value >
{};
// metafunction that returns the smallest power of two that is greater than or equal to x,
// and greater than or equal to sizeof(void*)
template <size_t x>
struct minimum_possible_alignment
{
static const size_t pot = round_up_power_of_two<x>::value;
static const size_t value = pot < sizeof(void*) ? sizeof(void*) : pot;
};
// function that allocates memory with alignment specified as a template parameter
template <typename T, size_t alignment=minimum_possible_alignment<sizeof(T)>::value >
T* aligned_malloc(size_t size) {
// double check that alignment is a multiple of sizeof(void*), as this is a prerequisite
// for posix_memalign()
static_assert( !(alignment%sizeof(void*)),
"alignment is not a multiple of sizeof(void*)");
static_assert( is_power_of_two<alignment>::value,
"alignment is not a power of two");
void *ptr;
int result = posix_memalign(&ptr, alignment, size*sizeof(T));
if(result)
ptr=nullptr;
return reinterpret_cast<T*>(ptr);
}
template <typename T>
bool test_align(T *ptr, size_t align=minimum_possible_alignment<sizeof(T)>::value) {
if(ptr==nullptr)
return false;
size_t t = reinterpret_cast<size_t>(ptr);
return !(t&(align-1));
}
template <typename T>
bool align_by_type(size_t size) {
T *ptr = aligned_malloc<T>(size);
bool success = test_align(ptr);
std::cout << ((success&&ptr!=nullptr) ? "good" : "bad ") << " for " << (type_printer<T>::print()) << std::endl;;
return success;
}
int main(void) {
static_assert(minimum_possible_alignment<1>::value == 8, "bad alignment calculated");
static_assert(minimum_possible_alignment<2>::value == 8, "bad alignment calculated");
static_assert(minimum_possible_alignment<3>::value == 8, "bad alignment calculated");
static_assert(minimum_possible_alignment<4>::value == 8, "bad alignment calculated");
static_assert(minimum_possible_alignment<5>::value == 8, "bad alignment calculated");
static_assert(minimum_possible_alignment<6>::value == 8, "bad alignment calculated");
static_assert(minimum_possible_alignment<7>::value == 8, "bad alignment calculated");
static_assert(minimum_possible_alignment<8>::value == 8, "bad alignment calculated");
static_assert(minimum_possible_alignment<9>::value == 16, "bad alignment calculated");
static_assert(minimum_possible_alignment<10>::value == 16, "bad alignment calculated");
static_assert(minimum_possible_alignment<11>::value == 16, "bad alignment calculated");
static_assert(minimum_possible_alignment<12>::value == 16, "bad alignment calculated");
static_assert(minimum_possible_alignment<13>::value == 16, "bad alignment calculated");
static_assert(minimum_possible_alignment<14>::value == 16, "bad alignment calculated");
static_assert(minimum_possible_alignment<15>::value == 16, "bad alignment calculated");
static_assert(minimum_possible_alignment<16>::value == 16, "bad alignment calculated");
static_assert(minimum_possible_alignment<17>::value == 32, "bad alignment calculated");
static_assert(minimum_possible_alignment<18>::value == 32, "bad alignment calculated");
static_assert(minimum_possible_alignment<19>::value == 32, "bad alignment calculated");
static_assert(minimum_possible_alignment<20>::value == 32, "bad alignment calculated");
static_assert(minimum_possible_alignment<21>::value == 32, "bad alignment calculated");
static_assert(minimum_possible_alignment<22>::value == 32, "bad alignment calculated");
static_assert(minimum_possible_alignment<23>::value == 32, "bad alignment calculated");
static_assert(minimum_possible_alignment<24>::value == 32, "bad alignment calculated");
static_assert(minimum_possible_alignment<25>::value == 32, "bad alignment calculated");
static_assert(minimum_possible_alignment<26>::value == 32, "bad alignment calculated");
static_assert(minimum_possible_alignment<27>::value == 32, "bad alignment calculated");
static_assert(minimum_possible_alignment<28>::value == 32, "bad alignment calculated");
static_assert(minimum_possible_alignment<29>::value == 32, "bad alignment calculated");
static_assert(minimum_possible_alignment<30>::value == 32, "bad alignment calculated");
static_assert(minimum_possible_alignment<31>::value == 32, "bad alignment calculated");
static_assert(minimum_possible_alignment<32>::value == 32, "bad alignment calculated");
static_assert(minimum_possible_alignment<33>::value == 64, "bad alignment calculated");
align_by_type<char>(128);
align_by_type<int>(128);
align_by_type<double>(128);
align_by_type<threepack<char>>(128);
align_by_type<threepack<int>>(128);
align_by_type<threepack<double>>(128);
align_by_type<fourpack<char>>(128);
align_by_type<fourpack<int>>(128);
align_by_type<fourpack<double>>(128);
align_by_type<fourpack<long long>>(128);
// uncommet these to trigger compile time assertions
//aligned_malloc<char, 3>(200); // alignment is not multiple of sizeof(void*)
//aligned_malloc<char, 24>(200); // alignment is not power of two
return 0;
}
|
#include <stdlib.h>
#include <iostream>
#include <type_traits>
#include <string>
#include <sstream>
template <typename T>
struct threepack {
T v1;
T v2;
T v3;
};
template <typename T>
struct fourpack {
T v1;
T v2;
T v3;
T v4;
};
template <typename T>
struct type_printer {
static std::string print () {
std::stringstream s;
s << "unknown(" << sizeof(T) << ")";
return s.str();
}
};
template <>
struct type_printer<char> {
static std::string print () {
return std::string("char");
}
};
template <>
struct type_printer<int> {
static std::string print () {
return std::string("int");
}
};
template <>
struct type_printer<float> {
static std::string print () {
return std::string("float");
}
};
template <>
struct type_printer<double> {
static std::string print () {
return std::string("double");
}
};
template <typename T>
struct type_printer<threepack<T>> {
static std::string print () {
std::stringstream s;
s << "threepack<" << type_printer<T>::print() << ">";
return s.str();
}
};
template <typename T>
struct type_printer<fourpack<T>> {
static std::string print () {
std::stringstream s;
s << "fourpack<" << type_printer<T>::print() << ">";
return s.str();
}
};
// meta function that returns true if x is a power of two (including 1)
template <size_t x>
struct is_power_of_two : std::integral_constant< bool, !(x&(x-1)) > {};
// meta function that returns the smallest power of two that is strictly greater than x
template <size_t x, size_t p=1>
struct next_power_of_two : std::integral_constant< size_t, next_power_of_two<x-(x&p), (p<<1) >::value> {};
template <size_t p>
struct next_power_of_two<0,p> : std::integral_constant<size_t, p> {};
// metafunction that returns the smallest power of two that is greater than or equal to x
template <size_t x>
struct round_up_power_of_two
: std::integral_constant< size_t, is_power_of_two<x>::value ? x : next_power_of_two<x>::value >
{};
// metafunction that returns the smallest power of two that is greater than or equal to x,
// and greater than or equal to sizeof(void*)
template <size_t x>
struct minimum_possible_alignment
{
static const size_t pot = round_up_power_of_two<x>::value;
static const size_t value = pot < sizeof(void*) ? sizeof(void*) : pot;
};
// function that allocates memory with alignment specified as a template parameter
template <typename T, size_t alignment=minimum_possible_alignment<sizeof(T)>::value >
T* aligned_malloc(size_t size) {
// double check that alignment is a multiple of sizeof(void*), as this is a prerequisite
// for posix_memalign()
static_assert( !(alignment%sizeof(void*)),
"alignment is not a multiple of sizeof(void*)");
static_assert( is_power_of_two<alignment>::value,
"alignment is not a power of two");
void *ptr;
int result = posix_memalign(&ptr, alignment, size*sizeof(T));
if(result)
ptr=nullptr;
return reinterpret_cast<T*>(ptr);
}
template <typename T>
bool test_align(T *ptr, size_t align=minimum_possible_alignment<sizeof(T)>::value) {
if(ptr==nullptr)
return false;
size_t t = reinterpret_cast<size_t>(ptr);
return !(t&(align-1));
}
template <typename T>
bool align_by_type(size_t size) {
T *ptr = aligned_malloc<T>(size);
bool success = test_align(ptr);
std::cout << ((success&&ptr!=nullptr) ? "good" : "bad ") << " for " << (type_printer<T>::print()) << std::endl;;
return success;
}
int main(void) {
static_assert(minimum_possible_alignment<1>::value == 8, "bad alignment calculated");
static_assert(minimum_possible_alignment<2>::value == 8, "bad alignment calculated");
static_assert(minimum_possible_alignment<3>::value == 8, "bad alignment calculated");
static_assert(minimum_possible_alignment<4>::value == 8, "bad alignment calculated");
static_assert(minimum_possible_alignment<5>::value == 8, "bad alignment calculated");
static_assert(minimum_possible_alignment<6>::value == 8, "bad alignment calculated");
static_assert(minimum_possible_alignment<7>::value == 8, "bad alignment calculated");
static_assert(minimum_possible_alignment<8>::value == 8, "bad alignment calculated");
static_assert(minimum_possible_alignment<9>::value == 16, "bad alignment calculated");
static_assert(minimum_possible_alignment<10>::value == 16, "bad alignment calculated");
static_assert(minimum_possible_alignment<11>::value == 16, "bad alignment calculated");
static_assert(minimum_possible_alignment<12>::value == 16, "bad alignment calculated");
static_assert(minimum_possible_alignment<13>::value == 16, "bad alignment calculated");
static_assert(minimum_possible_alignment<14>::value == 16, "bad alignment calculated");
static_assert(minimum_possible_alignment<15>::value == 16, "bad alignment calculated");
static_assert(minimum_possible_alignment<16>::value == 16, "bad alignment calculated");
static_assert(minimum_possible_alignment<17>::value == 32, "bad alignment calculated");
static_assert(minimum_possible_alignment<18>::value == 32, "bad alignment calculated");
static_assert(minimum_possible_alignment<19>::value == 32, "bad alignment calculated");
static_assert(minimum_possible_alignment<20>::value == 32, "bad alignment calculated");
static_assert(minimum_possible_alignment<21>::value == 32, "bad alignment calculated");
static_assert(minimum_possible_alignment<22>::value == 32, "bad alignment calculated");
static_assert(minimum_possible_alignment<23>::value == 32, "bad alignment calculated");
static_assert(minimum_possible_alignment<24>::value == 32, "bad alignment calculated");
static_assert(minimum_possible_alignment<25>::value == 32, "bad alignment calculated");
static_assert(minimum_possible_alignment<26>::value == 32, "bad alignment calculated");
static_assert(minimum_possible_alignment<27>::value == 32, "bad alignment calculated");
static_assert(minimum_possible_alignment<28>::value == 32, "bad alignment calculated");
static_assert(minimum_possible_alignment<29>::value == 32, "bad alignment calculated");
static_assert(minimum_possible_alignment<30>::value == 32, "bad alignment calculated");
static_assert(minimum_possible_alignment<31>::value == 32, "bad alignment calculated");
static_assert(minimum_possible_alignment<32>::value == 32, "bad alignment calculated");
static_assert(minimum_possible_alignment<33>::value == 64, "bad alignment calculated");
align_by_type<char>(128);
align_by_type<int>(128);
align_by_type<double>(128);
align_by_type<threepack<char>>(128);
align_by_type<threepack<int>>(128);
align_by_type<threepack<double>>(128);
align_by_type<fourpack<char>>(128);
align_by_type<fourpack<int>>(128);
align_by_type<fourpack<double>>(128);
align_by_type<fourpack<long long>>(128);
// uncommet these to trigger compile time assertions
//aligned_malloc<char, 3>(200); // alignment is not multiple of sizeof(void*)
//aligned_malloc<char, 24>(200); // alignment is not power of two
return 0;
}
|
support types larger than 128 bytes
|
support types larger than 128 bytes
|
C++
|
bsd-3-clause
|
bcumming/cpp-etc
|
ffe13e93ee0e0408cd54bdcc1982f247e075d241
|
src/lca_demo.cpp
|
src/lca_demo.cpp
|
#include <bits/stdc++.h>
int numberOfNodes, MAXLOG;
std::vector< std::vector<int> > adjList;
int parent[50005], nodeHeight[50005];
bool visited[50005];
int binaryLiftDp[50005][27];
void dfs(int currentNode, int currentParent)
{
visited[currentNode] = true;
parent[currentNode] = currentParent;
nodeHeight[currentNode] = nodeHeight[currentParent] + 1;
int adjacencySize = adjList[currentNode].size();
for(int idx = 0; idx < adjacencySize; idx++){
int nextNode = adjList[currentNode][idx];
if(!visited[nextNode])
{
dfs(nextNode, currentNode);
}
}
}
int getMaxLog(){
int curValue = 1;
int curLog = 1;
while(curValue < numberOfNodes) curValue *= 2, curLog++;
return curLog;
}
void initializeDP()
{
nodeHeight[-1] = -1;
MAXLOG = getMaxLog();
dfs(0, -1);
for(int i = 0; i < numberOfNodes; i++) binaryLiftDp[i][0] = parent[i];
for(int i = 1; i <= MAXLOG; i++)
{
for(int j = 0; j < numberOfNodes; j++)
{
if(binaryLiftDp[j][i - 1] + 1)
binaryLiftDp[j][i] = binaryLiftDp[binaryLiftDp[j][i - 1]][i - 1];
else binaryLiftDp[j][i] = -1;
}
}
}
int LCA(int a, int b)
{
if(nodeHeight[a] < nodeHeight[b]) std::swap(a,b);
for(int i = MAXLOG; i >= 0; i--)
{
if(binaryLiftDp[a][i] + 1 && nodeHeight[binaryLiftDp[a][i]] >= nodeHeight[b])
a = binaryLiftDp[a][i];
}
if(!(a - b)) return a;
for(int i = MAXLOG; i >= 0; i--)
{
if(binaryLiftDp[a][i] + 1 && binaryLiftDp[a][i] - binaryLiftDp[b][i])
a = binaryLiftDp[a][i], b = binaryLiftDp[b][i];
}
return parent[a];
}
void buildTree()
{
printf("Enter number of nodes of the tree: ");
scanf("%d", &numberOfNodes);
adjList.resize(numberOfNodes, std::vector<int> ());
for(int i = 0; i < numberOfNodes - 1; i++)
{
int firstNode, secondNode;
printf("Enter the two nodes to be connected: ");
scanf("%d %d", &firstNode, &secondNode);
adjList[firstNode].push_back(secondNode);
adjList[secondNode].push_back(firstNode);
}
}
void answerQueries()
{
int queryCount;
printf("Enter the number of queries: ");
scanf("%d", &queryCount);
for(int i = 0; i < queryCount; i++)
{
int firstNode, secondNode;
printf("Enter the two nodes : ");
scanf("%d %d", &firstNode, &secondNode);
printf("%d\n", LCA(firstNode, secondNode));
}
}
int main()
{
buildTree();
initializeDP();
answerQueries();
}
|
#include <cstdio>
#include <vector>
const int MAX_NODE = 5000;
const int MAX_LOG = 20;
int numberOfNodes, maxLog;
std::vector< std::vector<int> > adjList;
int parent[MAX_NODE], nodeHeight[MAX_NODE];
bool visited[MAX_NODE];
int binaryLiftDp[MAX_NODE][MAX_LOG];
void dfs(int currentNode, int currentParent)
{
visited[currentNode] = true;
parent[currentNode] = currentParent;
nodeHeight[currentNode] = nodeHeight[currentParent] + 1;
int adjacencySize = adjList[currentNode].size();
for(int idx = 0; idx < adjacencySize; idx++){
int nextNode = adjList[currentNode][idx];
if(!visited[nextNode])
{
dfs(nextNode, currentNode);
}
}
}
int getMaxLog(){
int curValue = 1;
int curLog = 1;
while(curValue < numberOfNodes) curValue *= 2, curLog++;
return curLog;
}
void initializeDP()
{
nodeHeight[-1] = -1;
maxLog = getMaxLog();
dfs(0, -1);
for(int i = 0; i < numberOfNodes; i++) binaryLiftDp[i][0] = parent[i];
for(int i = 1; i <= maxLog; i++)
{
for(int j = 0; j < numberOfNodes; j++)
{
if(binaryLiftDp[j][i - 1] + 1)
binaryLiftDp[j][i] = binaryLiftDp[binaryLiftDp[j][i - 1]][i - 1];
else binaryLiftDp[j][i] = -1;
}
}
}
int LCA(int a, int b)
{
if(nodeHeight[a] < nodeHeight[b]) std::swap(a,b);
for(int i = maxLog; i >= 0; i--)
{
if(binaryLiftDp[a][i] + 1 && nodeHeight[binaryLiftDp[a][i]] >= nodeHeight[b])
a = binaryLiftDp[a][i];
}
if(!(a - b)) return a;
for(int i = maxLog; i >= 0; i--)
{
if(binaryLiftDp[a][i] + 1 && binaryLiftDp[a][i] - binaryLiftDp[b][i])
a = binaryLiftDp[a][i], b = binaryLiftDp[b][i];
}
return parent[a];
}
void buildTree()
{
printf("Enter number of nodes of the tree: ");
scanf("%d", &numberOfNodes);
adjList.resize(numberOfNodes, std::vector<int> ());
for(int i = 0; i < numberOfNodes - 1; i++)
{
int firstNode, secondNode;
printf("Enter the two nodes to be connected: ");
scanf("%d %d", &firstNode, &secondNode);
adjList[firstNode].push_back(secondNode);
adjList[secondNode].push_back(firstNode);
}
}
void answerQueries()
{
int queryCount;
printf("Enter the number of queries: ");
scanf("%d", &queryCount);
for(int i = 0; i < queryCount; i++)
{
int firstNode, secondNode;
printf("Enter the two nodes : ");
scanf("%d %d", &firstNode, &secondNode);
printf("%d\n", LCA(firstNode, secondNode));
}
}
int main()
{
buildTree();
initializeDP();
answerQueries();
}
|
Add const size for array
|
Add const size for array
|
C++
|
mit
|
xtaci/algorithms,xtaci/algorithms,greyg00s/algorithms,greyg00s/algorithms
|
696dc4bb13d27b647284f952e42ff6b48d36dd04
|
paddle/fluid/imperative/reducer.cc
|
paddle/fluid/imperative/reducer.cc
|
// Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "paddle/fluid/imperative/reducer.h"
namespace paddle {
namespace imperative {
#if defined(PADDLE_WITH_NCCL)
std::shared_ptr<Reducer> Reducer::s_instance_ = NULL;
Reducer::Reducer(const std::vector<std::shared_ptr<imperative::VarBase>> &vars,
const std::vector<std::vector<size_t>> &group_indices,
const std::vector<bool> &is_sparse_gradient,
std::shared_ptr<imperative::ParallelContext> parallel_ctx)
: vars_(vars),
group_indices_(group_indices),
is_sparse_gradient_(is_sparse_gradient),
parallel_ctx_(parallel_ctx) {
VLOG(3) << "Start construct the Reducer ...";
// initialize groups
InitializeGroups(group_indices);
{
for (size_t group_index = 0; group_index < group_indices.size();
++group_index) {
for (size_t var_index = 0; var_index < group_indices[group_index].size();
++var_index) {
size_t global_var_index = group_indices[group_index][var_index];
const auto variable_index = VariableIndex{
.group_index = group_index, .inside_group_index = var_index,
};
VLOG(3) << "add hook for var[" << vars_[global_var_index]->GradVarName()
<< "], it's in group [" << group_index << "]";
vars_[global_var_index]->SharedVar()->AddGradVarLeafBackwardHook(
std::unique_ptr<LambdaGradAccumulatorPostHook>(
new LambdaGradAccumulatorPostHook([=](VariableWrapper *grad) {
this->AddDistHook(grad, variable_index);
})));
}
}
}
compute_stream_ = static_cast<platform::CUDADeviceContext *>(
platform::DeviceContextPool::Instance().Get(place_))
->stream();
comm_stream_ = platform::NCCLCommContext::Instance().Get(0, place_)->stream();
events_.resize(group_indices.size());
for (auto &event : events_) {
event = platform::CudaEventResourcePool::Instance().New(
BOOST_GET_CONST(platform::CUDAPlace, place_).device);
}
comm_enent_ = platform::CudaEventResourcePool::Instance().New(
BOOST_GET_CONST(platform::CUDAPlace, place_).device);
std::call_once(once_flag_, []() {
std::atexit([]() { Reducer::GetInstance()->ReleaseReducer(); });
});
}
void Reducer::ReleaseReducer() {
for (auto &event : events_) {
event.reset();
}
comm_enent_.reset();
}
int64_t Reducer::InitializeDenseGroups(
const std::vector<size_t> &variable_indices_, Group *p_group) {
int64_t all_length = 0;
for (size_t index = 0; index < variable_indices_.size(); ++index) {
const auto variable_index = variable_indices_[index];
const auto &var = vars_[variable_index];
const auto var_name = var->Name();
PADDLE_ENFORCE_EQ(is_sparse_gradient_[variable_index], false,
platform::errors::PreconditionNotMet(
"Tensor `%s`'s GRAD must be LoDTensor, but received "
"GRAD is SelectedRows",
var_name));
auto lod_tensor = var->MutableVar()->GetMutable<framework::LoDTensor>();
PADDLE_ENFORCE_EQ(lod_tensor->IsInitialized(), true,
platform::errors::PreconditionNotMet(
"Tensor `%s` is not initialized.", var_name));
auto size = lod_tensor->numel();
PADDLE_ENFORCE_GT(
size, 0, platform::errors::PreconditionNotMet(
"The number of tensor `%s`'s elements is 0.", var_name));
all_length += size;
p_group->length_.push_back(size);
// for concat operator
p_group->dense_tensors_.push_back(framework::Tensor());
// check the dtype and place, it must be same.
auto dtype = var->DataType();
auto place = var->Place();
if (index > 0) {
PADDLE_ENFORCE_EQ(
dtype, p_group->dtype_,
platform::errors::PreconditionNotMet(
"Tensor %s has different dtype. Expected dtype is %s, but actual "
"dtype is %s",
var_name, framework::DataTypeToString(p_group->dtype_),
framework::DataTypeToString(dtype)));
PADDLE_ENFORCE_EQ(place, place_,
platform::errors::PreconditionNotMet(
"Tensor %s has different place. Expected place is "
"%s, but actual place is %s",
var_name, place_, place));
} else {
p_group->dtype_ = dtype;
place_ = place;
}
}
return all_length;
}
// Each parameter will be initialized according to the group information.
// For the sparse parameter, sparse_contents_ in the group directly points
// to the parameter. For dense parameters, first construct an empty Tensor().
// Then specify the actual memory in MarkVariableReady.
void Reducer::InitializeGroups(
const std::vector<std::vector<size_t>> &group_indices) {
VLOG(3) << "Start initialize groups ..";
// clear the group
groups_.clear();
groups_.reserve(group_indices.size());
auto group_nums = group_indices.size();
for (size_t group_index = 0; group_index < group_nums; ++group_index) {
const auto &variable_indices_ = group_indices[group_index];
PADDLE_ENFORCE_GT(
variable_indices_.size(), 0,
platform::errors::PreconditionNotMet(
"The number of group_index[`%d`]'s elements is 0.", group_index));
Group group;
group.variable_indices_ = variable_indices_;
int64_t all_length = 0;
// It's just for check the sparse or dense
auto first_varbase = vars_[variable_indices_.front()];
if (variable_indices_.size() == 1 &&
is_sparse_gradient_[variable_indices_.front()]) {
// process the sparse gradient. one sparse, one group
group.sparse_contents_ = first_varbase->MutableGradVar();
group.dtype_ = first_varbase->DataType();
group.is_sparse_ = true;
} else {
// process the dense gradient.
all_length = InitializeDenseGroups(variable_indices_, &group);
// Alloc the continuous space
auto tensor = group.dense_contents_.GetMutable<framework::LoDTensor>();
tensor->Resize(framework::make_ddim({all_length}))
.mutable_data(place_, group.dtype_);
}
// Debug Message For Reducer
VLOG(3) << "the groups_[" << group_index << "] basic message:";
VLOG(3) << "numul: " << all_length << " ;is_sparse: " << group.is_sparse_
<< " ;var number: " << group.variable_indices_.size();
groups_.emplace_back(std::move(group));
}
}
// After each batch is calculated, the counter of each group(group.pending_)
// and allreudce sequence counter(next_group_) will be cleaned up again.
void Reducer::PrepareForBackward() {
VLOG(3) << "start reseting count..";
next_group_ = 0;
std::for_each(groups_.begin(), groups_.end(), [](Group &group) {
group.pending_ = group.variable_indices_.size();
});
}
// Add hook function to each leaf node. When the gradient of a leaf node is
// generated, if it is the sparse parameter, it will directly execute allreduce,
// if it is the dense parameter, it will execute three steps: 1,
// MarkVariableReady. Find the position of the corresponding group
// through var_index, share the gradient memory and the group dense_tensors,
// the group counter is reduced by 1. 2, MarkGroupReady: When the group
// counter is 0, it means that allreduce can be emitted, and
// concat + allreduce + split is emitted in turn according to next_group_.
// 3, FinalizeBackward: after the end, synchronize each stream.
void Reducer::AddDistHook(VariableWrapper *var_warpper,
const VariableIndex &var_index) {
auto group_index = var_index.group_index;
auto &group = groups_[group_index];
if (!group.is_sparse_) {
// Only dense_contents_ need memory copy
MarkVariableReady(var_index, var_warpper);
}
if (--group.pending_ == 0) {
// can start allreduce
MarkGroupReady(group_index);
}
if (next_group_ == groups_.size()) {
FinalizeBackward();
}
}
void Reducer::MarkVariableReady(const VariableIndex &var_index,
VariableWrapper *var_warpper) {
auto group_index = var_index.group_index;
auto variable_index = var_index.inside_group_index;
auto &group = groups_[group_index];
auto length = group.length_[variable_index];
auto tensor = var_warpper->MutableVar()->GetMutable<framework::LoDTensor>();
group.dense_tensors_[variable_index].ShareDataWith(*tensor).Resize(
{static_cast<int64_t>(length)});
}
void Reducer::MarkGroupReady(size_t group_index) {
if (group_index > next_group_) {
LOG(WARNING) << "Maybe it need adjust the order of group";
return;
}
PADDLE_ENFORCE_CUDA_SUCCESS(
cudaEventRecord(events_[group_index].get(), compute_stream_));
PADDLE_ENFORCE_CUDA_SUCCESS(
cudaStreamWaitEvent(comm_stream_, events_[group_index].get(), 0));
for (; next_group_ < groups_.size() && groups_[next_group_].pending_ == 0;
++next_group_) {
auto &group = groups_[next_group_];
if (group.is_sparse_) {
VLOG(3) << "sparse group [" << next_group_ << "] start allreduce...";
parallel_ctx_->AllReduceByStream(*group.sparse_contents_,
group.sparse_contents_, 0, false);
} else {
VLOG(3) << "dense group [" << next_group_ << "] start allreduce...";
// Select common commstream to concat tensors
// group.dense_tensors ---> group.dense_contents_
group.ConcatTensors(*parallel_ctx_->GetDeviceContext(0));
// Start allreduce
parallel_ctx_->AllReduceByStream(group.dense_contents_,
&(group.dense_contents_), 0, false);
// Select common commstream to split tensors
// group.dense_contents_ ---> group.dense_tensors
group.SplitTensors(*parallel_ctx_->GetDeviceContext(0));
}
}
}
void Reducer::FinalizeBackward() {
PADDLE_ENFORCE_CUDA_SUCCESS(cudaEventRecord(comm_enent_.get(), comm_stream_));
PADDLE_ENFORCE_CUDA_SUCCESS(
cudaStreamWaitEvent(compute_stream_, comm_enent_.get(), 0));
VLOG(3) << "In the batch, Reducer is finished...";
}
// According to the size of each parameter, it is allocated to different groups.
// The sparse parameter occupies a group exclusively. The dense parameters of
// the same data type are assigned to the same group. When dividing groups, the
// size of each group will be limited according to each value in
// group_size_limits in turn. When it is not enough, it will be divided
// by the last value of group_size_limits. The limit value is 0, which
// means that the parameter will monopolize the group.
std::vector<std::vector<size_t>> AssignGroupBySize(
const std::vector<std::shared_ptr<imperative::VarBase>> &vars,
const std::vector<bool> &is_sparse_gradient,
const std::vector<size_t> &group_size_limits) {
PADDLE_ENFORCE_EQ(vars.size(), is_sparse_gradient.size(),
platform::errors::PreconditionNotMet(
"vars len must be equal to is_sparse_gradient len, but "
"[%lu] != [%lu]",
vars.size(), is_sparse_gradient.size()));
// the return vector
std::vector<std::vector<size_t>> res;
// Key: the var type
// Value: should use which index in group_size_limits for group size limit
std::unordered_map<std::string, size_t> group_limit_index;
// Key: the var type
// Value: <the var index in input tensors, total numel in this group>
std::unordered_map<std::string, std::pair<std::vector<size_t>, size_t>>
next_group;
for (size_t i = 0; i < vars.size(); ++i) {
const auto &var = vars[i];
if (is_sparse_gradient[i]) {
// we keep sparse var a single group
res.push_back({i});
continue;
}
const auto &var_dtype = var->DataType();
const auto var_dtype_str = framework::DataTypeToString(var_dtype);
VLOG(3) << "var[" << var->GradVarName() << "] 's type is "
<< var->DataType();
auto &group_info = next_group[var_dtype_str];
int64_t var_size = -1;
if (var->Var().IsType<framework::LoDTensor>()) {
var_size = var->Var().Get<framework::LoDTensor>().numel();
} else {
VLOG(3) << "var " << var->Name()
<< " is not tensor or selected_rows, so skip it";
continue;
}
group_info.first.push_back(i);
group_info.second += framework::SizeOfType(var_dtype) * var_size;
if (group_limit_index.find(var_dtype_str) == group_limit_index.end()) {
// means it is the first var of var_dtype
group_limit_index[var_dtype_str] = 0;
}
auto &cur_limit_index = group_limit_index[var_dtype_str];
if (group_info.second >= group_size_limits[cur_limit_index]) {
// exceed group capacity and create a new group
res.emplace_back(std::move(group_info.first));
group_info = std::pair<std::vector<size_t>, size_t>();
cur_limit_index =
(std::min)(cur_limit_index + 1, group_size_limits.size() - 1);
}
}
// add the final groups
for (auto &e : next_group) {
auto &group_info = e.second;
if (!group_info.first.empty()) {
res.emplace_back(std::move(group_info.first));
}
}
for (const auto &group_index : res) {
PADDLE_ENFORCE_NE(
group_index.empty(), true,
platform::errors::PreconditionNotMet(
"AssignGroupBySize construct empty group, please check."));
}
std::sort(res.begin(), res.end(),
[](const std::vector<size_t> &x, const std::vector<size_t> &y) {
return x.front() < y.front();
});
return res;
}
#endif
} // namespace imperative
} // namespace paddle
|
// Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "paddle/fluid/imperative/reducer.h"
namespace paddle {
namespace imperative {
#if defined(PADDLE_WITH_NCCL)
std::shared_ptr<Reducer> Reducer::s_instance_ = NULL;
Reducer::Reducer(const std::vector<std::shared_ptr<imperative::VarBase>> &vars,
const std::vector<std::vector<size_t>> &group_indices,
const std::vector<bool> &is_sparse_gradient,
std::shared_ptr<imperative::ParallelContext> parallel_ctx)
: vars_(vars),
group_indices_(group_indices),
is_sparse_gradient_(is_sparse_gradient),
parallel_ctx_(parallel_ctx) {
VLOG(3) << "Start construct the Reducer ...";
// initialize groups
InitializeGroups(group_indices);
{
for (size_t group_index = 0; group_index < group_indices.size();
++group_index) {
for (size_t var_index = 0; var_index < group_indices[group_index].size();
++var_index) {
size_t global_var_index = group_indices[group_index][var_index];
const auto variable_index = VariableIndex{
.group_index = group_index, .inside_group_index = var_index,
};
VLOG(3) << "add hook for var[" << vars_[global_var_index]->GradVarName()
<< "], it's in group [" << group_index << "]";
vars_[global_var_index]->SharedVar()->AddGradVarLeafBackwardHook(
std::unique_ptr<LambdaGradAccumulatorPostHook>(
new LambdaGradAccumulatorPostHook([=](VariableWrapper *grad) {
this->AddDistHook(grad, variable_index);
})));
}
}
}
compute_stream_ = static_cast<platform::CUDADeviceContext *>(
platform::DeviceContextPool::Instance().Get(place_))
->stream();
comm_stream_ = platform::NCCLCommContext::Instance().Get(0, place_)->stream();
events_.resize(group_indices.size());
for (auto &event : events_) {
event = platform::CudaEventResourcePool::Instance().New(
BOOST_GET_CONST(platform::CUDAPlace, place_).device);
}
comm_enent_ = platform::CudaEventResourcePool::Instance().New(
BOOST_GET_CONST(platform::CUDAPlace, place_).device);
std::call_once(once_flag_, []() {
std::atexit([]() { Reducer::GetInstance()->ReleaseReducer(); });
});
}
void Reducer::ReleaseReducer() {
for (auto &event : events_) {
event.reset();
}
comm_enent_.reset();
}
int64_t Reducer::InitializeDenseGroups(
const std::vector<size_t> &variable_indices_, Group *p_group) {
int64_t all_length = 0;
for (size_t index = 0; index < variable_indices_.size(); ++index) {
const auto variable_index = variable_indices_[index];
const auto &var = vars_[variable_index];
const auto var_name = var->Name();
PADDLE_ENFORCE_EQ(is_sparse_gradient_[variable_index], false,
platform::errors::PreconditionNotMet(
"Tensor `%s`'s GRAD must be LoDTensor, but received "
"GRAD is SelectedRows",
var_name));
auto lod_tensor = var->MutableVar()->GetMutable<framework::LoDTensor>();
PADDLE_ENFORCE_EQ(lod_tensor->IsInitialized(), true,
platform::errors::PreconditionNotMet(
"Tensor `%s` is not initialized.", var_name));
auto size = lod_tensor->numel();
PADDLE_ENFORCE_GT(
size, 0, platform::errors::PreconditionNotMet(
"The number of tensor `%s`'s elements is 0.", var_name));
all_length += size;
p_group->length_.push_back(size);
// for concat operator
p_group->dense_tensors_.push_back(framework::Tensor());
// check the dtype and place, it must be same.
auto dtype = var->DataType();
auto place = var->Place();
if (index > 0) {
PADDLE_ENFORCE_EQ(
dtype, p_group->dtype_,
platform::errors::PreconditionNotMet(
"Tensor %s has different dtype. Expected dtype is %s, but actual "
"dtype is %s",
var_name, framework::DataTypeToString(p_group->dtype_),
framework::DataTypeToString(dtype)));
PADDLE_ENFORCE_EQ(place, place_,
platform::errors::PreconditionNotMet(
"Tensor %s has different place. Expected place is "
"%s, but actual place is %s",
var_name, place_, place));
} else {
p_group->dtype_ = dtype;
place_ = place;
}
}
return all_length;
}
// Each parameter will be initialized according to the group information.
// For the sparse parameter, sparse_contents_ in the group directly points
// to the parameter. For dense parameters, first construct an empty Tensor().
// Then specify the actual memory in MarkVariableReady.
void Reducer::InitializeGroups(
const std::vector<std::vector<size_t>> &group_indices) {
VLOG(3) << "Start initialize groups ..";
// clear the group
groups_.clear();
groups_.reserve(group_indices.size());
auto group_nums = group_indices.size();
for (size_t group_index = 0; group_index < group_nums; ++group_index) {
const auto &variable_indices_ = group_indices[group_index];
PADDLE_ENFORCE_GT(
variable_indices_.size(), 0,
platform::errors::PreconditionNotMet(
"The number of group_index[`%d`]'s elements is 0.", group_index));
Group group;
group.variable_indices_ = variable_indices_;
int64_t all_length = 0;
// It's just for check the sparse or dense
auto first_varbase = vars_[variable_indices_.front()];
if (variable_indices_.size() == 1 &&
is_sparse_gradient_[variable_indices_.front()]) {
// process the sparse gradient. one sparse, one group
group.sparse_contents_ = first_varbase->MutableGradVar();
group.dtype_ = first_varbase->DataType();
group.is_sparse_ = true;
} else {
// process the dense gradient.
all_length = InitializeDenseGroups(variable_indices_, &group);
// Alloc the continuous space
auto tensor = group.dense_contents_.GetMutable<framework::LoDTensor>();
tensor->Resize(framework::make_ddim({all_length}))
.mutable_data(place_, group.dtype_);
}
// Debug Message For Reducer
VLOG(3) << "the groups_[" << group_index << "] basic message:";
VLOG(3) << "numul: " << all_length << " ;is_sparse: " << group.is_sparse_
<< " ;var number: " << group.variable_indices_.size();
groups_.emplace_back(std::move(group));
}
}
// After each batch is calculated, the counter of each group(group.pending_)
// and allreudce sequence counter(next_group_) will be cleaned up again.
void Reducer::PrepareForBackward() {
VLOG(3) << "start reseting count..";
next_group_ = 0;
std::for_each(groups_.begin(), groups_.end(), [](Group &group) {
group.pending_ = group.variable_indices_.size();
});
}
// Add hook function to each leaf node. When the gradient of a leaf node is
// generated, if it is the sparse parameter, it will directly execute allreduce,
// if it is the dense parameter, it will execute three steps: 1,
// MarkVariableReady. Find the position of the corresponding group
// through var_index, share the gradient memory and the group dense_tensors,
// the group counter is reduced by 1. 2, MarkGroupReady: When the group
// counter is 0, it means that allreduce can be emitted, and
// concat + allreduce + split is emitted in turn according to next_group_.
// 3, FinalizeBackward: after the end, synchronize each stream.
void Reducer::AddDistHook(VariableWrapper *var_warpper,
const VariableIndex &var_index) {
auto group_index = var_index.group_index;
auto &group = groups_[group_index];
if (!group.is_sparse_) {
// Only dense_contents_ need memory copy
MarkVariableReady(var_index, var_warpper);
}
if (--group.pending_ == 0) {
// can start allreduce
MarkGroupReady(group_index);
}
if (next_group_ == groups_.size()) {
FinalizeBackward();
}
}
void Reducer::MarkVariableReady(const VariableIndex &var_index,
VariableWrapper *var_warpper) {
auto group_index = var_index.group_index;
auto variable_index = var_index.inside_group_index;
auto &group = groups_[group_index];
auto length = group.length_[variable_index];
auto tensor = var_warpper->MutableVar()->GetMutable<framework::LoDTensor>();
group.dense_tensors_[variable_index].ShareDataWith(*tensor).Resize(
{static_cast<int64_t>(length)});
}
void Reducer::MarkGroupReady(size_t group_index) {
if (group_index > next_group_) {
VLOG(3) << "Maybe it need adjust the order of group";
return;
}
PADDLE_ENFORCE_CUDA_SUCCESS(
cudaEventRecord(events_[group_index].get(), compute_stream_));
PADDLE_ENFORCE_CUDA_SUCCESS(
cudaStreamWaitEvent(comm_stream_, events_[group_index].get(), 0));
for (; next_group_ < groups_.size() && groups_[next_group_].pending_ == 0;
++next_group_) {
auto &group = groups_[next_group_];
if (group.is_sparse_) {
VLOG(3) << "sparse group [" << next_group_ << "] start allreduce...";
parallel_ctx_->AllReduceByStream(*group.sparse_contents_,
group.sparse_contents_, 0, false);
} else {
VLOG(3) << "dense group [" << next_group_ << "] start allreduce...";
// Select common commstream to concat tensors
// group.dense_tensors ---> group.dense_contents_
group.ConcatTensors(*parallel_ctx_->GetDeviceContext(0));
// Start allreduce
parallel_ctx_->AllReduceByStream(group.dense_contents_,
&(group.dense_contents_), 0, false);
// Select common commstream to split tensors
// group.dense_contents_ ---> group.dense_tensors
group.SplitTensors(*parallel_ctx_->GetDeviceContext(0));
}
}
}
void Reducer::FinalizeBackward() {
PADDLE_ENFORCE_CUDA_SUCCESS(cudaEventRecord(comm_enent_.get(), comm_stream_));
PADDLE_ENFORCE_CUDA_SUCCESS(
cudaStreamWaitEvent(compute_stream_, comm_enent_.get(), 0));
VLOG(3) << "In the batch, Reducer is finished...";
}
// According to the size of each parameter, it is allocated to different groups.
// The sparse parameter occupies a group exclusively. The dense parameters of
// the same data type are assigned to the same group. When dividing groups, the
// size of each group will be limited according to each value in
// group_size_limits in turn. When it is not enough, it will be divided
// by the last value of group_size_limits. The limit value is 0, which
// means that the parameter will monopolize the group.
std::vector<std::vector<size_t>> AssignGroupBySize(
const std::vector<std::shared_ptr<imperative::VarBase>> &vars,
const std::vector<bool> &is_sparse_gradient,
const std::vector<size_t> &group_size_limits) {
PADDLE_ENFORCE_EQ(vars.size(), is_sparse_gradient.size(),
platform::errors::PreconditionNotMet(
"vars len must be equal to is_sparse_gradient len, but "
"[%lu] != [%lu]",
vars.size(), is_sparse_gradient.size()));
// the return vector
std::vector<std::vector<size_t>> res;
// Key: the var type
// Value: should use which index in group_size_limits for group size limit
std::unordered_map<std::string, size_t> group_limit_index;
// Key: the var type
// Value: <the var index in input tensors, total numel in this group>
std::unordered_map<std::string, std::pair<std::vector<size_t>, size_t>>
next_group;
for (size_t i = 0; i < vars.size(); ++i) {
const auto &var = vars[i];
if (is_sparse_gradient[i]) {
// we keep sparse var a single group
res.push_back({i});
continue;
}
const auto &var_dtype = var->DataType();
const auto var_dtype_str = framework::DataTypeToString(var_dtype);
VLOG(3) << "var[" << var->GradVarName() << "] 's type is "
<< var->DataType();
auto &group_info = next_group[var_dtype_str];
int64_t var_size = -1;
if (var->Var().IsType<framework::LoDTensor>()) {
var_size = var->Var().Get<framework::LoDTensor>().numel();
} else {
VLOG(3) << "var " << var->Name()
<< " is not tensor or selected_rows, so skip it";
continue;
}
group_info.first.push_back(i);
group_info.second += framework::SizeOfType(var_dtype) * var_size;
if (group_limit_index.find(var_dtype_str) == group_limit_index.end()) {
// means it is the first var of var_dtype
group_limit_index[var_dtype_str] = 0;
}
auto &cur_limit_index = group_limit_index[var_dtype_str];
if (group_info.second >= group_size_limits[cur_limit_index]) {
// exceed group capacity and create a new group
res.emplace_back(std::move(group_info.first));
group_info = std::pair<std::vector<size_t>, size_t>();
cur_limit_index =
(std::min)(cur_limit_index + 1, group_size_limits.size() - 1);
}
}
// add the final groups
for (auto &e : next_group) {
auto &group_info = e.second;
if (!group_info.first.empty()) {
res.emplace_back(std::move(group_info.first));
}
}
for (const auto &group_index : res) {
PADDLE_ENFORCE_NE(
group_index.empty(), true,
platform::errors::PreconditionNotMet(
"AssignGroupBySize construct empty group, please check."));
}
std::sort(res.begin(), res.end(),
[](const std::vector<size_t> &x, const std::vector<size_t> &y) {
return x.front() < y.front();
});
return res;
}
#endif
} // namespace imperative
} // namespace paddle
|
fix the warning of reducer (#29323)
|
fix the warning of reducer (#29323)
|
C++
|
apache-2.0
|
PaddlePaddle/Paddle,PaddlePaddle/Paddle,PaddlePaddle/Paddle,luotao1/Paddle,PaddlePaddle/Paddle,luotao1/Paddle,PaddlePaddle/Paddle,luotao1/Paddle,PaddlePaddle/Paddle,luotao1/Paddle,PaddlePaddle/Paddle,luotao1/Paddle,luotao1/Paddle,luotao1/Paddle
|
a767d3b25baffcb18634af1876f098ad56f76ec2
|
phonon/tests/fakebackend/mediaobject.cpp
|
phonon/tests/fakebackend/mediaobject.cpp
|
/* This file is part of the KDE project
Copyright (C) 2006-2007 Matthias Kretz <[email protected]>
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) version 3, or any
later version accepted by the membership of KDE e.V. (or its
successor approved by the membership of KDE e.V.), Nokia Corporation
(or its successors, if any) and the KDE Free Qt Foundation, which shall
act as a proxy defined in Section 6 of version 3 of the license.
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, see <http://www.gnu.org/licenses/>.
*/
#include "mediaobject.h"
#include <QtCore/QTimer>
#include "stream.h"
#include "../../abstractmediastream_p.h"
#include <QtCore/QVector>
#include <cmath>
#include <QtCore/QFile>
#include <QtCore/QByteRef>
#include <QtCore/QStringList>
#include "audionode.h"
#include "videonode.h"
namespace Phonon
{
namespace Fake
{
static const int SAMPLE_RATE = 44100;
static const float SAMPLE_RATE_FLOAT = 44100.0f;
static const int FRAME_RATE = 25;
static const int SAMPLES_PER_FRAME = SAMPLE_RATE / FRAME_RATE;
MediaObject::MediaObject(QObject *parent)
: QObject(parent)
, m_state(Phonon::LoadingState)
, m_tickTimer(new QTimer(this))
, m_bufferSize(SAMPLES_PER_FRAME)//512)
, m_lastSamplesMissing(0)
, m_position(0.0f)
, m_frequency(440.0f)
, m_prefinishMarkReachedNotEmitted(true), m_waiting(0)
{
//kDebug(604) ;
connect(m_tickTimer, SIGNAL(timeout()), SLOT(emitTick()));
}
MediaObject::~MediaObject()
{
//kDebug(604) ;
}
State MediaObject::state() const
{
//kDebug(604) ;
return m_state;
}
bool MediaObject::hasVideo() const
{
//kDebug(604) ;
return false;
}
bool MediaObject::isSeekable() const
{
//kDebug(604) ;
return true;
}
qint64 MediaObject::currentTime() const
{
//kDebug(604) ;
switch(state())
{
case Phonon::PausedState:
case Phonon::BufferingState:
return m_startTime.msecsTo(m_pauseTime);
case Phonon::PlayingState:
return m_startTime.elapsed();
case Phonon::StoppedState:
case Phonon::LoadingState:
return 0;
case Phonon::ErrorState:
break;
}
return -1;
}
qint32 MediaObject::tickInterval() const
{
//kDebug(604) ;
return m_tickInterval;
}
void MediaObject::setTickInterval(qint32 newTickInterval)
{
//kDebug(604) ;
m_tickInterval = newTickInterval;
if (m_tickInterval <= 0)
m_tickTimer->setInterval(50);
else
m_tickTimer->setInterval(newTickInterval);
}
void MediaObject::play()
{
//kDebug(604) ;
if (m_state == Phonon::LoadingState) {
setState(Phonon::BufferingState);
} else {
setState(Phonon::PlayingState);
}
}
QString MediaObject::errorString() const
{
return QString();
}
Phonon::ErrorType MediaObject::errorType() const
{
return Phonon::NoError;
}
void MediaObject::setState(State newstate)
{
if (newstate == m_state)
return;
State oldstate = m_state;
m_state = newstate;
switch(newstate)
{
case Phonon::PausedState:
case Phonon::BufferingState:
m_pauseTime.start();
break;
case Phonon::PlayingState:
m_tickTimer->start();
if (oldstate == Phonon::PausedState || oldstate == Phonon::BufferingState)
m_startTime = m_startTime.addMSecs(m_pauseTime.elapsed());
else
m_startTime.start();
break;
case Phonon::StoppedState:
case Phonon::ErrorState:
case Phonon::LoadingState:
m_startTime = QTime();
break;
}
//kDebug(604) << "emit stateChanged(" << newstate << ", " << oldstate << ")";
emit stateChanged(newstate, oldstate);
}
static const float TWOPI = 6.28318530718f;
static const float maxFrequency = 1760.0f;
static const float minFrequency = 440.0f;
static const float frequencyToDelta = TWOPI / SAMPLE_RATE_FLOAT;
void MediaObject::fillBuffer(QVector<float> *buffer)
{
//static QFile createdump("createdump");
//if (!createdump.isOpen())
//createdump.open(QIODevice::WriteOnly);
m_frequency *= 1.059463094359f;
if (m_frequency > maxFrequency)
m_frequency = minFrequency;
float delta = frequencyToDelta * m_frequency;
float *data = buffer->data();
const float * const end = data + m_bufferSize;
while (data != end)
{
const float sample = std::sin(m_position);
//createdump.write(QByteArray::number(sample) + "\n");
*(data++) = sample;
m_position += delta;
if (m_position > TWOPI)
m_position -= TWOPI;
}
}
void MediaObject::fillFrameData(Phonon::Experimental::VideoFrame *frame)
{
Q_UNUSED(frame);
//X static quint32 frameCount = 0;
//X quint8 *dataPtr = reinterpret_cast<quint8 *>(frame->data.data());
//X for (int y = 0; y < frame->height; ++y)
//X for (int x = 0; x < frame->width; ++x)
//X {
//X *dataPtr++ = static_cast<quint8>(0xff);
//X *dataPtr++ = static_cast<quint8>((x + frameCount) * 2 / 3); //red
//X *dataPtr++ = static_cast<quint8>(y + frameCount); //green
//X *dataPtr++ = static_cast<quint8>(frameCount / 2); //blue
//X }
//X ++frameCount;
}
qint64 MediaObject::totalTime() const
{
//kDebug(604) ;
return 1000 *60 *3; // 3 minutes
}
qint32 MediaObject::prefinishMark() const
{
//kDebug(604) ;
return m_prefinishMark;
}
qint32 MediaObject::transitionTime() const
{
return m_transitionTime;
}
void MediaObject::setTransitionTime(qint32 time)
{
m_transitionTime = time;
}
qint64 MediaObject::remainingTime() const
{
return totalTime() - currentTime();
}
MediaSource MediaObject::source() const
{
return m_source;
}
void MediaObject::setNextSource(const MediaSource &source)
{
m_nextSource = source;
}
void MediaObject::setSource(const MediaSource &source)
{
//kDebug(604) ;
m_prefinishMarkReachedNotEmitted = true;
m_source = source;
setState(Phonon::LoadingState);
switch (m_source.type()) {
case MediaSource::Invalid:
return;
case MediaSource::Disc:
Q_ASSERT(m_source.discType() != NoDisc);
break;
case MediaSource::Url:
Q_ASSERT(m_source.url().isValid());
break;
case MediaSource::LocalFile:
Q_ASSERT(!m_source.fileName().isEmpty());
break;
case MediaSource::Stream:
//Stream *s = new Stream(m_source, this);
//Q_ASSERT(qobject_cast<Stream *>(m_source.stream()->d_ptr->streamInterface));
break;
}
emit totalTimeChanged(totalTime());
QMultiMap<QString, QString> metaData;
metaData.insert("TITLE", "Fake video");
metaData.insert("ARTIST", "Matthias Kretz");
emit metaDataChanged(metaData);
QTimer::singleShot(50, this, SLOT(loadingComplete()));
}
void MediaObject::loadingComplete()
{
if (state() == Phonon::LoadingState) {
setState(Phonon::StoppedState);
} else if (state() == Phonon::BufferingState) {
setState(Phonon::PlayingState);
}
}
void MediaObject::setPrefinishMark(qint32 newPrefinishMark)
{
//kDebug(604) ;
m_prefinishMark = newPrefinishMark;
if (currentTime() < totalTime() - m_prefinishMark) // not about to finish
m_prefinishMarkReachedNotEmitted = true;
}
void MediaObject::pause()
{
//kDebug(604) ;
switch (state()) {
case PlayingState:
case BufferingState:
case StoppedState:
m_tickTimer->stop();
setState(Phonon::PausedState);
break;
case PausedState:
case LoadingState:
case ErrorState:
break;
}
}
void MediaObject::stop()
{
//kDebug(604) ;
if (state() == Phonon::PlayingState || state() == Phonon::BufferingState || state() == Phonon::PausedState) {
m_tickTimer->stop();
setState(Phonon::StoppedState);
m_position = 0.0f;
m_frequency = 440.0f;
m_prefinishMarkReachedNotEmitted = true;
}
}
void MediaObject::seek(qint64 time)
{
//kDebug(604) ;
if (isSeekable())
{
switch(state())
{
case Phonon::PausedState:
case Phonon::BufferingState:
m_startTime = m_pauseTime;
break;
case Phonon::PlayingState:
m_startTime.start();
break;
case Phonon::StoppedState:
case Phonon::ErrorState:
case Phonon::LoadingState:
return; // cannot seek
}
m_startTime = m_startTime.addMSecs(-time);
}
if (currentTime() < totalTime() - m_prefinishMark) // not about to finish
m_prefinishMarkReachedNotEmitted = true;
}
void MediaObject::emitTick()
{
//kDebug(604) << "emit tick(" << currentTime() << ")";
int tickInterval = 50;
if (m_tickInterval > 0)
{
emit tick(currentTime());
tickInterval = m_tickInterval;
}
/* if (m_waiting == 0) {
QVector<float> buffer(m_bufferSize);
Experimental::VideoFrame frame;
frame.width = 320;
frame.height = 240;
frame.colorspace = Experimental::VideoFrame::Format_RGBA8;
frame.data.resize(frame.width * frame.height * 4);
const int availableSamples = tickInterval * SAMPLE_RATE / 1000 + m_lastSamplesMissing;
const int bufferCount = availableSamples / m_bufferSize;
m_lastSamplesMissing = availableSamples - bufferCount * m_bufferSize;
for (int i = 0; i < bufferCount; ++i)
{
fillBuffer(&buffer);
foreach (AudioNode *an, m_audioNodes) {
an->processBuffer(buffer);
}
fillFrameData(&frame);
foreach (VideoNode *vn, m_videoNodes) {
vn->processFrame(frame);
}
}
}
*/
if (currentTime() >= totalTime() - m_prefinishMark) { // about to finish
if (m_prefinishMarkReachedNotEmitted) {
m_prefinishMarkReachedNotEmitted = false;
emit prefinishMarkReached(totalTime() - currentTime());
}
}
if (currentTime() >= totalTime()) // finished
{
emit aboutToFinish();
if (m_nextSource.type() == MediaSource::Invalid) {
stop();
emit finished();
} else {
m_prefinishMarkReachedNotEmitted = true;
m_source = m_nextSource;
m_nextSource = MediaSource();
switch (m_source.type()) {
case MediaSource::Invalid:
abort();
case MediaSource::Disc:
Q_ASSERT(m_source.discType() != NoDisc);
break;
case MediaSource::Url:
Q_ASSERT(m_source.url().isValid());
break;
case MediaSource::LocalFile:
Q_ASSERT(!m_source.fileName().isEmpty());
break;
case MediaSource::Stream:
break;
}
emit totalTimeChanged(totalTime());
QMultiMap<QString, QString> metaData;
metaData.insert("TITLE", "Fake video");
metaData.insert("ARTIST", "Matthias Kretz");
emit metaDataChanged(metaData);
}
}
}
bool MediaObject::wait()
{
++m_waiting;
return true;
}
bool MediaObject::done()
{
--m_waiting;
return true;
}
void MediaObject::addAudioNode(AudioNode *node)
{
m_audioNodes << node;
node->setHasInput(true);
}
void MediaObject::addVideoNode(VideoNode *node)
{
m_videoNodes << node;
node->setHasInput(true);
}
bool MediaObject::removeAudioNode(AudioNode *node)
{
node->setHasInput(false);
return 1 == m_audioNodes.removeAll(node);
}
bool MediaObject::removeVideoNode(VideoNode *node)
{
node->setHasInput(false);
return 1 == m_videoNodes.removeAll(node);
}
}}
#include "moc_mediaobject.cpp"
// vim: sw=4 ts=4
|
/* This file is part of the KDE project
Copyright (C) 2006-2007 Matthias Kretz <[email protected]>
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) version 3, or any
later version accepted by the membership of KDE e.V. (or its
successor approved by the membership of KDE e.V.), Nokia Corporation
(or its successors, if any) and the KDE Free Qt Foundation, which shall
act as a proxy defined in Section 6 of version 3 of the license.
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, see <http://www.gnu.org/licenses/>.
*/
#include "mediaobject.h"
#include <QtCore/QTimer>
#include "stream.h"
#include "../../abstractmediastream_p.h"
#include <QtCore/QVector>
#include <cmath>
#include <QtCore/QFile>
#include <QtCore/QByteRef>
#include <QtCore/QStringList>
#include "audionode.h"
#include "videonode.h"
namespace Phonon
{
namespace Fake
{
static const int SAMPLE_RATE = 44100;
static const float SAMPLE_RATE_FLOAT = 44100.0f;
static const int FRAME_RATE = 25;
static const int SAMPLES_PER_FRAME = SAMPLE_RATE / FRAME_RATE;
MediaObject::MediaObject(QObject *parent)
: QObject(parent)
, m_state(Phonon::LoadingState)
, m_tickTimer(new QTimer(this))
, m_bufferSize(SAMPLES_PER_FRAME)//512)
, m_lastSamplesMissing(0)
, m_position(0.0f)
, m_frequency(440.0f)
, m_prefinishMarkReachedNotEmitted(true), m_waiting(0)
{
//kDebug(604) ;
connect(m_tickTimer, SIGNAL(timeout()), SLOT(emitTick()));
}
MediaObject::~MediaObject()
{
//kDebug(604) ;
}
State MediaObject::state() const
{
//kDebug(604) ;
return m_state;
}
bool MediaObject::hasVideo() const
{
//kDebug(604) ;
return false;
}
bool MediaObject::isSeekable() const
{
//kDebug(604) ;
return true;
}
qint64 MediaObject::currentTime() const
{
//kDebug(604) ;
switch(state())
{
case Phonon::PausedState:
case Phonon::BufferingState:
return m_startTime.msecsTo(m_pauseTime);
case Phonon::PlayingState:
return m_startTime.elapsed();
case Phonon::StoppedState:
case Phonon::LoadingState:
return 0;
case Phonon::ErrorState:
break;
}
return -1;
}
qint32 MediaObject::tickInterval() const
{
//kDebug(604) ;
return m_tickInterval;
}
void MediaObject::setTickInterval(qint32 newTickInterval)
{
//kDebug(604) ;
m_tickInterval = newTickInterval;
if (m_tickInterval <= 0)
m_tickTimer->setInterval(50);
else
m_tickTimer->setInterval(newTickInterval);
}
void MediaObject::play()
{
//kDebug(604) ;
if (m_state == Phonon::LoadingState) {
setState(Phonon::BufferingState);
} else {
setState(Phonon::PlayingState);
}
}
QString MediaObject::errorString() const
{
return QString();
}
Phonon::ErrorType MediaObject::errorType() const
{
return Phonon::NoError;
}
void MediaObject::setState(State newstate)
{
if (newstate == m_state)
return;
State oldstate = m_state;
m_state = newstate;
switch(newstate)
{
case Phonon::PausedState:
case Phonon::BufferingState:
m_pauseTime.start();
break;
case Phonon::PlayingState:
m_tickTimer->start();
if (oldstate == Phonon::PausedState || oldstate == Phonon::BufferingState)
m_startTime = m_startTime.addMSecs(m_pauseTime.elapsed());
else
m_startTime.start();
break;
case Phonon::StoppedState:
case Phonon::ErrorState:
case Phonon::LoadingState:
m_startTime = QTime();
break;
}
//kDebug(604) << "emit stateChanged(" << newstate << ", " << oldstate << ")";
emit stateChanged(newstate, oldstate);
}
static const float TWOPI = 6.28318530718f;
static const float maxFrequency = 1760.0f;
static const float minFrequency = 440.0f;
static const float frequencyToDelta = TWOPI / SAMPLE_RATE_FLOAT;
void MediaObject::fillBuffer(QVector<float> *buffer)
{
//static QFile createdump("createdump");
//if (!createdump.isOpen())
//createdump.open(QIODevice::WriteOnly);
m_frequency *= 1.059463094359f;
if (m_frequency > maxFrequency)
m_frequency = minFrequency;
float delta = frequencyToDelta * m_frequency;
float *data = buffer->data();
const float * const end = data + m_bufferSize;
while (data != end)
{
const float sample = std::sin(m_position);
//createdump.write(QByteArray::number(sample) + "\n");
*(data++) = sample;
m_position += delta;
if (m_position > TWOPI)
m_position -= TWOPI;
}
}
void MediaObject::fillFrameData(Phonon::Experimental::VideoFrame *frame)
{
Q_UNUSED(frame);
//X static quint32 frameCount = 0;
//X quint8 *dataPtr = reinterpret_cast<quint8 *>(frame->data.data());
//X for (int y = 0; y < frame->height; ++y)
//X for (int x = 0; x < frame->width; ++x)
//X {
//X *dataPtr++ = static_cast<quint8>(0xff);
//X *dataPtr++ = static_cast<quint8>((x + frameCount) * 2 / 3); //red
//X *dataPtr++ = static_cast<quint8>(y + frameCount); //green
//X *dataPtr++ = static_cast<quint8>(frameCount / 2); //blue
//X }
//X ++frameCount;
}
qint64 MediaObject::totalTime() const
{
//kDebug(604) ;
return 1000 *60 *3; // 3 minutes
}
qint32 MediaObject::prefinishMark() const
{
//kDebug(604) ;
return m_prefinishMark;
}
qint32 MediaObject::transitionTime() const
{
return m_transitionTime;
}
void MediaObject::setTransitionTime(qint32 time)
{
m_transitionTime = time;
}
qint64 MediaObject::remainingTime() const
{
return totalTime() - currentTime();
}
MediaSource MediaObject::source() const
{
return m_source;
}
void MediaObject::setNextSource(const MediaSource &source)
{
m_nextSource = source;
}
void MediaObject::setSource(const MediaSource &source)
{
//kDebug(604) ;
m_prefinishMarkReachedNotEmitted = true;
m_source = source;
setState(Phonon::LoadingState);
switch (m_source.type()) {
case MediaSource::Invalid:
case MediaSource::Empty:
return;
case MediaSource::Disc:
Q_ASSERT(m_source.discType() != NoDisc);
break;
case MediaSource::Url:
Q_ASSERT(m_source.url().isValid());
break;
case MediaSource::LocalFile:
Q_ASSERT(!m_source.fileName().isEmpty());
break;
case MediaSource::Stream:
//Stream *s = new Stream(m_source, this);
//Q_ASSERT(qobject_cast<Stream *>(m_source.stream()->d_ptr->streamInterface));
break;
}
emit totalTimeChanged(totalTime());
QMultiMap<QString, QString> metaData;
metaData.insert("TITLE", "Fake video");
metaData.insert("ARTIST", "Matthias Kretz");
emit metaDataChanged(metaData);
QTimer::singleShot(50, this, SLOT(loadingComplete()));
}
void MediaObject::loadingComplete()
{
if (state() == Phonon::LoadingState) {
setState(Phonon::StoppedState);
} else if (state() == Phonon::BufferingState) {
setState(Phonon::PlayingState);
}
}
void MediaObject::setPrefinishMark(qint32 newPrefinishMark)
{
//kDebug(604) ;
m_prefinishMark = newPrefinishMark;
if (currentTime() < totalTime() - m_prefinishMark) // not about to finish
m_prefinishMarkReachedNotEmitted = true;
}
void MediaObject::pause()
{
//kDebug(604) ;
switch (state()) {
case PlayingState:
case BufferingState:
case StoppedState:
m_tickTimer->stop();
setState(Phonon::PausedState);
break;
case PausedState:
case LoadingState:
case ErrorState:
break;
}
}
void MediaObject::stop()
{
//kDebug(604) ;
if (state() == Phonon::PlayingState || state() == Phonon::BufferingState || state() == Phonon::PausedState) {
m_tickTimer->stop();
setState(Phonon::StoppedState);
m_position = 0.0f;
m_frequency = 440.0f;
m_prefinishMarkReachedNotEmitted = true;
}
}
void MediaObject::seek(qint64 time)
{
//kDebug(604) ;
if (isSeekable())
{
switch(state())
{
case Phonon::PausedState:
case Phonon::BufferingState:
m_startTime = m_pauseTime;
break;
case Phonon::PlayingState:
m_startTime.start();
break;
case Phonon::StoppedState:
case Phonon::ErrorState:
case Phonon::LoadingState:
return; // cannot seek
}
m_startTime = m_startTime.addMSecs(-time);
}
if (currentTime() < totalTime() - m_prefinishMark) // not about to finish
m_prefinishMarkReachedNotEmitted = true;
}
void MediaObject::emitTick()
{
//kDebug(604) << "emit tick(" << currentTime() << ")";
int tickInterval = 50;
if (m_tickInterval > 0)
{
emit tick(currentTime());
tickInterval = m_tickInterval;
}
/* if (m_waiting == 0) {
QVector<float> buffer(m_bufferSize);
Experimental::VideoFrame frame;
frame.width = 320;
frame.height = 240;
frame.colorspace = Experimental::VideoFrame::Format_RGBA8;
frame.data.resize(frame.width * frame.height * 4);
const int availableSamples = tickInterval * SAMPLE_RATE / 1000 + m_lastSamplesMissing;
const int bufferCount = availableSamples / m_bufferSize;
m_lastSamplesMissing = availableSamples - bufferCount * m_bufferSize;
for (int i = 0; i < bufferCount; ++i)
{
fillBuffer(&buffer);
foreach (AudioNode *an, m_audioNodes) {
an->processBuffer(buffer);
}
fillFrameData(&frame);
foreach (VideoNode *vn, m_videoNodes) {
vn->processFrame(frame);
}
}
}
*/
if (currentTime() >= totalTime() - m_prefinishMark) { // about to finish
if (m_prefinishMarkReachedNotEmitted) {
m_prefinishMarkReachedNotEmitted = false;
emit prefinishMarkReached(totalTime() - currentTime());
}
}
if (currentTime() >= totalTime()) // finished
{
emit aboutToFinish();
if (m_nextSource.type() == MediaSource::Empty || m_nextSource.type() == MediaSource::Invalid) {
stop();
emit finished();
} else {
m_prefinishMarkReachedNotEmitted = true;
m_source = m_nextSource;
m_nextSource = MediaSource();
switch (m_source.type()) {
case MediaSource::Empty:
case MediaSource::Invalid:
abort();
case MediaSource::Disc:
Q_ASSERT(m_source.discType() != NoDisc);
break;
case MediaSource::Url:
Q_ASSERT(m_source.url().isValid());
break;
case MediaSource::LocalFile:
Q_ASSERT(!m_source.fileName().isEmpty());
break;
case MediaSource::Stream:
break;
}
emit totalTimeChanged(totalTime());
QMultiMap<QString, QString> metaData;
metaData.insert("TITLE", "Fake video");
metaData.insert("ARTIST", "Matthias Kretz");
emit metaDataChanged(metaData);
}
}
}
bool MediaObject::wait()
{
++m_waiting;
return true;
}
bool MediaObject::done()
{
--m_waiting;
return true;
}
void MediaObject::addAudioNode(AudioNode *node)
{
m_audioNodes << node;
node->setHasInput(true);
}
void MediaObject::addVideoNode(VideoNode *node)
{
m_videoNodes << node;
node->setHasInput(true);
}
bool MediaObject::removeAudioNode(AudioNode *node)
{
node->setHasInput(false);
return 1 == m_audioNodes.removeAll(node);
}
bool MediaObject::removeVideoNode(VideoNode *node)
{
node->setHasInput(false);
return 1 == m_videoNodes.removeAll(node);
}
}}
#include "moc_mediaobject.cpp"
// vim: sw=4 ts=4
|
handle MediaSource::Empty like Invalid
|
handle MediaSource::Empty like Invalid
|
C++
|
lgpl-2.1
|
KDE/phonon-quicktime,KDE/phonon-mmf,KDE/phonon-gstreamer,KDE/phonon-xine,KDE/phonon-xine,KDE/phonon-xine,KDE/phonon-directshow,KDE/phonon-gstreamer,shadeslayer/phonon-gstreamer,KDE/phonon-waveout,KDE/phonon-directshow,shadeslayer/phonon-gstreamer,shadeslayer/phonon-gstreamer
|
d1f03be7a542b15b1b7c085d86b7b63e9f2fd9e0
|
hmLib/algorithm/sampling.hpp
|
hmLib/algorithm/sampling.hpp
|
#ifndef HMLIB_ALGORITHM_SAMPLING_INC
#define HMLIB_ALGORITHM_SAMPLING_INC 104
#
/*
===algorithm::sampling===
ある範囲の中から値を選択するアルゴリズムを提供する
algorithm::sampling:v1_04/140731 hmIto
可能なsamplerに、add/clear関数を追加
手動で一個ずつデータを追加 / すべてクリアする関数
algorithm::sampling:v1_03/140708 hmIto
shuffle_samplerを追加
イテレータでレンジを受け取り、シャッフルして順に返す
枯渇すると、endを返す
algorithm::sampling:v1_02/130917 hmIto
例外処理のヘッダが不足していた問題を修正
algorithm::sampling:v1_01/130711 hmIto
random_sampler追加
イテレータでレンジを受け取り、その中からoperator()でランダムに返す
algorithm::sampling:v1_00/130328 hmIto
algorithmから分離
*/
#include<algorithm>
#include<vector>
#ifndef HMLIB_RANDOM_INC
# include<hmLib/random.hpp>
#endif
#ifndef HMLIB_EXCEPTIONS_INC
# include<hmLib/exceptions.hpp>
#endif
namespace hmLib{
namespace algorithm{
//ランダム選択
template<class InputIterator,class OutputIterator>
OutputIterator random_sample(InputIterator Begin,InputIterator End,OutputIterator Out){
unsigned int Size=0;
InputIterator Itr;
for(Itr=Begin;Itr!=End;++Itr)++Size;
unsigned int Pos=hmLib::random::uniform_int(0,Size-1);
Itr=Begin;
for(unsigned int Cnt=0;Cnt<Pos;++Cnt)++Itr;
*Out=*Itr;
++Out;
return Out;
}
//ランダム選択 OutputIteratorの範囲を埋めるまで
template<class InputIterator,class OutputIterator>
OutputIterator random_sample(InputIterator Begin,InputIterator End,OutputIterator OutBegin,OutputIterator OutEnd){
unsigned int Size=0;
InputIterator Itr;
for(Itr=Begin;Itr!=End;++Itr)++Size;
for(;OutBegin!=OutEnd;++OutBegin){
unsigned int Pos=hmLib::random::uniform_int(0,Size-1);
Itr=Begin;
for(unsigned int Cnt=0;Cnt<Pos;++Cnt)++Itr;
*OutBegin=*Itr;
}
return OutBegin;
}
//ランダム選択 n個分
template<class InputIterator,class OutputIterator>
OutputIterator random_sample(InputIterator Begin,InputIterator End,OutputIterator Out,unsigned int n){
unsigned int Size=0;
InputIterator Itr;
for(Itr=Begin;Itr!=End;++Itr)++Size;
for(unsigned int m=0;m!=n;++m){
unsigned int Pos=hmLib::random::uniform_int(0,Size-1);
Itr=Begin;
for(unsigned int Cnt=0;Cnt<Pos;++Cnt)++Itr;
*Out=*Itr;
++Out;
}
return Out;
}
//ランダム選択クラス
template<typename InputIterator>
class random_sampler{
private:
InputIterator Begin;
InputIterator End;
public:
random_sampler(){}
random_sampler(InputIterator Begin_,InputIterator End_){sync(Begin_,End_);}
public:
InputIterator operator()(){
return Begin+hmLib::random::uniform_int(0,End-Begin-1);
}
void sync(InputIterator Begin_,InputIterator End_){
Begin=Begin_;
End=End_;
}
};
//ランダム選択クラスのビルダー
template<typename InputIterator>
random_sampler<InputIterator> make_random_sampler(InputIterator Begin_,InputIterator End_){
return random_sampler<InputIterator>(Begin_,End_);
}
//ルーレット選択
template<class InputIterator,class FnRealValue,class OutputIterator>
OutputIterator roulette_sample(InputIterator Begin,InputIterator End,FnRealValue Value,OutputIterator Out){
double TotalFitness=0.;
InputIterator Itr;
for(Itr=Begin;Itr!=End;++Itr){
TotalFitness+=Value(*Itr);
}
double SelectFitnes=hmLib::random::uniform_real(0.,TotalFitness);
for(Itr=Begin;Itr!=End;++Itr){
SelectFitness-=Value(*Itr);
if(SelectFitness<=0.)break;
}
*Out=*Itr;
++Out;
return Out;
}
//ルーレット選択 OutputIteratorの範囲を埋めるまで
template<class InputIterator,class FnRealValue,class OutputIterator>
OutputIterator roulette_sample(InputIterator Begin,InputIterator End,FnRealValue Value,OutputIterator OutBegin,OutputIterator OutEnd){
double TotalFitness=0.;
InputIterator Itr;
for(Itr=Begin;Itr!=End;++Itr){
TotalFitness+=Value(*Itr);
}
for(;OutBegin!=OutEnd;++OutBegin){
double SelectFitnes=hmLib::random::uniform_real(0.,TotalFitness);
for(Itr=Begin;Itr!=End;++Itr){
SelectFitness-=Value(*Itr);
if(SelectFitness<=0.)break;
}
*OutBegin=*Itr;
++OutBegin;
}
return OutBegin;
}
//ルーレット選択 n個分
template<class InputIterator,class FnRealValue,class OutputIterator>
OutputIterator roulette_sample(InputIterator Begin,InputIterator End,FnRealValue Value,OutputIterator Out,unsigned int n){
double TotalFitness=0.;
InputIterator Itr;
for(Itr=Begin;Itr!=End;++Itr){
TotalFitness+=Value(*Itr);
}
for(unsigned int m=0;m!=n;++m){
double SelectFitnes=hmLib::random::uniform_real(0.,TotalFitness);
for(Itr=Begin;Itr!=End;++Itr){
SelectFitness-=Value(*Itr);
if(SelectFitness<=0.)break;
}
*Out=*Itr;
++Out;
}
return Out;
}
//ルーレット選択クラス
template<typename InputIterator>
class roulette_sampler{
struct assess_itr{
InputIterator Itr;
double Val;
public:
assess_itr(double Val_):Val(Val_){}
assess_itr(InputIterator Itr_,double Val_):Itr(Itr_),Val(Val_){}
bool operator<(const assess_itr& My_)const{return Val<My_.Val;}
};
private:
std::vector<assess_itr> AssessVec;
public:
roulette_sampler(){}
template<typename fnAssess>
roulette_sampler(InputIterator Begin_,InputIterator End_,fnAssess FnAssess_){sync(Begin_,End_,FnAssess_);}
public:
InputIterator operator()(){
return std::lower_bound(
AssessVec.begin()
,AssessVec.end()
,assess_itr(hmLib::random::uniform_real(0.,assess())))->Itr;
}
double assess()const{
if(AssessVec.size()==0)return 0.0;
return AssessVec.back().Val;
}
template<typename fnAssess>
void sync(InputIterator Begin_,InputIterator End_,fnAssess FnAssess_){
double Val=0.;
AssessVec.clear();
while(Begin_!=End_){
Val+=FnAssess_(*Begin_);
AssessVec.push_back(assess_itr(Begin_++,Val));
}
}
unsigned int size()const{return AssessVec.size();}
void clear(){AssessVec.clear();}
void add(InputIterator Itr_,double Assess_){
AssessVec.push_back(assess_itr(Itr_,Assess_+assess()));
}
};
//ルーレット選択クラスのビルダー
template<typename InputIterator,typename fnAssess>
roulette_sampler<InputIterator> make_roulette_sampler(InputIterator Begin_,InputIterator End_,fnAssess FnAssess_){
return roulette_sampler<InputIterator>(Begin_,End_,FnAssess_);
}
//シャッフル選択クラス
template<typename InputIterator>
class shuffle_sampler {
typedef typename std::vector<InputIterator>::iterator iterator;
private:
std::vector<InputIterator> Vec;
iterator Now;
InputIterator End;
public:
shuffle_sampler() {}
shuffle_sampler(InputIterator Begin_, InputIterator End_) { sync(Begin_, End_); }
public:
InputIterator operator()() {
if(Now==Vec.end())return End;
return *(Now++);
}
InputIterator sample(bool IsAutoShuffle_=true) {
if(Now==Vec.end()){
if(!IsAutoShuffle_ || Vec.empty())return End;
shuffle();
}
return *(Now++);
}
operator bool()const { return Vec.size()>0 && Now!=Vec.end(); }
void shuffle() {
std::shuffle(Vec.begin(), Vec.end(), hmLib::random::Engine);
Now=Vec.begin();
}
void sync(InputIterator Begin_, InputIterator End_) {
End=End_;
Vec.clear();
for(; Begin_!=End_; ++Begin_) {
Vec.push_back(Begin_);
}
shuffle();
}
unsigned int size()const{return Vec.size();}
void clear(){Vec.clear();}
void add(InputIterator Itr_,bool SuppressShuffle_=false){
Vec.push_back(Itr_);
if(!SuppressShuffle_)shuffle();
}
};
//シャッフル選択クラスのビルダー
template<typename InputIterator>
shuffle_sampler<InputIterator> make_shuffle_sampler(InputIterator Begin_, InputIterator End_) {
return shuffle_sampler<InputIterator>(Begin_, End_);
}
}
}
#
#endif
|
#ifndef HMLIB_ALGORITHM_SAMPLING_INC
#define HMLIB_ALGORITHM_SAMPLING_INC 105
#
/*
===algorithm::sampling===
ある範囲の中から値を選択するアルゴリズムを提供する
algorithm::sampling:v2_00/160426 hmIto
build系関数をmakeに変更
distance/next等のiteratorへの特殊されている関数を利用するよう変更
hmLib::randomへの依存性を削除
algorithm::sampling:v1_04/140731 hmIto
可能なsamplerに、add/clear関数を追加
手動で一個ずつデータを追加 / すべてクリアする関数
algorithm::sampling:v1_03/140708 hmIto
shuffle_samplerを追加
イテレータでレンジを受け取り、シャッフルして順に返す
枯渇すると、endを返す
algorithm::sampling:v1_02/130917 hmIto
例外処理のヘッダが不足していた問題を修正
algorithm::sampling:v1_01/130711 hmIto
random_sampler追加
イテレータでレンジを受け取り、その中からoperator()でランダムに返す
algorithm::sampling:v1_00/130328 hmIto
algorithmから分離
*/
#include<algorithm>
#include<numeric>
#include<vector>
#include<random>
namespace hmLib{
namespace algorithm{
//ランダム選択
template<typename InputIterator, typename RandEngine>
InputIterator random_sample(InputIterator Begin,InputIterator End, RandEngine&& Engine){
if(Begin == End)return End;
return std::next(Begin, std::uniform_int<int>(0,std::distance(Begin,End)-1)(Engine));
}
//ランダム選択 OutputIteratorの範囲を埋めるまで
template<typename InputIterator, typename OutputIterator, typename RandEngine>
void random_sample(InputIterator Begin,InputIterator End,OutputIterator OutBegin,OutputIterator OutEnd, RandEngine&& Engine){
if(Begin == End)return End;
std::uniform_int<int> Dist(0, std::distance(Begin, End) - 1);
while(OutBegin!=OutEnd){
*OutBegin++ = *std::next(Begin, Dist(Engine));
}
}
//ランダム選択 n個分
template<typename InputIterator, typename OutputIterator, typename RandEngine>
OutputIterator random_sample(InputIterator Begin,InputIterator End, OutputIterator Out, unsigned int n, RandEngine&& Engine){
if(Begin == End)return End;
std::uniform_int<int> Dist(0, std::distance(Begin, End) - 1);
for(unsigned int i = 0; i < n; ++i){
*Out++ = *std::next(Begin, Dist(Engine));
}
return Out;
}
//ランダム選択クラス
template<typename InputIterator>
class random_sampler{
using dist_type = std::uniform_int_distribution<int>;
private:
InputIterator Begin;
dist_type Dist;
public:
random_sampler(){}
random_sampler(InputIterator Begin_,InputIterator End_){sync(Begin_,End_);}
public:
template<typename RandEngine>
InputIterator operator()(RandEngine Engine){
return std::next(Begin, Dist(Engine));
}
void sync(InputIterator Begin_,InputIterator End_){
Begin=Begin_;
dist_type::param_type prm(0, std::distance(Begin_, End_));
Dist.param(prm);
}
};
//ランダム選択クラスのビルダー
template<typename InputIterator>
random_sampler<InputIterator> make_random_sampler(InputIterator Begin_,InputIterator End_){
return random_sampler<InputIterator>(Begin_,End_);
}
//ルーレット選択
template<typename InputIterator, typename fnAssess, typename RandEngine>
InputIterator roulette_sample(InputIterator Begin,InputIterator End, fnAssess&& FnAssess, RandEngine&& Engine){
if(Begin == End)return End;
double TotalFitness = 0;
std::for_each(Begin, End, [&](decltype(*Begin)& Val){TotalFitness += FnAssess(Val); });
double SelectFitness =std::uniform_real_distribution<double>(0.,TotalFitness)(Engine);
for(;Begin!=End; ++Begin){
SelectFitness-= FnAssess(*Begin);
if(SelectFitness <= 0.)break;
}
return Begin;
}
//ルーレット選択 OutputIteratorの範囲を埋めるまで
template<typename InputIterator, typename OutputIterator, typename fnAssess, typename RandEngine>
void roulette_sample(InputIterator Begin,InputIterator End, fnAssess&& FnAssess,OutputIterator OutBegin,OutputIterator OutEnd, RandEngine&& Engine){
if(Begin == End)return End;
double TotalFitness = 0;
std::for_each(Begin, End, [&](decltype(*Begin)& Val){TotalFitness += FnAssess(Val); });
std::uniform_real_distribution<double> Dist(0., TotalFitness);
while(OutBegin != OutEnd){
double SelectFitness = Dist(Engine);
for(auto Itr = Begin; Itr != End; ++Itr){
SelectFitness -= FnAssess(*Itr);
if(SelectFitness <= 0.)break;
}
*OutBegin++ = *Itr;
}
}
//ルーレット選択 n個分
template<typename InputIterator, typename OutputIterator, typename fnAssess, typename RandEngine>
OutputIterator roulette_sample(InputIterator Begin,InputIterator End, fnAssess&& FnAssess, OutputIterator Out, unsigned int n, RandEngine&& Engine){
if(Begin == End)return End;
double TotalFitness = 0;
std::for_each(Begin, End, [&](decltype(*Begin)& Val){TotalFitness += FnAssess(Val); });
std::uniform_real_distribution<double> Dist(0., TotalFitness);
for(unsigned int i = 0; i < n; ++i){
double SelectFitness = Dist(Engine);
for(auto Itr = Begin; Itr != End; ++Itr){
SelectFitness -= FnAssess(*Itr);
if(SelectFitness <= 0.)break;
}
*Out++ = *Itr;
}
return Out;
}
//ルーレット選択クラス
template<typename InputIterator>
class roulette_sampler{
struct assess_itr{
InputIterator Itr;
double Val;
public:
assess_itr(double Val_):Val(Val_){}
assess_itr(InputIterator Itr_,double Val_):Itr(Itr_),Val(Val_){}
bool operator<(const assess_itr& My_)const{return Val<My_.Val;}
};
private:
std::vector<assess_itr> AssessVec;
public:
roulette_sampler(){}
template<typename fnAssess>
roulette_sampler(InputIterator Begin_,InputIterator End_,fnAssess&& FnAssess_){sync(Begin_,End_, std::forward(FnAssess_));}
public:
template<typename RandEngine>
InputIterator operator()(RandEngine Engine){
return std::lower_bound(
AssessVec.begin()
,AssessVec.end()
,assess_itr(InputIterator(), std::uniform_real_distribution<double>(0.,assess())(Engine))
)->Itr;
}
double assess()const{
if(AssessVec.size()==0)return 0.0;
return AssessVec.back().Val;
}
template<typename fnAssess>
void sync(InputIterator Begin_,InputIterator End_,fnAssess&& FnAssess_){
double Val=0.;
AssessVec.clear();
while(Begin_!=End_){
Val+=FnAssess_(*Begin_);
AssessVec.push_back(assess_itr(Begin_++,Val));
}
}
unsigned int size()const{return AssessVec.size();}
void clear(){AssessVec.clear();}
void add(InputIterator Itr_,double Assess_){
AssessVec.push_back(assess_itr(Itr_,Assess_+assess()));
}
};
//ルーレット選択クラスのビルダー
template<typename InputIterator,typename fnAssess>
roulette_sampler<InputIterator> make_roulette_sampler(InputIterator Begin_,InputIterator End_,fnAssess&& FnAssess_){
return roulette_sampler<InputIterator>(Begin_,End_,std::forward(FnAssess_));
}
//シャッフル選択クラス
template<typename InputIterator>
class shuffle_sampler {
typedef typename std::vector<InputIterator>::iterator iterator;
private:
std::vector<InputIterator> Vec;
iterator Now;
InputIterator End;
public:
shuffle_sampler() {}
shuffle_sampler(InputIterator Begin_, InputIterator End_) { sync(Begin_, End_); }
public:
InputIterator operator()() {
if(Now==Vec.end())return End;
return *(Now++);
}
InputIterator sample(bool IsAutoShuffle_=true) {
if(Now==Vec.end()){
if(!IsAutoShuffle_ || Vec.empty())return End;
shuffle();
}
return *(Now++);
}
operator bool()const { return Vec.size()>0 && Now!=Vec.end(); }
template<typename RandEngine>
void shuffle(RandEngine&& Engine) {
std::shuffle(Vec.begin(), Vec.end(), Engine);
Now=Vec.begin();
}
void sync(InputIterator Begin_, InputIterator End_) {
End=End_;
Vec.clear();
for(; Begin_!=End_; ++Begin_) {
Vec.push_back(Begin_);
}
shuffle();
}
unsigned int size()const{return Vec.size();}
void clear(){Vec.clear();}
void add(InputIterator Itr_){Vec.push_back(Itr_);}
};
//シャッフル選択クラスのビルダー
template<typename InputIterator>
shuffle_sampler<InputIterator> make_shuffle_sampler(InputIterator Begin_, InputIterator End_) {
return shuffle_sampler<InputIterator>(Begin_, End_);
}
}
}
#
#endif
|
Modify for C++11 stype alogirthm. Using iterator functions, independece from the random engine.
|
Modify for C++11 stype alogirthm. Using iterator functions, independece from the random engine.
|
C++
|
mit
|
hmito/hmLib,hmito/hmLib
|
9f7126d2ed8d47ead3bed97045972cf172e89fba
|
tests/unittests/CoreGraphics.drawing/CGContextDrawing_FillModeTests.cpp
|
tests/unittests/CoreGraphics.drawing/CGContextDrawing_FillModeTests.cpp
|
//******************************************************************************
//
// Copyright (c) Microsoft. All rights reserved.
//
// This code is licensed under the MIT License (MIT).
//
// 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 "DrawingTest.h"
CGPathDrawingMode fillModes[] = { kCGPathFill, kCGPathFillStroke, kCGPathEOFill, kCGPathEOFillStroke };
class CGContextFillMode : public WhiteBackgroundTest<>, public ::testing::WithParamInterface<CGPathDrawingMode> {
CFStringRef CreateOutputFilename() {
CGPathDrawingMode fillMode = GetParam();
char* fillModeName;
switch (fillMode) {
case kCGPathFill:
fillModeName = "Fill";
break;
case kCGPathFillStroke:
fillModeName = "FillStroke";
break;
case kCGPathEOFill:
fillModeName = "EOFill";
break;
case kCGPathEOFillStroke:
fillModeName = "EOFillStroke";
break;
default:
break;
}
return CFStringCreateWithFormat(nullptr, nullptr, CFSTR("TestImage.CGContext.FillMode.%s.png"), fillModeName);
}
};
DRAW_TEST_P(CGContextFillMode, OverlappedEllipses) {
CGContextRef context = GetDrawingContext();
CGRect bounds = GetDrawingBounds();
bounds = CGRectInset(bounds, 16.f, 16.f);
CGFloat width = bounds.size.width;
CGFloat height = bounds.size.height;
CGFloat xstart = bounds.origin.x;
CGFloat ystart = bounds.origin.y;
CGPathDrawingMode fillMode = GetParam();
CGMutablePathRef leftCircles = CGPathCreateMutable();
CGPathMoveToPoint(leftCircles, NULL, xstart + .25 * width + .4 * height, ystart + .5 * height);
CGPathAddArc(leftCircles, NULL, xstart + .25 * width, ystart + .5 * height, .4 * height, 0, M_PI, true);
CGPathAddArc(leftCircles, NULL, xstart + .25 * width, ystart + .5 * height, .4 * height, M_PI, 0, true);
CGPathMoveToPoint(leftCircles, NULL, xstart + .25 * width + .3 * height, ystart + .5 * height);
CGPathAddArc(leftCircles, NULL, xstart + .25 * width, ystart + .5 * height, .3 * height, 0, M_PI, true);
CGPathAddArc(leftCircles, NULL, xstart + .25 * width, ystart + .5 * height, .3 * height, M_PI, 0, true);
CGPathMoveToPoint(leftCircles, NULL, xstart + .25 * width + .2 * height, ystart + .5 * height);
CGPathAddArc(leftCircles, NULL, xstart + .25 * width, ystart + .5 * height, .2 * height, 0, M_PI, true);
CGPathAddArc(leftCircles, NULL, xstart + .25 * width, ystart + .5 * height, .2 * height, M_PI, 0, true);
CGPathMoveToPoint(leftCircles, NULL, xstart + .25 * width + .1 * height, ystart + .5 * height);
CGPathAddArc(leftCircles, NULL, xstart + .25 * width, ystart + .5 * height, .1 * height, 0, M_PI, true);
CGPathAddArc(leftCircles, NULL, xstart + .25 * width, ystart + .5 * height, .1 * height, M_PI, 0, true);
CGPathCloseSubpath(leftCircles);
CGMutablePathRef rightCircles = CGPathCreateMutable();
CGPathMoveToPoint(rightCircles, NULL, xstart + .75 * width + .4 * height, ystart + .5 * height);
CGPathAddArc(rightCircles, NULL, xstart + .75 * width, ystart + .5 * height, .4 * height, 0, M_PI, false);
CGPathAddArc(rightCircles, NULL, xstart + .75 * width, ystart + .5 * height, .4 * height, M_PI, 0, false);
CGPathMoveToPoint(rightCircles, NULL, xstart + .75 * width + .3 * height, ystart + .5 * height);
CGPathAddArc(rightCircles, NULL, xstart + .75 * width, ystart + .5 * height, .3 * height, 0, M_PI, true);
CGPathAddArc(rightCircles, NULL, xstart + .75 * width, ystart + .5 * height, .3 * height, M_PI, 0, true);
CGPathMoveToPoint(rightCircles, NULL, xstart + .75 * width + .2 * height, ystart + .5 * height);
CGPathAddArc(rightCircles, NULL, xstart + .75 * width, ystart + .5 * height, .2 * height, 0, M_PI, false);
CGPathAddArc(rightCircles, NULL, xstart + .75 * width, ystart + .5 * height, .2 * height, M_PI, 0, false);
CGPathMoveToPoint(rightCircles, NULL, xstart + .75 * width + .1 * height, ystart + .5 * height);
CGPathAddArc(rightCircles, NULL, xstart + .75 * width, ystart + .5 * height, .1 * height, 0, M_PI, true);
CGPathAddArc(rightCircles, NULL, xstart + .75 * width, ystart + .5 * height, .1 * height, M_PI, 0, true);
CGPathCloseSubpath(rightCircles);
CGContextAddPath(context, leftCircles);
CGContextAddPath(context, rightCircles);
CGContextSetRGBFillColor(context, 0, 0, 1, 1);
CGContextSetRGBStrokeColor(context, 1, 0, 0, 1);
CGContextDrawPath(context, fillMode);
CGPathRelease(leftCircles);
CGPathRelease(rightCircles);
}
INSTANTIATE_TEST_CASE_P(FillModes, CGContextFillMode, ::testing::ValuesIn(fillModes));
|
//******************************************************************************
//
// Copyright (c) Microsoft. All rights reserved.
//
// This code is licensed under the MIT License (MIT).
//
// 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 "DrawingTest.h"
CGPathDrawingMode fillModes[] = { kCGPathFill, kCGPathFillStroke, kCGPathEOFill, kCGPathEOFillStroke };
class CGContextFillMode : public WhiteBackgroundTest<>, public ::testing::WithParamInterface<CGPathDrawingMode> {
CFStringRef CreateOutputFilename() {
CGPathDrawingMode fillMode = GetParam();
const char* fillModeName;
switch (fillMode) {
case kCGPathFill:
fillModeName = "Fill";
break;
case kCGPathFillStroke:
fillModeName = "FillStroke";
break;
case kCGPathEOFill:
fillModeName = "EOFill";
break;
case kCGPathEOFillStroke:
fillModeName = "EOFillStroke";
break;
default:
break;
}
return CFStringCreateWithFormat(nullptr, nullptr, CFSTR("TestImage.CGContext.FillMode.%s.png"), fillModeName);
}
};
DRAW_TEST_P(CGContextFillMode, OverlappedEllipses) {
CGContextRef context = GetDrawingContext();
CGRect bounds = GetDrawingBounds();
bounds = CGRectInset(bounds, 16.f, 16.f);
CGFloat width = bounds.size.width;
CGFloat height = bounds.size.height;
CGFloat xstart = bounds.origin.x;
CGFloat ystart = bounds.origin.y;
CGPathDrawingMode fillMode = GetParam();
CGMutablePathRef leftCircles = CGPathCreateMutable();
CGPathMoveToPoint(leftCircles, NULL, xstart + .25 * width + .4 * height, ystart + .5 * height);
CGPathAddArc(leftCircles, NULL, xstart + .25 * width, ystart + .5 * height, .4 * height, 0, M_PI, true);
CGPathAddArc(leftCircles, NULL, xstart + .25 * width, ystart + .5 * height, .4 * height, M_PI, 0, true);
CGPathMoveToPoint(leftCircles, NULL, xstart + .25 * width + .3 * height, ystart + .5 * height);
CGPathAddArc(leftCircles, NULL, xstart + .25 * width, ystart + .5 * height, .3 * height, 0, M_PI, true);
CGPathAddArc(leftCircles, NULL, xstart + .25 * width, ystart + .5 * height, .3 * height, M_PI, 0, true);
CGPathMoveToPoint(leftCircles, NULL, xstart + .25 * width + .2 * height, ystart + .5 * height);
CGPathAddArc(leftCircles, NULL, xstart + .25 * width, ystart + .5 * height, .2 * height, 0, M_PI, true);
CGPathAddArc(leftCircles, NULL, xstart + .25 * width, ystart + .5 * height, .2 * height, M_PI, 0, true);
CGPathMoveToPoint(leftCircles, NULL, xstart + .25 * width + .1 * height, ystart + .5 * height);
CGPathAddArc(leftCircles, NULL, xstart + .25 * width, ystart + .5 * height, .1 * height, 0, M_PI, true);
CGPathAddArc(leftCircles, NULL, xstart + .25 * width, ystart + .5 * height, .1 * height, M_PI, 0, true);
CGPathCloseSubpath(leftCircles);
CGMutablePathRef rightCircles = CGPathCreateMutable();
CGPathMoveToPoint(rightCircles, NULL, xstart + .75 * width + .4 * height, ystart + .5 * height);
CGPathAddArc(rightCircles, NULL, xstart + .75 * width, ystart + .5 * height, .4 * height, 0, M_PI, false);
CGPathAddArc(rightCircles, NULL, xstart + .75 * width, ystart + .5 * height, .4 * height, M_PI, 0, false);
CGPathMoveToPoint(rightCircles, NULL, xstart + .75 * width + .3 * height, ystart + .5 * height);
CGPathAddArc(rightCircles, NULL, xstart + .75 * width, ystart + .5 * height, .3 * height, 0, M_PI, true);
CGPathAddArc(rightCircles, NULL, xstart + .75 * width, ystart + .5 * height, .3 * height, M_PI, 0, true);
CGPathMoveToPoint(rightCircles, NULL, xstart + .75 * width + .2 * height, ystart + .5 * height);
CGPathAddArc(rightCircles, NULL, xstart + .75 * width, ystart + .5 * height, .2 * height, 0, M_PI, false);
CGPathAddArc(rightCircles, NULL, xstart + .75 * width, ystart + .5 * height, .2 * height, M_PI, 0, false);
CGPathMoveToPoint(rightCircles, NULL, xstart + .75 * width + .1 * height, ystart + .5 * height);
CGPathAddArc(rightCircles, NULL, xstart + .75 * width, ystart + .5 * height, .1 * height, 0, M_PI, true);
CGPathAddArc(rightCircles, NULL, xstart + .75 * width, ystart + .5 * height, .1 * height, M_PI, 0, true);
CGPathCloseSubpath(rightCircles);
CGContextAddPath(context, leftCircles);
CGContextAddPath(context, rightCircles);
CGContextSetRGBFillColor(context, 0, 0, 1, 1);
CGContextSetRGBStrokeColor(context, 1, 0, 0, 1);
CGContextDrawPath(context, fillMode);
CGPathRelease(leftCircles);
CGPathRelease(rightCircles);
}
INSTANTIATE_TEST_CASE_P(FillModes, CGContextFillMode, ::testing::ValuesIn(fillModes));
|
Fix improper type assign in FillModeTests. invalid assignment of const char to char*
|
Fix improper type assign in FillModeTests.
invalid assignment of const char to char*
|
C++
|
mit
|
ehren/WinObjC,ehren/WinObjC,bbowman/WinObjC,pradipd/WinObjC,nathpete-msft/WinObjC,bbowman/WinObjC,pradipd/WinObjC,bbowman/WinObjC,nathpete-msft/WinObjC,nathpete-msft/WinObjC,nathpete-msft/WinObjC,nathpete-msft/WinObjC,bbowman/WinObjC,ehren/WinObjC,ehren/WinObjC,pradipd/WinObjC,bbowman/WinObjC,pradipd/WinObjC,pradipd/WinObjC,ehren/WinObjC
|
0d16465a0428a8f3ae10959e2de6011133e40221
|
runtime/browser/ui/native_app_window_views.cc
|
runtime/browser/ui/native_app_window_views.cc
|
// Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "xwalk/runtime/browser/ui/native_app_window_views.h"
#include "base/command_line.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/web_contents.h"
#include "grit/xwalk_resources.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/screen.h"
#include "ui/views/views_delegate.h"
#include "ui/views/controls/webview/webview.h"
#include "ui/views/widget/desktop_aura/desktop_screen.h"
#include "ui/views/widget/widget.h"
#include "xwalk/runtime/browser/image_util.h"
#include "xwalk/runtime/browser/ui/top_view_layout_views.h"
#include "xwalk/runtime/browser/ui/xwalk_views_delegate.h"
#include "xwalk/runtime/common/xwalk_notification_types.h"
#include "xwalk/runtime/common/xwalk_switches.h"
#if defined(OS_WIN)
#include "ui/views/window/native_frame_view.h"
#endif
#if defined(OS_LINUX) || defined(OS_WIN)
#include "xwalk/runtime/browser/ui/native_app_window_desktop.h"
#endif
#if defined(OS_TIZEN)
#include "xwalk/runtime/browser/ui/native_app_window_tizen.h"
#endif
namespace xwalk {
NativeAppWindowViews::NativeAppWindowViews(
const NativeAppWindow::CreateParams& create_params)
: web_contents_(create_params.web_contents),
web_view_(nullptr),
delegate_(create_params.delegate),
create_params_(create_params),
window_(nullptr),
is_fullscreen_(false),
minimum_size_(create_params.minimum_size),
maximum_size_(create_params.maximum_size),
resizable_(create_params.resizable) {
}
NativeAppWindowViews::~NativeAppWindowViews() {}
// Two-step initialization is needed here so that calls done by views::Widget to
// its delegate during views::Widget::Init() reach the correct implementation --
// e.g. ViewHierarchyChanged().
void NativeAppWindowViews::Initialize() {
CHECK(!window_);
window_ = new views::Widget;
views::Widget::InitParams params;
params.delegate = this;
params.remove_standard_frame = false;
params.use_system_default_icon = true;
params.show_state = create_params_.state;
params.parent = create_params_.parent;
#if defined(OS_TIZEN_MOBILE)
params.type = views::Widget::InitParams::TYPE_WINDOW_FRAMELESS;
// On Tizen apps are sized to the work area.
gfx::Rect bounds =
gfx::Screen::GetNativeScreen()->GetPrimaryDisplay().work_area();
params.bounds = bounds;
#else
// Fullscreen should have higher priority than window size.
if (create_params_.state != ui::SHOW_STATE_FULLSCREEN) {
params.type = views::Widget::InitParams::TYPE_WINDOW;
params.bounds = create_params_.bounds;
}
#endif
params.net_wm_pid = create_params_.net_wm_pid;
// Set the app icon if it is passed from command line.
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(switches::kAppIcon)) {
base::FilePath icon_file =
command_line->GetSwitchValuePath(switches::kAppIcon);
icon_ = xwalk_utils::LoadImageFromFilePath(icon_file);
} else {
// Otherwise, use the default icon for Crosswalk app.
ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
icon_ = rb.GetNativeImageNamed(IDR_XWALK_ICON_48);
}
window_->Init(params);
#if defined(OS_TIZEN_MOBILE)
// Set the bounds manually to avoid inset.
window_->SetBounds(bounds);
#elif !defined(USE_OZONE)
window_->CenterWindow(create_params_.bounds.size());
#endif
if (create_params_.state == ui::SHOW_STATE_FULLSCREEN)
SetFullscreen(true);
// TODO(hmin): Need to configure the maximum and minimum size of this window.
window_->AddObserver(this);
}
gfx::NativeWindow NativeAppWindowViews::GetNativeWindow() const {
return window_->GetNativeWindow();
}
void NativeAppWindowViews::UpdateIcon(const gfx::Image& icon) {
icon_ = icon;
window_->UpdateWindowIcon();
}
void NativeAppWindowViews::UpdateTitle(const base::string16& title) {
title_ = title;
window_->UpdateWindowTitle();
}
gfx::Rect NativeAppWindowViews::GetRestoredBounds() const {
return window_->GetRestoredBounds();
}
gfx::Rect NativeAppWindowViews::GetBounds() const {
return window_->GetWindowBoundsInScreen();
}
void NativeAppWindowViews::SetBounds(const gfx::Rect& bounds) {
window_->SetBounds(bounds);
}
void NativeAppWindowViews::Focus() {
// window_->Focus();
}
void NativeAppWindowViews::Show() {
window_->Show();
}
void NativeAppWindowViews::Hide() {
window_->Hide();
}
void NativeAppWindowViews::Maximize() {
window_->Maximize();
}
void NativeAppWindowViews::Minimize() {
window_->Minimize();
}
void NativeAppWindowViews::SetFullscreen(bool fullscreen) {
views::ViewsDelegate::views_delegate->SetShouldShowTitleBar(!fullscreen);
if (is_fullscreen_ == fullscreen)
return;
is_fullscreen_ = fullscreen;
window_->SetFullscreen(is_fullscreen_);
content::NotificationService::current()->Notify(
xwalk::NOTIFICATION_FULLSCREEN_CHANGED,
content::Source<NativeAppWindow>(this),
content::NotificationService::NoDetails());
}
void NativeAppWindowViews::Restore() {
window_->Restore();
}
void NativeAppWindowViews::FlashFrame(bool flash) {
window_->FlashFrame(flash);
}
void NativeAppWindowViews::Close() {
window_->Close();
}
bool NativeAppWindowViews::IsActive() const {
return window_->IsActive();
}
bool NativeAppWindowViews::IsMaximized() const {
return window_->IsMaximized();
}
bool NativeAppWindowViews::IsMinimized() const {
return window_->IsMinimized();
}
bool NativeAppWindowViews::IsFullscreen() const {
return is_fullscreen_;
}
TopViewLayout* NativeAppWindowViews::top_view_layout() {
return static_cast<TopViewLayout*>(GetLayoutManager());
}
////////////////////////////////////////////////////////////
// WidgetDelegate implementation
////////////////////////////////////////////////////////////
views::View* NativeAppWindowViews::GetInitiallyFocusedView() {
return web_view_;
}
views::View* NativeAppWindowViews::GetContentsView() {
return this;
}
views::Widget* NativeAppWindowViews::GetWidget() {
return window_;
}
const views::Widget* NativeAppWindowViews::GetWidget() const {
return window_;
}
base::string16 NativeAppWindowViews::GetWindowTitle() const {
return title_;
}
void NativeAppWindowViews::DeleteDelegate() {
window_->RemoveObserver(this);
delegate_->OnWindowDestroyed();
delete this;
}
gfx::ImageSkia NativeAppWindowViews::GetWindowAppIcon() {
return GetWindowIcon();
}
gfx::ImageSkia NativeAppWindowViews::GetWindowIcon() {
return *icon_.ToImageSkia();
}
bool NativeAppWindowViews::ShouldShowWindowTitle() const {
return true;
}
void NativeAppWindowViews::SaveWindowPlacement(const gfx::Rect& bounds,
ui::WindowShowState show_state) {
// TODO(hmin): views::WidgetDelegate::SaveWindowPlacement(bounds, show_state);
}
bool NativeAppWindowViews::GetSavedWindowPlacement(const views::Widget* widget,
gfx::Rect* bounds, ui::WindowShowState* show_state) const {
// TODO(hmin): Get the saved window placement.
return false;
}
bool NativeAppWindowViews::CanResize() const {
return resizable_ &&
(maximum_size_.IsEmpty() || minimum_size_ != maximum_size_);
}
bool NativeAppWindowViews::CanMaximize() const {
return resizable_ && maximum_size_.IsEmpty();
}
bool NativeAppWindowViews::CanMinimize() const {
return true;
}
#if defined(OS_WIN)
views::NonClientFrameView* NativeAppWindowViews::CreateNonClientFrameView(
views::Widget* widget) {
return new views::NativeFrameView(widget);
}
#endif
////////////////////////////////////////////////////////////
// views::View implementation
////////////////////////////////////////////////////////////
void NativeAppWindowViews::ChildPreferredSizeChanged(views::View* child) {
// We only re-layout when the top view changes its preferred size (and notify
// us by calling its own function PreferredSizeChanged()). We don't react to
// changes in preferred size for the content view since we are currently
// setting its bounds to the maximum size available.
if (child == top_view_layout()->top_view())
Layout();
}
void NativeAppWindowViews::ViewHierarchyChanged(
const ViewHierarchyChangedDetails& details) {
if (details.is_add && details.child == this) {
TopViewLayout* layout = new TopViewLayout();
SetLayoutManager(layout);
web_view_ = new views::WebView(nullptr);
web_view_->SetWebContents(web_contents_);
AddChildView(web_view_);
layout->set_content_view(web_view_);
}
}
void NativeAppWindowViews::OnFocus() {
web_view_->RequestFocus();
}
gfx::Size NativeAppWindowViews::GetMaximumSize() const {
return maximum_size_;
}
gfx::Size NativeAppWindowViews::GetMinimumSize() const {
return minimum_size_;
}
////////////////////////////////////////////////////////////
// views::WidgetObserver implementation
////////////////////////////////////////////////////////////
void NativeAppWindowViews::OnWidgetClosing(views::Widget* widget) {
}
void NativeAppWindowViews::OnWidgetCreated(views::Widget* widget) {
}
void NativeAppWindowViews::OnWidgetDestroying(views::Widget* widget) {
}
void NativeAppWindowViews::OnWidgetDestroyed(views::Widget* widget) {
}
void NativeAppWindowViews::OnWidgetBoundsChanged(views::Widget* widget,
const gfx::Rect& new_bounds) {
}
// static
NativeAppWindow* NativeAppWindow::Create(
const NativeAppWindow::CreateParams& create_params) {
NativeAppWindowViews* window;
#if defined(OS_TIZEN)
window = new NativeAppWindowTizen(create_params);
#elif defined(OS_LINUX) || defined(OS_WIN)
window = new NativeAppWindowDesktop(create_params);
#else
window = new NativeAppWindowViews(create_params);
#endif
window->Initialize();
return window;
}
// static
void NativeAppWindow::Initialize() {
CHECK(!views::ViewsDelegate::views_delegate);
gfx::Screen::SetScreenInstance(
gfx::SCREEN_TYPE_NATIVE, views::CreateDesktopScreen());
views::ViewsDelegate::views_delegate = new XWalkViewsDelegate();
}
} // namespace xwalk
|
// Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "xwalk/runtime/browser/ui/native_app_window_views.h"
#include <vector>
#include "base/command_line.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/web_contents.h"
#include "grit/xwalk_resources.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/screen.h"
#include "ui/views/views_delegate.h"
#include "ui/views/controls/webview/webview.h"
#include "ui/views/widget/desktop_aura/desktop_screen.h"
#include "ui/views/widget/widget.h"
#include "xwalk/runtime/browser/image_util.h"
#include "xwalk/runtime/browser/ui/top_view_layout_views.h"
#include "xwalk/runtime/browser/ui/xwalk_views_delegate.h"
#include "xwalk/runtime/common/xwalk_notification_types.h"
#include "xwalk/runtime/common/xwalk_switches.h"
#if defined(OS_WIN)
#include "ui/views/window/native_frame_view.h"
#endif
#if defined(OS_LINUX) || defined(OS_WIN)
#include "xwalk/runtime/browser/ui/native_app_window_desktop.h"
#endif
#if defined(OS_TIZEN)
#include "xwalk/runtime/browser/ui/native_app_window_tizen.h"
#endif
namespace xwalk {
NativeAppWindowViews::NativeAppWindowViews(
const NativeAppWindow::CreateParams& create_params)
: web_contents_(create_params.web_contents),
web_view_(nullptr),
delegate_(create_params.delegate),
create_params_(create_params),
window_(nullptr),
is_fullscreen_(false),
minimum_size_(create_params.minimum_size),
maximum_size_(create_params.maximum_size),
resizable_(create_params.resizable) {
}
NativeAppWindowViews::~NativeAppWindowViews() {}
// Two-step initialization is needed here so that calls done by views::Widget to
// its delegate during views::Widget::Init() reach the correct implementation --
// e.g. ViewHierarchyChanged().
void NativeAppWindowViews::Initialize() {
CHECK(!window_);
window_ = new views::Widget;
views::Widget::InitParams params;
params.delegate = this;
params.remove_standard_frame = false;
params.use_system_default_icon = true;
params.show_state = create_params_.state;
params.parent = create_params_.parent;
#if defined(OS_TIZEN_MOBILE)
params.type = views::Widget::InitParams::TYPE_WINDOW_FRAMELESS;
// On Tizen apps are sized to the work area.
gfx::Rect bounds =
gfx::Screen::GetNativeScreen()->GetPrimaryDisplay().work_area();
params.bounds = bounds;
#else
// Fullscreen should have higher priority than window size.
if (create_params_.state != ui::SHOW_STATE_FULLSCREEN) {
params.type = views::Widget::InitParams::TYPE_WINDOW;
params.bounds = create_params_.bounds;
}
#endif
params.net_wm_pid = create_params_.net_wm_pid;
// Set the app icon if it is passed from command line.
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(switches::kAppIcon)) {
base::FilePath icon_file =
command_line->GetSwitchValuePath(switches::kAppIcon);
icon_ = xwalk_utils::LoadImageFromFilePath(icon_file);
} else {
// Otherwise, use the default icon for Crosswalk app.
ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
icon_ = rb.GetNativeImageNamed(IDR_XWALK_ICON_48);
}
window_->Init(params);
#if defined(OS_TIZEN_MOBILE)
// Set the bounds manually to avoid inset.
window_->SetBounds(bounds);
#elif !defined(USE_OZONE)
window_->CenterWindow(create_params_.bounds.size());
#endif
if (create_params_.state == ui::SHOW_STATE_FULLSCREEN)
SetFullscreen(true);
// TODO(hmin): Need to configure the maximum and minimum size of this window.
window_->AddObserver(this);
}
gfx::NativeWindow NativeAppWindowViews::GetNativeWindow() const {
return window_->GetNativeWindow();
}
void NativeAppWindowViews::UpdateIcon(const gfx::Image& icon) {
icon_ = icon;
window_->UpdateWindowIcon();
}
void NativeAppWindowViews::UpdateTitle(const base::string16& title) {
title_ = title;
window_->UpdateWindowTitle();
}
gfx::Rect NativeAppWindowViews::GetRestoredBounds() const {
return window_->GetRestoredBounds();
}
gfx::Rect NativeAppWindowViews::GetBounds() const {
return window_->GetWindowBoundsInScreen();
}
void NativeAppWindowViews::SetBounds(const gfx::Rect& bounds) {
window_->SetBounds(bounds);
}
void NativeAppWindowViews::Focus() {
// window_->Focus();
}
void NativeAppWindowViews::Show() {
window_->Show();
}
void NativeAppWindowViews::Hide() {
window_->Hide();
}
void NativeAppWindowViews::Maximize() {
window_->Maximize();
}
void NativeAppWindowViews::Minimize() {
window_->Minimize();
}
void NativeAppWindowViews::SetFullscreen(bool fullscreen) {
views::ViewsDelegate::views_delegate->SetShouldShowTitleBar(!fullscreen);
if (is_fullscreen_ == fullscreen)
return;
is_fullscreen_ = fullscreen;
window_->SetFullscreen(is_fullscreen_);
content::NotificationService::current()->Notify(
xwalk::NOTIFICATION_FULLSCREEN_CHANGED,
content::Source<NativeAppWindow>(this),
content::NotificationService::NoDetails());
}
void NativeAppWindowViews::Restore() {
window_->Restore();
}
void NativeAppWindowViews::FlashFrame(bool flash) {
window_->FlashFrame(flash);
}
void NativeAppWindowViews::Close() {
window_->Close();
}
bool NativeAppWindowViews::IsActive() const {
return window_->IsActive();
}
bool NativeAppWindowViews::IsMaximized() const {
return window_->IsMaximized();
}
bool NativeAppWindowViews::IsMinimized() const {
return window_->IsMinimized();
}
bool NativeAppWindowViews::IsFullscreen() const {
return is_fullscreen_;
}
TopViewLayout* NativeAppWindowViews::top_view_layout() {
return static_cast<TopViewLayout*>(GetLayoutManager());
}
////////////////////////////////////////////////////////////
// WidgetDelegate implementation
////////////////////////////////////////////////////////////
views::View* NativeAppWindowViews::GetInitiallyFocusedView() {
return web_view_;
}
views::View* NativeAppWindowViews::GetContentsView() {
return this;
}
views::Widget* NativeAppWindowViews::GetWidget() {
return window_;
}
const views::Widget* NativeAppWindowViews::GetWidget() const {
return window_;
}
base::string16 NativeAppWindowViews::GetWindowTitle() const {
return title_;
}
void NativeAppWindowViews::DeleteDelegate() {
window_->RemoveObserver(this);
delegate_->OnWindowDestroyed();
delete this;
}
gfx::ImageSkia NativeAppWindowViews::GetWindowAppIcon() {
return GetWindowIcon();
}
gfx::ImageSkia NativeAppWindowViews::GetWindowIcon() {
const gfx::ImageSkia *result = icon_.ToImageSkia();
const std::vector<float> oldSupportedScales =
gfx::ImageSkia::GetSupportedScales();
std::vector<float> scale = { 1.0f };
gfx::ImageSkia::SetSupportedScales(scale);
// Ensure at least the ImageSkiaRep for the default 1x scale is attached to
// ImageSkia's storage
result->EnsureRepsForSupportedScales();
gfx::ImageSkia::SetSupportedScales(oldSupportedScales);
return *result;
}
bool NativeAppWindowViews::ShouldShowWindowTitle() const {
return true;
}
void NativeAppWindowViews::SaveWindowPlacement(const gfx::Rect& bounds,
ui::WindowShowState show_state) {
// TODO(hmin): views::WidgetDelegate::SaveWindowPlacement(bounds, show_state);
}
bool NativeAppWindowViews::GetSavedWindowPlacement(const views::Widget* widget,
gfx::Rect* bounds, ui::WindowShowState* show_state) const {
// TODO(hmin): Get the saved window placement.
return false;
}
bool NativeAppWindowViews::CanResize() const {
return resizable_ &&
(maximum_size_.IsEmpty() || minimum_size_ != maximum_size_);
}
bool NativeAppWindowViews::CanMaximize() const {
return resizable_ && maximum_size_.IsEmpty();
}
bool NativeAppWindowViews::CanMinimize() const {
return true;
}
#if defined(OS_WIN)
views::NonClientFrameView* NativeAppWindowViews::CreateNonClientFrameView(
views::Widget* widget) {
return new views::NativeFrameView(widget);
}
#endif
////////////////////////////////////////////////////////////
// views::View implementation
////////////////////////////////////////////////////////////
void NativeAppWindowViews::ChildPreferredSizeChanged(views::View* child) {
// We only re-layout when the top view changes its preferred size (and notify
// us by calling its own function PreferredSizeChanged()). We don't react to
// changes in preferred size for the content view since we are currently
// setting its bounds to the maximum size available.
if (child == top_view_layout()->top_view())
Layout();
}
void NativeAppWindowViews::ViewHierarchyChanged(
const ViewHierarchyChangedDetails& details) {
if (details.is_add && details.child == this) {
TopViewLayout* layout = new TopViewLayout();
SetLayoutManager(layout);
web_view_ = new views::WebView(nullptr);
web_view_->SetWebContents(web_contents_);
AddChildView(web_view_);
layout->set_content_view(web_view_);
}
}
void NativeAppWindowViews::OnFocus() {
web_view_->RequestFocus();
}
gfx::Size NativeAppWindowViews::GetMaximumSize() const {
return maximum_size_;
}
gfx::Size NativeAppWindowViews::GetMinimumSize() const {
return minimum_size_;
}
////////////////////////////////////////////////////////////
// views::WidgetObserver implementation
////////////////////////////////////////////////////////////
void NativeAppWindowViews::OnWidgetClosing(views::Widget* widget) {
}
void NativeAppWindowViews::OnWidgetCreated(views::Widget* widget) {
}
void NativeAppWindowViews::OnWidgetDestroying(views::Widget* widget) {
}
void NativeAppWindowViews::OnWidgetDestroyed(views::Widget* widget) {
}
void NativeAppWindowViews::OnWidgetBoundsChanged(views::Widget* widget,
const gfx::Rect& new_bounds) {
}
// static
NativeAppWindow* NativeAppWindow::Create(
const NativeAppWindow::CreateParams& create_params) {
NativeAppWindowViews* window;
#if defined(OS_TIZEN)
window = new NativeAppWindowTizen(create_params);
#elif defined(OS_LINUX) || defined(OS_WIN)
window = new NativeAppWindowDesktop(create_params);
#else
window = new NativeAppWindowViews(create_params);
#endif
window->Initialize();
return window;
}
// static
void NativeAppWindow::Initialize() {
CHECK(!views::ViewsDelegate::views_delegate);
gfx::Screen::SetScreenInstance(
gfx::SCREEN_TYPE_NATIVE, views::CreateDesktopScreen());
views::ViewsDelegate::views_delegate = new XWalkViewsDelegate();
}
} // namespace xwalk
|
Fix the incorrect icon update issue
|
[Linux] Fix the incorrect icon update issue
Ensure at least the ImageSkiaRep's for the default 1x scale is always
attached to ImageSkia's storage so that HasRepresentation for the
default 1x scale return a meaningful true then the icon updator can get
a chance to retrieve the 1x scale Rep.
BUG=XWALK-4763
|
C++
|
bsd-3-clause
|
lincsoon/crosswalk,baleboy/crosswalk,darktears/crosswalk,axinging/crosswalk,darktears/crosswalk,zeropool/crosswalk,xzhan96/crosswalk,weiyirong/crosswalk-1,Bysmyyr/crosswalk,darktears/crosswalk,dreamsxin/crosswalk,marcuspridham/crosswalk,stonegithubs/crosswalk,darktears/crosswalk,bestwpw/crosswalk,dreamsxin/crosswalk,minggangw/crosswalk,bestwpw/crosswalk,PeterWangIntel/crosswalk,darktears/crosswalk,tedshroyer/crosswalk,tedshroyer/crosswalk,jondwillis/crosswalk,Pluto-tv/crosswalk,crosswalk-project/crosswalk,jondwillis/crosswalk,Bysmyyr/crosswalk,jondong/crosswalk,rakuco/crosswalk,dreamsxin/crosswalk,jondong/crosswalk,bestwpw/crosswalk,zeropool/crosswalk,crosswalk-project/crosswalk,zliang7/crosswalk,marcuspridham/crosswalk,RafuCater/crosswalk,axinging/crosswalk,rakuco/crosswalk,stonegithubs/crosswalk,lincsoon/crosswalk,xzhan96/crosswalk,weiyirong/crosswalk-1,jondong/crosswalk,baleboy/crosswalk,xzhan96/crosswalk,zeropool/crosswalk,hgl888/crosswalk,jondong/crosswalk,Bysmyyr/crosswalk,minggangw/crosswalk,jondong/crosswalk,marcuspridham/crosswalk,Pluto-tv/crosswalk,bestwpw/crosswalk,weiyirong/crosswalk-1,amaniak/crosswalk,lincsoon/crosswalk,zeropool/crosswalk,jondwillis/crosswalk,heke123/crosswalk,amaniak/crosswalk,amaniak/crosswalk,PeterWangIntel/crosswalk,weiyirong/crosswalk-1,darktears/crosswalk,axinging/crosswalk,rakuco/crosswalk,lincsoon/crosswalk,baleboy/crosswalk,chuan9/crosswalk,heke123/crosswalk,Bysmyyr/crosswalk,RafuCater/crosswalk,hgl888/crosswalk,RafuCater/crosswalk,marcuspridham/crosswalk,weiyirong/crosswalk-1,Bysmyyr/crosswalk,xzhan96/crosswalk,heke123/crosswalk,chuan9/crosswalk,xzhan96/crosswalk,Pluto-tv/crosswalk,chuan9/crosswalk,crosswalk-project/crosswalk,lincsoon/crosswalk,lincsoon/crosswalk,zliang7/crosswalk,PeterWangIntel/crosswalk,hgl888/crosswalk,zeropool/crosswalk,Pluto-tv/crosswalk,minggangw/crosswalk,axinging/crosswalk,axinging/crosswalk,weiyirong/crosswalk-1,heke123/crosswalk,baleboy/crosswalk,jondwillis/crosswalk,hgl888/crosswalk,chuan9/crosswalk,zliang7/crosswalk,zliang7/crosswalk,stonegithubs/crosswalk,axinging/crosswalk,rakuco/crosswalk,Bysmyyr/crosswalk,crosswalk-project/crosswalk,weiyirong/crosswalk-1,PeterWangIntel/crosswalk,zliang7/crosswalk,RafuCater/crosswalk,RafuCater/crosswalk,amaniak/crosswalk,tedshroyer/crosswalk,stonegithubs/crosswalk,marcuspridham/crosswalk,zliang7/crosswalk,amaniak/crosswalk,tedshroyer/crosswalk,baleboy/crosswalk,baleboy/crosswalk,jondwillis/crosswalk,jondong/crosswalk,jondwillis/crosswalk,minggangw/crosswalk,lincsoon/crosswalk,dreamsxin/crosswalk,stonegithubs/crosswalk,minggangw/crosswalk,hgl888/crosswalk,marcuspridham/crosswalk,hgl888/crosswalk,RafuCater/crosswalk,amaniak/crosswalk,xzhan96/crosswalk,zliang7/crosswalk,chuan9/crosswalk,crosswalk-project/crosswalk,chuan9/crosswalk,xzhan96/crosswalk,dreamsxin/crosswalk,heke123/crosswalk,tedshroyer/crosswalk,baleboy/crosswalk,crosswalk-project/crosswalk,marcuspridham/crosswalk,darktears/crosswalk,rakuco/crosswalk,chuan9/crosswalk,tedshroyer/crosswalk,PeterWangIntel/crosswalk,zliang7/crosswalk,dreamsxin/crosswalk,axinging/crosswalk,baleboy/crosswalk,crosswalk-project/crosswalk,RafuCater/crosswalk,minggangw/crosswalk,bestwpw/crosswalk,amaniak/crosswalk,stonegithubs/crosswalk,jondong/crosswalk,zeropool/crosswalk,Pluto-tv/crosswalk,hgl888/crosswalk,jondong/crosswalk,minggangw/crosswalk,stonegithubs/crosswalk,darktears/crosswalk,crosswalk-project/crosswalk,tedshroyer/crosswalk,Pluto-tv/crosswalk,PeterWangIntel/crosswalk,dreamsxin/crosswalk,jondwillis/crosswalk,lincsoon/crosswalk,Pluto-tv/crosswalk,marcuspridham/crosswalk,zeropool/crosswalk,PeterWangIntel/crosswalk,bestwpw/crosswalk,hgl888/crosswalk,heke123/crosswalk,rakuco/crosswalk,xzhan96/crosswalk,Bysmyyr/crosswalk,heke123/crosswalk,heke123/crosswalk,rakuco/crosswalk,Bysmyyr/crosswalk,bestwpw/crosswalk,minggangw/crosswalk,rakuco/crosswalk
|
0582802a24d121c6874e331c5664cf2d0da555af
|
test/keyphrase-extraction/kpe_scd_tool.cc
|
test/keyphrase-extraction/kpe_scd_tool.cc
|
#include <idmlib/keyphrase-extraction/kpe_algorithm.h>
#include <boost/algorithm/string/split.hpp>
#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>
#include <util/scd_parser.h>
#include "../TestResources.h"
using namespace idmlib;
using namespace idmlib::kpe;
using namespace idmlib::util;
using namespace boost::filesystem;
namespace po = boost::program_options;
class FileKPEWriter
{
public:
FileKPEWriter(const std::string& file,izenelib::util::UString::EncodingType encoding)
:ofs_(file.c_str()), encoding_(encoding)
{
}
~FileKPEWriter()
{
ofs_.close();
}
void Callback(const izenelib::util::UString& str, uint32_t df, uint8_t score)
{
std::string s;
str.convertString(s, encoding_);
ofs_<<s<<","<<df<<std::endl;
}
private:
std::ofstream ofs_;
izenelib::util::UString::EncodingType encoding_;
};
int main(int ac, char** av)
{
po::options_description desc("Allowed options");
desc.add_options()
("help", "produce help message")
("resource-path,R", po::value<std::string>(), "KPE resource path")
("scd-path,S", po::value<std::string>(), "scd directory to be processed")
("property,P", po::value<std::string>(), "properties to be processed, seperate with comma(Title,Content), case insensitive")
("output-file,O", po::value<std::string>(), "output key-phrases file, include the string representation and df")
("kma-path,K", po::value<std::string>(), "if we want to process Korean collection, specify this kma path")
("working-path,W", po::value<std::string>(), "temp working path used for kpe, default: ./kpe_scd_working")
("max-doc,M", po::value<uint32_t>(), "max doc count which will be processed.")
;
std::string default_working_path = "./kpe_scd_working";
izenelib::util::UString::EncodingType encoding = izenelib::util::UString::UTF_8;
po::variables_map vm;
po::store(po::parse_command_line(ac, av, desc), vm);
po::notify(vm);
if (vm.count("help")) {
std::cout << desc << std::endl;
return 1;
}
std::string resource_path;
if (vm.count("resource-path")) {
resource_path = vm["resource-path"].as<std::string>();
std::cout << "resource-path: " << resource_path <<std::endl;
}
else {
std::cerr<<"resource-path not set"<<std::endl;
std::cerr << desc << std::endl;
return -1;
}
std::string scd_path;
std::vector<std::string> scdfile_list;
if (vm.count("scd-path")) {
scd_path = vm["scd-path"].as<std::string>();
try{
if (!is_directory(scd_path))
{
std::cerr<<scd_path<<"is not directory"<<std::endl;
return -1;
}
directory_iterator kItrEnd;
for (directory_iterator itr(scd_path); itr != kItrEnd; ++itr)
{
std::string file_name = itr->path().filename();
if (izenelib::util::ScdParser::checkSCDFormat(file_name) )
{
izenelib::util::SCD_TYPE scd_type = izenelib::util::ScdParser::checkSCDType(file_name);
if( scd_type == izenelib::util::INSERT_SCD ||scd_type == izenelib::util::UPDATE_SCD )
{
scdfile_list.push_back(itr->path().string() );
}
}
}
}
catch(std::exception& ex)
{
std::cerr<<"fs error"<<std::endl;
return -1;
}
if( scdfile_list.size()==0 )
{
std::cout<<"no scd file under "<<scd_path<<std::endl;
return 1;
}
std::cout << "scd-path: " << scd_path <<std::endl;
}
else {
std::cerr<<"scd-path not set"<<std::endl;
std::cerr << desc << std::endl;
return -1;
}
izenelib::am::rde_hash<izenelib::util::UString, bool> properties;
if (vm.count("property")) {
std::string property_str = vm["property"].as<std::string>();
std::vector<std::string> property_vec;
boost::algorithm::split( property_vec, property_str, boost::algorithm::is_any_of(",") );
std::vector<std::string> nonempty_property_vec;
for(uint32_t i=0;i<property_vec.size();i++)
{
if( property_vec[i] != "")
{
nonempty_property_vec.push_back(property_vec[i]);
izenelib::util::UString property_ustr(property_vec[i], encoding);
property_ustr.toLowerString();
properties.insert(property_ustr, 1);
}
}
if( nonempty_property_vec.size()==0)
{
std::cerr<<"property not set correctly"<<std::endl;
std::cerr << desc << std::endl;
return -1;
}
for(uint32_t i=0;i<nonempty_property_vec.size();i++)
{
std::cout<<"Process property: "<<nonempty_property_vec[i]<<std::endl;
}
}
else {
std::cerr<<"property not set"<<std::endl;
std::cerr << desc << std::endl;
return -1;
}
std::string output_file;
if (vm.count("output-file")) {
output_file = vm["output-file"].as<std::string>();
std::cout << "output-file: " << output_file <<std::endl;
}
else {
std::cerr<<"output-file not set"<<std::endl;
std::cerr << desc << std::endl;
return -1;
}
idmlib::util::IDMAnalyzer* analyzer = NULL;
if (vm.count("kma-path")) {
std::string kma_path = vm["kma-path"].as<std::string>();
std::cout << "kma-path: " << kma_path <<std::endl;
analyzer = new idmlib::util::IDMAnalyzer(kma_path);
} else {
std::cout << "kma-path not set"<<std::endl;
analyzer = new idmlib::util::IDMAnalyzer();
}
std::string working_path;
if (vm.count("working-path")) {
working_path = vm["working-path"].as<std::string>();
try
{
boost::filesystem::remove_all(working_path);
}
catch(std::exception& ex)
{
std::cerr<<"delete "<<working_path<<" error"<<std::endl;
return -1;
}
std::cout << "working-path: " << working_path <<std::endl;
}
else {
std::cout<<"working-path not set, use default "<<default_working_path<<std::endl;
working_path = default_working_path;
}
uint32_t max_doc = 0;
if (vm.count("max-doc")) {
max_doc = vm["max-doc"].as<uint32_t>();
std::cout << "max-doc: " << max_doc <<std::endl;
}
typedef KPEOutput<true, false, false> OutputType ;
typedef OutputType::function_type function_type ;
if( !analyzer->LoadT2SMapFile(resource_path+"/cs_ct") )
{
return -1;
}
FileKPEWriter file_writer(output_file, encoding);
function_type callback_func = boost::bind( &FileKPEWriter::Callback, &file_writer, _1, _2, _3);
KPEAlgorithm<OutputType>* kpe = new KPEAlgorithm<OutputType>(working_path, analyzer, callback_func);
if( !kpe->load(resource_path) )
{
return -1;
}
uint32_t docid = 0;
for(uint32_t i=0;i<scdfile_list.size();i++)
{
std::string scd_file = scdfile_list[i];
izenelib::util::ScdParser scd_parser(encoding);
if(!scd_parser.load(scd_file) )
{
std::cerr<<"load scd file failed."<<std::endl;
return -1;
}
izenelib::util::ScdParser::iterator it = scd_parser.begin();
while( it!= scd_parser.end() )
{
izenelib::util::SCDDocPtr doc = (*it);
if(!doc)
{
std::cerr<<"scd parsing error"<<std::endl;
break;
}
std::vector<std::pair<izenelib::util::UString, izenelib::util::UString> >::iterator p;
for (p = doc->begin(); p != doc->end(); p++)
{
izenelib::util::UString property_name = p->first;
property_name.toLowerString();
if( property_name == izenelib::util::UString("docid", encoding) )
{
docid++;
if( max_doc>0 && docid > max_doc ) break;
if( docid % 1000 == 0 )
{
std::cout<<"Processing "<<docid<<std::endl;
}
}
else if( properties.find( property_name) != NULL)
{
kpe->insert( p->second, docid);
}
}
++it;
}
}
kpe->close();
delete kpe;
delete analyzer;
boost::filesystem::remove_all(working_path);
return 0;
}
|
#include <idmlib/keyphrase-extraction/kpe_algorithm.h>
#include <boost/algorithm/string/split.hpp>
#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>
#include <util/scd_parser.h>
#include "../TestResources.h"
using namespace idmlib;
using namespace idmlib::kpe;
using namespace idmlib::util;
using namespace boost::filesystem;
namespace po = boost::program_options;
class FileKPEWriter
{
public:
FileKPEWriter(const std::string& file,izenelib::util::UString::EncodingType encoding)
:ofs_(file.c_str()), encoding_(encoding)
{
}
~FileKPEWriter()
{
ofs_.close();
}
void Callback(const izenelib::util::UString& str, uint32_t df, uint8_t score)
{
std::string s;
str.convertString(s, encoding_);
ofs_<<s<<","<<df<<std::endl;
}
private:
std::ofstream ofs_;
izenelib::util::UString::EncodingType encoding_;
};
int main(int ac, char** av)
{
po::options_description desc("Allowed options");
desc.add_options()
("help", "produce help message")
("resource-path,R", po::value<std::string>(), "KPE resource path")
("scd-path,S", po::value<std::string>(), "scd directory to be processed")
("property,P", po::value<std::string>(), "properties to be processed, seperate with comma(Title,Content), case insensitive")
("output-file,O", po::value<std::string>(), "output key-phrases file, include the string representation and df")
("kma-path,K", po::value<std::string>(), "if we want to process Korean collection, specify this kma path")
("working-path,W", po::value<std::string>(), "temp working path used for kpe, default: ./kpe_scd_working")
("max-doc,M", po::value<uint32_t>(), "max doc count which will be processed.")
("exclude-file,X", po::value<std::string>(), "exclude scd file name list")
;
std::string default_working_path = "./kpe_scd_working";
izenelib::util::UString::EncodingType encoding = izenelib::util::UString::UTF_8;
po::variables_map vm;
po::store(po::parse_command_line(ac, av, desc), vm);
po::notify(vm);
if (vm.count("help")) {
std::cout << desc << std::endl;
return 1;
}
std::string resource_path;
if (vm.count("resource-path")) {
resource_path = vm["resource-path"].as<std::string>();
std::cout << "resource-path: " << resource_path <<std::endl;
}
else {
std::cerr<<"resource-path not set"<<std::endl;
std::cerr << desc << std::endl;
return -1;
}
std::string exclude_file;
if (vm.count("exclude-file")) {
exclude_file = vm["exclude-file"].as<std::string>();
std::cout << "exclude-file: " << exclude_file <<std::endl;
}
izenelib::am::rde_hash<std::string, bool> exclude_map;
std::ifstream ifs(exclude_file.c_str());
std::string line;
while ( getline ( ifs,line ) )
{
exclude_map.insert(line, 1);
}
ifs.close();
std::string scd_path;
std::vector<std::string> scdfile_list;
if (vm.count("scd-path")) {
scd_path = vm["scd-path"].as<std::string>();
try{
if (!is_directory(scd_path))
{
std::cerr<<scd_path<<"is not directory"<<std::endl;
return -1;
}
directory_iterator kItrEnd;
for (directory_iterator itr(scd_path); itr != kItrEnd; ++itr)
{
std::string file_name = itr->path().filename();
if( exclude_map.find(file_name) )
{
std::cout<<file_name<<" in exclude list."<<std::endl;
continue;
}
if (izenelib::util::ScdParser::checkSCDFormat(file_name) )
{
izenelib::util::SCD_TYPE scd_type = izenelib::util::ScdParser::checkSCDType(file_name);
if( scd_type == izenelib::util::INSERT_SCD ||scd_type == izenelib::util::UPDATE_SCD )
{
scdfile_list.push_back(itr->path().string() );
}
}
}
}
catch(std::exception& ex)
{
std::cerr<<"fs error"<<std::endl;
return -1;
}
if( scdfile_list.size()==0 )
{
std::cout<<"no scd file under "<<scd_path<<std::endl;
return 1;
}
std::cout << "scd-path: " << scd_path <<std::endl;
}
else {
std::cerr<<"scd-path not set"<<std::endl;
std::cerr << desc << std::endl;
return -1;
}
izenelib::am::rde_hash<izenelib::util::UString, bool> properties;
if (vm.count("property")) {
std::string property_str = vm["property"].as<std::string>();
std::vector<std::string> property_vec;
boost::algorithm::split( property_vec, property_str, boost::algorithm::is_any_of(",") );
std::vector<std::string> nonempty_property_vec;
for(uint32_t i=0;i<property_vec.size();i++)
{
if( property_vec[i] != "")
{
nonempty_property_vec.push_back(property_vec[i]);
izenelib::util::UString property_ustr(property_vec[i], encoding);
property_ustr.toLowerString();
properties.insert(property_ustr, 1);
}
}
if( nonempty_property_vec.size()==0)
{
std::cerr<<"property not set correctly"<<std::endl;
std::cerr << desc << std::endl;
return -1;
}
for(uint32_t i=0;i<nonempty_property_vec.size();i++)
{
std::cout<<"Process property: "<<nonempty_property_vec[i]<<std::endl;
}
}
else {
std::cerr<<"property not set"<<std::endl;
std::cerr << desc << std::endl;
return -1;
}
std::string output_file;
if (vm.count("output-file")) {
output_file = vm["output-file"].as<std::string>();
std::cout << "output-file: " << output_file <<std::endl;
}
else {
std::cerr<<"output-file not set"<<std::endl;
std::cerr << desc << std::endl;
return -1;
}
idmlib::util::IDMAnalyzer* analyzer = NULL;
if (vm.count("kma-path")) {
std::string kma_path = vm["kma-path"].as<std::string>();
std::cout << "kma-path: " << kma_path <<std::endl;
analyzer = new idmlib::util::IDMAnalyzer(kma_path);
} else {
std::cout << "kma-path not set"<<std::endl;
analyzer = new idmlib::util::IDMAnalyzer();
}
std::string working_path;
if (vm.count("working-path")) {
working_path = vm["working-path"].as<std::string>();
try
{
boost::filesystem::remove_all(working_path);
}
catch(std::exception& ex)
{
std::cerr<<"delete "<<working_path<<" error"<<std::endl;
return -1;
}
std::cout << "working-path: " << working_path <<std::endl;
}
else {
std::cout<<"working-path not set, use default "<<default_working_path<<std::endl;
working_path = default_working_path;
}
uint32_t max_doc = 0;
if (vm.count("max-doc")) {
max_doc = vm["max-doc"].as<uint32_t>();
std::cout << "max-doc: " << max_doc <<std::endl;
}
typedef KPEOutput<true, false, false> OutputType ;
typedef OutputType::function_type function_type ;
if( !analyzer->LoadT2SMapFile(resource_path+"/cs_ct") )
{
return -1;
}
FileKPEWriter file_writer(output_file, encoding);
function_type callback_func = boost::bind( &FileKPEWriter::Callback, &file_writer, _1, _2, _3);
KPEAlgorithm<OutputType>* kpe = new KPEAlgorithm<OutputType>(working_path, analyzer, callback_func);
if( !kpe->load(resource_path) )
{
return -1;
}
uint32_t docid = 0;
for(uint32_t i=0;i<scdfile_list.size();i++)
{
std::string scd_file = scdfile_list[i];
izenelib::util::ScdParser scd_parser(encoding);
if(!scd_parser.load(scd_file) )
{
std::cerr<<"load scd file failed."<<std::endl;
return -1;
}
izenelib::util::ScdParser::iterator it = scd_parser.begin();
while( it!= scd_parser.end() )
{
izenelib::util::SCDDocPtr doc = (*it);
if(!doc)
{
std::cerr<<"scd parsing error"<<std::endl;
break;
}
std::vector<std::pair<izenelib::util::UString, izenelib::util::UString> >::iterator p;
for (p = doc->begin(); p != doc->end(); p++)
{
izenelib::util::UString property_name = p->first;
property_name.toLowerString();
if( property_name == izenelib::util::UString("docid", encoding) )
{
docid++;
if( max_doc>0 && docid > max_doc ) break;
if( docid % 1000 == 0 )
{
std::cout<<"Processing "<<docid<<std::endl;
}
}
else if( properties.find( property_name) != NULL)
{
kpe->insert( p->second, docid);
}
}
++it;
}
}
kpe->close();
std::ofstream ofs(exclude_file.c_str());
ofs<<std::endl;
for(uint32_t i=0;i<scdfile_list.size();i++)
{
boost::filesystem::path p(scdfile_list[i]);
ofs<<p.filename()<<std::endl;
}
ofs.close();
delete kpe;
delete analyzer;
boost::filesystem::remove_all(working_path);
return 0;
}
|
add exclude file.
|
add exclude file.
|
C++
|
apache-2.0
|
izenecloud/idmlib,pombredanne/idmlib,pombredanne/idmlib,izenecloud/idmlib,izenecloud/idmlib,pombredanne/idmlib,izenecloud/idmlib,izenecloud/idmlib,pombredanne/idmlib
|
9a8947d459ba9b5abd424010c11306190f6e4d4b
|
test/src/matchers/test_string_literal.cpp
|
test/src/matchers/test_string_literal.cpp
|
#include "tpunit++.hpp"
#include <mockitopp/mockitopp.hpp>
using mockitopp::mock_object;
using mockitopp::matcher::string_literal;
struct test_string_literal : tpunit::TestFixture
{
test_string_literal() : tpunit::TestFixture
(
TEST(test_string_literal::char_ptr),
TEST(test_string_literal::const_char_ptr)
)
{}
struct string_literal_test_interface
{
virtual int char_ptr(char*) = 0;
virtual int const_char_ptr(const char*) = 0;
};
void char_ptr()
{
mock_object<string_literal_test_interface> mock;
mock(&string_literal_test_interface::char_ptr).when(string_literal<char*>("FOO")).thenReturn(0);
mock(&string_literal_test_interface::char_ptr).when(string_literal<char*>("BAR")).thenReturn(1);
string_literal_test_interface& obj = mock.getInstance();
ASSERT_EQUAL(0, obj.char_ptr("FOO"));
ASSERT_EQUAL(1, obj.char_ptr("BAR"));
ASSERT_THROW(obj.char_ptr("NO MATCH"), mockitopp::partial_implementation_exception);
}
void const_char_ptr()
{
mock_object<string_literal_test_interface> mock;
mock(&string_literal_test_interface::const_char_ptr).when(string_literal<const char*>("1234567890")).thenReturn(0);
mock(&string_literal_test_interface::const_char_ptr).when(string_literal<const char*>("!@$#")).thenReturn(1);
string_literal_test_interface& obj = mock.getInstance();
ASSERT_EQUAL(0, obj.const_char_ptr("1234567890"));
ASSERT_EQUAL(1, obj.const_char_ptr("!@$#"));
ASSERT_THROW(obj.const_char_ptr("NO MATCH"), mockitopp::partial_implementation_exception);
}
} __test_string_literal;
|
#include "tpunit++.hpp"
#include <mockitopp/mockitopp.hpp>
using mockitopp::mock_object;
using mockitopp::matcher::string_literal;
struct test_string_literal : tpunit::TestFixture
{
test_string_literal() : tpunit::TestFixture
(
TEST(test_string_literal::char_ptr),
TEST(test_string_literal::const_char_ptr)
)
{}
struct string_literal_test_interface
{
virtual int char_ptr(char*) = 0;
virtual int const_char_ptr(const char*) = 0;
};
void char_ptr()
{
mock_object<string_literal_test_interface> mock;
mock(&string_literal_test_interface::char_ptr).when(string_literal<char*>(const_cast<char*>("FOO"))).thenReturn(0);
mock(&string_literal_test_interface::char_ptr).when(string_literal<char*>(const_cast<char*>("BAR"))).thenReturn(1);
string_literal_test_interface& obj = mock.getInstance();
ASSERT_EQUAL(0, obj.char_ptr(const_cast<char*>("FOO")));
ASSERT_EQUAL(1, obj.char_ptr(const_cast<char*>("BAR")));
ASSERT_THROW(obj.char_ptr(const_cast<char*>("NO MATCH")), mockitopp::partial_implementation_exception);
}
void const_char_ptr()
{
mock_object<string_literal_test_interface> mock;
mock(&string_literal_test_interface::const_char_ptr).when(string_literal<const char*>("1234567890")).thenReturn(0);
mock(&string_literal_test_interface::const_char_ptr).when(string_literal<const char*>("!@$#")).thenReturn(1);
string_literal_test_interface& obj = mock.getInstance();
ASSERT_EQUAL(0, obj.const_char_ptr("1234567890"));
ASSERT_EQUAL(1, obj.const_char_ptr("!@$#"));
ASSERT_THROW(obj.const_char_ptr("NO MATCH"), mockitopp::partial_implementation_exception);
}
} __test_string_literal;
|
Fix string literal warnings.
|
Fix string literal warnings.
Clang: -Wdeprecated-writable-strings
GCC: -Wwrite-strings
|
C++
|
mit
|
matthargett/mockitopp,tpounds/mockitopp,matthargett/mockitopp,tpounds/mockitopp
|
30e240cc91245b322075be90f883f822157eac8d
|
tools/tm.cc
|
tools/tm.cc
|
/* Simulator for deterministic Turing machines.
Based on the definition in Sipser's Introduction to the Theory of
Computation.
A state can be any integer. The start state is 0. Any negative
state is an accept state.
A symbol can be any string of non-whitespace characters. The blank
symbol is _.
Each line in the machine description specifies a transition:
q a r b d
where
- q is the current state
- a is the symbol read from the tape
- r is the new state
- b is the symbol written to the tape
- d is a direction: L (left), N (no move), or R (right)
The tape extends infinitely to the right, but not to the left.
Initially, characters are read from stdin, all the way to EOF, and
are encoded on the tape as 8-bit ASCII codes, most significant bit
first. The remainder of the tape is filled with blank symbols
(_). For example, "ABC" would be encoded as
010000010100001001000011___ ...
The head starts on the first square of the tape.
If the machine attempts to move the head to the left of the first
square, the head remains on the first square.
If the machine enters an accept state, the simulator exits with
status 0. If a move is not possible, the simulator exists with
status 1. In either case, the contents of the tape are written to
stdout, using the same encoding as described above. Symbols that
are neither 0 nor 1 are ignored, as are incomplete bytes.
*/
#include <iostream>
#include <fstream>
#include <sstream>
#include <map>
#include <string>
#include <vector>
#include <tuple>
#include <unistd.h>
using namespace std;
typedef int state_t;
typedef char symbol_t;
const symbol_t BLANK = '_';
const symbol_t ONE = '1';
const symbol_t ZERO = '0';
class parse_error: public std::runtime_error {
public:
parse_error(const std::string &message): runtime_error(message) { }
};
typedef std::tuple<state_t, symbol_t> condition;
typedef std::tuple<state_t, symbol_t, int> action;
class dtm {
std::map<condition, action> transitions;
public:
void add_transition(state_t q, symbol_t a, state_t r, symbol_t b, int d) {
if (transitions.count(make_tuple(q,a)) > 0)
throw std::runtime_error("machine is not deterministic at state " + to_string(q));
transitions.insert({make_tuple(q,a),make_tuple(r,b,d)});
}
bool find_transition(state_t q, symbol_t a, state_t &r, symbol_t &b, int &d) const {
auto it = transitions.find(make_tuple(q,a));
if (it != transitions.end()) {
std::tie(r, b, d) = it->second;
return true;
} else {
return false;
}
}
};
state_t convert_state(const string &s) {
size_t idx;
state_t q = stoi(s, &idx);
if (idx != s.size())
throw parse_error("invalid state: " + s);
return q;
}
symbol_t convert_symbol(const string &s) {
if (s.size() != 1)
throw parse_error("invalid symbol: " + s);
return s.at(0);
}
int convert_direction(const string &s) {
if (s == "L")
return -1;
else if (s == "N")
return 0;
else if (s == "R")
return 1;
else
throw parse_error("invalid direction: " + s);
}
void remove_comment(string &line) {
auto pos = line.find("//");
if (pos != string::npos)
line = line.substr(0, pos);
}
void split(const string &line, vector<string> &fields) {
istringstream iss(line);
string field;
fields.clear();
while (iss >> field)
fields.push_back(field);
}
void read_dtm(ifstream &is, dtm &m) {
string line;
while (getline(is, line)) {
remove_comment(line);
vector<string> fields;
split(line, fields);
if (fields.size() == 0)
continue;
try {
condition cond;
action act;
if (fields.size() != 5)
throw parse_error("could not read transition: " + line);
m.add_transition(convert_state(fields[0]), convert_symbol(fields[1]),
convert_state(fields[2]), convert_symbol(fields[3]),
convert_direction(fields[4]));
} catch (parse_error e) {
cerr << e.what() << endl;
exit(2);
}
}
}
bool run_dtm(const dtm &m, vector<symbol_t> &tape, int verbose=0) {
state_t q = 0;
vector<symbol_t>::size_type pos = 0, max_pos = 0;
bool accept;
long long int steps = 0;
while (true) {
while (pos+1 > tape.size())
tape.push_back(BLANK);
while (tape.back() == BLANK && tape.size() > pos+1)
tape.pop_back();
if (pos > max_pos)
max_pos = pos;
if (verbose >= 2) {
cerr << q << " | ";
for (vector<symbol_t>::size_type i=0; i<tape.size(); i++) {
if (i == pos)
cerr << "[" << tape[i] << "]";
else
cerr << tape[i];
}
cerr << endl;
}
if (q < 0) {
accept = true;
break;
}
int d;
if (!m.find_transition(q, tape[pos], q, tape[pos], d)) {
accept = false;
break;
}
if (d == 1)
++pos;
else if (d == -1 and pos > 0)
--pos;
++steps;
if (verbose == 1 && steps % 10000000 == 0) {
cerr << "running: steps=" << steps << " cells=" << max_pos+1 << endl;
}
}
if (verbose >= 1) {
cerr << "halt: accept=" << accept << " steps=" << steps << " cells=" << max_pos+1 << endl;
}
return accept;
}
void encode_tape(const string &s, vector<symbol_t> &tape) {
tape.clear();
for (auto c: s) {
for (int i=7; i>=0; i--)
tape.push_back(c & (1<<i) ? ONE : ZERO);
}
}
void decode_tape(const vector<symbol_t> &tape, string &s) {
s.clear();
char c = 0;
int k = 0;
for (const auto &a: tape) {
if (a == ONE) {
c = (c<<1) | 1;
k++;
} else if (a == ZERO) {
c = (c<<1) | 0;
k++;
}
if (k == 8) {
s.push_back(c);
c = 0;
k = 0;
}
}
}
void usage() {
cerr << "usage: tm [-n] [-v] <filename>\n";
exit(2);
}
int main(int argc, char *argv[]) {
int verbose = 0;
bool read_input = true;
int ch;
while ((ch = getopt(argc, argv, "nv")) != -1) {
switch (ch) {
case 'n':
read_input = false;
break;
case 'v':
verbose++;
break;
default:
usage();
}
}
argc -= optind;
argv += optind;
if (argc != 1) usage();
ifstream is(argv[0]);
dtm m;
if (!is) {
cerr << "could not open " << argv[0] << endl;
return 1;
}
read_dtm(is, m);
char c;
string s;
if (read_input)
while (cin.get(c))
s.push_back(c);
vector<symbol_t> tape;
encode_tape(s, tape);
if (run_dtm(m, tape, verbose)) {
decode_tape(tape, s);
cout << s;
return 0;
} else {
return 1;
}
}
|
/* Simulator for deterministic Turing machines.
Based on the definition in Sipser's Introduction to the Theory of
Computation.
A state can be any integer. The start state is 0. Any negative
state is an accept state.
A symbol can be any string of non-whitespace characters. The blank
symbol is _.
Each line in the machine description specifies a transition:
q a r b d
where
- q is the current state
- a is the symbol read from the tape
- r is the new state
- b is the symbol written to the tape
- d is a direction: L (left), N (no move), or R (right)
The tape extends infinitely to the right, but not to the left.
Initially, characters are read from stdin, all the way to EOF, and
are encoded on the tape as 8-bit ASCII codes, most significant bit
first. The remainder of the tape is filled with blank symbols
(_). For example, "ABC" would be encoded as
010000010100001001000011___ ...
The head starts on the first square of the tape.
If the machine attempts to move the head to the left of the first
square, the head remains on the first square.
If the machine enters an accept state, the simulator exits with
status 0. If a move is not possible, the simulator exists with
status 1. In either case, the contents of the tape are written to
stdout, using the same encoding as described above. Symbols that
are neither 0 nor 1 are ignored, as are incomplete bytes.
*/
#include <iostream>
#include <fstream>
#include <sstream>
#include <unordered_map>
#include <string>
#include <vector>
#include <tuple>
#include <unistd.h>
using namespace std;
typedef int state_t;
typedef char symbol_t;
const symbol_t BLANK = '_';
const symbol_t ONE = '1';
const symbol_t ZERO = '0';
class parse_error: public std::runtime_error {
public:
parse_error(const std::string &message): runtime_error(message) { }
};
typedef std::tuple<state_t, symbol_t> condition;
typedef std::tuple<state_t, symbol_t, int> action;
namespace std {
template<> struct hash<condition> {
std::size_t operator()(const condition &c) const {
return (std::get<0>(c) << 4) ^ std::get<1>(c);
}
};
}
class dtm {
std::unordered_map<condition, action> transitions;
public:
void add_transition(state_t q, symbol_t a, state_t r, symbol_t b, int d) {
if (transitions.count(make_tuple(q,a)) > 0)
throw std::runtime_error("machine is not deterministic at state " + to_string(q));
transitions.insert({make_tuple(q,a),make_tuple(r,b,d)});
}
bool find_transition(state_t q, symbol_t a, state_t &r, symbol_t &b, int &d) const {
auto it = transitions.find(make_tuple(q,a));
if (it != transitions.end()) {
std::tie(r, b, d) = it->second;
return true;
} else {
return false;
}
}
};
state_t convert_state(const string &s) {
size_t idx;
state_t q = stoi(s, &idx);
if (idx != s.size())
throw parse_error("invalid state: " + s);
return q;
}
symbol_t convert_symbol(const string &s) {
if (s.size() != 1)
throw parse_error("invalid symbol: " + s);
return s.at(0);
}
int convert_direction(const string &s) {
if (s == "L")
return -1;
else if (s == "N")
return 0;
else if (s == "R")
return 1;
else
throw parse_error("invalid direction: " + s);
}
void remove_comment(string &line) {
auto pos = line.find("//");
if (pos != string::npos)
line = line.substr(0, pos);
}
void split(const string &line, vector<string> &fields) {
istringstream iss(line);
string field;
fields.clear();
while (iss >> field)
fields.push_back(field);
}
void read_dtm(ifstream &is, dtm &m) {
string line;
while (getline(is, line)) {
remove_comment(line);
vector<string> fields;
split(line, fields);
if (fields.size() == 0)
continue;
try {
condition cond;
action act;
if (fields.size() != 5)
throw parse_error("could not read transition: " + line);
m.add_transition(convert_state(fields[0]), convert_symbol(fields[1]),
convert_state(fields[2]), convert_symbol(fields[3]),
convert_direction(fields[4]));
} catch (parse_error e) {
cerr << e.what() << endl;
exit(2);
}
}
}
bool run_dtm(const dtm &m, vector<symbol_t> &tape, int verbose=0) {
state_t q = 0;
vector<symbol_t>::size_type pos = 0, max_pos = 0;
bool accept;
long long int steps = 0;
while (true) {
while (pos+1 > tape.size())
tape.push_back(BLANK);
while (tape.back() == BLANK && tape.size() > pos+1)
tape.pop_back();
if (pos > max_pos)
max_pos = pos;
if (verbose >= 2) {
cerr << q << " | ";
for (vector<symbol_t>::size_type i=0; i<tape.size(); i++) {
if (i == pos)
cerr << "[" << tape[i] << "]";
else
cerr << tape[i];
}
cerr << endl;
}
if (q < 0) {
accept = true;
break;
}
int d;
if (!m.find_transition(q, tape[pos], q, tape[pos], d)) {
accept = false;
break;
}
if (d == 1)
++pos;
else if (d == -1 and pos > 0)
--pos;
++steps;
if (verbose == 1 && steps % 10000000 == 0) {
cerr << "running: steps=" << steps << " cells=" << max_pos+1 << endl;
}
}
if (verbose >= 1) {
cerr << "halt: accept=" << accept << " steps=" << steps << " cells=" << max_pos+1 << endl;
}
return accept;
}
void encode_tape(const string &s, vector<symbol_t> &tape) {
tape.clear();
for (auto c: s) {
for (int i=7; i>=0; i--)
tape.push_back(c & (1<<i) ? ONE : ZERO);
}
}
void decode_tape(const vector<symbol_t> &tape, string &s) {
s.clear();
char c = 0;
int k = 0;
for (const auto &a: tape) {
if (a == ONE) {
c = (c<<1) | 1;
k++;
} else if (a == ZERO) {
c = (c<<1) | 0;
k++;
}
if (k == 8) {
s.push_back(c);
c = 0;
k = 0;
}
}
}
void usage() {
cerr << "usage: tm [-n] [-v] <filename>\n";
exit(2);
}
int main(int argc, char *argv[]) {
int verbose = 0;
bool read_input = true;
int ch;
while ((ch = getopt(argc, argv, "nv")) != -1) {
switch (ch) {
case 'n':
read_input = false;
break;
case 'v':
verbose++;
break;
default:
usage();
}
}
argc -= optind;
argv += optind;
if (argc != 1) usage();
ifstream is(argv[0]);
dtm m;
if (!is) {
cerr << "could not open " << argv[0] << endl;
return 1;
}
read_dtm(is, m);
char c;
string s;
if (read_input)
while (cin.get(c))
s.push_back(c);
vector<symbol_t> tape;
encode_tape(s, tape);
if (run_dtm(m, tape, verbose)) {
decode_tape(tape, s);
cout << s;
return 0;
} else {
return 1;
}
}
|
speed up tm simulator a bit more
|
tm: speed up tm simulator a bit more
|
C++
|
mit
|
shinh/elvm,ND-CSE-30151/elvm,shinh/elvm,shinh/elvm,ND-CSE-30151/elvm,shinh/elvm,shinh/elvm,ND-CSE-30151/elvm,shinh/elvm,shinh/elvm,shinh/elvm
|
16eeedecb9594f9aaf0f9768a9d1c44b1acc1194
|
tests/test_queue.cc
|
tests/test_queue.cc
|
/*
* Copyright (C) 2015,2016,2017 deipi.com LLC and contributors. All rights reserved.
*
* 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 "test_queue.h"
#include "../src/queue.h"
#include "utils.h"
using namespace queue;
int test_unique() {
INIT_LOG
Queue<std::unique_ptr<std::string>> messages_queue;
messages_queue.push(std::make_unique<std::string>("This is a unique data"));
if (messages_queue.size() != 1) {
L_ERR(nullptr, "push is not working with unique_ptr.");
RETURN(1);
}
std::unique_ptr<std::string> msg;
if (!messages_queue.pop(msg)) {
L_ERR(nullptr, "pop is not working with unique_ptr.");
RETURN(1);
}
if (messages_queue.size() != 0) {
L_ERR(nullptr, "size is not working with unique_ptr.");
RETURN(1);
}
if (*msg != "This is a unique data") {
L_ERR(nullptr, "pop is changing memory with unique_ptr.");
RETURN(1);
}
RETURN(0);
}
int test_shared() {
INIT_LOG
Queue<std::shared_ptr<std::string>> messages_queue;
messages_queue.push(std::make_shared<std::string>("This is a shared data"));
if (messages_queue.size() != 1) {
L_ERR(nullptr, "push is not working with shared_ptr.");
RETURN(1);
}
std::shared_ptr<std::string> shared = messages_queue.front();
if (messages_queue.size() != 1) {
L_ERR(nullptr, "front is not working with shared_ptr.");
RETURN(1);
}
if (shared.use_count() != 2) {
L_ERR(nullptr, "Lose memory with shared_ptr.");
RETURN(1);
}
std::shared_ptr<std::string> msg;
if (!messages_queue.pop(msg)) {
L_ERR(nullptr, "pop is not working with shared_ptr.");
RETURN(1);
}
if (messages_queue.size() != 0) {
L_ERR(nullptr, "size is not working with shared_ptr.");
RETURN(1);
}
if (*msg != "This is a shared data") {
L_ERR(nullptr, "pop is changing memory with shared_ptr.");
RETURN(1);
}
RETURN(0);
}
int test_queue() {
INIT_LOG
Queue<int> q;
int val = 1;
q.push(val);
q.push(2);
q.push(3);
val = 4;
q.push(val);
if (q.size() != 4) {
L_ERR(nullptr, "push is not working with int.");
RETURN(1);
}
int i1, i2, i3, i4;
if (!q.pop(i1, 0) || !q.pop(i2, 0) || !q.pop(i3, 0) || !q.pop(i4, 0)) {
L_ERR(nullptr, "pop is not working with int.");
RETURN(1);
}
if (i1 != 1 || i2 != 2 || i3 != 3 || i4 != 4) {
L_ERR(nullptr, "pop is changing memory with int.");
RETURN(1);
}
RETURN(0);
}
int test_queue_set() {
INIT_LOG
QueueSet<int> q;
int val = 1;
q.push(val);
q.push(2);
val = 3;
q.push(val);
q.push(4);
q.push(1); // renew by default, doesn't insert a new item
if (q.size() != 4) {
L_ERR(nullptr, "QueueSet::push is not working.");
RETURN(1);
}
int i1, i2, i3, i4, i5 = 789;
if (!q.pop(i1, 0) || !q.pop(i2, 0) || !q.pop(i3, 0) || !q.pop(i4, 0) || q.pop(i5, 0)) {
L_ERR(nullptr, "QueueSet::pop is not working.");
RETURN(1);
}
if (i1 != 2 || i2 != 3 || i3 != 4 || i4 != 1 || i5 != 789) {
L_ERR(nullptr, "QueueSet::pop is changing memory.");
RETURN(1);
}
RETURN(0);
}
int test_queue_set_on_dup() {
INIT_LOG
QueueSet<int> q;
int val = 1;
q.push(val);
q.push(2);
q.push(3);
q.push(4);
q.push(1, [](int&){ return DupAction::leave; }); // doesn't touch the item
val = 2;
q.push(val, [](int&){ return DupAction::update; }); // updates the item inplace
q.push(3, [](int&){ return DupAction::renew; }); // renews the item
if (q.size() != 4) {
L_ERR(nullptr, "QueueSet::push with set_on_dup is not working.");
RETURN(1);
}
int i1, i2, i3, i4, i5 = 789;
if (!q.pop(i1, 0) || !q.pop(i2, 0) || !q.pop(i3, 0) || !q.pop(i4, 0) || q.pop(i5, 0)) {
L_ERR(nullptr, "QueueSet::pop with set_on_dup is not working.");
RETURN(1);
}
L_DEBUG(nullptr, "%d %d %d %d %d", i1, i2, i3, i4, i5);
if (i1 != 1 || i2 != 2 || i3 != 4 || i4 != 3 || i5 != 789) {
L_ERR(nullptr, "QueueSet::pop with set_on_dup is changing memory.");
RETURN(1);
}
RETURN(0);
}
int test_queue_constructor() {
INIT_LOG
std::pair<int, Queue<int>> foo = std::make_pair(1, Queue<int>());
foo.second.push(1);
foo.second.push(2);
foo.second.push(3);
int i1, i2, i3;
if (!foo.second.pop(i1, 0) || !foo.second.pop(i2, 0) || !foo.second.pop(i3, 0) || foo.second.size() != 0) {
L_ERR(nullptr, "QueueSet move constructor is not working.");
RETURN(1);
}
RETURN(0);
}
|
/*
* Copyright (C) 2015,2016,2017 deipi.com LLC and contributors. All rights reserved.
*
* 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 "test_queue.h"
#include "../src/queue.h"
#include "utils.h"
using namespace queue;
int test_unique() {
INIT_LOG
Queue<std::unique_ptr<std::string>> messages_queue;
messages_queue.push(std::make_unique<std::string>("This is a unique data"));
if (messages_queue.size() != 1) {
L_ERR(nullptr, "push is not working with unique_ptr.");
RETURN(1);
}
std::unique_ptr<std::string> msg;
if (!messages_queue.pop(msg)) {
L_ERR(nullptr, "pop is not working with unique_ptr.");
RETURN(1);
}
if (messages_queue.size() != 0) {
L_ERR(nullptr, "size is not working with unique_ptr.");
RETURN(1);
}
if (*msg != "This is a unique data") {
L_ERR(nullptr, "pop is changing memory with unique_ptr.");
RETURN(1);
}
RETURN(0);
}
int test_shared() {
INIT_LOG
Queue<std::shared_ptr<std::string>> messages_queue;
messages_queue.push(std::make_shared<std::string>("This is a shared data"));
if (messages_queue.size() != 1) {
L_ERR(nullptr, "push is not working with shared_ptr.");
RETURN(1);
}
std::shared_ptr<std::string> shared = messages_queue.front();
if (messages_queue.size() != 1) {
L_ERR(nullptr, "front is not working with shared_ptr.");
RETURN(1);
}
if (shared.use_count() != 2) {
L_ERR(nullptr, "Lose memory with shared_ptr.");
RETURN(1);
}
std::shared_ptr<std::string> msg;
if (!messages_queue.pop(msg)) {
L_ERR(nullptr, "pop is not working with shared_ptr.");
RETURN(1);
}
if (messages_queue.size() != 0) {
L_ERR(nullptr, "size is not working with shared_ptr.");
RETURN(1);
}
if (*msg != "This is a shared data") {
L_ERR(nullptr, "pop is changing memory with shared_ptr.");
RETURN(1);
}
RETURN(0);
}
int test_queue() {
INIT_LOG
Queue<int> q;
int val = 1;
q.push(val);
q.push(2);
q.push(3);
val = 4;
q.push(val);
if (q.size() != 4) {
L_ERR(nullptr, "push is not working with int.");
RETURN(1);
}
int i1, i2, i3, i4;
if (!q.pop(i1, 0) || !q.pop(i2, 0) || !q.pop(i3, 0) || !q.pop(i4, 0)) {
L_ERR(nullptr, "pop is not working with int.");
RETURN(1);
}
if (i1 != 1 || i2 != 2 || i3 != 3 || i4 != 4) {
L_ERR(nullptr, "pop is changing memory with int.");
RETURN(1);
}
RETURN(0);
}
int test_queue_set() {
INIT_LOG
QueueSet<int> q;
int val = 1;
q.push(val);
q.push(2);
val = 3;
q.push(val);
q.push(4);
q.push(1); // renew by default, doesn't insert a new item
if (q.size() != 4) {
L_ERR(nullptr, "QueueSet::push is not working.");
RETURN(1);
}
int i1, i2, i3, i4, i5 = 789;
if (!q.pop(i1, 0) || !q.pop(i2, 0) || !q.pop(i3, 0) || !q.pop(i4, 0) || q.pop(i5, 0)) {
L_ERR(nullptr, "QueueSet::pop is not working.");
RETURN(1);
}
if (i1 != 2 || i2 != 3 || i3 != 4 || i4 != 1 || i5 != 789) {
L_ERR(nullptr, "QueueSet::pop is changing memory.");
RETURN(1);
}
RETURN(0);
}
int test_queue_set_on_dup() {
INIT_LOG
QueueSet<int> q;
int val = 1;
q.push(val);
q.push(2);
q.push(3);
q.push(4);
q.push(1, [](int&){ return DupAction::leave; }); // doesn't touch the item
val = 2;
q.push(val, [](int&){ return DupAction::update; }); // updates the item inplace
q.push(3, [](int&){ return DupAction::renew; }); // renews the item
if (q.size() != 4) {
L_ERR(nullptr, "QueueSet::push with set_on_dup is not working.");
RETURN(1);
}
int i1, i2, i3, i4, i5 = 789;
if (!q.pop(i1, 0) || !q.pop(i2, 0) || !q.pop(i3, 0) || !q.pop(i4, 0) || q.pop(i5, 0)) {
L_ERR(nullptr, "QueueSet::pop with set_on_dup is not working.");
RETURN(1);
}
L_DEBUG(nullptr, "%d %d %d %d %d", i1, i2, i3, i4, i5);
if (i1 != 1 || i2 != 2 || i3 != 4 || i4 != 3 || i5 != 789) {
L_ERR(nullptr, "QueueSet::pop with set_on_dup is changing memory.");
RETURN(1);
}
RETURN(0);
}
int test_queue_constructor() {
INIT_LOG
Queue<int> queue;
queue.push(1);
queue.push(2);
queue.push(3);
int i1, i2, i3;
if (!queue.pop(i1, 0) || !queue.pop(i2, 0) || !queue.pop(i3, 0) || queue.size() != 0) {
L_ERR(nullptr, "Queue default constructor is not working.");
RETURN(1);
}
// Test move constructor.
Queue<int> q2(std::move(queue));
// Test move assigments.
q2 = Queue<int>();
RETURN(0);
}
|
Update tests in test_queue_constructor
|
Update tests in test_queue_constructor
|
C++
|
mit
|
Kronuz/Xapiand,Kronuz/Xapiand,Kronuz/Xapiand,Kronuz/Xapiand,Kronuz/Xapiand,Kronuz/Xapiand
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.