text stringlengths 54 60.6k |
|---|
<commit_before>#include "kernel.h"
#include "ilwisdata.h"
#include "coverage.h"
#include "symboltable.h"
#include "operationExpression.h"
#include "operationmetadata.h"
#include "commandhandler.h"
#include "operation.h"
#include "mastercatalog.h"
#include "uicontextmodel.h"
#include "drawers/draweroperation.h"
#include "drawers/drawerfactory.h"
#include "models/visualizationmanager.h"
#include "drawers/drawerinterface.h"
#include "../layerdrawer.h"
#include "adddrawer.h"
#include "../rootdrawer.h"
using namespace Ilwis;
using namespace Geodrawer;
REGISTER_OPERATION(AddDrawer)
AddDrawer::AddDrawer()
{
}
AddDrawer::~AddDrawer()
{
}
Ilwis::Geodrawer::AddDrawer::AddDrawer(quint64 metaid, const Ilwis::OperationExpression &expr) : DrawerOperation(metaid, expr)
{
}
bool AddDrawer::execute(ExecutionContext *ctx, SymbolTable &symTable)
{
if (_prepState == sNOTPREPARED)
if((_prepState = prepare(ctx,symTable)) != sPREPARED)
return false;
RootDrawer *rootdrawer = static_cast<RootDrawer *>(_rootDrawer);
Geodrawer::DrawerInterface *drawer;
if ( _coverage.isValid()) {
LayerDrawer *ldrawer = DrawerFactory::create<LayerDrawer>(_coverage->ilwisType(), rootdrawer, rootdrawer, IOOptions());
ldrawer->coverage(_coverage);
if ( rootdrawer->drawerCount(Geodrawer::ComplexDrawer::dtMAIN) == 0)
rootdrawer->coordinateSystem(_coverage->coordinateSystem());
rootdrawer->addSpatialDrawer(ldrawer,false);
QVariant var = qVariantFromValue((void *)ldrawer);
ctx->addOutput(symTable,var,"layerdrawer",_coverage->ilwisType(), Resource());
}else if ( _drawerCode != ""){
drawer = Geodrawer::DrawerFactory::create<>(_drawerCode, rootdrawer, rootdrawer, IOOptions());
rootdrawer->addDrawer(drawer,drawer->drawerType(),drawer->defaultOrder());
}
return true;
}
Ilwis::OperationImplementation *AddDrawer::create(quint64 metaid, const Ilwis::OperationExpression &expr)
{
return new AddDrawer(metaid, expr);
}
Ilwis::OperationImplementation::State AddDrawer::prepare(ExecutionContext *ctx, const SymbolTable &)
{
auto iter = ctx->_additionalInfo.find("rootdrawer");
if ( iter == ctx->_additionalInfo.end())
return sPREPAREFAILED;
if ( _expression.parameterCount() == 4){
QString url = _expression.input<QString>(2);
QString tpname = _expression.input<QString>(3);
IlwisTypes tp = IlwisObject::name2Type(tpname);
_coverage.prepare(url, tp);
if ( !_coverage.isValid())
return sPREPAREFAILED;
_coverage->loadData(); // loaddata now so that all attribute info( ranges) is known; we need to load the data anyway.
}else {
_drawerCode = _expression.input<QString>(1);
}
_rootDrawer = (DrawerInterface *) (*iter).second.value<void *>();
return sPREPARED;
}
quint64 AddDrawer::createMetadata()
{
OperationResource operation({"ilwis://operations/adddrawer"});
operation.setSyntax("adddrawer(viewid, drawername[,datasource, typename])");
operation.setDescription(TR("adds a new drawer to the layerview identified by viewid"));
operation.setInParameterCount({2,4});
operation.addInParameter(0,itINTEGER , TR("view id"),TR("id of the view to which this drawer has to be added"));
operation.addInParameter(1,itSTRING , TR("Drawer name/code"),TR("The name of the drawer or the type of drawer will be selected based on this parameter"));
operation.addInParameter(2,itSTRING , TR("Data source"),TR("The url that is used to retrieve the data for this layer"));
operation.addInParameter(3,itSTRING , TR("Data source typename"),TR("which data type is represented by this url"));
operation.setOutParameterCount({0});
operation.setKeywords("visualization");
mastercatalog()->addItems({operation});
return operation.id();
}
<commit_msg>added some guards<commit_after>#include "kernel.h"
#include "ilwisdata.h"
#include "coverage.h"
#include "symboltable.h"
#include "operationExpression.h"
#include "operationmetadata.h"
#include "commandhandler.h"
#include "operation.h"
#include "mastercatalog.h"
#include "uicontextmodel.h"
#include "drawers/draweroperation.h"
#include "drawers/drawerfactory.h"
#include "models/visualizationmanager.h"
#include "drawers/drawerinterface.h"
#include "../layerdrawer.h"
#include "adddrawer.h"
#include "../rootdrawer.h"
using namespace Ilwis;
using namespace Geodrawer;
REGISTER_OPERATION(AddDrawer)
AddDrawer::AddDrawer()
{
}
AddDrawer::~AddDrawer()
{
}
Ilwis::Geodrawer::AddDrawer::AddDrawer(quint64 metaid, const Ilwis::OperationExpression &expr) : DrawerOperation(metaid, expr)
{
}
bool AddDrawer::execute(ExecutionContext *ctx, SymbolTable &symTable)
{
if (_prepState == sNOTPREPARED)
if((_prepState = prepare(ctx,symTable)) != sPREPARED)
return false;
RootDrawer *rootdrawer = static_cast<RootDrawer *>(_rootDrawer);
Geodrawer::DrawerInterface *drawer;
if ( _coverage.isValid()) {
LayerDrawer *ldrawer = DrawerFactory::create<LayerDrawer>(_coverage->ilwisType(), rootdrawer, rootdrawer, IOOptions());
if ( !ldrawer){
return ERROR2(ERR_NO_INITIALIZED_2,"Drawer",_coverage->name());
}
ldrawer->coverage(_coverage);
if ( rootdrawer->drawerCount(Geodrawer::ComplexDrawer::dtMAIN) == 0)
rootdrawer->coordinateSystem(_coverage->coordinateSystem());
rootdrawer->addSpatialDrawer(ldrawer,false);
QVariant var = qVariantFromValue((void *)ldrawer);
ctx->addOutput(symTable,var,"layerdrawer",_coverage->ilwisType(), Resource());
}else if ( _drawerCode != ""){
drawer = Geodrawer::DrawerFactory::create<>(_drawerCode, rootdrawer, rootdrawer, IOOptions());
rootdrawer->addDrawer(drawer,drawer->drawerType(),drawer->defaultOrder());
}
return true;
}
Ilwis::OperationImplementation *AddDrawer::create(quint64 metaid, const Ilwis::OperationExpression &expr)
{
return new AddDrawer(metaid, expr);
}
Ilwis::OperationImplementation::State AddDrawer::prepare(ExecutionContext *ctx, const SymbolTable &)
{
auto iter = ctx->_additionalInfo.find("rootdrawer");
if ( iter == ctx->_additionalInfo.end())
return sPREPAREFAILED;
if ( _expression.parameterCount() == 4){
QString url = _expression.input<QString>(2);
QString tpname = _expression.input<QString>(3);
IlwisTypes tp = IlwisObject::name2Type(tpname);
if ( !hasType(tp , itCOVERAGE)){
ERROR2(ERR_ILLEGAL_VALUE_2,TR("dataype for layer drawer"), tpname) ;
return sPREPAREFAILED;
}
_coverage.prepare(url, tp);
if ( !_coverage.isValid()){
kernel()->issues()->log(QString("Could not open as %1, %2").arg(tpname).arg(url));
return sPREPAREFAILED;
}
_coverage->loadData();
}else {
_drawerCode = _expression.input<QString>(1);
}
_rootDrawer = (DrawerInterface *) (*iter).second.value<void *>();
return sPREPARED;
}
quint64 AddDrawer::createMetadata()
{
OperationResource operation({"ilwis://operations/adddrawer"});
operation.setSyntax("adddrawer(viewid, drawername[,datasource, typename])");
operation.setDescription(TR("adds a new drawer to the layerview identified by viewid"));
operation.setInParameterCount({2,4});
operation.addInParameter(0,itINTEGER , TR("view id"),TR("id of the view to which this drawer has to be added"));
operation.addInParameter(1,itSTRING , TR("Drawer name/code"),TR("The name of the drawer or the type of drawer will be selected based on this parameter"));
operation.addInParameter(2,itSTRING , TR("Data source"),TR("The url that is used to retrieve the data for this layer"));
operation.addInParameter(3,itSTRING , TR("Data source typename"),TR("which data type is represented by this url"));
operation.setOutParameterCount({0});
operation.setKeywords("visualization");
mastercatalog()->addItems({operation});
return operation.id();
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <fstream>
#include "Matrix.h"
using namespace std;
#define DW(__instruction) cout << #__instruction << "==" << (__instruction) << endl;
Matrix loadMatrixFromFile(const char* filename)
{
ifstream stream;
stream.open(filename, ifstream::in);
if(stream.good())
{
Matrix m(stream);
return m;
}
else
{
cout << "Nie udalo sie zaladowac macierzy";
throw "File Error";
}
}
int main()
{
try
{
Matrix m1 = loadMatrixFromFile("matrix1.txt");
Matrix m2 = loadMatrixFromFile("matrix2.txt");
Matrix m3 = loadMatrixFromFile("matrix3.txt");
Matrix m4 = loadMatrixFromFile("matrix4.txt");
cout << "---------------------Wczytano 4 macierze:\n" << m1 << m2 << m3 << m4;
cout << "\n\n\n---------------------Wykonywanie dodwania macierzy 1 i 2:\n";
DW(m1+m2);
DW(m1);
DW(m2);
DW(m1+=m2);
DW(m1);
DW(m2);
cout << "\n\n\n---------------------Wykonywanie odejmowania macierzy 1 i 2:\n";
DW(m1-m2);
DW(m1);
DW(m2);
DW(m1-=m2);
DW(m1);
DW(m2);
cout << "\n\n\n---------------------Wykonywanie mnozenia macierzy 1 i 3:\n";
DW(m1*m3);
DW(m1);
DW(m3);
DW(m1*=m3);
DW(m1);
DW(m3);
cout << "\n\n\n---------------------Test operatora przypisania i porownania:\n";
cout << m3 << m4;
DW(m3=m4);
cout << m3 << m4;
DW(m3==m4);
DW(m3!=m4);
DW(m1==m4);
DW(m2==m2);
cout << "\n\n\n---------------------Dostep do pojedynczego elementu:\n";
DW(m3(0, 0));
DW(m3(2, 1));
DW(m3(1, 2));
cout << "\n\n\n---------------------Rozroznanie pomiedzy operacja zapisu a odczytu - do sprawdzenia potrzebny debugger:\n";
m3(0, 0) = 5;
if(m3(0, 0) == 5)
{
m3(1, 1) = m3(0, 0);
}
cout << "\n\n\nZle wyrazenia:\n";
//DW(m3(1, 3)); //out of range
//DW(m4*m2); //zle wymiary do mnozenia
//DW(m4*=m2); //zle wymiary do mnozenia
//DW(m1+m3); //zle wymiary do dodawania
//DW(m1-m2); //zle wymiary do odejmowania
//DW(m1*=m2); //zle wymiary do mnozenia
//DW(m1+=m3); //zle wymiary do dodawania
//DW(m1-=m2); //zle wymiary do odejmowania
}
catch (string exception)
{
cout << exception;
}
catch (Exception e)
{
cout << e.name;
}
return 0;
}<commit_msg>Bugfix<commit_after>#include <iostream>
#include <fstream>
#include "Matrix.h"
using namespace std;
#define DW(__instruction) cout << #__instruction << "==" << (__instruction) << endl;
Matrix loadMatrixFromFile(const char* filename)
{
ifstream stream;
stream.open(filename, ifstream::in);
if(stream.good())
{
Matrix m(stream);
stream.close();
return m;
}
else
{
cout << "Nie udalo sie zaladowac macierzy";
throw "File Error";
}
}
int main()
{
try
{
Matrix m1 = loadMatrixFromFile("matrix1.txt");
Matrix m2 = loadMatrixFromFile("matrix2.txt");
Matrix m3 = loadMatrixFromFile("matrix3.txt");
Matrix m4 = loadMatrixFromFile("matrix4.txt");
cout << "---------------------Wczytano 4 macierze:\n" << m1 << m2 << m3 << m4;
cout << "\n\n\n---------------------Wykonywanie dodwania macierzy 1 i 2:\n";
DW(m1+m2);
DW(m1);
DW(m2);
DW(m1+=m2);
DW(m1);
DW(m2);
cout << "\n\n\n---------------------Wykonywanie odejmowania macierzy 1 i 2:\n";
DW(m1-m2);
DW(m1);
DW(m2);
DW(m1-=m2);
DW(m1);
DW(m2);
cout << "\n\n\n---------------------Wykonywanie mnozenia macierzy 1 i 3:\n";
DW(m1*m3);
DW(m1);
DW(m3);
DW(m1*=m3);
DW(m1);
DW(m3);
cout << "\n\n\n---------------------Test operatora przypisania i porownania:\n";
cout << m3 << m4;
DW(m3=m4);
cout << m3 << m4;
DW(m3==m4);
DW(m3!=m4);
DW(m1==m4);
DW(m2==m2);
cout << "\n\n\n---------------------Dostep do pojedynczego elementu:\n";
DW(m3(0, 0));
DW(m3(2, 1));
DW(m3(1, 2));
cout << "\n\n\n---------------------Rozroznanie pomiedzy operacja zapisu a odczytu - do sprawdzenia potrzebny debugger:\n";
m3(0, 0) = 5;
if(m3(0, 0) == 5)
{
m3(1, 1) = m3(0, 0);
}
cout << "\n\n\nZle wyrazenia:\n";
//DW(m3(1, 3)); //out of range
//DW(m4*m2); //zle wymiary do mnozenia
//DW(m4*=m2); //zle wymiary do mnozenia
//DW(m1+m3); //zle wymiary do dodawania
//DW(m1-m2); //zle wymiary do odejmowania
//DW(m1*=m2); //zle wymiary do mnozenia
//DW(m1+=m3); //zle wymiary do dodawania
//DW(m1-=m2); //zle wymiary do odejmowania
}
catch (string exception)
{
cout << exception;
}
catch (Exception e)
{
cout << e.name;
}
return 0;
}<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* 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/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include "showcols.hxx"
#include "fmsearch.hrc"
#include <tools/shl.hxx>
#include <dialmgr.hxx>
#include <vcl/msgbox.hxx>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <comphelper/extract.hxx>
#include <comphelper/types.hxx>
#define CUIFM_PROP_HIDDEN rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Hidden" ) )
#define CUIFM_PROP_LABEL rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Label" ) )
//==========================================================================
// FmShowColsDialog
//==========================================================================
DBG_NAME(FmShowColsDialog)
//--------------------------------------------------------------------------
FmShowColsDialog::FmShowColsDialog(Window* pParent)
:ModalDialog(pParent, CUI_RES(RID_SVX_DLG_SHOWGRIDCOLUMNS))
,m_aList(this, CUI_RES(1))
,m_aLabel(this, CUI_RES(1))
,m_aOK(this, CUI_RES(1))
,m_aCancel(this, CUI_RES(1))
{
DBG_CTOR(FmShowColsDialog,NULL);
m_aList.EnableMultiSelection(sal_True);
m_aOK.SetClickHdl( LINK( this, FmShowColsDialog, OnClickedOk ) );
FreeResource();
}
//--------------------------------------------------------------------------
FmShowColsDialog::~FmShowColsDialog()
{
DBG_DTOR(FmShowColsDialog,NULL);
}
//--------------------------------------------------------------------------
IMPL_LINK_NOARG(FmShowColsDialog, OnClickedOk)
{
DBG_ASSERT(m_xColumns.is(), "FmShowColsDialog::OnClickedOk : you should call SetColumns before executing the dialog !");
if (m_xColumns.is())
{
::com::sun::star::uno::Any aCol;
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > xCol;
for (sal_uInt16 i=0; i<m_aList.GetSelectEntryCount(); ++i)
{
m_xColumns->getByIndex(sal::static_int_cast<sal_Int32>(reinterpret_cast<sal_uIntPtr>(m_aList.GetEntryData(m_aList.GetSelectEntryPos(i))))) >>= xCol;
if (xCol.is())
{
try
{
xCol->setPropertyValue(CUIFM_PROP_HIDDEN, ::cppu::bool2any(sal_False));
}
catch(...)
{
OSL_FAIL("FmShowColsDialog::OnClickedOk Exception occurred!");
}
}
}
}
EndDialog(RET_OK);
return 0L;
}
//--------------------------------------------------------------------------
void FmShowColsDialog::SetColumns(const ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexContainer>& xCols)
{
DBG_ASSERT(xCols.is(), "FmShowColsDialog::SetColumns : invalid columns !");
if (!xCols.is())
return;
m_xColumns = xCols.get();
m_aList.Clear();
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet> xCurCol;
String sCurName;
for (sal_uInt16 i=0; i<xCols->getCount(); ++i)
{
sCurName.Erase();
::cppu::extractInterface(xCurCol, xCols->getByIndex(i));
sal_Bool bIsHidden = sal_False;
try
{
::com::sun::star::uno::Any aHidden = xCurCol->getPropertyValue(CUIFM_PROP_HIDDEN);
bIsHidden = ::comphelper::getBOOL(aHidden);
::rtl::OUString sName;
xCurCol->getPropertyValue(CUIFM_PROP_LABEL) >>= sName;
sCurName = sName;
}
catch(...)
{
OSL_FAIL("FmShowColsDialog::SetColumns Exception occurred!");
}
// if the col is hidden, put it into the list
if (bIsHidden)
m_aList.SetEntryData( m_aList.InsertEntry(sCurName), reinterpret_cast<void*>((sal_Int64)i) );
}
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>cui: kill RTL_CONSTASCII_USTRINGPARAM in macros<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* 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/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include "showcols.hxx"
#include "fmsearch.hrc"
#include <tools/shl.hxx>
#include <dialmgr.hxx>
#include <vcl/msgbox.hxx>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <comphelper/extract.hxx>
#include <comphelper/types.hxx>
#define CUIFM_PROP_HIDDEN "Hidden"
#define CUIFM_PROP_LABEL "Label"
//==========================================================================
// FmShowColsDialog
//==========================================================================
DBG_NAME(FmShowColsDialog)
//--------------------------------------------------------------------------
FmShowColsDialog::FmShowColsDialog(Window* pParent)
:ModalDialog(pParent, CUI_RES(RID_SVX_DLG_SHOWGRIDCOLUMNS))
,m_aList(this, CUI_RES(1))
,m_aLabel(this, CUI_RES(1))
,m_aOK(this, CUI_RES(1))
,m_aCancel(this, CUI_RES(1))
{
DBG_CTOR(FmShowColsDialog,NULL);
m_aList.EnableMultiSelection(sal_True);
m_aOK.SetClickHdl( LINK( this, FmShowColsDialog, OnClickedOk ) );
FreeResource();
}
//--------------------------------------------------------------------------
FmShowColsDialog::~FmShowColsDialog()
{
DBG_DTOR(FmShowColsDialog,NULL);
}
//--------------------------------------------------------------------------
IMPL_LINK_NOARG(FmShowColsDialog, OnClickedOk)
{
DBG_ASSERT(m_xColumns.is(), "FmShowColsDialog::OnClickedOk : you should call SetColumns before executing the dialog !");
if (m_xColumns.is())
{
::com::sun::star::uno::Any aCol;
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > xCol;
for (sal_uInt16 i=0; i<m_aList.GetSelectEntryCount(); ++i)
{
m_xColumns->getByIndex(sal::static_int_cast<sal_Int32>(reinterpret_cast<sal_uIntPtr>(m_aList.GetEntryData(m_aList.GetSelectEntryPos(i))))) >>= xCol;
if (xCol.is())
{
try
{
xCol->setPropertyValue(CUIFM_PROP_HIDDEN, ::cppu::bool2any(sal_False));
}
catch(...)
{
OSL_FAIL("FmShowColsDialog::OnClickedOk Exception occurred!");
}
}
}
}
EndDialog(RET_OK);
return 0L;
}
//--------------------------------------------------------------------------
void FmShowColsDialog::SetColumns(const ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexContainer>& xCols)
{
DBG_ASSERT(xCols.is(), "FmShowColsDialog::SetColumns : invalid columns !");
if (!xCols.is())
return;
m_xColumns = xCols.get();
m_aList.Clear();
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet> xCurCol;
String sCurName;
for (sal_uInt16 i=0; i<xCols->getCount(); ++i)
{
sCurName.Erase();
::cppu::extractInterface(xCurCol, xCols->getByIndex(i));
sal_Bool bIsHidden = sal_False;
try
{
::com::sun::star::uno::Any aHidden = xCurCol->getPropertyValue(CUIFM_PROP_HIDDEN);
bIsHidden = ::comphelper::getBOOL(aHidden);
::rtl::OUString sName;
xCurCol->getPropertyValue(CUIFM_PROP_LABEL) >>= sName;
sCurName = sName;
}
catch(...)
{
OSL_FAIL("FmShowColsDialog::SetColumns Exception occurred!");
}
// if the col is hidden, put it into the list
if (bIsHidden)
m_aList.SetEntryData( m_aList.InsertEntry(sCurName), reinterpret_cast<void*>((sal_Int64)i) );
}
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>/***************************************************************************
copyright : (C) 2002 - 2008 by Scott Wheeler
email : wheeler@kde.org
***************************************************************************/
/***************************************************************************
* This library is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License version *
* 2.1 as published by the Free Software Foundation. *
* *
* 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 *
* *
* Alternatively, this file is available under the Mozilla Public *
* License Version 1.1. You may obtain a copy of the License at *
* http://www.mozilla.org/MPL/ *
***************************************************************************/
#include <tbytevectorlist.h>
#include <tmap.h>
#include <tstring.h>
#include <tdebug.h>
#include "oggfile.h"
#include "oggpage.h"
#include "oggpageheader.h"
using namespace TagLib;
namespace
{
// Returns the first packet index of the right next page to the given one.
unsigned int nextPacketIndex(const Ogg::Page *page)
{
if(page->header()->lastPacketCompleted())
return page->firstPacketIndex() + page->packetCount();
else
return page->firstPacketIndex() + page->packetCount() - 1;
}
}
class Ogg::File::FilePrivate
{
public:
FilePrivate() :
firstPageHeader(0),
lastPageHeader(0)
{
pages.setAutoDelete(true);
}
~FilePrivate()
{
delete firstPageHeader;
delete lastPageHeader;
}
unsigned int streamSerialNumber;
List<Page *> pages;
PageHeader *firstPageHeader;
PageHeader *lastPageHeader;
Map<unsigned int, ByteVector> dirtyPackets;
};
////////////////////////////////////////////////////////////////////////////////
// public members
////////////////////////////////////////////////////////////////////////////////
Ogg::File::~File()
{
delete d;
}
ByteVector Ogg::File::packet(unsigned int i)
{
// Check to see if we're called setPacket() for this packet since the last
// save:
if(d->dirtyPackets.contains(i))
return d->dirtyPackets[i];
// If we haven't indexed the page where the packet we're interested in starts,
// begin reading pages until we have.
if(!readPages(i)) {
debug("Ogg::File::packet() -- Could not find the requested packet.");
return ByteVector();
}
// Look for the first page in which the requested packet starts.
List<Page *>::ConstIterator it = d->pages.begin();
while((*it)->containsPacket(i) == Page::DoesNotContainPacket)
++it;
// If the packet is completely contained in the first page that it's in.
// If the packet is *not* completely contained in the first page that it's a
// part of then that packet trails off the end of the page. Continue appending
// the pages' packet data until we hit a page that either does not end with the
// packet that we're fetching or where the last packet is complete.
ByteVector packet = (*it)->packets()[i - (*it)->firstPacketIndex()];
while(nextPacketIndex(*it) <= i) {
++it;
packet.append((*it)->packets().front());
}
return packet;
}
void Ogg::File::setPacket(unsigned int i, const ByteVector &p)
{
if(!readPages(i)) {
debug("Ogg::File::setPacket() -- Could not set the requested packet.");
return;
}
d->dirtyPackets[i] = p;
}
const Ogg::PageHeader *Ogg::File::firstPageHeader()
{
if(!d->firstPageHeader) {
const long firstPageHeaderOffset = find("OggS");
if(firstPageHeaderOffset < 0)
return 0;
d->firstPageHeader = new PageHeader(this, firstPageHeaderOffset);
}
return d->firstPageHeader->isValid() ? d->firstPageHeader : 0;
}
const Ogg::PageHeader *Ogg::File::lastPageHeader()
{
if(!d->lastPageHeader) {
const long lastPageHeaderOffset = rfind("OggS");
if(lastPageHeaderOffset < 0)
return 0;
d->lastPageHeader = new PageHeader(this, lastPageHeaderOffset);
}
return d->lastPageHeader->isValid() ? d->lastPageHeader : 0;
}
bool Ogg::File::save()
{
if(readOnly()) {
debug("Ogg::File::save() - Cannot save to a read only file.");
return false;
}
Map<unsigned int, ByteVector>::ConstIterator it;
for(it = d->dirtyPackets.begin(); it != d->dirtyPackets.end(); ++it)
writePacket(it->first, it->second);
d->dirtyPackets.clear();
return true;
}
////////////////////////////////////////////////////////////////////////////////
// protected members
////////////////////////////////////////////////////////////////////////////////
Ogg::File::File(FileName file) :
TagLib::File(file),
d(new FilePrivate())
{
}
Ogg::File::File(IOStream *stream) :
TagLib::File(stream),
d(new FilePrivate())
{
}
////////////////////////////////////////////////////////////////////////////////
// private members
////////////////////////////////////////////////////////////////////////////////
bool Ogg::File::readPages(unsigned int i)
{
while(true) {
unsigned int packetIndex;
long offset;
if(d->pages.isEmpty()) {
packetIndex = 0;
offset = find("OggS");
if(offset < 0)
return false;
}
else {
const Page *page = d->pages.back();
packetIndex = nextPacketIndex(page);
offset = page->fileOffset() + page->size();
}
// Enough pages have been fetched.
if(packetIndex > i)
return true;
// Read the next page and add it to the page list.
Page *nextPage = new Page(this, offset);
if(!nextPage->header()->isValid()) {
delete nextPage;
return false;
}
nextPage->setFirstPacketIndex(packetIndex);
d->pages.append(nextPage);
if(nextPage->header()->lastPageOfStream())
return false;
}
}
void Ogg::File::writePacket(unsigned int i, const ByteVector &packet)
{
if(!readPages(i)) {
debug("Ogg::File::writePacket() -- Could not find the requested packet.");
return;
}
// Look for the pages where the requested packet should belong to.
List<Page *>::ConstIterator it = d->pages.begin();
while((*it)->containsPacket(i) == Page::DoesNotContainPacket)
++it;
const Page *firstPage = *it;
while(nextPacketIndex(*it) <= i)
++it;
const Page *lastPage = *it;
// Replace the requested packet and create new pages to replace the located pages.
ByteVectorList packets = firstPage->packets();
packets[i - firstPage->firstPacketIndex()] = packet;
if(firstPage != lastPage && lastPage->packetCount() > 2) {
ByteVectorList lastPagePackets = lastPage->packets();
lastPagePackets.erase(lastPagePackets.begin());
packets.append(lastPagePackets);
}
// TODO: This pagination method isn't accurate for what's being done here.
// This should account for real possibilities like non-aligned packets and such.
List<Page *> pages = Page::paginate(packets,
Page::SinglePagePerGroup,
firstPage->header()->streamSerialNumber(),
firstPage->pageSequenceNumber(),
firstPage->header()->firstPacketContinued(),
lastPage->header()->lastPacketCompleted());
pages.setAutoDelete(true);
// Write the pages.
ByteVector data;
for(it = pages.begin(); it != pages.end(); ++it)
data.append((*it)->render());
const unsigned long originalOffset = firstPage->fileOffset();
const unsigned long originalLength = lastPage->fileOffset() + lastPage->size() - originalOffset;
insert(data, originalOffset, originalLength);
// Renumber the following pages if the pages have been split or merged.
const int numberOfNewPages
= pages.back()->pageSequenceNumber() - lastPage->pageSequenceNumber();
if(numberOfNewPages != 0) {
long pageOffset = originalOffset + data.size();
while(true) {
Page page(this, pageOffset);
if(!page.header()->isValid())
break;
page.setPageSequenceNumber(page.pageSequenceNumber() + numberOfNewPages);
const ByteVector data = page.render();
seek(pageOffset + 18);
writeBlock(data.mid(18, 8));
if(page.header()->lastPageOfStream())
break;
pageOffset += page.size();
}
}
// Discard all the pages to keep them up-to-date by fetching them again.
d->pages.clear();
}
<commit_msg>Fix possible Ogg packet losses.<commit_after>/***************************************************************************
copyright : (C) 2002 - 2008 by Scott Wheeler
email : wheeler@kde.org
***************************************************************************/
/***************************************************************************
* This library is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License version *
* 2.1 as published by the Free Software Foundation. *
* *
* 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 *
* *
* Alternatively, this file is available under the Mozilla Public *
* License Version 1.1. You may obtain a copy of the License at *
* http://www.mozilla.org/MPL/ *
***************************************************************************/
#include <tbytevectorlist.h>
#include <tmap.h>
#include <tstring.h>
#include <tdebug.h>
#include "oggfile.h"
#include "oggpage.h"
#include "oggpageheader.h"
using namespace TagLib;
namespace
{
// Returns the first packet index of the right next page to the given one.
unsigned int nextPacketIndex(const Ogg::Page *page)
{
if(page->header()->lastPacketCompleted())
return page->firstPacketIndex() + page->packetCount();
else
return page->firstPacketIndex() + page->packetCount() - 1;
}
}
class Ogg::File::FilePrivate
{
public:
FilePrivate() :
firstPageHeader(0),
lastPageHeader(0)
{
pages.setAutoDelete(true);
}
~FilePrivate()
{
delete firstPageHeader;
delete lastPageHeader;
}
unsigned int streamSerialNumber;
List<Page *> pages;
PageHeader *firstPageHeader;
PageHeader *lastPageHeader;
Map<unsigned int, ByteVector> dirtyPackets;
};
////////////////////////////////////////////////////////////////////////////////
// public members
////////////////////////////////////////////////////////////////////////////////
Ogg::File::~File()
{
delete d;
}
ByteVector Ogg::File::packet(unsigned int i)
{
// Check to see if we're called setPacket() for this packet since the last
// save:
if(d->dirtyPackets.contains(i))
return d->dirtyPackets[i];
// If we haven't indexed the page where the packet we're interested in starts,
// begin reading pages until we have.
if(!readPages(i)) {
debug("Ogg::File::packet() -- Could not find the requested packet.");
return ByteVector();
}
// Look for the first page in which the requested packet starts.
List<Page *>::ConstIterator it = d->pages.begin();
while((*it)->containsPacket(i) == Page::DoesNotContainPacket)
++it;
// If the packet is completely contained in the first page that it's in.
// If the packet is *not* completely contained in the first page that it's a
// part of then that packet trails off the end of the page. Continue appending
// the pages' packet data until we hit a page that either does not end with the
// packet that we're fetching or where the last packet is complete.
ByteVector packet = (*it)->packets()[i - (*it)->firstPacketIndex()];
while(nextPacketIndex(*it) <= i) {
++it;
packet.append((*it)->packets().front());
}
return packet;
}
void Ogg::File::setPacket(unsigned int i, const ByteVector &p)
{
if(!readPages(i)) {
debug("Ogg::File::setPacket() -- Could not set the requested packet.");
return;
}
d->dirtyPackets[i] = p;
}
const Ogg::PageHeader *Ogg::File::firstPageHeader()
{
if(!d->firstPageHeader) {
const long firstPageHeaderOffset = find("OggS");
if(firstPageHeaderOffset < 0)
return 0;
d->firstPageHeader = new PageHeader(this, firstPageHeaderOffset);
}
return d->firstPageHeader->isValid() ? d->firstPageHeader : 0;
}
const Ogg::PageHeader *Ogg::File::lastPageHeader()
{
if(!d->lastPageHeader) {
const long lastPageHeaderOffset = rfind("OggS");
if(lastPageHeaderOffset < 0)
return 0;
d->lastPageHeader = new PageHeader(this, lastPageHeaderOffset);
}
return d->lastPageHeader->isValid() ? d->lastPageHeader : 0;
}
bool Ogg::File::save()
{
if(readOnly()) {
debug("Ogg::File::save() - Cannot save to a read only file.");
return false;
}
Map<unsigned int, ByteVector>::ConstIterator it;
for(it = d->dirtyPackets.begin(); it != d->dirtyPackets.end(); ++it)
writePacket(it->first, it->second);
d->dirtyPackets.clear();
return true;
}
////////////////////////////////////////////////////////////////////////////////
// protected members
////////////////////////////////////////////////////////////////////////////////
Ogg::File::File(FileName file) :
TagLib::File(file),
d(new FilePrivate())
{
}
Ogg::File::File(IOStream *stream) :
TagLib::File(stream),
d(new FilePrivate())
{
}
////////////////////////////////////////////////////////////////////////////////
// private members
////////////////////////////////////////////////////////////////////////////////
bool Ogg::File::readPages(unsigned int i)
{
while(true) {
unsigned int packetIndex;
long offset;
if(d->pages.isEmpty()) {
packetIndex = 0;
offset = find("OggS");
if(offset < 0)
return false;
}
else {
const Page *page = d->pages.back();
packetIndex = nextPacketIndex(page);
offset = page->fileOffset() + page->size();
}
// Enough pages have been fetched.
if(packetIndex > i)
return true;
// Read the next page and add it to the page list.
Page *nextPage = new Page(this, offset);
if(!nextPage->header()->isValid()) {
delete nextPage;
return false;
}
nextPage->setFirstPacketIndex(packetIndex);
d->pages.append(nextPage);
if(nextPage->header()->lastPageOfStream())
return false;
}
}
void Ogg::File::writePacket(unsigned int i, const ByteVector &packet)
{
if(!readPages(i)) {
debug("Ogg::File::writePacket() -- Could not find the requested packet.");
return;
}
// Look for the pages where the requested packet should belong to.
List<Page *>::ConstIterator it = d->pages.begin();
while((*it)->containsPacket(i) == Page::DoesNotContainPacket)
++it;
const Page *firstPage = *it;
while(nextPacketIndex(*it) <= i)
++it;
const Page *lastPage = *it;
// Replace the requested packet and create new pages to replace the located pages.
ByteVectorList packets = firstPage->packets();
packets[i - firstPage->firstPacketIndex()] = packet;
if(firstPage != lastPage && lastPage->packetCount() > 1) {
ByteVectorList lastPagePackets = lastPage->packets();
lastPagePackets.erase(lastPagePackets.begin());
packets.append(lastPagePackets);
}
// TODO: This pagination method isn't accurate for what's being done here.
// This should account for real possibilities like non-aligned packets and such.
List<Page *> pages = Page::paginate(packets,
Page::SinglePagePerGroup,
firstPage->header()->streamSerialNumber(),
firstPage->pageSequenceNumber(),
firstPage->header()->firstPacketContinued(),
lastPage->header()->lastPacketCompleted());
pages.setAutoDelete(true);
// Write the pages.
ByteVector data;
for(it = pages.begin(); it != pages.end(); ++it)
data.append((*it)->render());
const unsigned long originalOffset = firstPage->fileOffset();
const unsigned long originalLength = lastPage->fileOffset() + lastPage->size() - originalOffset;
insert(data, originalOffset, originalLength);
// Renumber the following pages if the pages have been split or merged.
const int numberOfNewPages
= pages.back()->pageSequenceNumber() - lastPage->pageSequenceNumber();
if(numberOfNewPages != 0) {
long pageOffset = originalOffset + data.size();
while(true) {
Page page(this, pageOffset);
if(!page.header()->isValid())
break;
page.setPageSequenceNumber(page.pageSequenceNumber() + numberOfNewPages);
const ByteVector data = page.render();
seek(pageOffset + 18);
writeBlock(data.mid(18, 8));
if(page.header()->lastPageOfStream())
break;
pageOffset += page.size();
}
}
// Discard all the pages to keep them up-to-date by fetching them again.
d->pages.clear();
}
<|endoftext|> |
<commit_before>#include <shogun/lib/config.h>
#include <shogun/mathematics/Random.h>
#include <shogun/mathematics/Math.h>
#include <shogun/lib/SGVector.h>
#include <gtest/gtest.h>
#include <stdio.h>
using namespace shogun;
const uint32_t n_runs=1200000;
const uint32_t array_len=23;
/**
* NOTE: these unit tests were generated with MEXP=19937
* with other exponents it is expected to fail!
*/
TEST(Random, uint32_t)
{
CRandom* prng = new CRandom();
uint32_t r = prng->random_32();
SG_UNREF(prng);
EXPECT_EQ(1811630862U, r);
}
TEST(Random, uint64_t)
{
CRandom* prng = new CRandom();
uint64_t r = prng->random_64();
SG_UNREF(prng);
EXPECT_EQ(18328733385137801998U, r);
}
TEST(Random, fill_array_uint32)
{
CRandom* prng = new CRandom();
uint32_t t = 2228230814U;
SGVector<uint32_t> rv(2*SFMT_N32+1);
prng->fill_array(rv.vector, rv.vlen);
EXPECT_EQ(t, rv[SFMT_N32]);
}
#ifdef HAVE_SSE2
TEST(Random, fill_array_uint32_simd)
{
CRandom* prng = new CRandom();
uint32_t t = 2228230814U;
SGVector<uint32_t> rv(2*SFMT_N32);
prng->fill_array(rv.vector, rv.vlen);
SG_UNREF(prng);
EXPECT_EQ(t, rv[SFMT_N32]);
}
#endif
TEST(Random, fill_array_uint64)
{
CRandom* prng = new CRandom();
uint64_t t = 9564086722318310046U;
SGVector<uint64_t> rv(2*SFMT_N64+1);
prng->fill_array(rv.vector, rv.vlen);
SG_UNREF(prng);
EXPECT_EQ(t, rv[SFMT_N64]);
}
#ifdef HAVE_SSE2
TEST(Random, fill_array_uint64_simd)
{
CRandom* prng = new CRandom();
uint64_t t = 9564086722318310046U;
SGVector<uint64_t> rv(2*SFMT_N64);
prng->fill_array(rv.vector, rv.vlen);
SG_UNREF(prng);
EXPECT_EQ(t, rv[SFMT_N64]);
}
#endif
TEST(Random, fill_array_oc)
{
CRandom* prng = new CRandom();
float64_t t = 0.25551924513287405;
SGVector<float64_t> rv(2*dsfmt_get_min_array_size()+1);
prng->fill_array_oc(rv.vector, rv.vlen);
SG_UNREF(prng);
EXPECT_DOUBLE_EQ(t, rv[dsfmt_get_min_array_size()]);
}
#ifdef HAVE_SSE2
TEST(Random, fill_array_oc_simd)
{
CRandom* prng = new CRandom();
float64_t t = 0.25551924513287405;
SGVector<float64_t> rv(2*dsfmt_get_min_array_size());
prng->fill_array_oc(rv.vector, rv.vlen);
SG_UNREF(prng);
EXPECT_DOUBLE_EQ(t, rv[dsfmt_get_min_array_size()]);
}
#endif
TEST(Random, normal_distrib)
{
CRandom* prng = new CRandom();
float64_t t = 75.567130769021162;
float64_t r = prng->normal_distrib(100.0, 10.0);
SG_UNREF(prng);
EXPECT_DOUBLE_EQ(t, r);
}
TEST(Random, random_uint64_1_2)
{
CMath::init_random(17);
for (int32_t i=0; i<10000; i++)
{
uint64_t r=CMath::random((uint64_t) 1, (uint64_t) 2);
EXPECT_TRUE(r == 1 || r == 2);
}
}
TEST(Random, random_uint64_0_10)
{
CMath::init_random(17);
int rnds[10] = {0,0,0,0,0,0};
for (int32_t i=0; i<10000; i++)
{
uint64_t r=CMath::random((uint64_t) 0, (uint64_t) 9);
rnds[r]++;
}
for (int32_t i=0; i<10; i++) {
EXPECT_TRUE(rnds[i]>0);
}
}
TEST(Random, random_int64_1_2)
{
CMath::init_random(17);
for (int32_t i=0; i<10000; i++)
{
int64_t r=CMath::random((int64_t) 1, (int64_t) 2);
EXPECT_TRUE(r == 1 || r == 2);
}
}
TEST(Random, random_int64_0_10)
{
CMath::init_random(17);
int rnds[10] = {0,0,0,0,0,0};
for (int32_t i=0; i<10000; i++)
{
int64_t r=CMath::random((int64_t) 0, (int64_t) 9);
rnds[r]++;
}
for (int32_t i=0; i<10; i++) {
EXPECT_TRUE(rnds[i]>0);
}
}
TEST(Random, random_uint32_1_2)
{
CMath::init_random(17);
for (int32_t i=0; i<10000; i++)
{
uint32_t r=CMath::random((uint32_t) 1, (uint32_t) 2);
EXPECT_TRUE(r == 1 || r == 2);
}
}
TEST(Random, random_uint32_0_10)
{
CMath::init_random(17);
int rnds[10] = {0,0,0,0,0,0};
for (int32_t i=0; i<10000; i++)
{
uint32_t r=CMath::random((uint32_t) 0, (uint32_t) 9);
rnds[r]++;
}
for (int32_t i=0; i<10; i++) {
EXPECT_TRUE(rnds[i]>0);
}
}
TEST(Random, random_int32_1_2)
{
CMath::init_random(17);
for (int32_t i=0; i<10000; i++)
{
int32_t r=CMath::random((int32_t) 1, (int32_t) 2);
EXPECT_TRUE(r == 1 || r == 2);
}
}
TEST(Random, random_int64_range)
{
CMath::init_random(17);
int rnds[array_len];
for (uint32_t i=0; i<array_len; i++)
rnds[i]=0;
for (uint32_t i=0; i<n_runs; i++)
{
int64_t r=CMath::random((int64_t) 0, (int64_t) array_len-1);
rnds[r]++;
}
for (uint32_t i=0; i<array_len; i++) {
double pbin=double(rnds[i])/n_runs*100*array_len;
EXPECT_GE(pbin, 99.0);
}
}
TEST(Random, random_uint64_range)
{
CMath::init_random(17);
int rnds[array_len];
for (uint32_t i=0; i<array_len; i++)
rnds[i]=0;
for (uint32_t i=0; i<n_runs; i++)
{
uint64_t r=CMath::random((uint64_t) 0, (uint64_t) array_len-1);
rnds[r]++;
}
for (uint32_t i=0; i<array_len; i++) {
double pbin=double(rnds[i])/n_runs*100*array_len;
EXPECT_GE(pbin, 99.0);
}
}
TEST(Random, random_int32_range)
{
CMath::init_random(17);
int rnds[array_len];
for (uint32_t i=0; i<array_len; i++)
rnds[i]=0;
for (uint32_t i=0; i<n_runs; i++)
{
int32_t r=CMath::random((int32_t) 0, (int32_t) array_len-1);
rnds[r]++;
}
for (uint32_t i=0; i<array_len; i++) {
double pbin=double(rnds[i])/n_runs*100*array_len;
EXPECT_GE(pbin, 99.0);
}
}
TEST(Random, random_uint32_range)
{
CMath::init_random(17);
int rnds[array_len];
for (uint32_t i=0; i<array_len; i++)
rnds[i]=0;
for (uint32_t i=0; i<n_runs; i++)
{
uint32_t r=CMath::random((uint32_t) 0, (uint32_t) array_len-1);
rnds[r]++;
}
for (uint32_t i=0; i<array_len; i++) {
double pbin=double(rnds[i])/n_runs*100*array_len;
EXPECT_GE(pbin, 99.0);
}
}
TEST(Random, random_uint32_random_range)
{
CRandom* prng = new CRandom();
prng->set_seed(17);
int rnds[array_len];
for (uint32_t i=0; i<array_len; i++)
rnds[i]=0;
for (uint32_t i=0; i<n_runs; i++)
{
uint32_t r=prng->random_32() % array_len;
rnds[r]++;
}
for (uint32_t i=0; i<array_len; i++) {
double pbin=double(rnds[i])/n_runs*100*array_len;
EXPECT_GE(pbin, 99.0);
}
SG_UNREF(prng);
}
TEST(Random, random_float64_range)
{
CMath::init_random(17);
int rnds[array_len];
for (uint32_t i=0; i<array_len; i++)
rnds[i]=0;
for (uint32_t i=0; i<n_runs; i++)
{
int32_t r= (int32_t) CMath::random((float64_t) 0, (float64_t) array_len);
rnds[r]++;
}
for (uint32_t i=0; i<array_len; i++) {
double pbin=double(rnds[i])/n_runs*100*array_len;
EXPECT_GE(pbin, 99.0);
}
}
TEST(Random, random_float64_range2)
{
CMath::init_random(12345678);
float64_t min=1.0;
float64_t max=0.0;
for (uint32_t i=0; i<n_runs; i++)
{
float64_t r=CMath::random((float64_t) 0, (float64_t) 1.0);
min=CMath::min(min, r);
max=CMath::max(max, r);
}
EXPECT_GE(max, 0.99999);
EXPECT_LE(min, 0.00001);
}
<commit_msg>Fix leak in Random_unittest<commit_after>#include <shogun/lib/config.h>
#include <shogun/mathematics/Random.h>
#include <shogun/mathematics/Math.h>
#include <shogun/lib/SGVector.h>
#include <gtest/gtest.h>
#include <stdio.h>
using namespace shogun;
const uint32_t n_runs=1200000;
const uint32_t array_len=23;
/**
* NOTE: these unit tests were generated with MEXP=19937
* with other exponents it is expected to fail!
*/
TEST(Random, uint32_t)
{
CRandom* prng = new CRandom();
uint32_t r = prng->random_32();
SG_UNREF(prng);
EXPECT_EQ(1811630862U, r);
}
TEST(Random, uint64_t)
{
CRandom* prng = new CRandom();
uint64_t r = prng->random_64();
SG_UNREF(prng);
EXPECT_EQ(18328733385137801998U, r);
}
TEST(Random, fill_array_uint32)
{
CRandom* prng = new CRandom();
uint32_t t = 2228230814U;
SGVector<uint32_t> rv(2*SFMT_N32+1);
prng->fill_array(rv.vector, rv.vlen);
SG_UNREF(prng);
EXPECT_EQ(t, rv[SFMT_N32]);
}
#ifdef HAVE_SSE2
TEST(Random, fill_array_uint32_simd)
{
CRandom* prng = new CRandom();
uint32_t t = 2228230814U;
SGVector<uint32_t> rv(2*SFMT_N32);
prng->fill_array(rv.vector, rv.vlen);
SG_UNREF(prng);
EXPECT_EQ(t, rv[SFMT_N32]);
}
#endif
TEST(Random, fill_array_uint64)
{
CRandom* prng = new CRandom();
uint64_t t = 9564086722318310046U;
SGVector<uint64_t> rv(2*SFMT_N64+1);
prng->fill_array(rv.vector, rv.vlen);
SG_UNREF(prng);
EXPECT_EQ(t, rv[SFMT_N64]);
}
#ifdef HAVE_SSE2
TEST(Random, fill_array_uint64_simd)
{
CRandom* prng = new CRandom();
uint64_t t = 9564086722318310046U;
SGVector<uint64_t> rv(2*SFMT_N64);
prng->fill_array(rv.vector, rv.vlen);
SG_UNREF(prng);
EXPECT_EQ(t, rv[SFMT_N64]);
}
#endif
TEST(Random, fill_array_oc)
{
CRandom* prng = new CRandom();
float64_t t = 0.25551924513287405;
SGVector<float64_t> rv(2*dsfmt_get_min_array_size()+1);
prng->fill_array_oc(rv.vector, rv.vlen);
SG_UNREF(prng);
EXPECT_DOUBLE_EQ(t, rv[dsfmt_get_min_array_size()]);
}
#ifdef HAVE_SSE2
TEST(Random, fill_array_oc_simd)
{
CRandom* prng = new CRandom();
float64_t t = 0.25551924513287405;
SGVector<float64_t> rv(2*dsfmt_get_min_array_size());
prng->fill_array_oc(rv.vector, rv.vlen);
SG_UNREF(prng);
EXPECT_DOUBLE_EQ(t, rv[dsfmt_get_min_array_size()]);
}
#endif
TEST(Random, normal_distrib)
{
CRandom* prng = new CRandom();
float64_t t = 75.567130769021162;
float64_t r = prng->normal_distrib(100.0, 10.0);
SG_UNREF(prng);
EXPECT_DOUBLE_EQ(t, r);
}
TEST(Random, random_uint64_1_2)
{
CMath::init_random(17);
for (int32_t i=0; i<10000; i++)
{
uint64_t r=CMath::random((uint64_t) 1, (uint64_t) 2);
EXPECT_TRUE(r == 1 || r == 2);
}
}
TEST(Random, random_uint64_0_10)
{
CMath::init_random(17);
int rnds[10] = {0,0,0,0,0,0};
for (int32_t i=0; i<10000; i++)
{
uint64_t r=CMath::random((uint64_t) 0, (uint64_t) 9);
rnds[r]++;
}
for (int32_t i=0; i<10; i++) {
EXPECT_TRUE(rnds[i]>0);
}
}
TEST(Random, random_int64_1_2)
{
CMath::init_random(17);
for (int32_t i=0; i<10000; i++)
{
int64_t r=CMath::random((int64_t) 1, (int64_t) 2);
EXPECT_TRUE(r == 1 || r == 2);
}
}
TEST(Random, random_int64_0_10)
{
CMath::init_random(17);
int rnds[10] = {0,0,0,0,0,0};
for (int32_t i=0; i<10000; i++)
{
int64_t r=CMath::random((int64_t) 0, (int64_t) 9);
rnds[r]++;
}
for (int32_t i=0; i<10; i++) {
EXPECT_TRUE(rnds[i]>0);
}
}
TEST(Random, random_uint32_1_2)
{
CMath::init_random(17);
for (int32_t i=0; i<10000; i++)
{
uint32_t r=CMath::random((uint32_t) 1, (uint32_t) 2);
EXPECT_TRUE(r == 1 || r == 2);
}
}
TEST(Random, random_uint32_0_10)
{
CMath::init_random(17);
int rnds[10] = {0,0,0,0,0,0};
for (int32_t i=0; i<10000; i++)
{
uint32_t r=CMath::random((uint32_t) 0, (uint32_t) 9);
rnds[r]++;
}
for (int32_t i=0; i<10; i++) {
EXPECT_TRUE(rnds[i]>0);
}
}
TEST(Random, random_int32_1_2)
{
CMath::init_random(17);
for (int32_t i=0; i<10000; i++)
{
int32_t r=CMath::random((int32_t) 1, (int32_t) 2);
EXPECT_TRUE(r == 1 || r == 2);
}
}
TEST(Random, random_int64_range)
{
CMath::init_random(17);
int rnds[array_len];
for (uint32_t i=0; i<array_len; i++)
rnds[i]=0;
for (uint32_t i=0; i<n_runs; i++)
{
int64_t r=CMath::random((int64_t) 0, (int64_t) array_len-1);
rnds[r]++;
}
for (uint32_t i=0; i<array_len; i++) {
double pbin=double(rnds[i])/n_runs*100*array_len;
EXPECT_GE(pbin, 99.0);
}
}
TEST(Random, random_uint64_range)
{
CMath::init_random(17);
int rnds[array_len];
for (uint32_t i=0; i<array_len; i++)
rnds[i]=0;
for (uint32_t i=0; i<n_runs; i++)
{
uint64_t r=CMath::random((uint64_t) 0, (uint64_t) array_len-1);
rnds[r]++;
}
for (uint32_t i=0; i<array_len; i++) {
double pbin=double(rnds[i])/n_runs*100*array_len;
EXPECT_GE(pbin, 99.0);
}
}
TEST(Random, random_int32_range)
{
CMath::init_random(17);
int rnds[array_len];
for (uint32_t i=0; i<array_len; i++)
rnds[i]=0;
for (uint32_t i=0; i<n_runs; i++)
{
int32_t r=CMath::random((int32_t) 0, (int32_t) array_len-1);
rnds[r]++;
}
for (uint32_t i=0; i<array_len; i++) {
double pbin=double(rnds[i])/n_runs*100*array_len;
EXPECT_GE(pbin, 99.0);
}
}
TEST(Random, random_uint32_range)
{
CMath::init_random(17);
int rnds[array_len];
for (uint32_t i=0; i<array_len; i++)
rnds[i]=0;
for (uint32_t i=0; i<n_runs; i++)
{
uint32_t r=CMath::random((uint32_t) 0, (uint32_t) array_len-1);
rnds[r]++;
}
for (uint32_t i=0; i<array_len; i++) {
double pbin=double(rnds[i])/n_runs*100*array_len;
EXPECT_GE(pbin, 99.0);
}
}
TEST(Random, random_uint32_random_range)
{
CRandom* prng = new CRandom();
prng->set_seed(17);
int rnds[array_len];
for (uint32_t i=0; i<array_len; i++)
rnds[i]=0;
for (uint32_t i=0; i<n_runs; i++)
{
uint32_t r=prng->random_32() % array_len;
rnds[r]++;
}
for (uint32_t i=0; i<array_len; i++) {
double pbin=double(rnds[i])/n_runs*100*array_len;
EXPECT_GE(pbin, 99.0);
}
SG_UNREF(prng);
}
TEST(Random, random_float64_range)
{
CMath::init_random(17);
int rnds[array_len];
for (uint32_t i=0; i<array_len; i++)
rnds[i]=0;
for (uint32_t i=0; i<n_runs; i++)
{
int32_t r= (int32_t) CMath::random((float64_t) 0, (float64_t) array_len);
rnds[r]++;
}
for (uint32_t i=0; i<array_len; i++) {
double pbin=double(rnds[i])/n_runs*100*array_len;
EXPECT_GE(pbin, 99.0);
}
}
TEST(Random, random_float64_range2)
{
CMath::init_random(12345678);
float64_t min=1.0;
float64_t max=0.0;
for (uint32_t i=0; i<n_runs; i++)
{
float64_t r=CMath::random((float64_t) 0, (float64_t) 1.0);
min=CMath::min(min, r);
max=CMath::max(max, r);
}
EXPECT_GE(max, 0.99999);
EXPECT_LE(min, 0.00001);
}
<|endoftext|> |
<commit_before>#include "../base/SRC_FIRST.hpp"
#include "straight_text_element.hpp"
#include "overlay_renderer.hpp"
namespace graphics
{
void visSplit(strings::UniString const & visText,
buffer_vector<strings::UniString, 3> & res,
char const * delimiters,
size_t delimSize,
bool splitAllFound)
{
if (!splitAllFound)
{
if (visText.size() > 15)
{
/// split into two
size_t rs = visText.size() / 2;
size_t ls = visText.size() / 2;
size_t s;
while (true)
{
if (rs == visText.size() - 1)
break;
bool foundDelim = false;
for (int i = 0; i < delimSize; ++i)
if (visText[rs] == strings::UniChar(delimiters[i]))
{
foundDelim = true;
break;
}
if (foundDelim)
break;
++rs;
}
if (rs == visText.size() - 1)
{
while (true)
{
if (ls == 0)
break;
bool foundDelim = false;
for (int i = 0; i < delimSize; ++i)
if (visText[ls] == strings::UniChar(delimiters[i]))
{
foundDelim = true;
break;
}
if (foundDelim)
break;
--ls;
}
if (ls < 5)
s = visText.size() - 1;
else
s = ls;
}
else
s = rs;
res.push_back(strings::UniString());
res.back().resize(s + 1);
for (unsigned i = 0; i < s + 1; ++i)
res.back()[i] = visText[i];
if (s != visText.size() - 1)
{
res.push_back(strings::UniString());
res.back().resize(visText.size() - s - 1);
for (unsigned i = s + 1; i < visText.size(); ++i)
res.back()[i - s - 1] = visText[i];
}
}
else
res.push_back(visText);
}
else
{
size_t beg = 0;
size_t i = 0;
for (;i < visText.size(); ++i)
{
for (int j = 0; j < delimSize; ++j)
if (visText[i] == strings::UniChar(delimiters[j]))
{
strings::UniString s;
s.resize(i - beg);
for (unsigned k = beg; k < i; ++k)
s[k - beg] = visText[k];
res.push_back(s);
beg = i + 1;
}
}
strings::UniString s;
s.resize(i - beg);
for (unsigned k = beg; k < i; ++k)
s[k - beg] = visText[k];
res.push_back(s);
}
}
StraightTextElement::StraightTextElement(Params const & p)
: TextElement(p)
{
ASSERT(p.m_fontDesc.IsValid(), ());
buffer_vector<strings::UniString, 3> res;
if (p.m_doSplit && !isBidi())
{
res.clear();
if (!p.m_delimiters.empty())
visSplit(visText(), res, p.m_delimiters.c_str(), p.m_delimiters.size(), p.m_useAllParts);
else
visSplit(visText(), res, " \n\t", 3, p.m_useAllParts);
}
else
res.push_back(visText());
double allElemWidth = 0;
double allElemHeight = 0;
for (unsigned i = 0; i < res.size(); ++i)
{
m_glyphLayouts.push_back(GlyphLayout(p.m_glyphCache, p.m_fontDesc, m2::PointD(0, 0), res[i], graphics::EPosCenter));
m2::RectD r = m_glyphLayouts.back().boundRects().back().GetGlobalRect();
allElemWidth = max(r.SizeX(), allElemWidth);
allElemHeight += r.SizeY();
}
buffer_vector<strings::UniString, 3> auxRes;
if (p.m_auxFontDesc.IsValid() && (!auxVisText().empty()))
{
GlyphLayout l(p.m_glyphCache, p.m_auxFontDesc, m2::PointD(0, 0), auxVisText(), graphics::EPosCenter);
if (l.boundRects().back().GetGlobalRect().SizeX() > allElemWidth)
{
// should split
if (p.m_doSplit && !isAuxBidi())
{
if (!p.m_delimiters.empty())
visSplit(auxVisText(), auxRes, p.m_delimiters.c_str(), p.m_delimiters.size(), p.m_useAllParts);
else
visSplit(auxVisText(), auxRes, " \n\t", 3, p.m_useAllParts);
}
else
auxRes.push_back(auxVisText());
}
else
auxRes.push_back(auxVisText());
for (int i = 0; i < auxRes.size(); ++i)
{
m_glyphLayouts.push_back(GlyphLayout(p.m_glyphCache, p.m_auxFontDesc, m2::PointD(0, 0), auxRes[i], graphics::EPosCenter));
m2::RectD r = m_glyphLayouts.back().boundRects().back().GetGlobalRect();
allElemWidth = max(r.SizeX(), allElemWidth);
allElemHeight += r.SizeY();
}
}
double curShift = allElemHeight / 2;
/// performing aligning of glyphLayouts as for the center position
for (unsigned i = 0; i < m_glyphLayouts.size(); ++i)
{
double elemSize = m_glyphLayouts[i].boundRects().back().GetGlobalRect().SizeY();
m_glyphLayouts[i].setPivot(m_glyphLayouts[i].pivot() + m2::PointD(0, -curShift + elemSize / 2) + p.m_offset);
curShift -= elemSize;
}
if (position() & graphics::EPosLeft)
for (unsigned i = 0; i < m_glyphLayouts.size(); ++i)
m_glyphLayouts[i].setPivot(m_glyphLayouts[i].pivot() + m2::PointD(-allElemWidth / 2, 0));
if (position() & graphics::EPosRight)
for (unsigned i = 0; i < m_glyphLayouts.size(); ++i)
m_glyphLayouts[i].setPivot(m_glyphLayouts[i].pivot() + m2::PointD(allElemWidth / 2, 0));
if (position() & graphics::EPosAbove)
for (unsigned i = 0; i < m_glyphLayouts.size(); ++i)
m_glyphLayouts[i].setPivot(m_glyphLayouts[i].pivot() + m2::PointD(0, -allElemHeight / 2));
if (position() & graphics::EPosUnder)
for (unsigned i = 0; i < m_glyphLayouts.size(); ++i)
m_glyphLayouts[i].setPivot(m_glyphLayouts[i].pivot() + m2::PointD(0, allElemHeight / 2));
for (unsigned i = 0; i < m_glyphLayouts.size(); ++i)
{
m_offsets.push_back(m_glyphLayouts[i].pivot());
m_glyphLayouts[i].setPivot(m_offsets[i] + pivot());
}
}
StraightTextElement::Params::Params()
: m_minWordsInRow(2),
m_maxWordsInRow(4),
m_minSymInRow(10),
m_maxSymInRow(20),
m_doSplit(false)
{}
StraightTextElement::StraightTextElement(StraightTextElement const & src,
math::Matrix<double, 3, 3> const & m)
: TextElement(src),
m_glyphLayouts(src.m_glyphLayouts)
{
for (unsigned i = 0; i < m_glyphLayouts.size(); ++i)
m_offsets = src.m_offsets;
setPivot(pivot() * m);
for (unsigned i = 0; i < m_glyphLayouts.size(); ++i)
{
m_glyphLayouts[i].setPivot(pivot());
m_glyphLayouts[i].setOffset(m_offsets[i]);
}
}
vector<m2::AnyRectD> const & StraightTextElement::boundRects() const
{
if (isDirtyRect())
{
m_boundRects.clear();
for (size_t i = 0; i < m_glyphLayouts.size(); ++i)
copy(m_glyphLayouts[i].boundRects().begin(),
m_glyphLayouts[i].boundRects().end(),
back_inserter(m_boundRects));
setIsDirtyRect(false);
}
return m_boundRects;
}
void StraightTextElement::draw(OverlayRenderer * screen, math::Matrix<double, 3, 3> const & m) const
{
if (screen->isDebugging())
{
graphics::Color c(255, 255, 255, 32);
if (isFrozen())
c = graphics::Color(0, 0, 255, 64);
if (isNeedRedraw())
c = graphics::Color(255, 0, 0, 64);
screen->drawRectangle(roughBoundRect(), graphics::Color(255, 255, 0, 64), depth() - 0.2);
for (unsigned i = 0 ; i < boundRects().size(); ++i)
screen->drawRectangle(boundRects()[i], c, depth() - 0.2);
}
if (!isNeedRedraw())
return;
for (unsigned i = 0; i < m_glyphLayouts.size(); ++i)
{
if (m_glyphLayouts[i].fontDesc().m_isMasked)
drawTextImpl(m_glyphLayouts[i], screen, m, true, true, m_glyphLayouts[i].fontDesc(), depth());
}
for (unsigned i = 0; i < m_glyphLayouts.size(); ++i)
{
graphics::FontDesc fontDesc = m_glyphLayouts[i].fontDesc();
fontDesc.m_isMasked = false;
drawTextImpl(m_glyphLayouts[i], screen, m, true, true, fontDesc, depth() + 0.1);
}
}
void StraightTextElement::setPivot(m2::PointD const & pv)
{
m2::PointD oldPv = pivot();
m2::PointD offs = pv - oldPv;
TextElement::setPivot(pv);
for (unsigned i = 0; i < m_glyphLayouts.size(); ++i)
m_glyphLayouts[i].setPivot(m_glyphLayouts[i].pivot() + offs);
}
OverlayElement * StraightTextElement::clone(math::Matrix<double, 3, 3> const & m) const
{
return new StraightTextElement(*this, m);
}
bool StraightTextElement::hasSharpGeometry() const
{
return true;
}
}
<commit_msg>uninitialized variables bugfix.<commit_after>#include "../base/SRC_FIRST.hpp"
#include "straight_text_element.hpp"
#include "overlay_renderer.hpp"
namespace graphics
{
void visSplit(strings::UniString const & visText,
buffer_vector<strings::UniString, 3> & res,
char const * delimiters,
size_t delimSize,
bool splitAllFound)
{
if (!splitAllFound)
{
if (visText.size() > 15)
{
/// split into two
size_t rs = visText.size() / 2;
size_t ls = visText.size() / 2;
size_t s;
while (true)
{
if (rs == visText.size() - 1)
break;
bool foundDelim = false;
for (int i = 0; i < delimSize; ++i)
if (visText[rs] == strings::UniChar(delimiters[i]))
{
foundDelim = true;
break;
}
if (foundDelim)
break;
++rs;
}
if (rs == visText.size() - 1)
{
while (true)
{
if (ls == 0)
break;
bool foundDelim = false;
for (int i = 0; i < delimSize; ++i)
if (visText[ls] == strings::UniChar(delimiters[i]))
{
foundDelim = true;
break;
}
if (foundDelim)
break;
--ls;
}
if (ls < 5)
s = visText.size() - 1;
else
s = ls;
}
else
s = rs;
res.push_back(strings::UniString());
res.back().resize(s + 1);
for (unsigned i = 0; i < s + 1; ++i)
res.back()[i] = visText[i];
if (s != visText.size() - 1)
{
res.push_back(strings::UniString());
res.back().resize(visText.size() - s - 1);
for (unsigned i = s + 1; i < visText.size(); ++i)
res.back()[i - s - 1] = visText[i];
}
}
else
res.push_back(visText);
}
else
{
size_t beg = 0;
size_t i = 0;
for (;i < visText.size(); ++i)
{
for (int j = 0; j < delimSize; ++j)
if (visText[i] == strings::UniChar(delimiters[j]))
{
strings::UniString s;
s.resize(i - beg);
for (unsigned k = beg; k < i; ++k)
s[k - beg] = visText[k];
res.push_back(s);
beg = i + 1;
}
}
strings::UniString s;
s.resize(i - beg);
for (unsigned k = beg; k < i; ++k)
s[k - beg] = visText[k];
res.push_back(s);
}
}
StraightTextElement::StraightTextElement(Params const & p)
: TextElement(p)
{
ASSERT(p.m_fontDesc.IsValid(), ());
buffer_vector<strings::UniString, 3> res;
if (p.m_doSplit && !isBidi())
{
res.clear();
if (!p.m_delimiters.empty())
visSplit(visText(), res, p.m_delimiters.c_str(), p.m_delimiters.size(), p.m_useAllParts);
else
visSplit(visText(), res, " \n\t", 3, p.m_useAllParts);
}
else
res.push_back(visText());
double allElemWidth = 0;
double allElemHeight = 0;
for (unsigned i = 0; i < res.size(); ++i)
{
m_glyphLayouts.push_back(GlyphLayout(p.m_glyphCache, p.m_fontDesc, m2::PointD(0, 0), res[i], graphics::EPosCenter));
m2::RectD r = m_glyphLayouts.back().boundRects().back().GetGlobalRect();
allElemWidth = max(r.SizeX(), allElemWidth);
allElemHeight += r.SizeY();
}
buffer_vector<strings::UniString, 3> auxRes;
if (p.m_auxFontDesc.IsValid() && (!auxVisText().empty()))
{
GlyphLayout l(p.m_glyphCache, p.m_auxFontDesc, m2::PointD(0, 0), auxVisText(), graphics::EPosCenter);
if (l.boundRects().back().GetGlobalRect().SizeX() > allElemWidth)
{
// should split
if (p.m_doSplit && !isAuxBidi())
{
if (!p.m_delimiters.empty())
visSplit(auxVisText(), auxRes, p.m_delimiters.c_str(), p.m_delimiters.size(), p.m_useAllParts);
else
visSplit(auxVisText(), auxRes, " \n\t", 3, p.m_useAllParts);
}
else
auxRes.push_back(auxVisText());
}
else
auxRes.push_back(auxVisText());
for (int i = 0; i < auxRes.size(); ++i)
{
m_glyphLayouts.push_back(GlyphLayout(p.m_glyphCache, p.m_auxFontDesc, m2::PointD(0, 0), auxRes[i], graphics::EPosCenter));
m2::RectD r = m_glyphLayouts.back().boundRects().back().GetGlobalRect();
allElemWidth = max(r.SizeX(), allElemWidth);
allElemHeight += r.SizeY();
}
}
double curShift = allElemHeight / 2;
/// performing aligning of glyphLayouts as for the center position
for (unsigned i = 0; i < m_glyphLayouts.size(); ++i)
{
double elemSize = m_glyphLayouts[i].boundRects().back().GetGlobalRect().SizeY();
m_glyphLayouts[i].setPivot(m_glyphLayouts[i].pivot() + m2::PointD(0, -curShift + elemSize / 2) + p.m_offset);
curShift -= elemSize;
}
if (position() & graphics::EPosLeft)
for (unsigned i = 0; i < m_glyphLayouts.size(); ++i)
m_glyphLayouts[i].setPivot(m_glyphLayouts[i].pivot() + m2::PointD(-allElemWidth / 2, 0));
if (position() & graphics::EPosRight)
for (unsigned i = 0; i < m_glyphLayouts.size(); ++i)
m_glyphLayouts[i].setPivot(m_glyphLayouts[i].pivot() + m2::PointD(allElemWidth / 2, 0));
if (position() & graphics::EPosAbove)
for (unsigned i = 0; i < m_glyphLayouts.size(); ++i)
m_glyphLayouts[i].setPivot(m_glyphLayouts[i].pivot() + m2::PointD(0, -allElemHeight / 2));
if (position() & graphics::EPosUnder)
for (unsigned i = 0; i < m_glyphLayouts.size(); ++i)
m_glyphLayouts[i].setPivot(m_glyphLayouts[i].pivot() + m2::PointD(0, allElemHeight / 2));
for (unsigned i = 0; i < m_glyphLayouts.size(); ++i)
{
m_offsets.push_back(m_glyphLayouts[i].pivot());
m_glyphLayouts[i].setPivot(m_offsets[i] + pivot());
}
}
StraightTextElement::Params::Params()
: m_minWordsInRow(2),
m_maxWordsInRow(4),
m_minSymInRow(10),
m_maxSymInRow(20),
m_doSplit(false),
m_useAllParts(true),
m_offset(0, 0),
m_delimiters("\n")
{}
StraightTextElement::StraightTextElement(StraightTextElement const & src,
math::Matrix<double, 3, 3> const & m)
: TextElement(src),
m_glyphLayouts(src.m_glyphLayouts)
{
for (unsigned i = 0; i < m_glyphLayouts.size(); ++i)
m_offsets = src.m_offsets;
setPivot(pivot() * m);
for (unsigned i = 0; i < m_glyphLayouts.size(); ++i)
{
m_glyphLayouts[i].setPivot(pivot());
m_glyphLayouts[i].setOffset(m_offsets[i]);
}
}
vector<m2::AnyRectD> const & StraightTextElement::boundRects() const
{
if (isDirtyRect())
{
m_boundRects.clear();
for (size_t i = 0; i < m_glyphLayouts.size(); ++i)
copy(m_glyphLayouts[i].boundRects().begin(),
m_glyphLayouts[i].boundRects().end(),
back_inserter(m_boundRects));
setIsDirtyRect(false);
}
return m_boundRects;
}
void StraightTextElement::draw(OverlayRenderer * screen, math::Matrix<double, 3, 3> const & m) const
{
if (screen->isDebugging())
{
graphics::Color c(255, 255, 255, 32);
if (isFrozen())
c = graphics::Color(0, 0, 255, 64);
if (isNeedRedraw())
c = graphics::Color(255, 0, 0, 64);
screen->drawRectangle(roughBoundRect(), graphics::Color(255, 255, 0, 64), depth() - 0.2);
for (unsigned i = 0 ; i < boundRects().size(); ++i)
screen->drawRectangle(boundRects()[i], c, depth() - 0.2);
}
if (!isNeedRedraw())
return;
for (unsigned i = 0; i < m_glyphLayouts.size(); ++i)
{
if (m_glyphLayouts[i].fontDesc().m_isMasked)
drawTextImpl(m_glyphLayouts[i], screen, m, true, true, m_glyphLayouts[i].fontDesc(), depth());
}
for (unsigned i = 0; i < m_glyphLayouts.size(); ++i)
{
graphics::FontDesc fontDesc = m_glyphLayouts[i].fontDesc();
fontDesc.m_isMasked = false;
drawTextImpl(m_glyphLayouts[i], screen, m, true, true, fontDesc, depth() + 0.1);
}
}
void StraightTextElement::setPivot(m2::PointD const & pv)
{
m2::PointD oldPv = pivot();
m2::PointD offs = pv - oldPv;
TextElement::setPivot(pv);
for (unsigned i = 0; i < m_glyphLayouts.size(); ++i)
m_glyphLayouts[i].setPivot(m_glyphLayouts[i].pivot() + offs);
}
OverlayElement * StraightTextElement::clone(math::Matrix<double, 3, 3> const & m) const
{
return new StraightTextElement(*this, m);
}
bool StraightTextElement::hasSharpGeometry() const
{
return true;
}
}
<|endoftext|> |
<commit_before>#pragma once
#include "eigen.hh"
#include "geometry/ray.hh"
namespace slam {
class CameraModel {
public:
using Vec2 = Eigen::Vector2d;
using Vec3 = Eigen::Vector3d;
using Vec4 = Eigen::Vector4d;
using ProjMat = Eigen::Matrix<double, 3, 3>;
CameraModel(const ProjMat& K) : K_(K){};
//
// @param *: use google pls
//
CameraModel(const double f_x, const double f_y, const double u_0, const double v_0) {
K_.setZero();
K_(0, 0) = f_x;
K_(1, 1) = f_y;
K_(0, 2) = u_0;
K_(1, 2) = v_0;
K_(2, 2) = 1.0;
}
// @param camera_point: Point in the camera frame (3d)
// @returns The point projected into image space
Vec2 project(const Vec3& camera_point) const {
const Vec3 projected_h = K_ * camera_point;
const Vec2 projected = projected_h.head<2>() / projected_h(2);
return projected;
}
// Fire that little guy right back through the image plane!
//
// @param image_point: Point in the image frame (2d)
// @returns ray passing through the image point, originating at the center of projection
geometry::Ray unproject(const Vec2& image_point) const {
const Eigen::PartialPivLU<ProjMat>& K_inv = get_k_inv();
const Vec3 image_point_h = Vec3(image_point.x(), image_point.y(), 1.0);
// const Vec3 soln = K_inv.solve(K_.transpose() * image_point_h);
const Vec3 soln = K_inv.solve(image_point_h);
const Vec3 unprojected = soln;
// std::cout << "upj : " << unprojected.norm() << std::endl;
// const geometry::Ray unprojected_ray{.origin = Vec3::Zero(), .direction = unprojected};
const geometry::Ray unprojected_ray{.origin = Vec3::Zero(), .direction = unprojected.normalized()};
// const geometry::Ray unprojected_ray{.origin = Vec3::Zero(), .direction = unprojected_fx.normalized()};
return unprojected_ray;
}
const ProjMat& get_k() const {
return K_;
}
const Eigen::PartialPivLU<ProjMat>& get_k_inv() const {
if (!inv_set_) {
// const ProjMat ktk = K_.transpose() * K_;
K_inv_ = Eigen::PartialPivLU<ProjMat>(K_);
inv_set_ = true;
}
return K_inv_;
}
private:
ProjMat K_;
// Inversion cache
mutable bool inv_set_ = false;
mutable Eigen::PartialPivLU<ProjMat> K_inv_;
};
}
<commit_msg>More rename ray<commit_after>#pragma once
#include "eigen.hh"
#include "geometry/shapes/ray.hh"
namespace slam {
class CameraModel {
public:
using Vec2 = Eigen::Vector2d;
using Vec3 = Eigen::Vector3d;
using Vec4 = Eigen::Vector4d;
using ProjMat = Eigen::Matrix<double, 3, 3>;
CameraModel(const ProjMat& K) : K_(K){};
//
// @param *: use google pls
//
CameraModel(const double f_x, const double f_y, const double u_0, const double v_0) {
K_.setZero();
K_(0, 0) = f_x;
K_(1, 1) = f_y;
K_(0, 2) = u_0;
K_(1, 2) = v_0;
K_(2, 2) = 1.0;
}
// @param camera_point: Point in the camera frame (3d)
// @returns The point projected into image space
Vec2 project(const Vec3& camera_point) const {
const Vec3 projected_h = K_ * camera_point;
const Vec2 projected = projected_h.head<2>() / projected_h(2);
return projected;
}
// Fire that little guy right back through the image plane!
//
// @param image_point: Point in the image frame (2d)
// @returns ray passing through the image point, originating at the center of projection
geometry::Ray unproject(const Vec2& image_point) const {
const Eigen::PartialPivLU<ProjMat>& K_inv = get_k_inv();
const Vec3 image_point_h = Vec3(image_point.x(), image_point.y(), 1.0);
// const Vec3 soln = K_inv.solve(K_.transpose() * image_point_h);
const Vec3 soln = K_inv.solve(image_point_h);
const Vec3 unprojected = soln;
// std::cout << "upj : " << unprojected.norm() << std::endl;
// const geometry::Ray unprojected_ray{.origin = Vec3::Zero(), .direction = unprojected};
const geometry::Ray unprojected_ray{.origin = Vec3::Zero(), .direction = unprojected.normalized()};
// const geometry::Ray unprojected_ray{.origin = Vec3::Zero(), .direction = unprojected_fx.normalized()};
return unprojected_ray;
}
const ProjMat& get_k() const {
return K_;
}
const Eigen::PartialPivLU<ProjMat>& get_k_inv() const {
if (!inv_set_) {
// const ProjMat ktk = K_.transpose() * K_;
K_inv_ = Eigen::PartialPivLU<ProjMat>(K_);
inv_set_ = true;
}
return K_inv_;
}
private:
ProjMat K_;
// Inversion cache
mutable bool inv_set_ = false;
mutable Eigen::PartialPivLU<ProjMat> K_inv_;
};
}
<|endoftext|> |
<commit_before>/**
* Touhou Community Reliant Automatic Patcher
* Cheap command-line patch stack configuration tool
*
* ----
*
* Game searching front-end code.
*/
#include <thcrap.h>
#include "configure.h"
static const char games_js_fn[] = "config/games.js";
static const char* ChooseLocation(const char *id, json_t *locs)
{
size_t num_versions = json_object_size(locs);
if(num_versions == 1) {
const char *loc = json_object_iter_key(json_object_iter(locs));
const char *variety = json_object_get_string(locs, loc);
log_printf("Found %s (%s) at %s\n", id, variety, loc);
return loc;
} else if(num_versions > 1) {
const char *loc;
json_t *val;
size_t i = 0;
size_t loc_num;
log_printf("Found %d versions of %s:\n\n", num_versions, id);
json_object_foreach(locs, loc, val) {
++i;
con_clickable(i); log_printf(" [%2d] %s: %s\n", i, loc, json_string_value(val));
}
printf("\n");
do {
con_printf("Pick a version to run the patch on: (1 - %u): ", num_versions);
wchar_t *buf = console_read();
if (swscanf(buf, L"%u", &loc_num) != 1)
loc_num = 0;
delete[] buf;
} while (loc_num < 1 || loc_num > num_versions);
i = 0;
json_object_foreach(locs, loc, val) {
if(++i == loc_num) {
return loc;
}
}
}
return NULL;
}
// Work around a bug in Windows 7 and later by sending
// BFFM_SETSELECTION a second time.
// https://connect.microsoft.com/VisualStudio/feedback/details/518103/bffm-setselection-does-not-work-with-shbrowseforfolder-on-windows-7
typedef struct {
ITEMIDLIST *path;
int attempts;
} initial_path_t;
int CALLBACK SetInitialBrowsePathProc(HWND hWnd, UINT uMsg, LPARAM lp, LPARAM pData)
{
initial_path_t *ip = (initial_path_t *)pData;
if(ip) {
switch(uMsg) {
case BFFM_INITIALIZED:
ip->attempts = 0;
// fallthrough
case BFFM_SELCHANGED:
if(ip->attempts < 2) {
SendMessageW(hWnd, BFFM_SETSELECTION, FALSE, (LPARAM)ip->path);
ip->attempts++;
}
}
}
return 0;
}
#define UnkRelease(p) do { IUnknown** __p = (IUnknown**)(p); (*__p)->Release(); (*__p) = NULL; } while(0)
static int SelectFolderVista(PIDLIST_ABSOLUTE initial_path, PIDLIST_ABSOLUTE& pidl, const wchar_t* window_title) {
// Those two functions are absent in XP, so we have to load them dynamically
HMODULE shell32 = GetModuleHandle(L"Shell32.dll");
auto pSHCreateItemFromIDList = (HRESULT(WINAPI *)(PCIDLIST_ABSOLUTE, REFIID, void**))GetProcAddress(shell32, "SHCreateItemFromIDList");
auto pSHGetIDListFromObject = (HRESULT(WINAPI *)(IUnknown*, PIDLIST_ABSOLUTE*))GetProcAddress(shell32, "SHGetIDListFromObject");
if (!pSHCreateItemFromIDList || !pSHGetIDListFromObject) {
return -1;
}
IFileDialog *pfd = NULL;
CoCreateInstance(CLSID_FileOpenDialog, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&pfd));
if (!pfd) return -1;
IShellItem* psi = NULL;
pSHCreateItemFromIDList(initial_path, IID_PPV_ARGS(&psi));
if (!psi) {
UnkRelease(&pfd);
return -1;
}
pfd->SetDefaultFolder(psi);
UnkRelease(&psi);
pfd->SetOptions(
FOS_NOCHANGEDIR | FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM
| FOS_PATHMUSTEXIST | FOS_FILEMUSTEXIST | FOS_DONTADDTORECENT);
pfd->SetTitle(window_title);
HRESULT hr = pfd->Show(con_hwnd());
if (SUCCEEDED(hr)) {
if (SUCCEEDED(pfd->GetResult(&psi))) {
pSHGetIDListFromObject(psi, &pidl);
UnkRelease(&psi);
UnkRelease(&pfd);
return 0;
}
}
UnkRelease(&pfd);
if (hr == HRESULT_FROM_WIN32(ERROR_CANCELLED)) {
return 0;
}
return -1;
}
static int SelectFolderXP(PIDLIST_ABSOLUTE initial_path, PIDLIST_ABSOLUTE& pidl, const wchar_t* window_title) {
BROWSEINFOW bi = { 0 };
initial_path_t ip = { 0 };
ip.path = initial_path;
bi.lpszTitle = window_title;
bi.ulFlags = BIF_RETURNONLYFSDIRS | BIF_NONEWFOLDERBUTTON | BIF_USENEWUI;
bi.hwndOwner = con_hwnd();
bi.lpfn = SetInitialBrowsePathProc;
bi.lParam = (LPARAM)&ip;
pidl = SHBrowseForFolderW(&bi);
return 0;
}
PIDLIST_ABSOLUTE SelectFolder(PIDLIST_ABSOLUTE initial_path, const wchar_t* window_title) {
PIDLIST_ABSOLUTE pidl = NULL;
if (-1 == SelectFolderVista(initial_path, pidl, window_title)) {
SelectFolderXP(initial_path, pidl, window_title);
}
return pidl;
}
json_t *sort_json(json_t *in)
{
std::vector<const char*> keys;
const char *key;
json_t *val;
json_object_foreach(in, key, val) {
keys.push_back(key);
}
std::sort(keys.begin(), keys.end(), [](const char *s1, const char *s2) {
WCHAR_T_DEC(s1);
WCHAR_T_DEC(s2);
WCHAR_T_CONV(s1);
WCHAR_T_CONV(s2);
int sort_result = CompareStringW(LOCALE_INVARIANT, 0,
s1_w, -1, s2_w, -1);
WCHAR_T_FREE(s1);
WCHAR_T_FREE(s2);
if (sort_result == 0) {
throw std::runtime_error("CompareStringsEx failed");
}
return sort_result == CSTR_LESS_THAN;
});
json_t *out = json_object();
for (const char *key : keys) {
json_object_set(out, key, json_object_get(in, key));
}
json_decref(in);
return out;
}
json_t* ConfigureLocateGames(const char *games_js_path)
{
json_t *games;
int repeat = 0;
cls(0);
log_printf("--------------\n");
log_printf("Locating games\n");
log_printf("--------------\n");
log_printf(
"\n"
"\n"
);
games = json_load_file_report("config/games.js");
if(json_object_size(games) != 0) {
log_printf("You already have a %s with the following contents:\n\n", games_js_fn);
json_dump_log(games, JSON_INDENT(2) | JSON_SORT_KEYS);
log_printf(
"\n"
"\n"
"Patch data will be downloaded or updated for all the games listed.\n"
"\n"
);
con_clickable("a"); log_printf("\t* (A)dd new games to this list and keep existing ones?\n");
con_clickable("r"); log_printf("\t* Clear this list and (r)escan?\n");
con_clickable("k"); log_printf("\t* (K)eep this list and continue?\n");
log_printf("\n");
char ret = Ask<3>(nullptr, { 'a', 'r', 'k' | DEFAULT_ANSWER });
if(ret == 'k') {
return games;
} else if(ret == 'r') {
json_object_clear(games);
}
} else {
games = json_object();
log_printf(
"You don't have a %s yet.\n"
"\n"
"Thus, I now need to search for patchable games installed on your system.\n"
"This only has to be done once - unless, of course, you later move the games\n"
"to different directories.\n"
"\n"
"Depending on the number of drives and your directory structure,\n"
"this may take a while. You can speed up this process by giving me a\n"
"common root path shared by all games you want to patch.\n"
"\n"
"For example, if you have 'Double Dealing Character' in \n"
"\n"
"\tC:\\Games\\Touhou\\DDC\\\n"
"\n"
"and 'Imperishable Night' in\n"
"\n"
"\tC:\\Games\\Touhou\\IN\\\n"
"\n"
"you would now specify \n"
"\n"
"\tC:\\Games\\Touhou\\\n"
"\n"
"... unless, of course, your Touhou games are spread out all over your drives -\n"
"in which case there's no way around a complete search.\n"
"\n"
"Furthermore, please note that you may experience issues with\n"
"static English-patched versions of the games,\n"
"as such the originals are recommended.\n"
"\n"
"\n",
games_js_fn
);
pause();
}
PIDLIST_ABSOLUTE initial_path = NULL;
// BFFM_SETSELECTION does this anyway if we pass a string, so we
// might as well do the slash conversion in win32_utf8's wrapper
// while we're at it.
SHParseDisplayNameU(games_js_path, NULL, &initial_path, 0, NULL);
CoInitialize(NULL);
do {
wchar_t search_path_w[MAX_PATH] = {0};
json_t *found = NULL;
PIDLIST_ABSOLUTE pidl = SelectFolder(initial_path, L"Root path for game search (cancel to search entire system):");
if (pidl && SHGetPathFromIDListW(pidl, search_path_w)) {
PathAddBackslashW(search_path_w);
CoTaskMemFree(pidl);
}
int search_path_len = wcslen(search_path_w)*UTF8_MUL + 1;
VLA(char, search_path, search_path_len);
StringToUTF8(search_path, search_path_w, search_path_len);
repeat = 0;
log_printf(
"Searching games%s%s... this may take a while...\n\n",
search_path[0] ? " in " : " on the entire system",
search_path[0] ? search_path: ""
);
console_print_percent(-1);
found = SearchForGames(search_path, games);
VLA_FREE(search_path);
if(json_object_size(found)) {
found = sort_json(found);
char *games_js_str = NULL;
const char *id;
json_t *locs;
json_object_foreach(found, id, locs) {
const char *loc = ChooseLocation(id, locs);
json_object_set_new(games, id, json_string(loc));
printf("\n");
}
SetCurrentDirectory(games_js_path);
games = sort_json(games);
games_js_str = json_dumps(games, JSON_INDENT(2));
if(!file_write_text(games_js_fn, games_js_str)) {
log_printf("The following game locations have been identified and written to %s:\n", games_js_fn);
log_printf(games_js_str);
log_printf("\n");
} else if(!file_write_error(games_js_fn)) {
games = json_decref_safe(games);
}
SAFE_FREE(games_js_str);
} else if(json_object_size(games)) {
log_printf("No new game locations found.\n");
} else {
log_printf("No game locations found.\n");
if(search_path_w[0]) {
repeat = console_ask_yn("Search in a different directory?") == 'y';
}
if(!repeat) {
log_printf(
"No patch shortcuts will be created.\n"
"Please re-run this configuration tool after you have acquired some games\n"
"supported by the patches.\n"
);
pause();
}
}
json_decref(found);
} while(repeat);
CoUninitialize();
CoTaskMemFree(initial_path);
return games;
}
<commit_msg>winconsole: pass owner as argument to SelectFolder<commit_after>/**
* Touhou Community Reliant Automatic Patcher
* Cheap command-line patch stack configuration tool
*
* ----
*
* Game searching front-end code.
*/
#include <thcrap.h>
#include "configure.h"
static const char games_js_fn[] = "config/games.js";
static const char* ChooseLocation(const char *id, json_t *locs)
{
size_t num_versions = json_object_size(locs);
if(num_versions == 1) {
const char *loc = json_object_iter_key(json_object_iter(locs));
const char *variety = json_object_get_string(locs, loc);
log_printf("Found %s (%s) at %s\n", id, variety, loc);
return loc;
} else if(num_versions > 1) {
const char *loc;
json_t *val;
size_t i = 0;
size_t loc_num;
log_printf("Found %d versions of %s:\n\n", num_versions, id);
json_object_foreach(locs, loc, val) {
++i;
con_clickable(i); log_printf(" [%2d] %s: %s\n", i, loc, json_string_value(val));
}
printf("\n");
do {
con_printf("Pick a version to run the patch on: (1 - %u): ", num_versions);
wchar_t *buf = console_read();
if (swscanf(buf, L"%u", &loc_num) != 1)
loc_num = 0;
delete[] buf;
} while (loc_num < 1 || loc_num > num_versions);
i = 0;
json_object_foreach(locs, loc, val) {
if(++i == loc_num) {
return loc;
}
}
}
return NULL;
}
// Work around a bug in Windows 7 and later by sending
// BFFM_SETSELECTION a second time.
// https://connect.microsoft.com/VisualStudio/feedback/details/518103/bffm-setselection-does-not-work-with-shbrowseforfolder-on-windows-7
typedef struct {
ITEMIDLIST *path;
int attempts;
} initial_path_t;
int CALLBACK SetInitialBrowsePathProc(HWND hWnd, UINT uMsg, LPARAM lp, LPARAM pData)
{
initial_path_t *ip = (initial_path_t *)pData;
if(ip) {
switch(uMsg) {
case BFFM_INITIALIZED:
ip->attempts = 0;
// fallthrough
case BFFM_SELCHANGED:
if(ip->attempts < 2) {
SendMessageW(hWnd, BFFM_SETSELECTION, FALSE, (LPARAM)ip->path);
ip->attempts++;
}
}
}
return 0;
}
#define UnkRelease(p) do { IUnknown** __p = (IUnknown**)(p); (*__p)->Release(); (*__p) = NULL; } while(0)
static int SelectFolderVista(HWND owner, PIDLIST_ABSOLUTE initial_path, PIDLIST_ABSOLUTE& pidl, const wchar_t* window_title) {
// Those two functions are absent in XP, so we have to load them dynamically
HMODULE shell32 = GetModuleHandle(L"Shell32.dll");
auto pSHCreateItemFromIDList = (HRESULT(WINAPI *)(PCIDLIST_ABSOLUTE, REFIID, void**))GetProcAddress(shell32, "SHCreateItemFromIDList");
auto pSHGetIDListFromObject = (HRESULT(WINAPI *)(IUnknown*, PIDLIST_ABSOLUTE*))GetProcAddress(shell32, "SHGetIDListFromObject");
if (!pSHCreateItemFromIDList || !pSHGetIDListFromObject) {
return -1;
}
IFileDialog *pfd = NULL;
CoCreateInstance(CLSID_FileOpenDialog, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&pfd));
if (!pfd) return -1;
IShellItem* psi = NULL;
pSHCreateItemFromIDList(initial_path, IID_PPV_ARGS(&psi));
if (!psi) {
UnkRelease(&pfd);
return -1;
}
pfd->SetDefaultFolder(psi);
UnkRelease(&psi);
pfd->SetOptions(
FOS_NOCHANGEDIR | FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM
| FOS_PATHMUSTEXIST | FOS_FILEMUSTEXIST | FOS_DONTADDTORECENT);
pfd->SetTitle(window_title);
HRESULT hr = pfd->Show(owner);
if (SUCCEEDED(hr)) {
if (SUCCEEDED(pfd->GetResult(&psi))) {
pSHGetIDListFromObject(psi, &pidl);
UnkRelease(&psi);
UnkRelease(&pfd);
return 0;
}
}
UnkRelease(&pfd);
if (hr == HRESULT_FROM_WIN32(ERROR_CANCELLED)) {
return 0;
}
return -1;
}
static int SelectFolderXP(HWND owner, PIDLIST_ABSOLUTE initial_path, PIDLIST_ABSOLUTE& pidl, const wchar_t* window_title) {
BROWSEINFOW bi = { 0 };
initial_path_t ip = { 0 };
ip.path = initial_path;
bi.lpszTitle = window_title;
bi.ulFlags = BIF_RETURNONLYFSDIRS | BIF_NONEWFOLDERBUTTON | BIF_USENEWUI;
bi.hwndOwner = owner;
bi.lpfn = SetInitialBrowsePathProc;
bi.lParam = (LPARAM)&ip;
pidl = SHBrowseForFolderW(&bi);
return 0;
}
PIDLIST_ABSOLUTE SelectFolder(HWND owner, PIDLIST_ABSOLUTE initial_path, const wchar_t* window_title) {
PIDLIST_ABSOLUTE pidl = NULL;
if (-1 == SelectFolderVista(owner, initial_path, pidl, window_title)) {
SelectFolderXP(owner, initial_path, pidl, window_title);
}
return pidl;
}
json_t *sort_json(json_t *in)
{
std::vector<const char*> keys;
const char *key;
json_t *val;
json_object_foreach(in, key, val) {
keys.push_back(key);
}
std::sort(keys.begin(), keys.end(), [](const char *s1, const char *s2) {
WCHAR_T_DEC(s1);
WCHAR_T_DEC(s2);
WCHAR_T_CONV(s1);
WCHAR_T_CONV(s2);
int sort_result = CompareStringW(LOCALE_INVARIANT, 0,
s1_w, -1, s2_w, -1);
WCHAR_T_FREE(s1);
WCHAR_T_FREE(s2);
if (sort_result == 0) {
throw std::runtime_error("CompareStringsEx failed");
}
return sort_result == CSTR_LESS_THAN;
});
json_t *out = json_object();
for (const char *key : keys) {
json_object_set(out, key, json_object_get(in, key));
}
json_decref(in);
return out;
}
json_t* ConfigureLocateGames(const char *games_js_path)
{
json_t *games;
int repeat = 0;
cls(0);
log_printf("--------------\n");
log_printf("Locating games\n");
log_printf("--------------\n");
log_printf(
"\n"
"\n"
);
games = json_load_file_report("config/games.js");
if(json_object_size(games) != 0) {
log_printf("You already have a %s with the following contents:\n\n", games_js_fn);
json_dump_log(games, JSON_INDENT(2) | JSON_SORT_KEYS);
log_printf(
"\n"
"\n"
"Patch data will be downloaded or updated for all the games listed.\n"
"\n"
);
con_clickable("a"); log_printf("\t* (A)dd new games to this list and keep existing ones?\n");
con_clickable("r"); log_printf("\t* Clear this list and (r)escan?\n");
con_clickable("k"); log_printf("\t* (K)eep this list and continue?\n");
log_printf("\n");
char ret = Ask<3>(nullptr, { 'a', 'r', 'k' | DEFAULT_ANSWER });
if(ret == 'k') {
return games;
} else if(ret == 'r') {
json_object_clear(games);
}
} else {
games = json_object();
log_printf(
"You don't have a %s yet.\n"
"\n"
"Thus, I now need to search for patchable games installed on your system.\n"
"This only has to be done once - unless, of course, you later move the games\n"
"to different directories.\n"
"\n"
"Depending on the number of drives and your directory structure,\n"
"this may take a while. You can speed up this process by giving me a\n"
"common root path shared by all games you want to patch.\n"
"\n"
"For example, if you have 'Double Dealing Character' in \n"
"\n"
"\tC:\\Games\\Touhou\\DDC\\\n"
"\n"
"and 'Imperishable Night' in\n"
"\n"
"\tC:\\Games\\Touhou\\IN\\\n"
"\n"
"you would now specify \n"
"\n"
"\tC:\\Games\\Touhou\\\n"
"\n"
"... unless, of course, your Touhou games are spread out all over your drives -\n"
"in which case there's no way around a complete search.\n"
"\n"
"Furthermore, please note that you may experience issues with\n"
"static English-patched versions of the games,\n"
"as such the originals are recommended.\n"
"\n"
"\n",
games_js_fn
);
pause();
}
PIDLIST_ABSOLUTE initial_path = NULL;
// BFFM_SETSELECTION does this anyway if we pass a string, so we
// might as well do the slash conversion in win32_utf8's wrapper
// while we're at it.
SHParseDisplayNameU(games_js_path, NULL, &initial_path, 0, NULL);
CoInitialize(NULL);
do {
wchar_t search_path_w[MAX_PATH] = {0};
json_t *found = NULL;
PIDLIST_ABSOLUTE pidl = SelectFolder(con_hwnd(), initial_path, L"Root path for game search (cancel to search entire system):");
if (pidl && SHGetPathFromIDListW(pidl, search_path_w)) {
PathAddBackslashW(search_path_w);
CoTaskMemFree(pidl);
}
int search_path_len = wcslen(search_path_w)*UTF8_MUL + 1;
VLA(char, search_path, search_path_len);
StringToUTF8(search_path, search_path_w, search_path_len);
repeat = 0;
log_printf(
"Searching games%s%s... this may take a while...\n\n",
search_path[0] ? " in " : " on the entire system",
search_path[0] ? search_path: ""
);
console_print_percent(-1);
found = SearchForGames(search_path, games);
VLA_FREE(search_path);
if(json_object_size(found)) {
found = sort_json(found);
char *games_js_str = NULL;
const char *id;
json_t *locs;
json_object_foreach(found, id, locs) {
const char *loc = ChooseLocation(id, locs);
json_object_set_new(games, id, json_string(loc));
printf("\n");
}
SetCurrentDirectory(games_js_path);
games = sort_json(games);
games_js_str = json_dumps(games, JSON_INDENT(2));
if(!file_write_text(games_js_fn, games_js_str)) {
log_printf("The following game locations have been identified and written to %s:\n", games_js_fn);
log_printf(games_js_str);
log_printf("\n");
} else if(!file_write_error(games_js_fn)) {
games = json_decref_safe(games);
}
SAFE_FREE(games_js_str);
} else if(json_object_size(games)) {
log_printf("No new game locations found.\n");
} else {
log_printf("No game locations found.\n");
if(search_path_w[0]) {
repeat = console_ask_yn("Search in a different directory?") == 'y';
}
if(!repeat) {
log_printf(
"No patch shortcuts will be created.\n"
"Please re-run this configuration tool after you have acquired some games\n"
"supported by the patches.\n"
);
pause();
}
}
json_decref(found);
} while(repeat);
CoUninitialize();
CoTaskMemFree(initial_path);
return games;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: unowrapper.hxx,v $
*
* $Revision: 1.1.1.1 $
*
* last change: $Author: hr $ $Date: 2000-09-18 17:02:08 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* 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
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _TOOLKIT_HELPER_UNOWRAPPER_HXX_
#define _TOOLKIT_HELPER_UNOWRAPPER_HXX_
#ifndef _COM_SUN_STAR_AWT_XTOOLKIT_HPP_
#include <com/sun/star/awt/XToolkit.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XGRAPHICS_HPP_
#include <com/sun/star/awt/XGraphics.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XWINDOWPEER_HPP_
#include <com/sun/star/awt/XWindowPeer.hpp>
#endif
#include <vcl/unowrap.hxx>
#include <vcl/window.hxx>
// ----------------------------------------------------
// class UnoWrapper
// ----------------------------------------------------
class UnoWrapper : public UnoWrapperBase
{
private:
::com::sun::star::uno::Reference< ::com::sun::star::awt::XToolkit> mxToolkit;
public:
UnoWrapper();
void Destroy();
// Toolkit
virtual ::com::sun::star::uno::Reference< ::com::sun::star::awt::XToolkit> GetVCLToolkit();
virtual void RegisterUnoServices();
// Graphics
virtual ::com::sun::star::uno::Reference< ::com::sun::star::awt::XGraphics> CreateGraphics( OutputDevice* pOutDev );
virtual void ReleaseAllGraphics( OutputDevice* pOutDev );
// Window
virtual ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindowPeer> GetWindowInterface( Window* pWindow, BOOL bCreate );
virtual void SetWindowInterface( Window* pWindow, ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindowPeer> xIFace );
void WindowDestroyed( Window* pWindow );
void WindowEvent_Move( Window* pWindow );
void WindowEvent_Resize( Window* pWindow );
void WindowEvent_Show( Window* pWindow, BOOL bShow );
void WindowEvent_Close( Window* pWindow );
void WindowEvent_Minimize( Window* pWindow );
void WindowEvent_Normalize( Window* pWindow );
void WindowEvent_Activate( Window* pWindow, BOOL bActivated );
void WindowEvent_MouseButtonUp( Window* pWindow, const MouseEvent& rEvt );
void WindowEvent_MouseButtonDown( Window* pWindow, const MouseEvent& rEvt );
void WindowEvent_MouseMove( Window* pWindow, const MouseEvent& rEvt );
void WindowEvent_Command( Window* pWindow, const CommandEvent& rCEvt );
void WindowEvent_KeyInput( Window* pWindow, const KeyEvent& rEvt );
void WindowEvent_KeyUp( Window* pWindow, const KeyEvent& rEvt );
void WindowEvent_GetFocus( Window* pWindow );
void WindowEvent_LoseFocus( Window* pWindow );
void WindowEvent_Paint( Window* pWindow, const Rectangle& rRect );
::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > getNewUnoServiceManager();
};
#endif // _TOOLKIT_HELPER_UNOWRAPPER_HXX_
<commit_msg>VCL without main<commit_after>/*************************************************************************
*
* $RCSfile: unowrapper.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: mm $ $Date: 2001-02-23 17:42:39 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* 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
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _TOOLKIT_HELPER_UNOWRAPPER_HXX_
#define _TOOLKIT_HELPER_UNOWRAPPER_HXX_
#ifndef _COM_SUN_STAR_AWT_XTOOLKIT_HPP_
#include <com/sun/star/awt/XToolkit.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XGRAPHICS_HPP_
#include <com/sun/star/awt/XGraphics.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XWINDOWPEER_HPP_
#include <com/sun/star/awt/XWindowPeer.hpp>
#endif
#include <vcl/unowrap.hxx>
#include <vcl/window.hxx>
// ----------------------------------------------------
// class UnoWrapper
// ----------------------------------------------------
class UnoWrapper : public UnoWrapperBase
{
private:
::com::sun::star::uno::Reference< ::com::sun::star::awt::XToolkit> mxToolkit;
public:
UnoWrapper( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XToolkit>& rxToolkit );
void Destroy();
// Toolkit
virtual ::com::sun::star::uno::Reference< ::com::sun::star::awt::XToolkit> GetVCLToolkit();
virtual void RegisterUnoServices();
// Graphics
virtual ::com::sun::star::uno::Reference< ::com::sun::star::awt::XGraphics> CreateGraphics( OutputDevice* pOutDev );
virtual void ReleaseAllGraphics( OutputDevice* pOutDev );
// Window
virtual ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindowPeer> GetWindowInterface( Window* pWindow, BOOL bCreate );
virtual void SetWindowInterface( Window* pWindow, ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindowPeer> xIFace );
void WindowDestroyed( Window* pWindow );
void WindowEvent_Move( Window* pWindow );
void WindowEvent_Resize( Window* pWindow );
void WindowEvent_Show( Window* pWindow, BOOL bShow );
void WindowEvent_Close( Window* pWindow );
void WindowEvent_Minimize( Window* pWindow );
void WindowEvent_Normalize( Window* pWindow );
void WindowEvent_Activate( Window* pWindow, BOOL bActivated );
void WindowEvent_MouseButtonUp( Window* pWindow, const MouseEvent& rEvt );
void WindowEvent_MouseButtonDown( Window* pWindow, const MouseEvent& rEvt );
void WindowEvent_MouseMove( Window* pWindow, const MouseEvent& rEvt );
void WindowEvent_Command( Window* pWindow, const CommandEvent& rCEvt );
void WindowEvent_KeyInput( Window* pWindow, const KeyEvent& rEvt );
void WindowEvent_KeyUp( Window* pWindow, const KeyEvent& rEvt );
void WindowEvent_GetFocus( Window* pWindow );
void WindowEvent_LoseFocus( Window* pWindow );
void WindowEvent_Paint( Window* pWindow, const Rectangle& rRect );
::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > getNewUnoServiceManager();
};
#endif // _TOOLKIT_HELPER_UNOWRAPPER_HXX_
<|endoftext|> |
<commit_before>#include <iostream>
#include <sstream>
#include "Myexception.h"
#include "chain.h"
using namespace std;
void chain :: readAndStoreFromFile(char* fileName)
{
//This function reads integers from the file given by fileName then store them in the chain
/*ifstream in;
ifstream infile("input.txt");
stringstream
in.open(filename.c_str());
if (!in) return; // file doesn't exist
int line;
while(in >> line) {
insert(listSize, line);
}*/
ifstream infile(fileName.c_str()) ;
string line;
while(getline(infile, line)) {
istringstream iss(line);
int n;
iss >> n;
}
/*int line;
while(std::getline(data, line))
std::stringstream str(line);
std::string text;
std::getline(str,text,'=');
double value;
str >> value;
}*/
}
void chain :: eraseModuloValue(int theInt)
{
//This function erases all the entries from the list which are multiple of theInt
for(int i=0; i<listSize; i++) {
int value = *this->get(i);
if (value/theInt > 0 && value != theInt) remove(i);
}
}
void chain :: oddAndEvenOrdering()
{
//This function reorders the list such a way that all odd numbers precede all even numbers.
//Note that for two odd (even) numbers i and j, the ordering between i and j should be intact after reordering.
}
void chain :: reverse()
{
//Reverses the list
}
chain :: chain(int initialCapacity)
{
//Constructor
if(initialCapacity < 1)
{
ostringstream s;
s << "Initial capacity = " << initialCapacity << " Must be > 0";
throw illegalParameterValue(s.str());
}
firstNode = NULL;
listSize = 0;
}
chain :: ~chain()
{
//Destructor. Delete all nodes in chain
while(firstNode != NULL)
{
//delete firstNode
chainNode* nextNode = firstNode->next;
delete firstNode;
firstNode = nextNode;
}
}
int* chain :: get(int theIndex) const
{
//Return element whose index is theIndex.
//Throw illegalIndex exception if no such element.
try{
checkIndex(theIndex);
}
catch(illegalIndex &e){
e.outputMessage();
return NULL;
}
chainNode* currentNode = firstNode;
for(int i=0;i<theIndex;i++)
currentNode = currentNode->next;
return ¤tNode->element;
}
int chain :: indexOf(const int& theElement) const
{
//Return index of first occurrence of theElement.
//Return -1 of theElement not in list.
chainNode* currentNode = firstNode;
int index = 0;
while(currentNode != NULL && currentNode->element != theElement)
{
//move to the next node
currentNode = currentNode->next;
index++;
}
//make sure we found matching element
if(currentNode == NULL)
return -1;
else
return index;
}
void chain :: erase(int theIndex)
{
//Delete the element whose index is theIndex.
//Throw illegalIndex exception if no such element.
try{
checkIndex(theIndex);
}
catch(illegalIndex &e){
e.outputMessage();
return;
}
chainNode* deleteNode;
if(theIndex == 0)
{
//remove first node from chain
deleteNode = firstNode;
firstNode = firstNode->next;
}
else
{
//use p to get to predecessor of desired node
chainNode* p = firstNode;
for(int i=0;i<theIndex-1;i++)
p = p->next;
deleteNode = p->next;
p->next = p->next->next; //remove deleteNode from chain
}
listSize--;
delete deleteNode;
}
void chain :: insert(int theIndex, const int& theElement)
{
//Insert theElement so that its index is theIndex.
try{
if (theIndex < 0 || theIndex > listSize)
{// invalid index
ostringstream s;
s << "index = " << theIndex << " size = " << listSize;
throw illegalIndex(s.str());
}
}
catch(illegalIndex &e){
e.outputMessage();
return;
}
if(theIndex == 0)
//insert at front
firstNode = new chainNode(theElement, firstNode);
else
{
chainNode *p = firstNode;
for(int i=0;i<theIndex-1;i++)
p = p->next;
//insert after p
p->next = new chainNode(theElement, p->next);
}
listSize++;
}
void chain :: output() const
{
//Put the list into the output.
for(int i=0;i<listSize;i++)
cout << *this->get(i) << " ";
cout<<endl;
}
void chain::checkIndex(int theIndex) const
{
// Verify that theIndex is between 0 and
// listSize - 1.
if (theIndex < 0 || theIndex >= listSize){
ostringstream s;
s << "index = " << theIndex << " size = "
<< listSize<<", the input index is invalid";
throw illegalIndex(s.str());
}
}
<commit_msg>Update chain.cpp<commit_after>#include <iostream>
#include <sstream>
#include "Myexception.h"
#include "chain.h"
using namespace std;
void chain :: readAndStoreFromFile(char* fileName)
{
//This function reads integers from the file given by fileName then store them in the chain
/*ifstream in;
ifstream infile("input.txt");
stringstream
in.open(filename.c_str());
if (!in) return; // file doesn't exist
int line;
while(in >> line) {
insert(listSize, line);
}*/
ifstream infile(fileName.c_str()) ;
string line;
while(getline(infile, line)) {
istringstream iss(line);
int n;
iss >> n;
insert(listSize, n);
}
/*int line;
while(std::getline(data, line))
std::stringstream str(line);
std::string text;
std::getline(str,text,'=');
double value;
str >> value;
}*/
}
void chain :: eraseModuloValue(int theInt)
{
//This function erases all the entries from the list which are multiple of theInt
for(int i=0; i<listSize; i++) {
int value = *this->get(i);
if (value/theInt > 0 && value != theInt) remove(i);
}
}
void chain :: oddAndEvenOrdering()
{
//This function reorders the list such a way that all odd numbers precede all even numbers.
//Note that for two odd (even) numbers i and j, the ordering between i and j should be intact after reordering.
}
void chain :: reverse()
{
//Reverses the list
}
chain :: chain(int initialCapacity)
{
//Constructor
if(initialCapacity < 1)
{
ostringstream s;
s << "Initial capacity = " << initialCapacity << " Must be > 0";
throw illegalParameterValue(s.str());
}
firstNode = NULL;
listSize = 0;
}
chain :: ~chain()
{
//Destructor. Delete all nodes in chain
while(firstNode != NULL)
{
//delete firstNode
chainNode* nextNode = firstNode->next;
delete firstNode;
firstNode = nextNode;
}
}
int* chain :: get(int theIndex) const
{
//Return element whose index is theIndex.
//Throw illegalIndex exception if no such element.
try{
checkIndex(theIndex);
}
catch(illegalIndex &e){
e.outputMessage();
return NULL;
}
chainNode* currentNode = firstNode;
for(int i=0;i<theIndex;i++)
currentNode = currentNode->next;
return ¤tNode->element;
}
int chain :: indexOf(const int& theElement) const
{
//Return index of first occurrence of theElement.
//Return -1 of theElement not in list.
chainNode* currentNode = firstNode;
int index = 0;
while(currentNode != NULL && currentNode->element != theElement)
{
//move to the next node
currentNode = currentNode->next;
index++;
}
//make sure we found matching element
if(currentNode == NULL)
return -1;
else
return index;
}
void chain :: erase(int theIndex)
{
//Delete the element whose index is theIndex.
//Throw illegalIndex exception if no such element.
try{
checkIndex(theIndex);
}
catch(illegalIndex &e){
e.outputMessage();
return;
}
chainNode* deleteNode;
if(theIndex == 0)
{
//remove first node from chain
deleteNode = firstNode;
firstNode = firstNode->next;
}
else
{
//use p to get to predecessor of desired node
chainNode* p = firstNode;
for(int i=0;i<theIndex-1;i++)
p = p->next;
deleteNode = p->next;
p->next = p->next->next; //remove deleteNode from chain
}
listSize--;
delete deleteNode;
}
void chain :: insert(int theIndex, const int& theElement)
{
//Insert theElement so that its index is theIndex.
try{
if (theIndex < 0 || theIndex > listSize)
{// invalid index
ostringstream s;
s << "index = " << theIndex << " size = " << listSize;
throw illegalIndex(s.str());
}
}
catch(illegalIndex &e){
e.outputMessage();
return;
}
if(theIndex == 0)
//insert at front
firstNode = new chainNode(theElement, firstNode);
else
{
chainNode *p = firstNode;
for(int i=0;i<theIndex-1;i++)
p = p->next;
//insert after p
p->next = new chainNode(theElement, p->next);
}
listSize++;
}
void chain :: output() const
{
//Put the list into the output.
for(int i=0;i<listSize;i++)
cout << *this->get(i) << " ";
cout<<endl;
}
void chain::checkIndex(int theIndex) const
{
// Verify that theIndex is between 0 and
// listSize - 1.
if (theIndex < 0 || theIndex >= listSize){
ostringstream s;
s << "index = " << theIndex << " size = "
<< listSize<<", the input index is invalid";
throw illegalIndex(s.str());
}
}
<|endoftext|> |
<commit_before>/**
*main.cpp
*
*@author neucrack
*@date 2016-04-21
*
*/
#include "hardware.h"
#include "app.h"
#include "Interrupt.h"
App app;
void Timer2_IRQ();
// ----------------------------------------------------------------------------
int
main(int argc, char* argv[])
{
app.Init();
// Infinite loop
while (1)
{
//光强传感器值,大概范围0~300
lightSensor.Converted();
app.mLightSensor = lightSensor.mConvertedVoltage[0]*100;
//循环
app.loop();
}
}
//定时器2 中断,1ms中断一次,用来放步进电机的中断处理函数
void Timer2_IRQ()
{
app.TimerInterrupt();
}
// ----------------------------------------------------------------------------
<commit_msg>timer bug fix (not start............................)<commit_after>/**
*main.cpp
*
*@author neucrack
*@date 2016-04-21
*
*/
#include "hardware.h"
#include "app.h"
#include "Interrupt.h"
App app;
void Timer2_IRQ();
// ----------------------------------------------------------------------------
int
main(int argc, char* argv[])
{
app.Init();
timer.Start();
// Infinite loop
while (1)
{
//光强传感器值,大概范围0~300
lightSensor.Converted();
app.mLightSensor = lightSensor.mConvertedVoltage[0]*100;
//循环
app.loop();
}
}
//定时器2 中断,1ms中断一次,用来放步进电机的中断处理函数
void Timer2_IRQ()
{
app.TimerInterrupt();
}
// ----------------------------------------------------------------------------
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include "PoolFactory.h"
#include <folly/json.h>
#include "mcrouter/ClientPool.h"
#include "mcrouter/ConfigApi.h"
#include "mcrouter/lib/fbi/cpp/util.h"
#include "mcrouter/McrouterLogFailure.h"
#include "mcrouter/options.h"
#include "mcrouter/ProxyClientCommon.h"
namespace facebook { namespace memcache { namespace mcrouter {
namespace {
bool isQosClassValid(uint64_t qos) {
return qos <= 4;
}
bool isQosPathValid(uint64_t qos) {
return qos <= 3;
}
void parseQos(std::string parentName, const folly::dynamic& jQos,
uint64_t& qosClass, uint64_t& qosPath) {
if (!jQos.isObject()) {
logFailure(memcache::failure::Category::kInvalidConfig,
"{}: qos must be an object.", parentName);
return;
}
uint64_t prevClass = qosClass;
if (auto jClass = jQos.get_ptr("class")) {
if (jClass->isInt() && isQosClassValid(jClass->getInt())) {
qosClass = jClass->getInt();
} else {
logFailure(memcache::failure::Category::kInvalidConfig,
"{}: qos.class must be an integer in the range [0, 4]",
parentName);
}
}
if (auto jPath = jQos.get_ptr("path")) {
if (jPath->isInt() && isQosPathValid(jPath->getInt())) {
qosPath = jPath->getInt();
} else {
logFailure(memcache::failure::Category::kInvalidConfig,
"{}: qos.path must be an integer in the range [0, 3]",
parentName);
qosClass = prevClass;
}
}
}
mc_protocol_t parseProtocol(const folly::dynamic& obj, mc_protocol_t def) {
if (auto jprotocol = obj.get_ptr("protocol")) {
if (!jprotocol->isString()) {
logFailure(memcache::failure::Category::kInvalidConfig,
"Pool protocol: expected string, {} found",
jprotocol->typeName());
return def;
}
auto str = jprotocol->stringPiece();
if (equalStr("ascii", str, folly::asciiCaseInsensitive)) {
return mc_ascii_protocol;
} else if (equalStr("umbrella", str, folly::asciiCaseInsensitive)) {
return mc_umbrella_protocol;
} else {
logFailure(memcache::failure::Category::kInvalidConfig,
"Unknown protocol '{}'", str);
}
}
return def;
}
} // anonymous namespace
PoolFactory::PoolFactory(const folly::dynamic& config,
ConfigApi& configApi,
const McrouterOptions& opts)
: configApi_(configApi),
opts_(opts) {
checkLogic(config.isObject(), "config is not an object");
if (auto jpools = config.get_ptr("pools")) {
checkLogic(jpools->isObject(), "config: 'pools' is not an object");
for (const auto& it : jpools->items()) {
parsePool(it.first.stringPiece().str(), it.second);
}
}
}
std::shared_ptr<ClientPool>
PoolFactory::parsePool(const folly::dynamic& json) {
checkLogic(json.isString() || json.isObject(),
"Pool should be a string (name of pool) or an object");
if (json.isString()) {
return parsePool(json.stringPiece().str(), json);
} else {
auto name = json.get_ptr("name");
checkLogic(name && name->isString(), "Pool should have string 'name'");
return parsePool(name->stringPiece().str(), json);
}
}
std::shared_ptr<ClientPool>
PoolFactory::parsePool(const std::string& name, const folly::dynamic& json) {
auto seenPoolIt = pools_.find(name);
if (seenPoolIt != pools_.end()) {
return seenPoolIt->second;
}
if (json.isString()) {
// get the pool from ConfigApi
std::string jsonStr;
checkLogic(configApi_.get(ConfigType::Pool, name, jsonStr),
"Can not read pool: {}", name);
return parsePool(name, parseJsonString(jsonStr));
} else {
// one day we may add inheriting from local pool
if (auto jinherit = json.get_ptr("inherit")) {
checkLogic(jinherit->isString(),
"Pool {}: inherit is not a string", name);
auto path = jinherit->stringPiece().str();
std::string jsonStr;
checkLogic(configApi_.get(ConfigType::Pool, path, jsonStr),
"Can not read pool from: {}", path);
auto newJson = parseJsonString(jsonStr);
for (auto& it : json.items()) {
newJson.insert(it.first, it.second);
}
newJson.erase("inherit");
return parsePool(name, newJson);
}
}
// pool_locality
std::chrono::milliseconds timeout{opts_.server_timeout_ms};
if (auto jlocality = json.get_ptr("pool_locality")) {
if (!jlocality->isString()) {
logFailure(memcache::failure::Category::kInvalidConfig,
"Pool {}: pool_locality is not a string", name);
} else {
auto str = jlocality->stringPiece();
if (str == "cluster") {
if (opts_.cluster_pools_timeout_ms != 0) {
timeout = std::chrono::milliseconds(opts_.cluster_pools_timeout_ms);
}
} else if (str == "region") {
if (opts_.regional_pools_timeout_ms != 0) {
timeout = std::chrono::milliseconds(opts_.regional_pools_timeout_ms);
}
} else {
logFailure(memcache::failure::Category::kInvalidConfig,
"Pool {}: '{}' pool locality is not supported", name, str);
}
}
}
// region & cluster
std::string region, cluster;
if (auto jregion = json.get_ptr("region")) {
if (!jregion->isString()) {
logFailure(memcache::failure::Category::kInvalidConfig,
"Pool {}: pool_region is not a string", name);
} else {
region = jregion->stringPiece().str();
}
}
if (auto jcluster = json.get_ptr("cluster")) {
if (!jcluster->isString()) {
logFailure(memcache::failure::Category::kInvalidConfig,
"Pool {}: pool_cluster is not a string", name);
} else {
cluster = jcluster->stringPiece().str();
}
}
if (auto jtimeout = json.get_ptr("server_timeout")) {
if (!jtimeout->isInt()) {
logFailure(memcache::failure::Category::kInvalidConfig,
"Pool {}: server_timeout is not an int", name);
} else {
timeout = std::chrono::milliseconds(jtimeout->getInt());
}
}
if (!region.empty() && !cluster.empty()) {
auto& route = opts_.default_route;
if (region == route.getRegion() && cluster == route.getCluster()) {
if (opts_.within_cluster_timeout_ms != 0) {
timeout = std::chrono::milliseconds(opts_.within_cluster_timeout_ms);
}
} else if (region == route.getRegion()) {
if (opts_.cross_cluster_timeout_ms != 0) {
timeout = std::chrono::milliseconds(opts_.cross_cluster_timeout_ms);
}
} else {
if (opts_.cross_region_timeout_ms != 0) {
timeout = std::chrono::milliseconds(opts_.cross_region_timeout_ms);
}
}
}
auto protocol = parseProtocol(json, mc_ascii_protocol);
bool keep_routing_prefix = false;
if (auto jkeep_routing_prefix = json.get_ptr("keep_routing_prefix")) {
checkLogic(jkeep_routing_prefix->isBool(),
"Pool {}: keep_routing_prefix is not a bool");
keep_routing_prefix = jkeep_routing_prefix->getBool();
}
uint64_t qosClass = opts_.default_qos_class;
uint64_t qosPath = opts_.default_qos_path;
if (auto jqos = json.get_ptr("qos")) {
parseQos(folly::sformat("Pool {}", name), *jqos, qosClass, qosPath);
}
bool useSsl = false;
if (auto juseSsl = json.get_ptr("use_ssl")) {
checkLogic(juseSsl->isBool(), "Pool {}: use_ssl is not a bool", name);
useSsl = juseSsl->getBool();
}
// servers
auto jservers = json.get_ptr("servers");
checkLogic(jservers, "Pool {}: servers not found", name);
checkLogic(jservers->isArray(), "Pool {}: servers is not an array", name);
auto clientPool = std::make_shared<ClientPool>(name);
for (size_t i = 0; i < jservers->size(); ++i) {
const auto& server = jservers->at(i);
auto ap = std::make_shared<AccessPoint>();
bool serverUseSsl = useSsl;
uint64_t serverQosClass = qosClass;
uint64_t serverQosPath = qosPath;
checkLogic(server.isString() || server.isObject(),
"Pool {}: server #{} is not a string/object", name, i);
if (server.isString()) {
// we support both host:port and host:port:protocol
checkLogic(AccessPoint::create(server.stringPiece(), protocol, *ap),
"Pool {}: invalid server {}", name, server.stringPiece());
} else { // object
auto jhostname = server.get_ptr("hostname");
checkLogic(jhostname,
"Pool {}: hostname not found for server #{}", name, i);
checkLogic(jhostname->isString(),
"Pool {}: hostname is not a string for server #{}", name, i);
if (auto jqos = server.get_ptr("qos")) {
parseQos(folly::sformat("Pool {}, server #{}", name, i),
*jqos, qosClass, qosPath);
}
if (auto juseSsl = server.get_ptr("use_ssl")) {
checkLogic(juseSsl->isBool(),
"Pool {}: use_ssl is not a bool for server #{}", name, i);
serverUseSsl = juseSsl->getBool();
}
checkLogic(AccessPoint::create(jhostname->stringPiece(),
parseProtocol(server, protocol), *ap),
"Pool {}: invalid server #{}", name, i);
}
auto client = clientPool->emplaceClient(
timeout,
std::move(ap),
keep_routing_prefix,
serverUseSsl,
serverQosClass,
serverQosPath);
clients_.push_back(std::move(client));
} // servers
// weights
if (auto jweights = json.get_ptr("weights")) {
clientPool->setWeights(*jweights);
}
pools_.emplace(name, clientPool);
return clientPool;
}
}}} // facebook::memcache::mcrouter
<commit_msg>Do not reconfigure on invalid protocol<commit_after>/*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include "PoolFactory.h"
#include <folly/json.h>
#include "mcrouter/ClientPool.h"
#include "mcrouter/ConfigApi.h"
#include "mcrouter/lib/fbi/cpp/util.h"
#include "mcrouter/McrouterLogFailure.h"
#include "mcrouter/options.h"
#include "mcrouter/ProxyClientCommon.h"
namespace facebook { namespace memcache { namespace mcrouter {
namespace {
bool isQosClassValid(uint64_t qos) {
return qos <= 4;
}
bool isQosPathValid(uint64_t qos) {
return qos <= 3;
}
void parseQos(std::string parentName, const folly::dynamic& jQos,
uint64_t& qosClass, uint64_t& qosPath) {
if (!jQos.isObject()) {
logFailure(memcache::failure::Category::kInvalidConfig,
"{}: qos must be an object.", parentName);
return;
}
uint64_t prevClass = qosClass;
if (auto jClass = jQos.get_ptr("class")) {
if (jClass->isInt() && isQosClassValid(jClass->getInt())) {
qosClass = jClass->getInt();
} else {
logFailure(memcache::failure::Category::kInvalidConfig,
"{}: qos.class must be an integer in the range [0, 4]",
parentName);
}
}
if (auto jPath = jQos.get_ptr("path")) {
if (jPath->isInt() && isQosPathValid(jPath->getInt())) {
qosPath = jPath->getInt();
} else {
logFailure(memcache::failure::Category::kInvalidConfig,
"{}: qos.path must be an integer in the range [0, 3]",
parentName);
qosClass = prevClass;
}
}
}
mc_protocol_t parseProtocol(const folly::dynamic& obj, mc_protocol_t def) {
if (auto jprotocol = obj.get_ptr("protocol")) {
checkLogic(jprotocol->isString(),
"Protocol: expected string, {} found",
jprotocol->typeName());
auto str = jprotocol->stringPiece();
if (equalStr("ascii", str, folly::asciiCaseInsensitive)) {
return mc_ascii_protocol;
} else if (equalStr("umbrella", str, folly::asciiCaseInsensitive)) {
return mc_umbrella_protocol;
}
checkLogic(false, "Unknown protocol '{}'", str);
}
return def;
}
} // anonymous namespace
PoolFactory::PoolFactory(const folly::dynamic& config,
ConfigApi& configApi,
const McrouterOptions& opts)
: configApi_(configApi),
opts_(opts) {
checkLogic(config.isObject(), "config is not an object");
if (auto jpools = config.get_ptr("pools")) {
checkLogic(jpools->isObject(), "config: 'pools' is not an object");
for (const auto& it : jpools->items()) {
parsePool(it.first.stringPiece().str(), it.second);
}
}
}
std::shared_ptr<ClientPool>
PoolFactory::parsePool(const folly::dynamic& json) {
checkLogic(json.isString() || json.isObject(),
"Pool should be a string (name of pool) or an object");
if (json.isString()) {
return parsePool(json.stringPiece().str(), json);
} else {
auto name = json.get_ptr("name");
checkLogic(name && name->isString(), "Pool should have string 'name'");
return parsePool(name->stringPiece().str(), json);
}
}
std::shared_ptr<ClientPool>
PoolFactory::parsePool(const std::string& name, const folly::dynamic& json) {
auto seenPoolIt = pools_.find(name);
if (seenPoolIt != pools_.end()) {
return seenPoolIt->second;
}
if (json.isString()) {
// get the pool from ConfigApi
std::string jsonStr;
checkLogic(configApi_.get(ConfigType::Pool, name, jsonStr),
"Can not read pool: {}", name);
return parsePool(name, parseJsonString(jsonStr));
} else {
// one day we may add inheriting from local pool
if (auto jinherit = json.get_ptr("inherit")) {
checkLogic(jinherit->isString(),
"Pool {}: inherit is not a string", name);
auto path = jinherit->stringPiece().str();
std::string jsonStr;
checkLogic(configApi_.get(ConfigType::Pool, path, jsonStr),
"Can not read pool from: {}", path);
auto newJson = parseJsonString(jsonStr);
for (auto& it : json.items()) {
newJson.insert(it.first, it.second);
}
newJson.erase("inherit");
return parsePool(name, newJson);
}
}
// pool_locality
std::chrono::milliseconds timeout{opts_.server_timeout_ms};
if (auto jlocality = json.get_ptr("pool_locality")) {
if (!jlocality->isString()) {
logFailure(memcache::failure::Category::kInvalidConfig,
"Pool {}: pool_locality is not a string", name);
} else {
auto str = jlocality->stringPiece();
if (str == "cluster") {
if (opts_.cluster_pools_timeout_ms != 0) {
timeout = std::chrono::milliseconds(opts_.cluster_pools_timeout_ms);
}
} else if (str == "region") {
if (opts_.regional_pools_timeout_ms != 0) {
timeout = std::chrono::milliseconds(opts_.regional_pools_timeout_ms);
}
} else {
logFailure(memcache::failure::Category::kInvalidConfig,
"Pool {}: '{}' pool locality is not supported", name, str);
}
}
}
// region & cluster
std::string region, cluster;
if (auto jregion = json.get_ptr("region")) {
if (!jregion->isString()) {
logFailure(memcache::failure::Category::kInvalidConfig,
"Pool {}: pool_region is not a string", name);
} else {
region = jregion->stringPiece().str();
}
}
if (auto jcluster = json.get_ptr("cluster")) {
if (!jcluster->isString()) {
logFailure(memcache::failure::Category::kInvalidConfig,
"Pool {}: pool_cluster is not a string", name);
} else {
cluster = jcluster->stringPiece().str();
}
}
if (auto jtimeout = json.get_ptr("server_timeout")) {
if (!jtimeout->isInt()) {
logFailure(memcache::failure::Category::kInvalidConfig,
"Pool {}: server_timeout is not an int", name);
} else {
timeout = std::chrono::milliseconds(jtimeout->getInt());
}
}
if (!region.empty() && !cluster.empty()) {
auto& route = opts_.default_route;
if (region == route.getRegion() && cluster == route.getCluster()) {
if (opts_.within_cluster_timeout_ms != 0) {
timeout = std::chrono::milliseconds(opts_.within_cluster_timeout_ms);
}
} else if (region == route.getRegion()) {
if (opts_.cross_cluster_timeout_ms != 0) {
timeout = std::chrono::milliseconds(opts_.cross_cluster_timeout_ms);
}
} else {
if (opts_.cross_region_timeout_ms != 0) {
timeout = std::chrono::milliseconds(opts_.cross_region_timeout_ms);
}
}
}
auto protocol = parseProtocol(json, mc_ascii_protocol);
bool keep_routing_prefix = false;
if (auto jkeep_routing_prefix = json.get_ptr("keep_routing_prefix")) {
checkLogic(jkeep_routing_prefix->isBool(),
"Pool {}: keep_routing_prefix is not a bool");
keep_routing_prefix = jkeep_routing_prefix->getBool();
}
uint64_t qosClass = opts_.default_qos_class;
uint64_t qosPath = opts_.default_qos_path;
if (auto jqos = json.get_ptr("qos")) {
parseQos(folly::sformat("Pool {}", name), *jqos, qosClass, qosPath);
}
bool useSsl = false;
if (auto juseSsl = json.get_ptr("use_ssl")) {
checkLogic(juseSsl->isBool(), "Pool {}: use_ssl is not a bool", name);
useSsl = juseSsl->getBool();
}
// servers
auto jservers = json.get_ptr("servers");
checkLogic(jservers, "Pool {}: servers not found", name);
checkLogic(jservers->isArray(), "Pool {}: servers is not an array", name);
auto clientPool = std::make_shared<ClientPool>(name);
for (size_t i = 0; i < jservers->size(); ++i) {
const auto& server = jservers->at(i);
auto ap = std::make_shared<AccessPoint>();
bool serverUseSsl = useSsl;
uint64_t serverQosClass = qosClass;
uint64_t serverQosPath = qosPath;
checkLogic(server.isString() || server.isObject(),
"Pool {}: server #{} is not a string/object", name, i);
if (server.isString()) {
// we support both host:port and host:port:protocol
checkLogic(AccessPoint::create(server.stringPiece(), protocol, *ap),
"Pool {}: invalid server {}", name, server.stringPiece());
} else { // object
auto jhostname = server.get_ptr("hostname");
checkLogic(jhostname,
"Pool {}: hostname not found for server #{}", name, i);
checkLogic(jhostname->isString(),
"Pool {}: hostname is not a string for server #{}", name, i);
if (auto jqos = server.get_ptr("qos")) {
parseQos(folly::sformat("Pool {}, server #{}", name, i),
*jqos, qosClass, qosPath);
}
if (auto juseSsl = server.get_ptr("use_ssl")) {
checkLogic(juseSsl->isBool(),
"Pool {}: use_ssl is not a bool for server #{}", name, i);
serverUseSsl = juseSsl->getBool();
}
checkLogic(AccessPoint::create(jhostname->stringPiece(),
parseProtocol(server, protocol), *ap),
"Pool {}: invalid server #{}", name, i);
}
auto client = clientPool->emplaceClient(
timeout,
std::move(ap),
keep_routing_prefix,
serverUseSsl,
serverQosClass,
serverQosPath);
clients_.push_back(std::move(client));
} // servers
// weights
if (auto jweights = json.get_ptr("weights")) {
clientPool->setWeights(*jweights);
}
pools_.emplace(name, clientPool);
return clientPool;
}
}}} // facebook::memcache::mcrouter
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2014 Andrew Duggan
* Copyright (C) 2014 Synaptics Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <getopt.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <dirent.h>
#include <unistd.h>
#include <time.h>
#include <string>
#include <sstream>
#include <time.h>
#include "hiddevice.h"
#include "rmi4update.h"
#define VERSION_MAJOR 1
#define VERSION_MINOR 3
#define VERSION_SUBMINOR 9
#define RMI4UPDATE_GETOPTS "hfd:t:pclvm"
bool needDebugMessage;
void printHelp(const char *prog_name)
{
fprintf(stdout, "Usage: %s [OPTIONS] FIRMWAREFILE\n", prog_name);
fprintf(stdout, "\t-h, --help\t\tPrint this message\n");
fprintf(stdout, "\t-f, --force\t\tForce updating firmware even it the image provided is older\n\t\t\t\tthen the current firmware on the device.\n");
fprintf(stdout, "\t-d, --device\t\thidraw device file associated with the device being updated.\n");
fprintf(stdout, "\t-p, --fw-props\t\tPrint the firmware properties.\n");
fprintf(stdout, "\t-c, --config-id\t\tPrint the config id.\n");
fprintf(stdout, "\t-l, --lockdown\t\tPerform lockdown.\n");
fprintf(stdout, "\t-v, --version\t\tPrint version number.\n");
fprintf(stdout, "\t-t, --device-type\tFilter by device type [touchpad or touchscreen].\n");
}
void printVersion()
{
fprintf(stdout, "rmi4update version %d.%d.%d\n",
VERSION_MAJOR, VERSION_MINOR, VERSION_SUBMINOR);
}
int GetFirmwareProps(const char * deviceFile, std::string &props, bool configid)
{
HIDDevice rmidevice;
int rc = UPDATE_SUCCESS;
std::stringstream ss;
rc = rmidevice.Open(deviceFile);
if (rc)
return rc;
if (needDebugMessage)
rmidevice.m_hasDebug = true;
// Clear all interrupts before parsing to avoid unexpected interrupts.
rmidevice.ToggleInterruptMask(false);
rmidevice.ScanPDT(0x1);
rmidevice.QueryBasicProperties();
// Restore the interrupts
rmidevice.ToggleInterruptMask(true);
if (configid) {
ss << std::hex << rmidevice.GetConfigID();
} else {
ss << rmidevice.GetFirmwareVersionMajor() << "."
<< rmidevice.GetFirmwareVersionMinor() << "."
<< rmidevice.GetFirmwareID();
if (rmidevice.InBootloader())
ss << " bootloader";
}
props = ss.str();
return rc;
}
int main(int argc, char **argv)
{
int rc;
FirmwareImage image;
int opt;
int index;
char *deviceName = NULL;
const char *firmwareName = NULL;
bool force = false;
static struct option long_options[] = {
{"help", 0, NULL, 'h'},
{"force", 0, NULL, 'f'},
{"device", 1, NULL, 'd'},
{"fw-props", 0, NULL, 'p'},
{"config-id", 0, NULL, 'c'},
{"lockdown", 0, NULL, 'l'},
{"version", 0, NULL, 'v'},
{"device-type", 1, NULL, 't'},
{0, 0, 0, 0},
};
bool printFirmwareProps = false;
bool printConfigid = false;
bool performLockdown = false;
needDebugMessage = false;
HIDDevice device;
enum RMIDeviceType deviceType = RMI_DEVICE_TYPE_ANY;
while ((opt = getopt_long(argc, argv, RMI4UPDATE_GETOPTS, long_options, &index)) != -1) {
switch (opt) {
case 'h':
printHelp(argv[0]);
return 0;
case 'f':
force = true;
break;
case 'd':
deviceName = optarg;
break;
case 'p':
printFirmwareProps = true;
break;
case 'c':
printFirmwareProps = true;
printConfigid = true;
break;
case 'l':
performLockdown = true;
break;
case 't':
if (!strcasecmp((const char *)optarg, "touchpad"))
deviceType = RMI_DEVICE_TYPE_TOUCHPAD;
else if (!strcasecmp((const char *)optarg, "touchscreen"))
deviceType = RMI_DEVICE_TYPE_TOUCHSCREEN;
break;
case 'v':
printVersion();
return 0;
case 'm':
needDebugMessage = true;
break;
default:
break;
}
}
if (printFirmwareProps) {
std::string props;
if (!deviceName) {
fprintf(stderr, "Specifiy which device to query\n");
return 1;
}
rc = GetFirmwareProps(deviceName, props, printConfigid);
if (rc) {
fprintf(stderr, "Failed to read properties from device: %s\n", update_err_to_string(rc));
return 1;
}
fprintf(stdout, "%s\n", props.c_str());
return 0;
}
if (optind < argc) {
firmwareName = argv[optind];
} else {
printHelp(argv[0]);
return -1;
}
rc = image.Initialize(firmwareName);
if (rc != UPDATE_SUCCESS) {
fprintf(stderr, "Failed to initialize the firmware image: %s\n", update_err_to_string(rc));
return 1;
}
if (deviceName) {
rc = device.Open(deviceName);
if (rc) {
fprintf(stderr, "%s: failed to initialize rmi device (%d): %s\n", argv[0], errno,
strerror(errno));
return 1;
}
} else {
if (!device.FindDevice(deviceType))
return 1;
}
if (needDebugMessage) {
device.m_hasDebug = true;
}
RMI4Update update(device, image);
rc = update.UpdateFirmware(force, performLockdown);
if (rc != UPDATE_SUCCESS)
{
device.Reset();
return 1;
}
return 0;
}
<commit_msg>Update version for v1.3.10 release<commit_after>/*
* Copyright (C) 2014 Andrew Duggan
* Copyright (C) 2014 Synaptics Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <getopt.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <dirent.h>
#include <unistd.h>
#include <time.h>
#include <string>
#include <sstream>
#include <time.h>
#include "hiddevice.h"
#include "rmi4update.h"
#define VERSION_MAJOR 1
#define VERSION_MINOR 3
#define VERSION_SUBMINOR 10
#define RMI4UPDATE_GETOPTS "hfd:t:pclvm"
bool needDebugMessage;
void printHelp(const char *prog_name)
{
fprintf(stdout, "Usage: %s [OPTIONS] FIRMWAREFILE\n", prog_name);
fprintf(stdout, "\t-h, --help\t\tPrint this message\n");
fprintf(stdout, "\t-f, --force\t\tForce updating firmware even it the image provided is older\n\t\t\t\tthen the current firmware on the device.\n");
fprintf(stdout, "\t-d, --device\t\thidraw device file associated with the device being updated.\n");
fprintf(stdout, "\t-p, --fw-props\t\tPrint the firmware properties.\n");
fprintf(stdout, "\t-c, --config-id\t\tPrint the config id.\n");
fprintf(stdout, "\t-l, --lockdown\t\tPerform lockdown.\n");
fprintf(stdout, "\t-v, --version\t\tPrint version number.\n");
fprintf(stdout, "\t-t, --device-type\tFilter by device type [touchpad or touchscreen].\n");
}
void printVersion()
{
fprintf(stdout, "rmi4update version %d.%d.%d\n",
VERSION_MAJOR, VERSION_MINOR, VERSION_SUBMINOR);
}
int GetFirmwareProps(const char * deviceFile, std::string &props, bool configid)
{
HIDDevice rmidevice;
int rc = UPDATE_SUCCESS;
std::stringstream ss;
rc = rmidevice.Open(deviceFile);
if (rc)
return rc;
if (needDebugMessage)
rmidevice.m_hasDebug = true;
// Clear all interrupts before parsing to avoid unexpected interrupts.
rmidevice.ToggleInterruptMask(false);
rmidevice.ScanPDT(0x1);
rmidevice.QueryBasicProperties();
// Restore the interrupts
rmidevice.ToggleInterruptMask(true);
if (configid) {
ss << std::hex << rmidevice.GetConfigID();
} else {
ss << rmidevice.GetFirmwareVersionMajor() << "."
<< rmidevice.GetFirmwareVersionMinor() << "."
<< rmidevice.GetFirmwareID();
if (rmidevice.InBootloader())
ss << " bootloader";
}
props = ss.str();
return rc;
}
int main(int argc, char **argv)
{
int rc;
FirmwareImage image;
int opt;
int index;
char *deviceName = NULL;
const char *firmwareName = NULL;
bool force = false;
static struct option long_options[] = {
{"help", 0, NULL, 'h'},
{"force", 0, NULL, 'f'},
{"device", 1, NULL, 'd'},
{"fw-props", 0, NULL, 'p'},
{"config-id", 0, NULL, 'c'},
{"lockdown", 0, NULL, 'l'},
{"version", 0, NULL, 'v'},
{"device-type", 1, NULL, 't'},
{0, 0, 0, 0},
};
bool printFirmwareProps = false;
bool printConfigid = false;
bool performLockdown = false;
needDebugMessage = false;
HIDDevice device;
enum RMIDeviceType deviceType = RMI_DEVICE_TYPE_ANY;
while ((opt = getopt_long(argc, argv, RMI4UPDATE_GETOPTS, long_options, &index)) != -1) {
switch (opt) {
case 'h':
printHelp(argv[0]);
return 0;
case 'f':
force = true;
break;
case 'd':
deviceName = optarg;
break;
case 'p':
printFirmwareProps = true;
break;
case 'c':
printFirmwareProps = true;
printConfigid = true;
break;
case 'l':
performLockdown = true;
break;
case 't':
if (!strcasecmp((const char *)optarg, "touchpad"))
deviceType = RMI_DEVICE_TYPE_TOUCHPAD;
else if (!strcasecmp((const char *)optarg, "touchscreen"))
deviceType = RMI_DEVICE_TYPE_TOUCHSCREEN;
break;
case 'v':
printVersion();
return 0;
case 'm':
needDebugMessage = true;
break;
default:
break;
}
}
if (printFirmwareProps) {
std::string props;
if (!deviceName) {
fprintf(stderr, "Specifiy which device to query\n");
return 1;
}
rc = GetFirmwareProps(deviceName, props, printConfigid);
if (rc) {
fprintf(stderr, "Failed to read properties from device: %s\n", update_err_to_string(rc));
return 1;
}
fprintf(stdout, "%s\n", props.c_str());
return 0;
}
if (optind < argc) {
firmwareName = argv[optind];
} else {
printHelp(argv[0]);
return -1;
}
rc = image.Initialize(firmwareName);
if (rc != UPDATE_SUCCESS) {
fprintf(stderr, "Failed to initialize the firmware image: %s\n", update_err_to_string(rc));
return 1;
}
if (deviceName) {
rc = device.Open(deviceName);
if (rc) {
fprintf(stderr, "%s: failed to initialize rmi device (%d): %s\n", argv[0], errno,
strerror(errno));
return 1;
}
} else {
if (!device.FindDevice(deviceType))
return 1;
}
if (needDebugMessage) {
device.m_hasDebug = true;
}
RMI4Update update(device, image);
rc = update.UpdateFirmware(force, performLockdown);
if (rc != UPDATE_SUCCESS)
{
device.Reset();
return 1;
}
return 0;
}
<|endoftext|> |
<commit_before>#ifndef __RMOL_RMOL_TYPES_HPP
#define __RMOL_RMOL_TYPES_HPP
// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <vector>
#include <list>
// Boost
#include <boost/shared_ptr.hpp>
namespace RMOL {
// Forward declarations
class RMOL_Service;
// ///////// Exceptions ///////////
class RootException : public std::exception {
};
class FileNotFoundException : public RootException {
};
class NonInitialisedServiceException : public RootException {
};
class MemoryAllocationException : public RootException {
};
class ObjectNotFoundException : public RootException {
};
class DocumentNotFoundException : public RootException {
};
// /////////////// Log /////////////
/** Level of logs. */
namespace LOG {
typedef enum {
CRITICAL = 0,
ERROR,
NOTIFICATION,
WARNING,
DEBUG,
VERBOSE,
LAST_VALUE
} EN_LogLevel;
}
// //////// Type definitions /////////
/** Pointer on the RMOL Service handler. */
typedef boost::shared_ptr<RMOL::RMOL_Service> RMOL_ServicePtr_T;
}
#endif // __RMOL_RMOL_TYPES_HPP
<commit_msg>[API] Fixed the RMOL_Service type definition for reference by other components.<commit_after>#ifndef __RMOL_RMOL_TYPES_HPP
#define __RMOL_RMOL_TYPES_HPP
// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <vector>
#include <list>
// Boost
#include <boost/shared_ptr.hpp>
namespace RMOL {
// Forward declarations
class RMOL_Service;
// ///////// Exceptions ///////////
class RootException : public std::exception {
};
class FileNotFoundException : public RootException {
};
class NonInitialisedServiceException : public RootException {
};
class MemoryAllocationException : public RootException {
};
class ObjectNotFoundException : public RootException {
};
class DocumentNotFoundException : public RootException {
};
// /////////////// Log /////////////
/** Level of logs. */
namespace LOG {
typedef enum {
CRITICAL = 0,
ERROR,
NOTIFICATION,
WARNING,
DEBUG,
VERBOSE,
LAST_VALUE
} EN_LogLevel;
}
// //////// Type definitions /////////
/** Pointer on the RMOL Service handler. */
typedef boost::shared_ptr<RMOL_Service> RMOL_ServicePtr_T;
}
#endif // __RMOL_RMOL_TYPES_HPP
<|endoftext|> |
<commit_before>// Macro to run TPC performance
// By default 6 performance components are added to
// the output:
// 1. AliPerformanceRes (TPC track resolution at DCA)
// 2. AliPerformanceResTPCInner (TPC track resolution at inner TPC wall)
// 3. AliPerformanceEff (TPC track reconstruction efficieny)
// 4. AliPerformanceDEdxTPCInner (TPC dEdxresponse - track parameters at TPC inner wall)
// 5. AliPerformanceDCA (TPC impact parameter resolution at DCA)
// 6. AliPerformanceTPC (TPC cluster and track information)
/*
//1. Run locally e.g.
gROOT->LoadMacro("$ALICE_ROOT/PWG1/macros/LoadMyLibs.C");
gROOT->LoadMacro("$ALICE_ROOT/PWG0/CreateESDChain.C");
TChain* chain = CreateESDChain("list_PbPb_EMCAL.txt", 1, 0);
chain->Lookup();
// set magnetic field
TGeoGlobalMagField::Instance()->SetField(new AliMagF("Maps","Maps", 2, 1., 1., 10., AliMagF::k5kG));
gROOT->LoadMacro("$ALICE_ROOT/PWG1/macros/RunPerformanceTask.C");
RunPerformanceTask(chain, kTRUE, kFALSE, kFALSE);
//2. Run on PROOF Lite e.g.
TProof::Open("");
gROOT->LoadMacro("$ALICE_ROOT/PWG1/macros/ProofEnableAliRoot.C");
ProofEnableAliRoot("/u/jacek/alice/AliRoot/HEAD/");
gROOT->LoadMacro("$ALICE_ROOT/PWG0/CreateESDChain.C");
TChain* chain = CreateESDChain("list_PbPb_EMCAL.txt",20, 0);
chain->Lookup();
// set magnetic field
TGeoGlobalMagField::Instance()->SetField(new AliMagF("Maps","Maps", 2, 1., 1., 10., AliMagF::k5kG));
gROOT->LoadMacro("$ALICE_ROOT/PWG1/macros/RunPerformanceTask.C");
RunPerformanceTask(chain, kTRUE, kFALSE, kTRUE);
//3. Run only on static PROOF at GSI e.g.
TProof::Reset("jacek@lxgrid5.gsi.de");
TProofMgr * proofmgr = TProof::Mgr("jacek@lxgrid5.gsi.de");
proofmgr->SetROOTVersion("523-04");
TProof * proof = proofmgr->CreateSession();
proof->SetParameter("PROOF_MaxSlavesPerNode", (Long_t)10000);
gROOT->LoadMacro("$ALICE_ROOT/PWG1/macros/ProofEnableAliRoot.C");
ProofEnableAliRoot("/u/jacek/alice/AliRoot/HEAD/");
gROOT->LoadMacro("$ALICE_ROOT/PWG0/CreateESDChain.C");
TChain* chain = CreateESDChain("esd_v4-16-Rev-08-grid.txt", 200, 0);
chain->Lookup();
// set magnetic field
TGeoGlobalMagField::Instance()->SetField(new AliMagF("Maps","Maps", 2, 1., 1., 10., AliMagF::k5kG));
gROOT->LoadMacro("$ALICE_ROOT/PWG1/macros/RunPerformanceTask.C");
RunPerformanceTask(chain, kTRUE, kFALSE, kTRUE);
//4. Make final spectra and store them in the
// output folder and generate control pictures e.g.
TFile f("TPC.Performance.root");
AliPerformanceEff * compObjEff = (AliPerformanceEff*)coutput->FindObject("AliPerformanceEff");
compObjEff->Analyse();
compObjEff->GetAnalysisFolder()->ls("*");
// create pictures
compObjEff->PrintHisto(kTRUE,"PerformanceEffQA.ps");
// store output QA histograms in file
TFile fout("PerformanceEffQAHisto.root","recreate");
compObjEff->GetAnalysisFolder()->Write();
fout.Close();
f.Close();
*/
//_____________________________________________________________________________
void RunPerformanceTask(TChain *chain, Bool_t bUseMCInfo=kTRUE, Bool_t bUseFriend=kTRUE, Bool_t bProof=kTRUE)
{
if(!chain)
{
AliDebug(AliLog::kError, "ERROR: No input chain available");
return;
}
// set Proof
if(bProof) {
/*
// ONLY FOR GSI
TProof::Reset("jacek@lxgrid5.gsi.de");
TProofMgr * proofmgr = TProof::Mgr("jacek@lxgrid5.gsi.de");
proofmgr->SetROOTVersion("523-04");
TProof * proof = proofmgr->CreateSession();
proof->SetParameter("PROOF_MaxSlavesPerNode", (Long_t)10000);
*/
//cout << "*** START PROOF Lite SESSION ***" << endl;
TProof::Open("");
gROOT->LoadMacro("ProofEnableAliRoot.C");
ProofEnableAliRoot("/u/jacek/alice/AliRoot/HEAD/");
}
//
// Create global cuts objects
//
// Create ESD track reconstruction cuts
AliRecInfoCuts *pRecInfoCuts = new AliRecInfoCuts();
if(pRecInfoCuts) {
pRecInfoCuts->SetMaxDCAToVertexXY(3.0);
pRecInfoCuts->SetMaxDCAToVertexZ(3.0);
pRecInfoCuts->SetMinNClustersTPC(50);
pRecInfoCuts->SetMinNClustersITS(2);
pRecInfoCuts->SetHistogramsOn(kFALSE);
} else {
AliDebug(AliLog::kError, "ERROR: Cannot create AliRecInfoCuts object");
}
// Create MC track reconstruction cuts
AliMCInfoCuts *pMCInfoCuts = new AliMCInfoCuts();
if(pMCInfoCuts) {
pMCInfoCuts->SetMinTrackLength(50);
} else {
AliDebug(AliLog::kError, "ERROR: Cannot AliMCInfoCuts object");
}
//
// Create performance objects and set cuts
//
enum { kTPC = 0, kTPCITS, kConstrained, kTPCInner, kTPCOuter, kTPCSec };
//
// Resolution
//
AliPerformanceRes *pCompRes0 = new AliPerformanceRes("AliPerformanceRes","AliPerformanceRes",kTPC,kFALSE);
if(!pCompRes0) {
AliDebug(AliLog::kError, "ERROR: Cannot create AliPerformanceRes object");
}
pCompRes0->SetAliRecInfoCuts(pRecInfoCuts);
pCompRes0->SetAliMCInfoCuts(pMCInfoCuts);
AliPerformanceRes *pCompRes3 = new AliPerformanceRes("AliPerformanceResTPCInner","AliPerformanceResTPCInner",kTPCInner,kFALSE);
if(!pCompRes3) {
AliDebug(AliLog::kError, "ERROR: Cannot create AliPerformanceResInnerTPC object");
}
pCompRes3->SetAliRecInfoCuts(pRecInfoCuts);
pCompRes3->SetAliMCInfoCuts(pMCInfoCuts);
AliPerformanceRes *pCompRes4 = new AliPerformanceRes("AliPerformanceResTPCOuter","AliPerformanceResTPCOuter",kTPCOuter,kFALSE);
if(!pCompRes4) {
AliDebug(AliLog::kError, "ERROR: Cannot create AliPerformanceResOuterTPC object");
}
pCompRes4->SetAliRecInfoCuts(pRecInfoCuts);
pCompRes4->SetAliMCInfoCuts(pMCInfoCuts);
//
// Efficiency
//
AliPerformanceEff *pCompEff0 = new AliPerformanceEff("AliPerformanceEff","AliPerformanceEff",kTPC,kFALSE);
if(!pCompEff0) {
AliDebug(AliLog::kError, "ERROR: Cannot create AliPerformanceEff object");
}
pCompEff0->SetAliRecInfoCuts(pRecInfoCuts);
pCompEff0->SetAliMCInfoCuts(pMCInfoCuts);
//
// dEdx
//
AliPerformanceDEdx *pCompDEdx3 = new AliPerformanceDEdx("AliPerformanceDEdxTPCInner","AliPerformanceDEdxTPCInner",kTPCInner,kFALSE);
if(!pCompDEdx3) {
AliDebug(AliLog::kError, "ERROR: Cannot create AliPerformanceDEdxTPCInner object");
}
pCompDEdx3->SetAliRecInfoCuts(pRecInfoCuts);
pCompDEdx3->SetAliMCInfoCuts(pMCInfoCuts);
//
// DCA
//
AliPerformanceDCA *pCompDCA0 = new AliPerformanceDCA("AliPerformanceDCA","AliPerformanceDCA",kTPC,kFALSE);
if(!pCompDCA0) {
AliDebug(AliLog::kError, "ERROR: Cannot create AliPerformanceDCA object");
}
pCompDCA0->SetAliRecInfoCuts(pRecInfoCuts);
pCompDCA0->SetAliMCInfoCuts(pMCInfoCuts);
//
// TPC performance
//
AliPerformanceTPC *pCompTPC0 = new AliPerformanceTPC("AliPerformanceTPC","AliPerformanceTPC",kTPC,kFALSE);
if(!pCompTPC0) {
AliDebug(AliLog::kError, "ERROR: Cannot create AliPerformanceTPC object");
}
pCompTPC0->SetAliRecInfoCuts(pRecInfoCuts);
pCompTPC0->SetAliMCInfoCuts(pMCInfoCuts);
// Swtich off all AliInfo (too much output!!!)
AliLog::SetGlobalLogLevel(AliLog::kError);
// Create the analysis manager
AliAnalysisManager *mgr = new AliAnalysisManager;
// Create task
AliPerformanceTask *task = new AliPerformanceTask("Performance","TPC Performance");
if (bUseMCInfo) task->SetUseMCInfo(kTRUE);
if (bUseFriend) task->SetUseESDfriend(kTRUE);
task->AddPerformanceObject( pCompRes0 );
task->AddPerformanceObject( pCompRes3 );
if(bUseFriend) task->AddPerformanceObject( pCompRes4 );
task->AddPerformanceObject( pCompEff0 );
task->AddPerformanceObject( pCompDEdx3 );
task->AddPerformanceObject( pCompDCA0 );
task->AddPerformanceObject( pCompTPC0 );
// Add task
mgr->AddTask(task);
// Add ESD handler
AliESDInputHandler* esdH = new AliESDInputHandler;
mgr->SetInputEventHandler(esdH);
if(bUseMCInfo) {
// Enable MC event handler
AliMCEventHandler* handler = new AliMCEventHandler;
handler->SetReadTR(kTRUE);
mgr->SetMCtruthEventHandler(handler);
}
// Create containers for input
AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();
mgr->ConnectInput(task, 0, cinput);
// Create containers for output
AliAnalysisDataContainer *coutput = mgr->CreateContainer("coutput", TList::Class(), AliAnalysisManager::kOutputContainer, Form("TPC.%s.root", task->GetName()));
mgr->ConnectOutput(task, 0, coutput);
// Enable debug printouts
mgr->SetDebugLevel(0);
if (!mgr->InitAnalysis())
return;
mgr->PrintStatus();
if(bProof) mgr->StartAnalysis("proof",chain);
else mgr->StartAnalysis("local",chain);
}
<commit_msg>small modifications<commit_after>// Macro to run TPC performance task (locally, proof).
//
// By default 7 performance components are added to
// the task:
// 1. AliPerformanceRes (TPC track resolution w.r.t MC at DCA)
// 2. AliPerformanceResTPCInner (TPC track resolution w.r.t MC at inner TPC wall)
// 3. AliPerformanceResTPCOuter (TPC track resolution w.r.t MC at outer TPC wall)
// 4. AliPerformanceEff (TPC track reconstruction efficiency, MC primaries)
// 5. AliPerformanceDEdxTPCInner (TPC dEdx response - track parameters at TPC inner wall)
// 6. AliPerformanceDCA (TPC impact parameters resolution at DCA)
// 7. AliPerformanceTPC (TPC cluster and track information)
//
/*
//1. Run locally e.g.
gROOT->LoadMacro("$ALICE_ROOT/PWG1/macros/LoadMyLibs.C");
gROOT->LoadMacro("$ALICE_ROOT/PWG0/CreateESDChain.C");
TChain* chain = CreateESDChain("list_flatP_JB.txt",10, 0);
chain->Lookup();
gROOT->LoadMacro("$ALICE_ROOT/PWG1/macros/RunPerformanceTask.C");
RunPerformanceTask(chain, kTRUE, kTRUE, kFALSE);
//2. Run on PROOF Lite e.g.
TProof::Open("");
gROOT->LoadMacro("$ALICE_ROOT/PWG1/macros/ProofEnableAliRoot.C");
ProofEnableAliRoot("/d/alice11/jacek/alice/x86_64/AliRoot/trunkJB/");
gROOT->LoadMacro("$ALICE_ROOT/PWG0/CreateESDChain.C");
TChain* chain = CreateESDChain("list_flatP_JB.txt",20, 0);
chain->Lookup();
gROOT->LoadMacro("$ALICE_ROOT/PWG1/macros/RunPerformanceTask.C");
RunPerformanceTask(chain, kTRUE, kTRUE, kTRUE);
//3. Run only on static PROOF at GSI e.g.
TProof::Reset("jacek@lxgrid5.gsi.de");
TProofMgr * proofmgr = TProof::Mgr("jacek@lxgrid5.gsi.de");
//proofmgr->SetROOTVersion("523-04");
TProof * proof = proofmgr->CreateSession();
proof->SetParameter("PROOF_MaxSlavesPerNode", (Long_t)10000);
gROOT->LoadMacro("$ALICE_ROOT/PWG1/macros/ProofEnableAliRoot.C");
ProofEnableAliRoot("/u/jacek/alice/AliRoot/HEAD/");
gROOT->LoadMacro("$ALICE_ROOT/PWG0/CreateESDChain.C");
TChain* chain = CreateESDChain("esd_v4-16-Rev-08-grid.txt", 200, 0);
chain->Lookup();
gROOT->LoadMacro("$ALICE_ROOT/PWG1/macros/RunPerformanceTask.C");
RunPerformanceTask(chain, kTRUE, kTRUE, kTRUE);
//4. Make final spectra and store them in the
// output folder and generate control pictures e.g.
TFile f("TPC.Performance.root");
AliPerformanceRes * compObjRes = (AliPerformanceRes*)coutput->FindObject("AliPerformanceResTPCOuter");
compObjRes->Analyse();
compObjRes->GetAnalysisFolder()->ls("*");
// create pictures
compObjRes->PrintHisto(kTRUE,"PerformanceResTPCOuterQA.ps");
// store output QA histograms in file
TFile fout("PerformanceResTPCOuterQAHisto.root","recreate");
compObjRes->GetAnalysisFolder()->Write();
fout.Close();
f.Close();
*/
//_____________________________________________________________________________
void RunPerformanceTask(TChain *chain, Bool_t bUseMCInfo=kTRUE, Bool_t bUseESDfriend=kTRUE, Bool_t bProof=kTRUE)
{
if(!chain)
{
AliDebug(AliLog::kError, "ERROR: No input chain available");
return;
}
//
// Swtich off all AliInfo (too much output!)
//
AliLog::SetGlobalLogLevel(AliLog::kError);
//
// Create analysis manager
//
AliAnalysisManager *mgr = new AliAnalysisManager;
if(!mgr) {
Error("runTPCQA","AliAnalysisManager not set!");
return;
}
//
// Set ESD input handler
//
AliESDInputHandler* esdH = new AliESDInputHandler;
if(!esdH) {
Error("runTPCQA","AliESDInputHandler not created!");
return;
}
if(bUseESDfriend) esdH->SetActiveBranches("ESDfriend");
mgr->SetInputEventHandler(esdH);
//
// Set MC input handler
//
if(bUseMCInfo) {
AliMCEventHandler* mcH = new AliMCEventHandler;
if(!esdH) {
Error("runTPCQA","AliMCEventHandler not created!");
return;
}
mcH->SetReadTR(kTRUE);
mgr->SetMCtruthEventHandler(mcH);
}
//
// Add task to AliAnalysisManager
//
gROOT->LoadMacro("$ALICE_ROOT/PWG1/macros/AddTaskPerformanceTPC.C");
AliPerformanceTask *tpcQA = AddTaskPerformanceTPC(bUseMCInfo,bUseESDfriend);
if(!tpcQA) {
Error("runTPCQA","TaskPerformanceTPC not created!");
return;
}
// Enable debug printouts
mgr->SetDebugLevel(0);
if (!mgr->InitAnalysis())
return;
mgr->PrintStatus();
if(bProof) mgr->StartAnalysis("proof",chain);
else mgr->StartAnalysis("local",chain);
}
<|endoftext|> |
<commit_before>// This file is part of the dune-gdt project:
// https://github.com/dune-community/dune-gdt
// Copyright 2010-2016 dune-gdt developers and contributors. All rights reserved.
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
// Authors:
// Felix Schindler (2012 - 2016)
// Rene Milk (2013 - 2014)
// Tobias Leibner (2014)
#ifndef DUNE_GDT_ASSEMBLER_SYSTEM_HH
#define DUNE_GDT_ASSEMBLER_SYSTEM_HH
#include <type_traits>
#include <memory>
#include <dune/common/deprecated.hh>
#include <dune/common/version.hh>
#include <dune/xt/grid/walker.hh>
#include <dune/xt/common/parallel/helper.hh>
#include <dune/gdt/spaces/interface.hh>
#include <dune/gdt/spaces/constraints.hh>
#include "wrapper.hh"
namespace Dune {
namespace GDT {
template <class TestSpaceImp,
class GridViewImp = typename TestSpaceImp::GridViewType,
class AnsatzSpaceImp = TestSpaceImp>
class SystemAssembler : public XT::Grid::Walker<GridViewImp>
{
static_assert(GDT::is_space<TestSpaceImp>::value, "TestSpaceImp has to be derived from SpaceInterface!");
static_assert(GDT::is_space<AnsatzSpaceImp>::value, "AnsatzSpaceImp has to be derived from SpaceInterface!");
static_assert(std::is_same<typename TestSpaceImp::RangeFieldType, typename AnsatzSpaceImp::RangeFieldType>::value,
"Types do not match!");
typedef XT::Grid::Walker<GridViewImp> BaseType;
typedef SystemAssembler<TestSpaceImp, GridViewImp, AnsatzSpaceImp> ThisType;
public:
typedef TestSpaceImp TestSpaceType;
typedef AnsatzSpaceImp AnsatzSpaceType;
typedef typename TestSpaceType::RangeFieldType RangeFieldType;
typedef typename BaseType::GridViewType GridViewType;
typedef typename BaseType::EntityType EntityType;
typedef typename BaseType::IntersectionType IntersectionType;
typedef XT::Grid::ApplyOn::WhichEntity<GridViewType> ApplyOnWhichEntity;
typedef XT::Grid::ApplyOn::WhichIntersection<GridViewType> ApplyOnWhichIntersection;
SystemAssembler(TestSpaceType test, AnsatzSpaceType ansatz, GridViewType grd_vw)
: BaseType(grd_vw)
, test_space_(test)
, ansatz_space_(ansatz)
{
}
SystemAssembler(TestSpaceType test, AnsatzSpaceType ansatz)
: BaseType(test.grid_view())
, test_space_(test)
, ansatz_space_(ansatz)
{
}
explicit SystemAssembler(TestSpaceType test)
: BaseType(test.grid_view())
, test_space_(test)
, ansatz_space_(test)
{
}
SystemAssembler(TestSpaceType test, GridViewType grd_vw)
: BaseType(grd_vw)
, test_space_(test)
, ansatz_space_(test)
{
}
SystemAssembler(ThisType&& source) = default;
const TestSpaceType& test_space() const
{
return *test_space_;
}
const AnsatzSpaceType& ansatz_space() const
{
return *ansatz_space_;
}
using BaseType::add;
template <class C>
void add(ConstraintsInterface<C>& constraints,
const ApplyOnWhichEntity* where = new XT::Grid::ApplyOn::AllEntities<GridViewType>())
{
typedef internal::ConstraintsWrapper<TestSpaceType, AnsatzSpaceType, GridViewType, typename C::derived_type>
WrapperType;
this->codim0_functors_.emplace_back(new WrapperType(test_space_, ansatz_space_, where, constraints.as_imp()));
} // ... add(...)
template <class V, class M>
void add(const LocalVolumeTwoFormAssembler<V>& local_assembler,
XT::LA::MatrixInterface<M, RangeFieldType>& matrix,
const ApplyOnWhichEntity* where = new XT::Grid::ApplyOn::AllEntities<GridViewType>())
{
assert(matrix.rows() == test_space_->mapper().size());
assert(matrix.cols() == ansatz_space_->mapper().size());
typedef internal::LocalVolumeTwoFormMatrixAssemblerWrapper<ThisType,
LocalVolumeTwoFormAssembler<V>,
typename M::derived_type>
WrapperType;
this->codim0_functors_.emplace_back(
new WrapperType(test_space_, ansatz_space_, where, local_assembler, matrix.as_imp()));
} // ... add(...)
template <class V, class M>
void add(const LocalCouplingTwoFormAssembler<V>& local_assembler,
XT::LA::MatrixInterface<M, RangeFieldType>& matrix,
const ApplyOnWhichIntersection* where = new XT::Grid::ApplyOn::AllIntersections<GridViewType>())
{
assert(matrix.rows() == test_space_->mapper().size());
assert(matrix.cols() == ansatz_space_->mapper().size());
typedef internal::LocalCouplingTwoFormMatrixAssemblerWrapper<ThisType,
LocalCouplingTwoFormAssembler<V>,
typename M::derived_type>
WrapperType;
this->codim1_functors_.emplace_back(
new WrapperType(test_space_, ansatz_space_, where, local_assembler, matrix.as_imp()));
} // ... add(...)
template <class V, class M>
void add(const LocalBoundaryTwoFormAssembler<V>& local_assembler,
XT::LA::MatrixInterface<M, RangeFieldType>& matrix,
const ApplyOnWhichIntersection* where = new XT::Grid::ApplyOn::AllIntersections<GridViewType>())
{
assert(matrix.rows() == test_space_->mapper().size());
assert(matrix.cols() == ansatz_space_->mapper().size());
typedef internal::LocalBoundaryTwoFormMatrixAssemblerWrapper<ThisType,
LocalBoundaryTwoFormAssembler<V>,
typename M::derived_type>
WrapperType;
this->codim1_functors_.emplace_back(
new WrapperType(test_space_, ansatz_space_, where, local_assembler, matrix.as_imp()));
} // ... add(...)
template <class L, class V>
void add(const LocalVolumeFunctionalAssembler<L>& local_assembler,
XT::LA::VectorInterface<V, RangeFieldType>& vector,
const ApplyOnWhichEntity* where = new XT::Grid::ApplyOn::AllEntities<GridViewType>())
{
assert(vector.size() == test_space_->mapper().size());
typedef internal::LocalVolumeFunctionalVectorAssemblerWrapper<ThisType,
LocalVolumeFunctionalAssembler<L>,
typename V::derived_type>
WrapperType;
this->codim0_functors_.emplace_back(new WrapperType(test_space_, where, local_assembler, vector.as_imp()));
} // ... add(...)
template <class L, class V>
void add(const LocalFaceFunctionalAssembler<L>& local_assembler,
XT::LA::VectorInterface<V, RangeFieldType>& vector,
const ApplyOnWhichIntersection* where = new XT::Grid::ApplyOn::AllIntersections<GridViewType>())
{
assert(vector.size() == test_space_->mapper().size());
typedef internal::LocalFaceFunctionalVectorAssemblerWrapper<ThisType,
LocalFaceFunctionalAssembler<L>,
typename V::derived_type>
WrapperType;
this->codim1_functors_.emplace_back(new WrapperType(test_space_, where, local_assembler, vector.as_imp()));
} // ... add(...)
void assemble(const bool use_tbb = false)
{
this->walk(use_tbb);
}
template <class Partitioning>
void assemble(const Partitioning& partitioning)
{
this->walk(partitioning);
}
protected:
const Dune::XT::Common::PerThreadValue<const TestSpaceType> test_space_;
const Dune::XT::Common::PerThreadValue<const AnsatzSpaceType> ansatz_space_;
}; // class SystemAssembler
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_ASSEMBLER_SYSTEM_HH
<commit_msg>[assembler.system] rename add -> append<commit_after>// This file is part of the dune-gdt project:
// https://github.com/dune-community/dune-gdt
// Copyright 2010-2016 dune-gdt developers and contributors. All rights reserved.
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
// Authors:
// Felix Schindler (2012 - 2016)
// Rene Milk (2013 - 2014)
// Tobias Leibner (2014)
#ifndef DUNE_GDT_ASSEMBLER_SYSTEM_HH
#define DUNE_GDT_ASSEMBLER_SYSTEM_HH
#include <type_traits>
#include <memory>
#include <dune/common/deprecated.hh>
#include <dune/common/version.hh>
#include <dune/xt/grid/walker.hh>
#include <dune/xt/common/parallel/helper.hh>
#include <dune/gdt/spaces/interface.hh>
#include <dune/gdt/spaces/constraints.hh>
#include "wrapper.hh"
namespace Dune {
namespace GDT {
template <class TestSpaceImp,
class GridViewImp = typename TestSpaceImp::GridViewType,
class AnsatzSpaceImp = TestSpaceImp>
class SystemAssembler : public XT::Grid::Walker<GridViewImp>
{
static_assert(GDT::is_space<TestSpaceImp>::value, "TestSpaceImp has to be derived from SpaceInterface!");
static_assert(GDT::is_space<AnsatzSpaceImp>::value, "AnsatzSpaceImp has to be derived from SpaceInterface!");
static_assert(std::is_same<typename TestSpaceImp::RangeFieldType, typename AnsatzSpaceImp::RangeFieldType>::value,
"Types do not match!");
typedef XT::Grid::Walker<GridViewImp> BaseType;
typedef SystemAssembler<TestSpaceImp, GridViewImp, AnsatzSpaceImp> ThisType;
public:
typedef TestSpaceImp TestSpaceType;
typedef AnsatzSpaceImp AnsatzSpaceType;
typedef typename TestSpaceType::RangeFieldType RangeFieldType;
typedef typename BaseType::GridViewType GridViewType;
typedef typename BaseType::EntityType EntityType;
typedef typename BaseType::IntersectionType IntersectionType;
typedef XT::Grid::ApplyOn::WhichEntity<GridViewType> ApplyOnWhichEntity;
typedef XT::Grid::ApplyOn::WhichIntersection<GridViewType> ApplyOnWhichIntersection;
SystemAssembler(TestSpaceType test, AnsatzSpaceType ansatz, GridViewType grd_vw)
: BaseType(grd_vw)
, test_space_(test)
, ansatz_space_(ansatz)
{
}
SystemAssembler(TestSpaceType test, AnsatzSpaceType ansatz)
: BaseType(test.grid_view())
, test_space_(test)
, ansatz_space_(ansatz)
{
}
explicit SystemAssembler(TestSpaceType test)
: BaseType(test.grid_view())
, test_space_(test)
, ansatz_space_(test)
{
}
SystemAssembler(TestSpaceType test, GridViewType grd_vw)
: BaseType(grd_vw)
, test_space_(test)
, ansatz_space_(test)
{
}
SystemAssembler(ThisType&& source) = default;
const TestSpaceType& test_space() const
{
return *test_space_;
}
const AnsatzSpaceType& ansatz_space() const
{
return *ansatz_space_;
}
using BaseType::append;
template <class C>
ThisType& append(ConstraintsInterface<C>& constraints,
const ApplyOnWhichEntity* where = new XT::Grid::ApplyOn::AllEntities<GridViewType>())
{
typedef internal::ConstraintsWrapper<TestSpaceType, AnsatzSpaceType, GridViewType, typename C::derived_type>
WrapperType;
this->codim0_functors_.emplace_back(new WrapperType(test_space_, ansatz_space_, where, constraints.as_imp()));
return *this;
} // ... append(...)
template <class V, class M>
ThisType& append(const LocalVolumeTwoFormAssembler<V>& local_assembler,
XT::LA::MatrixInterface<M, RangeFieldType>& matrix,
const ApplyOnWhichEntity* where = new XT::Grid::ApplyOn::AllEntities<GridViewType>())
{
assert(matrix.rows() == test_space_->mapper().size());
assert(matrix.cols() == ansatz_space_->mapper().size());
typedef internal::LocalVolumeTwoFormMatrixAssemblerWrapper<ThisType,
LocalVolumeTwoFormAssembler<V>,
typename M::derived_type>
WrapperType;
this->codim0_functors_.emplace_back(
new WrapperType(test_space_, ansatz_space_, where, local_assembler, matrix.as_imp()));
return *this;
} // ... append(...)
template <class V, class M>
ThisType& append(const LocalCouplingTwoFormAssembler<V>& local_assembler,
XT::LA::MatrixInterface<M, RangeFieldType>& matrix,
const ApplyOnWhichIntersection* where = new XT::Grid::ApplyOn::AllIntersections<GridViewType>())
{
assert(matrix.rows() == test_space_->mapper().size());
assert(matrix.cols() == ansatz_space_->mapper().size());
typedef internal::LocalCouplingTwoFormMatrixAssemblerWrapper<ThisType,
LocalCouplingTwoFormAssembler<V>,
typename M::derived_type>
WrapperType;
this->codim1_functors_.emplace_back(
new WrapperType(test_space_, ansatz_space_, where, local_assembler, matrix.as_imp()));
return *this;
} // ... append(...)
template <class V, class M>
ThisType& append(const LocalBoundaryTwoFormAssembler<V>& local_assembler,
XT::LA::MatrixInterface<M, RangeFieldType>& matrix,
const ApplyOnWhichIntersection* where = new XT::Grid::ApplyOn::AllIntersections<GridViewType>())
{
assert(matrix.rows() == test_space_->mapper().size());
assert(matrix.cols() == ansatz_space_->mapper().size());
typedef internal::LocalBoundaryTwoFormMatrixAssemblerWrapper<ThisType,
LocalBoundaryTwoFormAssembler<V>,
typename M::derived_type>
WrapperType;
this->codim1_functors_.emplace_back(
new WrapperType(test_space_, ansatz_space_, where, local_assembler, matrix.as_imp()));
return *this;
} // ... append(...)
template <class L, class V>
ThisType& append(const LocalVolumeFunctionalAssembler<L>& local_assembler,
XT::LA::VectorInterface<V, RangeFieldType>& vector,
const ApplyOnWhichEntity* where = new XT::Grid::ApplyOn::AllEntities<GridViewType>())
{
assert(vector.size() == test_space_->mapper().size());
typedef internal::LocalVolumeFunctionalVectorAssemblerWrapper<ThisType,
LocalVolumeFunctionalAssembler<L>,
typename V::derived_type>
WrapperType;
this->codim0_functors_.emplace_back(new WrapperType(test_space_, where, local_assembler, vector.as_imp()));
return *this;
} // ... append(...)
template <class L, class V>
ThisType& append(const LocalFaceFunctionalAssembler<L>& local_assembler,
XT::LA::VectorInterface<V, RangeFieldType>& vector,
const ApplyOnWhichIntersection* where = new XT::Grid::ApplyOn::AllIntersections<GridViewType>())
{
assert(vector.size() == test_space_->mapper().size());
typedef internal::LocalFaceFunctionalVectorAssemblerWrapper<ThisType,
LocalFaceFunctionalAssembler<L>,
typename V::derived_type>
WrapperType;
this->codim1_functors_.emplace_back(new WrapperType(test_space_, where, local_assembler, vector.as_imp()));
return *this;
} // ... append(...)
using BaseType::add;
template <class... Args>
DUNE_DEPRECATED_MSG("Use append() instead (since 11.01.2017)!")
ThisType& add(Args&&... args)
{
return append(std::forward<Args>(args)...);
}
void assemble(const bool use_tbb = false)
{
this->walk(use_tbb);
}
template <class Partitioning>
void assemble(const Partitioning& partitioning)
{
this->walk(partitioning);
}
protected:
const Dune::XT::Common::PerThreadValue<const TestSpaceType> test_space_;
const Dune::XT::Common::PerThreadValue<const AnsatzSpaceType> ansatz_space_;
}; // class SystemAssembler
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_ASSEMBLER_SYSTEM_HH
<|endoftext|> |
<commit_before>#include <iostream> /* allows to perform standard input and output operations */
#include <stdio.h> /* Standard input/output definitions */
#include <stdint.h> /* Standard input/output definitions */
#include <stdlib.h> /* defines several general purpose functions */
//#include <unistd.h> /* UNIX standard function definitions */
#include <fcntl.h> /* File control definitions */
#include <ctype.h> /* isxxx() */
#include <termios.h> /* POSIX terminal control definitions */
#include <errno.h> /* Error number definitions */
//#include <sqlite3.h>
#include <ros/ros.h> /* ROS */
#include <geometry_msgs/Twist.h> /* ROS Twist message */
#include <base_controller/encoders.h> /* Custom message /encoders */
#include <base_controller/md49data.h> /* Custom message /encoders */
const char* serialport_name="/dev/ttyS2"; /* defines used serialport on BPi. Use "/dev/ttyAMA0" for RPi*/
int serialport_bps=B38400; /* defines used baudrate on serialport */
int fd; /* serial port file descriptor */
struct termios orig; // backuped port options
int32_t EncoderL; /* stores encoder value left read from md49 */
int32_t EncoderR; /* stores encoder value right read from md49 */
char speed_l=128;
char speed_r=128; /* speed to set for MD49 */
char last_speed_l=128, last_speed_r=128; /* speed to set for MD49 */
double vr = 0.0;
double vl = 0.0;
double max_vr = 0.2;
double max_vl = 0.2;
double min_vr = 0.2;
double min_vl = 0.2;
double base_width = 0.4; /* Base width in meters */
unsigned char serialBuffer[18]; /* Serial buffer to store uart data */
void read_MD49_Data (void);
void set_MD49_speed (void);
int openSerialPort(const char * device, int bps);
void writeBytes(int descriptor, int count);
void readBytes(int descriptor, int count);
base_controller::encoders encoders;
base_controller::md49data md49data;
void cmd_vel_callback(const geometry_msgs::Twist& vel_cmd){
if (vel_cmd.linear.x>0){
speed_l = 255;
speed_r = 255;
}
if (vel_cmd.linear.x<0){
speed_l = 0;
speed_r = 0;
}
if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){
speed_l = 128;
speed_r = 128;
}
if (vel_cmd.angular.z>0){
speed_l = 0;
speed_r = 255;
}
if (vel_cmd.angular.z<0){
speed_l = 255;
speed_r = 0;
}
/*
//ANFANG Alternative
if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){vl=0;vr=0;}
else if(vel_cmd.linear.x == 0){
// turning
vr = vel_cmd.angular.z * base_width / 2.0;
vl = (-1) * vr;
}
else if(vel_cmd.angular.z == 0){
// forward / backward
vl = vr = vel_cmd.linear.x;
}
else{
// moving doing arcs
vl = vel_cmd.linear.x - vel_cmd.angular.z * base_width / 2.0;
if (vl > max_vl) {vl=max_vl;}
if (vl < min_vl) {vl=min_vl;}
vr = vel_cmd.linear.x + vel_cmd.angular.z * base_width / 2.0;
if (vr > max_vr) {vr=max_vr;}
if (vr < min_vr) {vr=min_vr;}
}
//ENDE Alternative
*/
}
int main( int argc, char* argv[] ){
// Init node
// *********
ros::init(argc, argv, "base_controller" );
ros::NodeHandle n;
ros::Subscriber sub = n.subscribe("/cmd_vel", 10, cmd_vel_callback);
ros::Publisher encoders_pub = n.advertise<base_controller::encoders>("encoders",10);
ros::Publisher md49data_pub = n.advertise<base_controller::md49data>("md49data",10);
ros::Rate loop_rate(20);
ROS_INFO("base_controller running...");
ROS_INFO("=============================");
ROS_INFO("Subscribing to topic /cmd_vel");
ROS_INFO("Publishing to topic /encoders");
ROS_INFO("Publishing to topic /md49data");
// Open serial port
// ****************
fd = openSerialPort(serialport_name, serialport_bps);
if (fd == -1){
ROS_FATAL("Could not open serialport at %s with %i",serialport_name,serialport_bps);
exit(1);
}
ROS_INFO("Opend serial port at %s with %i Bps",serialport_name,serialport_bps);
usleep(10000); // Sleep for UART to power up and set options
// Init MD49 defaults
// ******************
serialBuffer[0] = 0;
serialBuffer[1] = 0x37; // Command to enable rmd49 regulator
writeBytes(fd, 2);
md49data.regulator=1;
ROS_INFO("Set MD49 Regulator=Enabled");
serialBuffer[0] = 0;
serialBuffer[1] = 0x39; // Command to enable rmd49 regulator
writeBytes(fd, 2);
md49data.timeout=1;
ROS_INFO("Set MD49 Timeout=Enabled");
// Mainloop
// ********
while(n.ok())
{
// set speed as set through /cmd_vel on MD49 via UART
// **************************************************
set_MD49_speed();
// Read encoder- and other data from MD49 via UART
// ***********************************************
read_MD49_Data();
// Publish encoder values as read to topic /encoders
// *************************************************
encoders_pub.publish(encoders);
// Publish MD49 data as read to topic /md49data
// ********************************************
md49data.speed_l = serialBuffer[8];
md49data.speed_r = serialBuffer[9];
md49data.volts = serialBuffer[10];
md49data.current_l = serialBuffer[11];
md49data.current_r = serialBuffer[12];
md49data.error = serialBuffer[13];
md49data.acceleration = serialBuffer[14];
md49data.mode = serialBuffer[15];
md49data.regulator = serialBuffer[16];
md49data.timeout = serialBuffer[17];
md49data_pub.publish(md49data);
// ************
ros::spinOnce();
loop_rate.sleep();
}// end.mainloop
return 1;
} // end.main
void read_MD49_Data (void){
// Read encoder values as serial data from MD49
// ********************************************
serialBuffer[0] = 0;
serialBuffer[1] = 0x25; // Command to return encoder values
writeBytes(fd, 2);
readBytes(fd, 8);
// Set all values of custom message /encoders,
// *******************************************
encoders.encoder_l = serialBuffer[0] << 24; // Put together first encoder value
encoders.encoder_l |= (serialBuffer[1] << 16);
encoders.encoder_l |= (serialBuffer[2] << 8);
encoders.encoder_l |= (serialBuffer[3]);
encoders.encoder_r = serialBuffer[4] << 24; // Put together second encoder value
encoders.encoder_r |= (serialBuffer[5] << 16);
encoders.encoder_r |= (serialBuffer[6] << 8);
encoders.encoder_r |= (serialBuffer[7]);
encoders.encoderbyte1l=serialBuffer[0];
encoders.encoderbyte2l=serialBuffer[1];
encoders.encoderbyte3l=serialBuffer[2];
encoders.encoderbyte4l=serialBuffer[3];
encoders.encoderbyte1r=serialBuffer[4];
encoders.encoderbyte2r=serialBuffer[5];
encoders.encoderbyte3r=serialBuffer[6];
encoders.encoderbyte4r=serialBuffer[7];
// Read actual speed_l and speed_r
// as serial data from MD49
// *******************************
serialBuffer[0] = 0;
serialBuffer[1] = 0x21; // Command to return volts value
writeBytes(fd, 2);
readBytes(fd, 1);
md49data.speed_l=serialBuffer[0];
serialBuffer[0] = 0;
serialBuffer[1] = 0x22; // Command to return volts value
writeBytes(fd, 2);
readBytes(fd, 1);
md49data.speed_r=serialBuffer[0];
// Read actual volts
// as serial data from MD49
// ************************
serialBuffer[0] = 0;
serialBuffer[1] = 0x26; // Command to return volts value
writeBytes(fd, 2);
readBytes(fd, 1);
md49data.volts=serialBuffer[0];
// Read actual current_l and current_r
// as serial data from MD49
// ***********************************
serialBuffer[0] = 0;
serialBuffer[1] = 0x27; // Command to return volts value
writeBytes(fd, 2);
readBytes(fd, 1);
md49data.current_l =serialBuffer[0];
serialBuffer[0] = 0;
serialBuffer[1] = 0x28; // Command to return volts value
writeBytes(fd, 2);
readBytes(fd, 1);
md49data.current_r =serialBuffer[0];
// Read actual error
// as serial data from MD49
// ************************
serialBuffer[0] = 0;
serialBuffer[1] = 0x2D; // Command to return volts value
writeBytes(fd, 2);
readBytes(fd, 1);
md49data.error=serialBuffer[0];
// Read actual acceleration
// as serial data from MD49
// ************************
serialBuffer[0] = 0;
serialBuffer[1] = 0x2A; // Command to return volts value
writeBytes(fd, 2);
readBytes(fd, 1);
md49data.acceleration=serialBuffer[0];
// Read actual mode
// as serial data from MD49
// ************************
serialBuffer[0] = 0;
serialBuffer[1] = 0x2B; // Command to return volts value
writeBytes(fd, 2);
readBytes(fd, 1);
md49data.mode=serialBuffer[0];
// Output MD49 data on screen
// **************************
printf("\033[2J"); // clear the screen
printf("\033[H"); // position cursor at top-left corner
printf ("MD49-Data read from AVR-Master: \n");
printf("========================================\n");
printf("Encoder1 Byte1: %i ",encoders.encoderbyte1l);
printf("Byte2: %i ",encoders.encoderbyte2l);
printf("Byte3: % i ",encoders.encoderbyte3l);
printf("Byte4: %i \n",encoders.encoderbyte4l);
printf("Encoder2 Byte1: %i ",encoders.encoderbyte1r);
printf("Byte2: %i ",encoders.encoderbyte2r);
printf("Byte3: %i ",encoders.encoderbyte3r);
printf("Byte4: %i \n",encoders.encoderbyte4r);
printf("EncoderL: %i ",encoders.encoder_l);
printf("EncoderR: %i \n",encoders.encoder_r);
printf("========================================\n");
printf("SpeedL: %i ",md49data.speed_l);
printf("SpeedR: %i \n",md49data.speed_r);
printf("Volts: %i \n",md49data.volts);
printf("CurrentL: %i ",md49data.current_l);
printf("CurrentR: %i \n",md49data.current_r);
printf("Error: %i \n",md49data.error);
printf("Acceleration: %i \n",md49data.acceleration);
printf("Mode: %i \n",md49data.mode);
printf("Regulator: %i \n",md49data.regulator);
printf("Timeout: %i \n",md49data.timeout);
}
void set_MD49_speed(void){
serialBuffer[0] = 0;
serialBuffer[1] = 0x31; // Command to set motor speed
serialBuffer[2] = speed_l; // Speed to be set
serialBuffer[3] = 0;
serialBuffer[4] = 0x32;
serialBuffer[5] = speed_r;
writeBytes(fd, 6);
}
// Open serialport
// ***************
int openSerialPort(const char * device, int bps){
struct termios neu;
//char buf[128];
//fd = open(device, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK);
fd = open(device, O_RDWR | O_NOCTTY);
if (fd == -1)
{
ROS_WARN("openSerialPort %s error", device);
//sprintf(buf, "openSerialPort %s error", device);
//perror(buf);
}
else
{
tcgetattr(fd, &orig); /* save current serial settings */
tcgetattr(fd, &neu);
cfmakeraw(&neu);
cfsetispeed(&neu, bps);
cfsetospeed(&neu, bps);
tcflush(fd, TCIFLUSH);
tcsetattr(fd, TCSANOW, &neu); /* set new serial settings */
fcntl (fd, F_SETFL, O_RDWR);
}
return fd;
}
// Write bytes serial to UART
// **************************
void writeBytes(int descriptor, int count) {
if ((write(descriptor, serialBuffer, count)) == -1) { // Send data out
ROS_WARN("Error: writing at serialport");
//perror("Error writing");
close(descriptor); // Close port if there is an error
exit(1);
}
}
// Read bytes serial from UART
// ***************************
void readBytes(int descriptor, int count) {
if (read(descriptor, serialBuffer, count) == -1) { // Read back data into buf[]
ROS_WARN("Error: reading from serialport");
//perror("Error reading ");
close(descriptor); // Close port if there is an error
exit(1);
}
}
<commit_msg>Update code<commit_after>#include <iostream> /* allows to perform standard input and output operations */
#include <stdio.h> /* Standard input/output definitions */
#include <stdint.h> /* Standard input/output definitions */
#include <stdlib.h> /* defines several general purpose functions */
//#include <unistd.h> /* UNIX standard function definitions */
#include <fcntl.h> /* File control definitions */
#include <ctype.h> /* isxxx() */
#include <termios.h> /* POSIX terminal control definitions */
#include <errno.h> /* Error number definitions */
//#include <sqlite3.h>
#include <ros/ros.h> /* ROS */
#include <geometry_msgs/Twist.h> /* ROS Twist message */
#include <base_controller/encoders.h> /* Custom message /encoders */
#include <base_controller/md49data.h> /* Custom message /encoders */
const char* serialport_name="/dev/ttyS2"; /* defines used serialport on BPi. Use "/dev/ttyAMA0" for RPi*/
int serialport_bps=B38400; /* defines used baudrate on serialport */
int fd; /* serial port file descriptor */
struct termios orig; // backuped port options
int32_t EncoderL; /* stores encoder value left read from md49 */
int32_t EncoderR; /* stores encoder value right read from md49 */
char speed_l=128;
char speed_r=128; /* speed to set for MD49 */
char last_speed_l=128, last_speed_r=128; /* speed to set for MD49 */
double vr = 0.0;
double vl = 0.0;
double max_vr = 0.2;
double max_vl = 0.2;
double min_vr = 0.2;
double min_vl = 0.2;
double base_width = 0.4; /* Base width in meters */
unsigned char serialBuffer[18]; /* Serial buffer to store uart data */
void read_MD49_Data (void);
void set_MD49_speed (void);
int openSerialPort(const char * device, int bps);
void writeBytes(int descriptor, int count);
void readBytes(int descriptor, int count);
base_controller::encoders encoders;
base_controller::md49data md49data;
void cmd_vel_callback(const geometry_msgs::Twist& vel_cmd){
if (vel_cmd.linear.x>0){
speed_l = 255;
speed_r = 255;
}
if (vel_cmd.linear.x<0){
speed_l = 0;
speed_r = 0;
}
if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){
speed_l = 128;
speed_r = 128;
}
if (vel_cmd.angular.z>0){
speed_l = 0;
speed_r = 255;
}
if (vel_cmd.angular.z<0){
speed_l = 255;
speed_r = 0;
}
/*
//ANFANG Alternative
if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){vl=0;vr=0;}
else if(vel_cmd.linear.x == 0){
// turning
vr = vel_cmd.angular.z * base_width / 2.0;
vl = (-1) * vr;
}
else if(vel_cmd.angular.z == 0){
// forward / backward
vl = vr = vel_cmd.linear.x;
}
else{
// moving doing arcs
vl = vel_cmd.linear.x - vel_cmd.angular.z * base_width / 2.0;
if (vl > max_vl) {vl=max_vl;}
if (vl < min_vl) {vl=min_vl;}
vr = vel_cmd.linear.x + vel_cmd.angular.z * base_width / 2.0;
if (vr > max_vr) {vr=max_vr;}
if (vr < min_vr) {vr=min_vr;}
}
//ENDE Alternative
*/
}
int main( int argc, char* argv[] ){
// Init node
// *********
ros::init(argc, argv, "base_controller" );
ros::NodeHandle n;
ros::Subscriber sub = n.subscribe("/cmd_vel", 10, cmd_vel_callback);
ros::Publisher encoders_pub = n.advertise<base_controller::encoders>("encoders",10);
ros::Publisher md49data_pub = n.advertise<base_controller::md49data>("md49data",10);
ros::Rate loop_rate(20);
ROS_INFO("base_controller running...");
ROS_INFO("=============================");
ROS_INFO("Subscribing to topic /cmd_vel");
ROS_INFO("Publishing to topic /encoders");
ROS_INFO("Publishing to topic /md49data");
// Open serial port
// ****************
fd = openSerialPort(serialport_name, serialport_bps);
if (fd == -1){
ROS_FATAL("Could not open serialport at %s with %i",serialport_name,serialport_bps);
exit(1);
}
ROS_INFO("Opend serial port at %s with %i Bps",serialport_name,serialport_bps);
usleep(10000); // Sleep for UART to power up and set options
// Init MD49 defaults
// ******************
serialBuffer[0] = 0;
serialBuffer[1] = 0x37; // Command to enable rmd49 regulator
writeBytes(fd, 2);
md49data.regulator=1;
ROS_INFO("Set MD49 Regulator=Enabled");
serialBuffer[0] = 0;
serialBuffer[1] = 0x39; // Command to enable rmd49 regulator
writeBytes(fd, 2);
md49data.timeout=1;
ROS_INFO("Set MD49 Timeout=Enabled");
// Mainloop
// ********
while(n.ok())
{
// set speed as set through /cmd_vel on MD49 via UART
// **************************************************
set_MD49_speed();
// Read encoder- and other data from MD49 via UART
// ***********************************************
read_MD49_Data();
// Publish encoder values as read to topic /encoders
// *************************************************
encoders_pub.publish(encoders);
// Publish MD49 data as read to topic /md49data
// ********************************************
md49data_pub.publish(md49data);
// ************
ros::spinOnce();
loop_rate.sleep();
}// end.mainloop
return 1;
} // end.main
void read_MD49_Data (void){
// Read encoder values as serial data from MD49
// ********************************************
serialBuffer[0] = 0;
serialBuffer[1] = 0x25; // Command to return encoder values
writeBytes(fd, 2);
readBytes(fd, 8);
// Set all values of custom message /encoders,
// *******************************************
encoders.encoder_l = serialBuffer[0] << 24; // Put together first encoder value
encoders.encoder_l |= (serialBuffer[1] << 16);
encoders.encoder_l |= (serialBuffer[2] << 8);
encoders.encoder_l |= (serialBuffer[3]);
encoders.encoder_r = serialBuffer[4] << 24; // Put together second encoder value
encoders.encoder_r |= (serialBuffer[5] << 16);
encoders.encoder_r |= (serialBuffer[6] << 8);
encoders.encoder_r |= (serialBuffer[7]);
encoders.encoderbyte1l=serialBuffer[0];
encoders.encoderbyte2l=serialBuffer[1];
encoders.encoderbyte3l=serialBuffer[2];
encoders.encoderbyte4l=serialBuffer[3];
encoders.encoderbyte1r=serialBuffer[4];
encoders.encoderbyte2r=serialBuffer[5];
encoders.encoderbyte3r=serialBuffer[6];
encoders.encoderbyte4r=serialBuffer[7];
// Read actual speed_l and speed_r
// as serial data from MD49
// *******************************
serialBuffer[0] = 0;
serialBuffer[1] = 0x21; // Command to return volts value
writeBytes(fd, 2);
readBytes(fd, 1);
md49data.speed_l=serialBuffer[0];
serialBuffer[0] = 0;
serialBuffer[1] = 0x22; // Command to return volts value
writeBytes(fd, 2);
readBytes(fd, 1);
md49data.speed_r=serialBuffer[0];
// Read actual volts
// as serial data from MD49
// ************************
serialBuffer[0] = 0;
serialBuffer[1] = 0x26; // Command to return volts value
writeBytes(fd, 2);
readBytes(fd, 1);
md49data.volts=serialBuffer[0];
// Read actual current_l and current_r
// as serial data from MD49
// ***********************************
serialBuffer[0] = 0;
serialBuffer[1] = 0x27; // Command to return volts value
writeBytes(fd, 2);
readBytes(fd, 1);
md49data.current_l =serialBuffer[0];
serialBuffer[0] = 0;
serialBuffer[1] = 0x28; // Command to return volts value
writeBytes(fd, 2);
readBytes(fd, 1);
md49data.current_r =serialBuffer[0];
// Read actual error
// as serial data from MD49
// ************************
serialBuffer[0] = 0;
serialBuffer[1] = 0x2D; // Command to return volts value
writeBytes(fd, 2);
readBytes(fd, 1);
md49data.error=serialBuffer[0];
// Read actual acceleration
// as serial data from MD49
// ************************
serialBuffer[0] = 0;
serialBuffer[1] = 0x2A; // Command to return volts value
writeBytes(fd, 2);
readBytes(fd, 1);
md49data.acceleration=serialBuffer[0];
// Read actual mode
// as serial data from MD49
// ************************
serialBuffer[0] = 0;
serialBuffer[1] = 0x2B; // Command to return volts value
writeBytes(fd, 2);
readBytes(fd, 1);
md49data.mode=serialBuffer[0];
// Output MD49 data on screen
// **************************
printf("\033[2J"); // clear the screen
printf("\033[H"); // position cursor at top-left corner
printf ("MD49-Data read from AVR-Master: \n");
printf("========================================\n");
printf("Encoder1 Byte1: %i ",encoders.encoderbyte1l);
printf("Byte2: %i ",encoders.encoderbyte2l);
printf("Byte3: % i ",encoders.encoderbyte3l);
printf("Byte4: %i \n",encoders.encoderbyte4l);
printf("Encoder2 Byte1: %i ",encoders.encoderbyte1r);
printf("Byte2: %i ",encoders.encoderbyte2r);
printf("Byte3: %i ",encoders.encoderbyte3r);
printf("Byte4: %i \n",encoders.encoderbyte4r);
printf("EncoderL: %i ",encoders.encoder_l);
printf("EncoderR: %i \n",encoders.encoder_r);
printf("========================================\n");
printf("SpeedL: %i ",md49data.speed_l);
printf("SpeedR: %i \n",md49data.speed_r);
printf("Volts: %i \n",md49data.volts);
printf("CurrentL: %i ",md49data.current_l);
printf("CurrentR: %i \n",md49data.current_r);
printf("Error: %i \n",md49data.error);
printf("Acceleration: %i \n",md49data.acceleration);
printf("Mode: %i \n",md49data.mode);
printf("Regulator: %i \n",md49data.regulator);
printf("Timeout: %i \n",md49data.timeout);
}
void set_MD49_speed(void){
serialBuffer[0] = 0;
serialBuffer[1] = 0x31; // Command to set motor speed
serialBuffer[2] = speed_l; // Speed to be set
serialBuffer[3] = 0;
serialBuffer[4] = 0x32;
serialBuffer[5] = speed_r;
writeBytes(fd, 6);
}
// Open serialport
// ***************
int openSerialPort(const char * device, int bps){
struct termios neu;
//char buf[128];
//fd = open(device, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK);
fd = open(device, O_RDWR | O_NOCTTY);
if (fd == -1)
{
ROS_WARN("openSerialPort %s error", device);
//sprintf(buf, "openSerialPort %s error", device);
//perror(buf);
}
else
{
tcgetattr(fd, &orig); /* save current serial settings */
tcgetattr(fd, &neu);
cfmakeraw(&neu);
cfsetispeed(&neu, bps);
cfsetospeed(&neu, bps);
tcflush(fd, TCIFLUSH);
tcsetattr(fd, TCSANOW, &neu); /* set new serial settings */
fcntl (fd, F_SETFL, O_RDWR);
}
return fd;
}
// Write bytes serial to UART
// **************************
void writeBytes(int descriptor, int count) {
if ((write(descriptor, serialBuffer, count)) == -1) { // Send data out
ROS_WARN("Error: writing at serialport");
//perror("Error writing");
close(descriptor); // Close port if there is an error
exit(1);
}
}
// Read bytes serial from UART
// ***************************
void readBytes(int descriptor, int count) {
if (read(descriptor, serialBuffer, count) == -1) { // Read back data into buf[]
ROS_WARN("Error: reading from serialport");
//perror("Error reading ");
close(descriptor); // Close port if there is an error
exit(1);
}
}
<|endoftext|> |
<commit_before>#include "PackPkg.h"
#include "check_params.h"
#include <ee/Exception.h>
#include <gum/FilepathHelper.h>
#include <gum/StringHelper.h>
#include <fstream>
namespace edb
{
PackPkg::PackPkg()
: m_buf(NULL)
, m_buf_size(0)
{
}
PackPkg::~PackPkg()
{
delete[] m_buf;
}
std::string PackPkg::Command() const
{
return "pack-pkg";
}
std::string PackPkg::Description() const
{
return "pack multi ep files to one pkg file";
}
std::string PackPkg::Usage() const
{
return Command() + " [dir] [name]";
}
int PackPkg::Run(int argc, char *argv[])
{
if (!check_number(this, argc, 4)) return -1;
if (!check_folder(argv[2])) return -1;
Trigger(argv[2], argv[3]);
return 0;
}
void PackPkg::Trigger(const std::string& dir, const std::string& name)
{
std::vector<uint32_t> epe_size, ept_size;
std::string filepath = gum::FilepathHelper::Absolute(dir, name + ".epe");
if (!gum::FilepathHelper::Exists(filepath)) {
throw ee::Exception("no epe file %s", filepath.c_str());
}
epe_size.push_back(GetFileSize(filepath));
int i = 1;
while (true)
{
std::string filename = name + "." + gum::StringHelper::ToString(i) + ".epe";
std::string filepath = gum::FilepathHelper::Absolute(dir, filename);
if (!gum::FilepathHelper::Exists(filepath)) {
break;
} else {
epe_size.push_back(GetFileSize(filepath));
}
++i;
}
filepath = gum::FilepathHelper::Absolute(dir, name + ".ept");
if (!gum::FilepathHelper::Exists(filepath)) {
throw ee::Exception("no ept file %s", filepath.c_str());
}
ept_size.push_back(GetFileSize(filepath));
i = 1;
while (true)
{
std::string filename = name + "." + gum::StringHelper::ToString(i) + ".ept";
std::string filepath = gum::FilepathHelper::Absolute(dir, filename);
if (!gum::FilepathHelper::Exists(filepath)) {
break;
} else {
ept_size.push_back(GetFileSize(filepath));
}
++i;
}
if (epe_size.size() <= 1 || ept_size.size() <= 1) {
throw ee::Exception("less ep file dir: %s, name: %s, epe %d, ept %d",
dir.c_str(), name.c_str(), epe_size.size(), ept_size.size());
}
filepath = gum::FilepathHelper::Absolute(dir, name + ".pkg");
std::ofstream fout(filepath.c_str(), std::ios::binary);
// header
uint16_t count = epe_size.size();
fout.write(reinterpret_cast<const char*>(&count), sizeof(count));
count = ept_size.size();
fout.write(reinterpret_cast<const char*>(&count), sizeof(count));
//
uint32_t data_head = sizeof(uint16_t) * 2 + sizeof(uint32_t) * (epe_size.size() + ept_size.size());
uint32_t ptr = data_head;
// epe header
for (int i = 0, n = epe_size.size(); i < n; ++i)
{
uint32_t size = epe_size[i];
fout.write(reinterpret_cast<const char*>(&ptr), sizeof(ptr));
printf("++ epe ptr %d\n", ptr);
ptr += size;
}
// ept header
for (int i = 0, n = ept_size.size(); i < n; ++i)
{
uint32_t size = ept_size[i];
fout.write(reinterpret_cast<const char*>(&ptr), sizeof(ptr));
ptr += size;
}
// epe data
filepath = gum::FilepathHelper::Absolute(dir, name + ".epe");
WriteFile(filepath, epe_size[0], fout);
for (int i = 1, n = epe_size.size(); i < n; ++i)
{
std::string filename = name + "." + gum::StringHelper::ToString(i) + ".epe";
std::string filepath = gum::FilepathHelper::Absolute(dir, filename);
WriteFile(filepath, epe_size[i], fout);
}
// ept data
filepath = gum::FilepathHelper::Absolute(dir, name + ".ept");
WriteFile(filepath, ept_size[0], fout);
for (int i = 1, n = ept_size.size(); i < n; ++i)
{
std::string filename = name + "." + gum::StringHelper::ToString(i) + ".ept";
std::string filepath = gum::FilepathHelper::Absolute(dir, filename);
WriteFile(filepath, ept_size[i], fout);
}
fout.close();
}
uint32_t PackPkg::GetFileSize(const std::string& filepath)
{
std::locale::global(std::locale(""));
std::ifstream fin(filepath.c_str(), std::ios::binary);
std::locale::global(std::locale("C"));
fin.seekg(0, std::ios::end);
uint32_t size = fin.tellg();
fin.close();
return size;
}
void PackPkg::WriteFile(const std::string& src, uint32_t size, std::ofstream& fout)
{
if (m_buf_size < size)
{
delete[] m_buf;
m_buf = new unsigned char[size * 2];
m_buf_size = size * 2;
}
std::locale::global(std::locale(""));
std::ifstream fin(src.c_str(), std::ios::binary);
std::locale::global(std::locale("C"));
fin.read(reinterpret_cast<char*>(m_buf), size);
fout.write(reinterpret_cast<const char*>(m_buf), size);
fin.close();
}
}<commit_msg>rm debug log<commit_after>#include "PackPkg.h"
#include "check_params.h"
#include <ee/Exception.h>
#include <gum/FilepathHelper.h>
#include <gum/StringHelper.h>
#include <fstream>
namespace edb
{
PackPkg::PackPkg()
: m_buf(NULL)
, m_buf_size(0)
{
}
PackPkg::~PackPkg()
{
delete[] m_buf;
}
std::string PackPkg::Command() const
{
return "pack-pkg";
}
std::string PackPkg::Description() const
{
return "pack multi ep files to one pkg file";
}
std::string PackPkg::Usage() const
{
return Command() + " [dir] [name]";
}
int PackPkg::Run(int argc, char *argv[])
{
if (!check_number(this, argc, 4)) return -1;
if (!check_folder(argv[2])) return -1;
Trigger(argv[2], argv[3]);
return 0;
}
void PackPkg::Trigger(const std::string& dir, const std::string& name)
{
std::vector<uint32_t> epe_size, ept_size;
std::string filepath = gum::FilepathHelper::Absolute(dir, name + ".epe");
if (!gum::FilepathHelper::Exists(filepath)) {
throw ee::Exception("no epe file %s", filepath.c_str());
}
epe_size.push_back(GetFileSize(filepath));
int i = 1;
while (true)
{
std::string filename = name + "." + gum::StringHelper::ToString(i) + ".epe";
std::string filepath = gum::FilepathHelper::Absolute(dir, filename);
if (!gum::FilepathHelper::Exists(filepath)) {
break;
} else {
epe_size.push_back(GetFileSize(filepath));
}
++i;
}
filepath = gum::FilepathHelper::Absolute(dir, name + ".ept");
if (!gum::FilepathHelper::Exists(filepath)) {
throw ee::Exception("no ept file %s", filepath.c_str());
}
ept_size.push_back(GetFileSize(filepath));
i = 1;
while (true)
{
std::string filename = name + "." + gum::StringHelper::ToString(i) + ".ept";
std::string filepath = gum::FilepathHelper::Absolute(dir, filename);
if (!gum::FilepathHelper::Exists(filepath)) {
break;
} else {
ept_size.push_back(GetFileSize(filepath));
}
++i;
}
if (epe_size.size() <= 1 || ept_size.size() <= 1) {
throw ee::Exception("less ep file dir: %s, name: %s, epe %d, ept %d",
dir.c_str(), name.c_str(), epe_size.size(), ept_size.size());
}
filepath = gum::FilepathHelper::Absolute(dir, name + ".pkg");
std::ofstream fout(filepath.c_str(), std::ios::binary);
// header
uint16_t count = epe_size.size();
fout.write(reinterpret_cast<const char*>(&count), sizeof(count));
count = ept_size.size();
fout.write(reinterpret_cast<const char*>(&count), sizeof(count));
//
uint32_t data_head = sizeof(uint16_t) * 2 + sizeof(uint32_t) * (epe_size.size() + ept_size.size());
uint32_t ptr = data_head;
// epe header
for (int i = 0, n = epe_size.size(); i < n; ++i)
{
uint32_t size = epe_size[i];
fout.write(reinterpret_cast<const char*>(&ptr), sizeof(ptr));
ptr += size;
}
// ept header
for (int i = 0, n = ept_size.size(); i < n; ++i)
{
uint32_t size = ept_size[i];
fout.write(reinterpret_cast<const char*>(&ptr), sizeof(ptr));
ptr += size;
}
// epe data
filepath = gum::FilepathHelper::Absolute(dir, name + ".epe");
WriteFile(filepath, epe_size[0], fout);
for (int i = 1, n = epe_size.size(); i < n; ++i)
{
std::string filename = name + "." + gum::StringHelper::ToString(i) + ".epe";
std::string filepath = gum::FilepathHelper::Absolute(dir, filename);
WriteFile(filepath, epe_size[i], fout);
}
// ept data
filepath = gum::FilepathHelper::Absolute(dir, name + ".ept");
WriteFile(filepath, ept_size[0], fout);
for (int i = 1, n = ept_size.size(); i < n; ++i)
{
std::string filename = name + "." + gum::StringHelper::ToString(i) + ".ept";
std::string filepath = gum::FilepathHelper::Absolute(dir, filename);
WriteFile(filepath, ept_size[i], fout);
}
fout.close();
}
uint32_t PackPkg::GetFileSize(const std::string& filepath)
{
std::locale::global(std::locale(""));
std::ifstream fin(filepath.c_str(), std::ios::binary);
std::locale::global(std::locale("C"));
fin.seekg(0, std::ios::end);
uint32_t size = fin.tellg();
fin.close();
return size;
}
void PackPkg::WriteFile(const std::string& src, uint32_t size, std::ofstream& fout)
{
if (m_buf_size < size)
{
delete[] m_buf;
m_buf = new unsigned char[size * 2];
m_buf_size = size * 2;
}
std::locale::global(std::locale(""));
std::ifstream fin(src.c_str(), std::ios::binary);
std::locale::global(std::locale("C"));
fin.read(reinterpret_cast<char*>(m_buf), size);
fout.write(reinterpret_cast<const char*>(m_buf), size);
fin.close();
}
}<|endoftext|> |
<commit_before>#ifndef MPACK_BUFFEROBJECT_HPP
#define MPACK_BUFFEROBJECT_HPP
#include "Types.hpp"
#include "Debug.hpp"
namespace MPACK
{
namespace Graphics
{
template<GLenum target> class BufferObject
{
public:
BufferObject();
~BufferObject();
GLvoid Init(GLvoid *data, GLuint size, GLenum usage=GL_STATIC_DRAW);
GLvoid Update(GLvoid *pointer, GLuint size);
GLvoid Bind();
GLvoid Unbind();
GLvoid Destroy();
GLuint GetSize();
GLuint GetUsage();
static GLvoid UnbindCurrentBuffer();
private:
GLuint m_ibo;
GLuint m_size;
GLenum m_usage;
static GLuint s_currBuffer;
};
template<GLenum target> inline BufferObject<target>::BufferObject()
: m_ibo(NULL), m_size(NULL), m_usage(NULL)
{
}
template<GLenum target> inline BufferObject<target>::~BufferObject()
{
Destroy();
}
template<GLenum target> inline GLvoid BufferObject<target>::Init(GLvoid *data, GLuint size, GLenum usage)
{
Destroy();
m_size=size;
m_usage=usage;
GL_CHECK( glGenBuffers(1,&m_ibo) );
Bind();
GL_CHECK( glBufferData(target,m_size,data,m_usage) );
}
template<GLenum target> inline GLvoid BufferObject<target>::Update(GLvoid *pointer, GLuint size)
{
if(size>m_size)
{
size=m_size;
}
Bind();
GL_CHECK( glBufferSubData(target,0,size,pointer) );
}
template<GLenum target> inline GLvoid BufferObject<target>::Bind()
{
if(s_currBuffer!=m_ibo)
{
GL_CHECK( glBindBuffer(target,m_ibo) );
s_currBuffer=m_ibo;
}
}
template<GLenum target> inline GLvoid BufferObject<target>::Unbind()
{
if(s_currBuffer!=0)
{
GL_CHECK( glBindBuffer(target,0) );
s_currBuffer=0;
}
}
template<GLenum target> inline GLvoid BufferObject<target>::Destroy()
{
if(m_ibo)
{
if(s_currBuffer==m_ibo)
{
GL_CHECK( glBindBuffer(target,0) );
s_currBuffer=0;
}
GL_CHECK( glDeleteBuffers(1,&m_ibo) );
}
}
template<GLenum target> inline GLuint BufferObject<target>::GetSize()
{
return m_size;
}
template<GLenum target> inline GLenum BufferObject<target>::GetUsage()
{
return m_usage;
}
template<GLenum target> inline GLvoid BufferObject<target>::UnbindCurrentBuffer()
{
if(s_currBuffer!=0)
{
GL_CHECK( glBindBuffer(target,0) );
s_currBuffer=0;
}
}
typedef BufferObject<GL_ARRAY_BUFFER> VertexBufferObject;
typedef BufferObject<GL_ELEMENT_ARRAY_BUFFER> IndexBufferObject;
}
}
#endif
<commit_msg>Fix conversion warnings<commit_after>#ifndef MPACK_BUFFEROBJECT_HPP
#define MPACK_BUFFEROBJECT_HPP
#include "Types.hpp"
#include "Debug.hpp"
namespace MPACK
{
namespace Graphics
{
template<GLenum target> class BufferObject
{
public:
BufferObject();
~BufferObject();
GLvoid Init(GLvoid *data, GLuint size, GLenum usage=GL_STATIC_DRAW);
GLvoid Update(GLvoid *pointer, GLuint size);
GLvoid Bind();
GLvoid Unbind();
GLvoid Destroy();
GLuint GetSize();
GLuint GetUsage();
static GLvoid UnbindCurrentBuffer();
private:
GLuint m_ibo;
GLuint m_size;
GLenum m_usage;
static GLuint s_currBuffer;
};
template<GLenum target> inline BufferObject<target>::BufferObject()
: m_ibo(0), m_size(0), m_usage(0)
{
}
template<GLenum target> inline BufferObject<target>::~BufferObject()
{
Destroy();
}
template<GLenum target> inline GLvoid BufferObject<target>::Init(GLvoid *data, GLuint size, GLenum usage)
{
Destroy();
m_size=size;
m_usage=usage;
GL_CHECK( glGenBuffers(1,&m_ibo) );
Bind();
GL_CHECK( glBufferData(target,m_size,data,m_usage) );
}
template<GLenum target> inline GLvoid BufferObject<target>::Update(GLvoid *pointer, GLuint size)
{
if(size>m_size)
{
size=m_size;
}
Bind();
GL_CHECK( glBufferSubData(target,0,size,pointer) );
}
template<GLenum target> inline GLvoid BufferObject<target>::Bind()
{
if(s_currBuffer!=m_ibo)
{
GL_CHECK( glBindBuffer(target,m_ibo) );
s_currBuffer=m_ibo;
}
}
template<GLenum target> inline GLvoid BufferObject<target>::Unbind()
{
if(s_currBuffer!=0)
{
GL_CHECK( glBindBuffer(target,0) );
s_currBuffer=0;
}
}
template<GLenum target> inline GLvoid BufferObject<target>::Destroy()
{
if(m_ibo)
{
if(s_currBuffer==m_ibo)
{
GL_CHECK( glBindBuffer(target,0) );
s_currBuffer=0;
}
GL_CHECK( glDeleteBuffers(1,&m_ibo) );
}
}
template<GLenum target> inline GLuint BufferObject<target>::GetSize()
{
return m_size;
}
template<GLenum target> inline GLenum BufferObject<target>::GetUsage()
{
return m_usage;
}
template<GLenum target> inline GLvoid BufferObject<target>::UnbindCurrentBuffer()
{
if(s_currBuffer!=0)
{
GL_CHECK( glBindBuffer(target,0) );
s_currBuffer=0;
}
}
typedef BufferObject<GL_ARRAY_BUFFER> VertexBufferObject;
typedef BufferObject<GL_ELEMENT_ARRAY_BUFFER> IndexBufferObject;
}
}
#endif
<|endoftext|> |
<commit_before>
#include "../src/AtomicStack.h"
#include "../src/LocalWriteEM.h"
#include "test_suite.h"
using namespace peloton;
using namespace index;
// This must be instanciated in the translation unit where it is
// used. Otherwise the compiler is not able to know its existence
// which causes the linker to complain
template <uint64_t core_num, typename GarbageNode>
std::unordered_map<void *, void *>
LocalWriteEMFactory<core_num, GarbageNode>::instance_map{};
// Number of cores we test EM on (this does not have to match the number
// of cores on the testing machine since we only test correctness but
// not performance)
static const uint64_t CoreNum = 40;
// Declear stack and its node type here
using StackType = AtomicStack<uint64_t>;
using NodeType = typename StackType::NodeType;
// Since the EM type is defined by the EMFactory type, we could
// make it easier
using EMFactory = \
LocalWriteEMFactory<CoreNum, std::remove_pointer<NodeType>::type>;
using EM = typename EMFactory::TargetType;
/*
* RandomNumberBenchmark() - Benchmark random number genrator inside C++11
*/
void RandomNumberBenchmark(int thread_num, int iter) {
PrintTestName("RandomNumberBenchmark");
auto f = [thread_num, iter](uint64_t id) -> void {
Random<uint64_t, 0, -1> r{};
// Avoid optimization
std::vector<uint64_t> v{};
v.reserve(1);
// Bring it into the cache such that we do not suffer from cache miss
v[0] = 1;
for(int i = 0;i < iter;i++) {
uint64_t num = r();
// This should be a cached write, so super fast
v[0] = num;
}
return;
};
Timer t{true};
StartThreads(thread_num, f);
double duration = t.Stop();
dbg_printf("Thread num = %d, Iteration = %d, Duration = %f\n",
thread_num,
iter,
duration);
dbg_printf(" Throughput = %f M op/sec\n",
static_cast<double>(iter) / duration / 1024.0 / 1024.0);
dbg_printf(" Throughput = %f M op/(sec * thread)\n",
static_cast<double>(iter) / duration / 1024.0 / 1024.0 / thread_num);
return;
}
/*
* GetThreadAffinityBenchmark() - Measures how fast we could call this function
*/
void GetThreadAffinityBenchmark() {
PrintTestName("GetThreadAffinityBenchmark");
Timer t{true};
constexpr int iter = 10000000;
// We need this to avoid the following loop being optimized out
std::vector<int> v{};
v.reserve(10);
for(int i = 0;i < iter;i++) {
int core_id = GetThreadAffinity();
v[0] = core_id;
}
double duration = t.Stop();
dbg_printf("Time usage (iter %d) = %f\n", iter, duration);
dbg_printf(" Throughput = %f op/second\n",
static_cast<double>(iter) / duration);
return;
}
/*
* SimpleBenchmark() - Benchmark how EM works without workload - just announce
* entry & exit and it's all
*/
void SimpleBenchmark(uint64_t thread_num, uint64_t op_num) {
PrintTestName("SimpleBenchmark");
// This instance must be created by the factory
EM *em = EMFactory::GetInstance();
auto func = [em, thread_num, op_num](uint64_t id) {
// This is the core ID this thread is logically pinned to
// physically we do not make any constraint here
uint64_t core_id = id % CoreNum;
// And then announce entry on its own processor
for(uint64_t i = 0;i < op_num;i++) {
em->AnnounceEnter(core_id);
}
};
Timer t{true};
// Let threads start
StartThreads(thread_num, func);
double duration = t.Stop();
EMFactory::FreeInstance(em);
dbg_printf("Tests of %lu threads, %lu operations each took %f seconds\n",
thread_num,
op_num,
duration);
dbg_printf(" Throughput = %f M op/sec\n",
static_cast<double>(thread_num * op_num) / duration / (1024.0 * 1024.0));
dbg_printf(" Throughput Per Thread = %f M op/sec\n",
static_cast<double>(op_num) / duration / (1024.0 * 1024.0));
return;
}
int main() {
GetThreadAffinityBenchmark();
RandomNumberBenchmark(8, 100000000);
SimpleBenchmark(40, 1024 * 1024 * 30);
return 0;
}
<commit_msg>Adding Hasher benchmark<commit_after>
#include "../src/AtomicStack.h"
#include "../src/LocalWriteEM.h"
#include "test_suite.h"
using namespace peloton;
using namespace index;
// This must be instanciated in the translation unit where it is
// used. Otherwise the compiler is not able to know its existence
// which causes the linker to complain
template <uint64_t core_num, typename GarbageNode>
std::unordered_map<void *, void *>
LocalWriteEMFactory<core_num, GarbageNode>::instance_map{};
// Number of cores we test EM on (this does not have to match the number
// of cores on the testing machine since we only test correctness but
// not performance)
static const uint64_t CoreNum = 40;
// Declear stack and its node type here
using StackType = AtomicStack<uint64_t>;
using NodeType = typename StackType::NodeType;
// Since the EM type is defined by the EMFactory type, we could
// make it easier
using EMFactory = \
LocalWriteEMFactory<CoreNum, std::remove_pointer<NodeType>::type>;
using EM = typename EMFactory::TargetType;
/*
* IntHasherBenchmark() - Benchmarks integer number hash function from
* Murmurhash3
*/
void IntHasherBenchmark(uint64_t iter) {
std::vector<uint64_t> v{};
v.reserve(1);
SimpleInt64Hasher hash{};
Timer t{true};
printf("asasasas\n");
for(uint64_t i = 0;i < iter;i++) {
v[0] = i;
printf("%lu ", i);
}
(void)hash;
double duration = t.Stop();
dbg_printf("Iteration = %lu, Duration = %f\n",
iter,
duration);
dbg_printf(" Throughput = %f M op/sec\n",
static_cast<double>(iter) / duration / 1024.0 / 1024.0);
return;
}
/*
* RandomNumberBenchmark() - Benchmark random number genrator inside C++11
*/
void RandomNumberBenchmark(int thread_num, int iter) {
PrintTestName("RandomNumberBenchmark");
auto f = [thread_num, iter](uint64_t id) -> void {
Random<uint64_t, 0, -1> r{};
// Avoid optimization
std::vector<uint64_t> v{};
v.reserve(1);
// Bring it into the cache such that we do not suffer from cache miss
v[0] = 1;
for(int i = 0;i < iter;i++) {
uint64_t num = r();
// This should be a cached write, so super fast
v[0] = num;
}
return;
};
Timer t{true};
StartThreads(thread_num, f);
double duration = t.Stop();
dbg_printf("Thread num = %d, Iteration = %d, Duration = %f\n",
thread_num,
iter,
duration);
dbg_printf(" Throughput = %f M op/sec\n",
static_cast<double>(iter) / duration / 1024.0 / 1024.0);
dbg_printf(" Throughput = %f M op/(sec * thread)\n",
static_cast<double>(iter) / duration / 1024.0 / 1024.0 / thread_num);
return;
}
/*
* GetThreadAffinityBenchmark() - Measures how fast we could call this function
*/
void GetThreadAffinityBenchmark() {
PrintTestName("GetThreadAffinityBenchmark");
Timer t{true};
constexpr int iter = 10000000;
// We need this to avoid the following loop being optimized out
std::vector<int> v{};
v.reserve(10);
for(int i = 0;i < iter;i++) {
int core_id = GetThreadAffinity();
v[0] = core_id;
}
double duration = t.Stop();
dbg_printf("Time usage (iter %d) = %f\n", iter, duration);
dbg_printf(" Throughput = %f op/second\n",
static_cast<double>(iter) / duration);
return;
}
/*
* SimpleBenchmark() - Benchmark how EM works without workload - just announce
* entry & exit and it's all
*/
void SimpleBenchmark(uint64_t thread_num, uint64_t op_num) {
PrintTestName("SimpleBenchmark");
// This instance must be created by the factory
EM *em = EMFactory::GetInstance();
auto func = [em, thread_num, op_num](uint64_t id) {
// This is the core ID this thread is logically pinned to
// physically we do not make any constraint here
uint64_t core_id = id % CoreNum;
// And then announce entry on its own processor
for(uint64_t i = 0;i < op_num;i++) {
em->AnnounceEnter(core_id);
}
};
Timer t{true};
// Let threads start
StartThreads(thread_num, func);
double duration = t.Stop();
EMFactory::FreeInstance(em);
dbg_printf("Tests of %lu threads, %lu operations each took %f seconds\n",
thread_num,
op_num,
duration);
dbg_printf(" Throughput = %f M op/sec\n",
static_cast<double>(thread_num * op_num) / duration / (1024.0 * 1024.0));
dbg_printf(" Throughput Per Thread = %f M op/sec\n",
static_cast<double>(op_num) / duration / (1024.0 * 1024.0));
return;
}
int main() {
GetThreadAffinityBenchmark();
IntHasherBenchmark(100000000);
RandomNumberBenchmark(1, 100000000);
SimpleBenchmark(40, 1024 * 1024 * 30);
return 0;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include <fstream>
#include <cstdint>
using namespace std;
template <class T>
struct Node
{
T data;
Node<T>* left;
Node<T>* right;
};
template <class T>
class BinaryTree
{
private:
Node<T> *root;
uint16_t CountElements = 0;
public:
BinaryTree();
~BinaryTree();
void deleteNode(Node<T>* temp);
void insert_node(const T&);
void print()const;
Node<T>*root_()const;
Node<T> *find_node(const T&, Node<T>*)const;
void show(Node<T>*, unsigned int)const;
void out()const;
void reading(const std::string&);
void writing(const std::string&)const;
bool search_result(const T& value)const;
Node<T>* get_pointer(const T& value, Node<T>* temp)const;
};
template<typename T>
BinaryTree<T>::BinaryTree()
{
root = nullptr;
}
template<class T>
Node<T>*BinaryTree<T>::root_()const
{
return root;
}
template<typename T>
BinaryTree<T>::~BinaryTree()
{
deleteNode(root);
}
template<typename T>
Node<T> *BinaryTree<T>::get_pointer(const T& value, Node<T>* temp)const
{
if (temp == 0 || value == temp->data)
return temp;
if (value > temp->data)
return get_pointer(value, temp->right);
else return get_pointer(value, temp->left);
}
template<typename T>
bool BinaryTree<T>::search_result(const T& value)const
{
return get_pointer(value, root);
}
template<typename T>
void BinaryTree<T>::deleteNode(Node<T>* temp)
{
if (!temp)
return;
if (temp->left)
{
deleteNode(temp->left);
temp->left = nullptr;
}
if (temp->right)
{
deleteNode(temp->right);
temp->right = nullptr;
}
delete temp;
}
template<typename T>
void BinaryTree<T>::insert_node(const T&x)
{
if (find_node(x, root_())) return;
Node<T>* MyTree = new Node<T>;
MyTree->data = x;
MyTree->left = MyTree->right = 0;
Node<T>* buff = root;
Node<T>* temp = root;
while (temp)
{
buff = temp;
if (x < temp->data)
temp = temp->left;
else
temp = temp->right;
}
if (!buff)
root = MyTree;
else
{
if (x < buff->data)
buff->left = MyTree;
else
buff->right = MyTree;
}
++CountElements;
}
template<typename T>
Node<T>* BinaryTree<T>::find_node(const T& value, Node<T>* temp) const
{
if (temp == 0 || value == temp->data)
return temp;
if (value > temp->data)
return find_node(value, temp->right);
else
return find_node(value, temp->left);
}
template<typename T>
void BinaryTree<T>::reading(const std::string& filename)
{
ifstream fin(filename);
if (root != nullptr)
deleteNode(root);
int k;
fin >> k;
T temp;
for (int i = 0; i < k; ++i)
{
fin >> temp;
insert_node(temp);
}
fin.close();
}
template<typename T>
void BinaryTree<T>::writing(const std::string& filename)const
{
ofstream file_1(filename);
file_1 << CountElements << "\t";
output(file_1, root);
file_1.close();
}
void tree<T>::output(ostream& ost, Node<T>* temp)const
{
if (!temp) return;
ost << temp->data << " ";
output(ost, temp->left);
output(ost, temp->right);
}
<commit_msg>Update BinaryTree.hpp<commit_after>#include <iostream>
#include <string>
#include <fstream>
#include <cstdint>
using namespace std;
template <class T>
struct Node
{
T data;
Node<T>* left;
Node<T>* right;
};
template <class T>
class BinaryTree
{
private:
Node<T> *root;
uint16_t CountElements = 0;
public:
BinaryTree();
~BinaryTree();
void deleteNode(Node<T>* temp);
void insert_node(const T&);
void print()const;
Node<T>*root_()const;
Node<T> *find_node(const T&, Node<T>*)const;
void output(ostream&, Node<T>*)const
void reading(const std::string&);
void writing(const std::string&)const;
bool search_result(const T& value)const;
Node<T>* get_pointer(const T& value, Node<T>* temp)const;
};
template<typename T>
BinaryTree<T>::BinaryTree()
{
root = nullptr;
}
template<class T>
Node<T>*BinaryTree<T>::root_()const
{
return root;
}
template<typename T>
BinaryTree<T>::~BinaryTree()
{
deleteNode(root);
}
template<typename T>
Node<T> *BinaryTree<T>::get_pointer(const T& value, Node<T>* temp)const
{
if (temp == 0 || value == temp->data)
return temp;
if (value > temp->data)
return get_pointer(value, temp->right);
else return get_pointer(value, temp->left);
}
template<typename T>
bool BinaryTree<T>::search_result(const T& value)const
{
return get_pointer(value, root);
}
template<typename T>
void BinaryTree<T>::deleteNode(Node<T>* temp)
{
if (!temp)
return;
if (temp->left)
{
deleteNode(temp->left);
temp->left = nullptr;
}
if (temp->right)
{
deleteNode(temp->right);
temp->right = nullptr;
}
delete temp;
}
template<typename T>
void BinaryTree<T>::insert_node(const T&x)
{
if (find_node(x, root_())) return;
Node<T>* MyTree = new Node<T>;
MyTree->data = x;
MyTree->left = MyTree->right = 0;
Node<T>* buff = root;
Node<T>* temp = root;
while (temp)
{
buff = temp;
if (x < temp->data)
temp = temp->left;
else
temp = temp->right;
}
if (!buff)
root = MyTree;
else
{
if (x < buff->data)
buff->left = MyTree;
else
buff->right = MyTree;
}
++CountElements;
}
template<typename T>
Node<T>* BinaryTree<T>::find_node(const T& value, Node<T>* temp) const
{
if (temp == 0 || value == temp->data)
return temp;
if (value > temp->data)
return find_node(value, temp->right);
else
return find_node(value, temp->left);
}
template<typename T>
void BinaryTree<T>::reading(const std::string& filename)
{
ifstream fin(filename);
if (root != nullptr)
deleteNode(root);
int k;
fin >> k;
T temp;
for (int i = 0; i < k; ++i)
{
fin >> temp;
insert_node(temp);
}
fin.close();
}
template<typename T>
void BinaryTree<T>::writing(const std::string& filename)const
{
ofstream file_1(filename);
file_1 << CountElements << "\t";
output(file_1, root);
file_1.close();
}
void BinaryTree<T>::output(ostream& ost, Node<T>* buff)const
{
if (!temp) return;
ost << temp->data << " ";
output(ost, buff->left);
output(ost, buff->right);
}
<|endoftext|> |
<commit_before>#pragma once
/**
@file
@brief logger
Copyright (C) Cybozu Labs, Inc., all rights reserved.
*/
#include <cybozu/format.hpp>
#include <cybozu/time.hpp>
#ifdef _WIN32
#else
#include <syslog.h>
#endif
namespace cybozu {
enum LogPriority {
LogDebug = 0,
LogInfo = 1,
LogWarning = 2,
LogError = 3
};
namespace log_local {
class Logger {
int priority_;
FILE *fp_;
bool doClose_;
bool useSyslog_;
public:
Logger()
: priority_(cybozu::LogDebug)
, fp_(stderr)
, doClose_(false)
, useSyslog_(true)
{
}
~Logger()
{
closeFile();
}
void put(LogPriority priority, const std::string& str)
{
if (priority < priority_) return;
if (fp_) {
cybozu::Time cur(true);
if (fprintf(fp_, "%s %s\n", cur.toString(false).c_str(), str.c_str()) < 0) {
fprintf(stderr, "ERR:cybozu:Logger:put:fprintf:%s\n", str.c_str());
}
if (fflush(fp_) < 0) {
fprintf(stderr, "ERR:cybozu:Logger:put:fflush:%s\n", str.c_str());
}
}
if (useSyslog_) {
#ifdef __linux__
int pri = LOG_CRIT;
if (priority == LogDebug) {
pri = LOG_DEBUG;
} else if (priority == LogInfo) {
pri = LOG_INFO;
} else if (priority == LogWarning) {
pri = LOG_WARNING;
}
::syslog(pri, "%s\n", str.c_str());
#endif
}
}
void put(LogPriority priority, const char *format, va_list args)
{
if (priority < priority_) return;
std::string str;
cybozu::vformat(str, format, args);
put(priority, str);
}
static Logger& getInstance()
{
static Logger logger;
return logger;
}
/*
@note : not thread safe
@param path [in] open path for log
*/
void openFile(const std::string& path)
{
FILE *fp = 0;
#ifdef _MSC_VER
if (fopen_s(&fp, path.c_str(), "a+b")) fp = 0;
#else
fp = fopen(path.c_str(), "a+b");
#endif
if (fp == 0) throw cybozu::Exception("cybozu:Logger:openFile") << path;
closeFile();
fp_ = fp;
doClose_ = true;
useSyslog_ = false;
}
/*
set FILE pointer
@param fp [in] write log to fp if fp != NULL
@note Logger does not close the pointer
*/
void set(FILE *fp)
{
closeFile();
fp_ = fp;
doClose_ = false;
useSyslog_ = false;
}
/*
use syslog if useSyslog is true
*/
void useSyslog(bool useSyslog)
{
useSyslog_ = useSyslog;
}
bool closeFile() throw()
{
if (!doClose_ || fp_ == 0) return true;
if (fp_ == stdout || fp_ == stderr) {
fp_ = NULL;
return true;
}
bool isOK = fclose(fp_) == 0;
fp_ = NULL;
return isOK;
}
void setPriority(LogPriority priority)
{
priority_ = priority;
}
};
} // cybozu::log_local
/*
write log to path(default is stderr, syslog)
@param path [in] open path for log
@note this function is not thread safe
*/
inline void OpenLogFile(const std::string& path)
{
return log_local::Logger::getInstance().openFile(path);
}
/*
set FILE pointer
@param fp [in] write log to fp if fp != NULL
@note Logger does not close the pointer
@note this function is not thread safe
*/
inline void SetLogFILE(FILE *fp)
{
return log_local::Logger::getInstance().set(fp);
}
/*
use syslog if useSyslog is true
*/
inline void useSyslog(bool useSyslog)
{
log_local::Logger::getInstance().useSyslog(useSyslog);
}
/*
set priority(default cybozu::LogDebug)
does not show the message of which is less or equal to the priority
*/
inline void SetLogPriority(LogPriority priority)
{
log_local::Logger::getInstance().setPriority(priority);
}
/*
write log like printf
Linux : default is syslog
Windows : default is file(use openFile)
*/
#ifdef __GNUC__
inline void PutLog(LogPriority priority, const char *format, ...) throw() __attribute__((format(printf, 2, 3)));
#endif
inline void PutLog(LogPriority priority, const char *format, ...) throw()
try
{
va_list args;
va_start(args, format);
log_local::Logger::getInstance().put(priority, format, args);
va_end(args);
} catch (std::exception& e) {
fprintf(stderr, "faital error in cybozu::PutLog %s\n", e.what());
} catch (...) {
fprintf(stderr, "faital error in cybozu::PutLog\n");
}
} // cybozu
namespace cybozu {
/*
write log like std::cout
Linux : default is syslog
Windows : default is file(use openFile)
*/
class Log {
LogPriority pri_;
std::ostringstream os_;
Log(const Log&);
void operator=(const Log&);
public:
explicit Log(LogPriority priority = cybozu::LogInfo) : pri_(priority) { }
~Log()
try
{
log_local::Logger::getInstance().put(pri_, os_.str());
} catch (std::exception& e) {
fprintf(stderr, "faital error in cybozu::Log %s\n", e.what());
} catch (...) {
fprintf(stderr, "faital error in cybozu::Log\n");
}
template<class T>
Log& operator<<(const T& t) { os_ << t; return *this; }
};
} // cybozu
<commit_msg>add throw() for Log() and Logger()<commit_after>#pragma once
/**
@file
@brief logger
Copyright (C) Cybozu Labs, Inc., all rights reserved.
*/
#include <cybozu/format.hpp>
#include <cybozu/time.hpp>
#ifdef _WIN32
#else
#include <syslog.h>
#endif
namespace cybozu {
enum LogPriority {
LogDebug = 0,
LogInfo = 1,
LogWarning = 2,
LogError = 3
};
namespace log_local {
class Logger {
int priority_;
FILE *fp_;
bool doClose_;
bool useSyslog_;
public:
Logger()
: priority_(cybozu::LogDebug)
, fp_(stderr)
, doClose_(false)
, useSyslog_(true)
{
}
~Logger() throw()
{
closeFile();
}
void put(LogPriority priority, const std::string& str)
{
if (priority < priority_) return;
if (fp_) {
cybozu::Time cur(true);
if (fprintf(fp_, "%s %s\n", cur.toString(false).c_str(), str.c_str()) < 0) {
fprintf(stderr, "ERR:cybozu:Logger:put:fprintf:%s\n", str.c_str());
}
if (fflush(fp_) < 0) {
fprintf(stderr, "ERR:cybozu:Logger:put:fflush:%s\n", str.c_str());
}
}
if (useSyslog_) {
#ifdef __linux__
int pri = LOG_CRIT;
if (priority == LogDebug) {
pri = LOG_DEBUG;
} else if (priority == LogInfo) {
pri = LOG_INFO;
} else if (priority == LogWarning) {
pri = LOG_WARNING;
}
::syslog(pri, "%s\n", str.c_str());
#endif
}
}
void put(LogPriority priority, const char *format, va_list args)
{
if (priority < priority_) return;
std::string str;
cybozu::vformat(str, format, args);
put(priority, str);
}
static Logger& getInstance()
{
static Logger logger;
return logger;
}
/*
@note : not thread safe
@param path [in] open path for log
*/
void openFile(const std::string& path)
{
FILE *fp = 0;
#ifdef _MSC_VER
if (fopen_s(&fp, path.c_str(), "a+b")) fp = 0;
#else
fp = fopen(path.c_str(), "a+b");
#endif
if (fp == 0) throw cybozu::Exception("cybozu:Logger:openFile") << path;
closeFile();
fp_ = fp;
doClose_ = true;
useSyslog_ = false;
}
/*
set FILE pointer
@param fp [in] write log to fp if fp != NULL
@note Logger does not close the pointer
*/
void set(FILE *fp)
{
closeFile();
fp_ = fp;
doClose_ = false;
useSyslog_ = false;
}
/*
use syslog if useSyslog is true
*/
void useSyslog(bool useSyslog)
{
useSyslog_ = useSyslog;
}
bool closeFile() throw()
{
if (!doClose_ || fp_ == 0) return true;
if (fp_ == stdout || fp_ == stderr) {
fp_ = NULL;
return true;
}
bool isOK = fclose(fp_) == 0;
fp_ = NULL;
return isOK;
}
void setPriority(LogPriority priority)
{
priority_ = priority;
}
};
} // cybozu::log_local
/*
write log to path(default is stderr, syslog)
@param path [in] open path for log
@note this function is not thread safe
*/
inline void OpenLogFile(const std::string& path)
{
return log_local::Logger::getInstance().openFile(path);
}
/*
set FILE pointer
@param fp [in] write log to fp if fp != NULL
@note Logger does not close the pointer
@note this function is not thread safe
*/
inline void SetLogFILE(FILE *fp)
{
return log_local::Logger::getInstance().set(fp);
}
/*
use syslog if useSyslog is true
*/
inline void useSyslog(bool useSyslog)
{
log_local::Logger::getInstance().useSyslog(useSyslog);
}
/*
set priority(default cybozu::LogDebug)
does not show the message of which is less or equal to the priority
*/
inline void SetLogPriority(LogPriority priority)
{
log_local::Logger::getInstance().setPriority(priority);
}
/*
write log like printf
Linux : default is syslog
Windows : default is file(use openFile)
*/
#ifdef __GNUC__
inline void PutLog(LogPriority priority, const char *format, ...) throw() __attribute__((format(printf, 2, 3)));
#endif
inline void PutLog(LogPriority priority, const char *format, ...) throw()
try
{
va_list args;
va_start(args, format);
log_local::Logger::getInstance().put(priority, format, args);
va_end(args);
} catch (std::exception& e) {
fprintf(stderr, "faital error in cybozu::PutLog %s\n", e.what());
} catch (...) {
fprintf(stderr, "faital error in cybozu::PutLog\n");
}
} // cybozu
namespace cybozu {
/*
write log like std::cout
Linux : default is syslog
Windows : default is file(use openFile)
*/
class Log {
LogPriority pri_;
std::ostringstream os_;
Log(const Log&);
void operator=(const Log&);
public:
explicit Log(LogPriority priority = cybozu::LogInfo) : pri_(priority) { }
~Log() throw()
{
try {
log_local::Logger::getInstance().put(pri_, os_.str());
} catch (std::exception& e) {
fprintf(stderr, "faital error in cybozu::Log %s\n", e.what());
} catch (...) {
fprintf(stderr, "faital error in cybozu::Log\n");
}
}
template<class T>
Log& operator<<(const T& t) { os_ << t; return *this; }
};
} // cybozu
<|endoftext|> |
<commit_before>// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// This test insures that
// csharp/src/Google.Protobuf/Reflection/Descriptor.cs match exactly
// what would be generated by the protocol compiler. The file is not
// generated automatically at build time.
//
// If this test fails, run the script
// "generate_descriptor_proto.sh" and add the changed files under
// csharp/src/ to your changelist.
#include <map>
#include <google/protobuf/compiler/csharp/csharp_generator.h>
#include <google/protobuf/compiler/importer.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <google/protobuf/stubs/map_util.h>
#include <google/protobuf/stubs/stl_util.h>
#include <google/protobuf/stubs/strutil.h>
#include <google/protobuf/stubs/substitute.h>
#include <google/protobuf/testing/file.h>
#include <google/protobuf/testing/file.h>
#include <google/protobuf/testing/googletest.h>
#include <gtest/gtest.h>
namespace google {
namespace protobuf {
namespace compiler {
namespace csharp {
namespace {
class MockErrorCollector : public MultiFileErrorCollector {
public:
MockErrorCollector() {}
~MockErrorCollector() {}
string text_;
// implements ErrorCollector ---------------------------------------
void AddError(const string& filename, int line, int column,
const string& message) {
strings::SubstituteAndAppend(&text_, "$0:$1:$2: $3\n",
filename, line, column, message);
}
};
class MockGeneratorContext : public GeneratorContext {
public:
MockGeneratorContext() {}
~MockGeneratorContext() {
STLDeleteValues(&files_);
}
void ExpectFileMatches(const string& virtual_filename,
const string& physical_filename) {
string* expected_contents = FindPtrOrNull(files_, virtual_filename);
ASSERT_TRUE(expected_contents != NULL)
<< "Generator failed to generate file: " << virtual_filename;
string actual_contents;
GOOGLE_CHECK_OK(
File::GetContents(TestSourceDir() + "/" + physical_filename,
&actual_contents, true))
<< "Unable to get " << physical_filename;
EXPECT_TRUE(actual_contents == *expected_contents)
<< physical_filename << " needs to be regenerated. Please run "
"generate_descriptor_proto.sh. Then add this file "
"to your CL.";
}
// implements GeneratorContext --------------------------------------
virtual io::ZeroCopyOutputStream* Open(const string& filename) {
string** map_slot = &files_[filename];
delete *map_slot;
*map_slot = new string;
return new io::StringOutputStream(*map_slot);
}
private:
std::map<string, string*> files_;
};
class GenerateAndTest {
public:
GenerateAndTest() {}
void Run(const FileDescriptor* proto_file, string file1, string file2) {
ASSERT_TRUE(proto_file != NULL) << TestSourceDir();
ASSERT_TRUE(generator_.Generate(proto_file, parameter_,
&context_, &error_));
context_.ExpectFileMatches(file1, file2);
}
void SetParameter(string parameter) {
parameter_ = parameter;
}
private:
Generator generator_;
MockGeneratorContext context_;
string error_;
string parameter_;
};
TEST(CsharpBootstrapTest, GeneratedCsharpDescriptorMatches) {
MockErrorCollector error_collector;
DiskSourceTree source_tree;
Importer importer(&source_tree, &error_collector);
GenerateAndTest generate_test;
generate_test.SetParameter("base_namespace=Google.Protobuf");
source_tree.MapPath("", TestSourceDir());
generate_test.Run(importer.Import("google/protobuf/descriptor.proto"),
"Reflection/Descriptor.cs",
"../csharp/src/Google.Protobuf/Reflection/Descriptor.cs");
generate_test.Run(importer.Import("google/protobuf/any.proto"),
"WellKnownTypes/Any.cs",
"../csharp/src/Google.Protobuf/WellKnownTypes/Any.cs");
generate_test.Run(importer.Import("google/protobuf/api.proto"),
"WellKnownTypes/Api.cs",
"../csharp/src/Google.Protobuf/WellKnownTypes/Api.cs");
generate_test.Run(importer.Import("google/protobuf/duration.proto"),
"WellKnownTypes/Duration.cs",
"../csharp/src/Google.Protobuf/WellKnownTypes/Duration.cs");
generate_test.Run(importer.Import("google/protobuf/empty.proto"),
"WellKnownTypes/Empty.cs",
"../csharp/src/Google.Protobuf/WellKnownTypes/Empty.cs");
generate_test.Run(importer.Import("google/protobuf/field_mask.proto"),
"WellKnownTypes/FieldMask.cs",
"../csharp/src/Google.Protobuf/WellKnownTypes/FieldMask.cs");
generate_test.Run(importer.Import("google/protobuf/source_context.proto"),
"WellKnownTypes/SourceContext.cs",
"../csharp/src/Google.Protobuf/WellKnownTypes/SourceContext.cs");
generate_test.Run(importer.Import("google/protobuf/struct.proto"),
"WellKnownTypes/Struct.cs",
"../csharp/src/Google.Protobuf/WellKnownTypes/Struct.cs");
generate_test.Run(importer.Import("google/protobuf/timestamp.proto"),
"WellKnownTypes/Timestamp.cs",
"../csharp/src/Google.Protobuf/WellKnownTypes/Timestamp.cs");
generate_test.Run(importer.Import("google/protobuf/type.proto"),
"WellKnownTypes/Type.cs",
"../csharp/src/Google.Protobuf/WellKnownTypes/Type.cs");
generate_test.Run(importer.Import("google/protobuf/wrappers.proto"),
"WellKnownTypes/Wrappers.cs",
"../csharp/src/Google.Protobuf/WellKnownTypes/Wrappers.cs");
generate_test.SetParameter("");
source_tree.MapPath("", TestSourceDir() + "/../examples");
generate_test.Run(importer.Import("addressbook.proto"),
"Addressbook.cs",
"../csharp/src/AddressBook/Addressbook.cs");
source_tree.MapPath("", TestSourceDir() + "/../conformance");
generate_test.Run(importer.Import("conformance.proto"),
"Conformance.cs",
"../csharp/src/Google.Protobuf.Conformance/Conformance.cs");
EXPECT_EQ("", error_collector.text_);
}
} // namespace
} // namespace csharp
} // namespace compiler
} // namespace protobuf
} // namespace google
<commit_msg>Skip C# test in C++ only distribution.<commit_after>// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// This test insures that
// csharp/src/Google.Protobuf/Reflection/Descriptor.cs match exactly
// what would be generated by the protocol compiler. The file is not
// generated automatically at build time.
//
// If this test fails, run the script
// "generate_descriptor_proto.sh" and add the changed files under
// csharp/src/ to your changelist.
#include <map>
#include <google/protobuf/compiler/csharp/csharp_generator.h>
#include <google/protobuf/compiler/importer.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <google/protobuf/stubs/map_util.h>
#include <google/protobuf/stubs/stl_util.h>
#include <google/protobuf/stubs/strutil.h>
#include <google/protobuf/stubs/substitute.h>
#include <google/protobuf/testing/file.h>
#include <google/protobuf/testing/file.h>
#include <google/protobuf/testing/googletest.h>
#include <gtest/gtest.h>
namespace google {
namespace protobuf {
namespace compiler {
namespace csharp {
namespace {
class MockErrorCollector : public MultiFileErrorCollector {
public:
MockErrorCollector() {}
~MockErrorCollector() {}
string text_;
// implements ErrorCollector ---------------------------------------
void AddError(const string& filename, int line, int column,
const string& message) {
strings::SubstituteAndAppend(&text_, "$0:$1:$2: $3\n",
filename, line, column, message);
}
};
class MockGeneratorContext : public GeneratorContext {
public:
MockGeneratorContext() {}
~MockGeneratorContext() {
STLDeleteValues(&files_);
}
void ExpectFileMatches(const string& virtual_filename,
const string& physical_filename) {
string* expected_contents = FindPtrOrNull(files_, virtual_filename);
ASSERT_TRUE(expected_contents != NULL)
<< "Generator failed to generate file: " << virtual_filename;
string actual_contents;
GOOGLE_CHECK_OK(
File::GetContents(TestSourceDir() + "/" + physical_filename,
&actual_contents, true))
<< "Unable to get " << physical_filename;
EXPECT_TRUE(actual_contents == *expected_contents)
<< physical_filename << " needs to be regenerated. Please run "
"generate_descriptor_proto.sh. Then add this file "
"to your CL.";
}
// implements GeneratorContext --------------------------------------
virtual io::ZeroCopyOutputStream* Open(const string& filename) {
string** map_slot = &files_[filename];
delete *map_slot;
*map_slot = new string;
return new io::StringOutputStream(*map_slot);
}
private:
std::map<string, string*> files_;
};
class GenerateAndTest {
public:
GenerateAndTest() {}
void Run(const FileDescriptor* proto_file, string file1, string file2) {
ASSERT_TRUE(proto_file != NULL) << TestSourceDir();
ASSERT_TRUE(generator_.Generate(proto_file, parameter_,
&context_, &error_));
context_.ExpectFileMatches(file1, file2);
}
void SetParameter(string parameter) {
parameter_ = parameter;
}
private:
Generator generator_;
MockGeneratorContext context_;
string error_;
string parameter_;
};
TEST(CsharpBootstrapTest, GeneratedCsharpDescriptorMatches) {
// Skip this whole test if the csharp directory doesn't exist (i.e., a C++11
// only distribution).
string descriptor_file_name =
"../csharp/src/Google.Protobuf/Reflection/Descriptor.cs";
if (!File::Exists(TestSourceDir() + "/" + descriptor_file_name)) {
return;
}
MockErrorCollector error_collector;
DiskSourceTree source_tree;
Importer importer(&source_tree, &error_collector);
GenerateAndTest generate_test;
generate_test.SetParameter("base_namespace=Google.Protobuf");
source_tree.MapPath("", TestSourceDir());
generate_test.Run(importer.Import("google/protobuf/descriptor.proto"),
"Reflection/Descriptor.cs",
"../csharp/src/Google.Protobuf/Reflection/Descriptor.cs");
generate_test.Run(importer.Import("google/protobuf/any.proto"),
"WellKnownTypes/Any.cs",
"../csharp/src/Google.Protobuf/WellKnownTypes/Any.cs");
generate_test.Run(importer.Import("google/protobuf/api.proto"),
"WellKnownTypes/Api.cs",
"../csharp/src/Google.Protobuf/WellKnownTypes/Api.cs");
generate_test.Run(importer.Import("google/protobuf/duration.proto"),
"WellKnownTypes/Duration.cs",
"../csharp/src/Google.Protobuf/WellKnownTypes/Duration.cs");
generate_test.Run(importer.Import("google/protobuf/empty.proto"),
"WellKnownTypes/Empty.cs",
"../csharp/src/Google.Protobuf/WellKnownTypes/Empty.cs");
generate_test.Run(importer.Import("google/protobuf/field_mask.proto"),
"WellKnownTypes/FieldMask.cs",
"../csharp/src/Google.Protobuf/WellKnownTypes/FieldMask.cs");
generate_test.Run(importer.Import("google/protobuf/source_context.proto"),
"WellKnownTypes/SourceContext.cs",
"../csharp/src/Google.Protobuf/WellKnownTypes/SourceContext.cs");
generate_test.Run(importer.Import("google/protobuf/struct.proto"),
"WellKnownTypes/Struct.cs",
"../csharp/src/Google.Protobuf/WellKnownTypes/Struct.cs");
generate_test.Run(importer.Import("google/protobuf/timestamp.proto"),
"WellKnownTypes/Timestamp.cs",
"../csharp/src/Google.Protobuf/WellKnownTypes/Timestamp.cs");
generate_test.Run(importer.Import("google/protobuf/type.proto"),
"WellKnownTypes/Type.cs",
"../csharp/src/Google.Protobuf/WellKnownTypes/Type.cs");
generate_test.Run(importer.Import("google/protobuf/wrappers.proto"),
"WellKnownTypes/Wrappers.cs",
"../csharp/src/Google.Protobuf/WellKnownTypes/Wrappers.cs");
generate_test.SetParameter("");
source_tree.MapPath("", TestSourceDir() + "/../examples");
generate_test.Run(importer.Import("addressbook.proto"),
"Addressbook.cs",
"../csharp/src/AddressBook/Addressbook.cs");
source_tree.MapPath("", TestSourceDir() + "/../conformance");
generate_test.Run(importer.Import("conformance.proto"),
"Conformance.cs",
"../csharp/src/Google.Protobuf.Conformance/Conformance.cs");
EXPECT_EQ("", error_collector.text_);
}
} // namespace
} // namespace csharp
} // namespace compiler
} // namespace protobuf
} // namespace google
<|endoftext|> |
<commit_before>
#pragma once
#include <nstd/Base.hpp>
class String;
class Debug
{
public:
static int print(const tchar* str);
static int printf(const tchar* format, ...);
#ifndef NDEBUG
static bool getSourceLine(void* addr, String& file, int& line);
#endif
};
#ifdef _MSC_VER
void __cdecl __debugbreak(void);
#define TRAP() __debugbreak()
#else
#if defined(__GNUC__) && defined(_ARM)
__attribute__((gnu_inline, always_inline)) static void __inline__ TRAP(void) {__asm__ volatile("BKPT");}
#else
#define TRAP() __builtin_trap()
#endif
#endif
#ifdef NDEBUG
#undef TRAP
#define TRAP() ((void)0)
#define ASSERT(exp) ((void)1)
#define VERIFY(exp) ((void)(exp))
#else
#ifdef _MSC_VER
#define ASSERT(exp) ((void)(!(exp) && Debug::printf(_T("%s(%u): assertion failed: %s\n"), __TFILE__, __LINE__, _T(#exp)) && (TRAP(), 1)))
#define VERIFY(exp) ((void)(!(exp) && Debug::printf(_T("%s(%u): verification failed: %s\n"), __TFILE__, __LINE__, _T(#exp)) && (TRAP(), 1)))
#else
#define ASSERT(exp) ((void)(!(exp) && Debug::printf(_T("%s:%u: assertion failed: %s\n"), __TFILE__, __LINE__, #exp) && (TRAP(), 1)))
#define VERIFY(exp) ((void)(!(exp) && Debug::printf(_T("%s:%u: verification failed: %s\n"), __TFILE__, __LINE__, #exp) && (TRAP(), 1)))
#endif
#endif
<commit_msg>Debug: Evaluate assertions when DEBUG macro is set<commit_after>
#pragma once
#include <nstd/Base.hpp>
class String;
class Debug
{
public:
static int print(const tchar* str);
static int printf(const tchar* format, ...);
#ifndef NDEBUG
static bool getSourceLine(void* addr, String& file, int& line);
#endif
};
#ifdef _MSC_VER
void __cdecl __debugbreak(void);
#define TRAP() __debugbreak()
#else
#if defined(__GNUC__) && defined(_ARM)
__attribute__((gnu_inline, always_inline)) static void __inline__ TRAP(void) {__asm__ volatile("BKPT");}
#else
#define TRAP() __builtin_trap()
#endif
#endif
#if defined(NDEBUG) && !defined(DEBUG)
#undef TRAP
#define TRAP() ((void)0)
#define ASSERT(exp) ((void)1)
#define VERIFY(exp) ((void)(exp))
#else
#ifdef _MSC_VER
#define ASSERT(exp) ((void)(!(exp) && Debug::printf(_T("%s(%u): assertion failed: %s\n"), __TFILE__, __LINE__, _T(#exp)) && (TRAP(), 1)))
#define VERIFY(exp) ((void)(!(exp) && Debug::printf(_T("%s(%u): verification failed: %s\n"), __TFILE__, __LINE__, _T(#exp)) && (TRAP(), 1)))
#else
#define ASSERT(exp) ((void)(!(exp) && Debug::printf(_T("%s:%u: assertion failed: %s\n"), __TFILE__, __LINE__, #exp) && (TRAP(), 1)))
#define VERIFY(exp) ((void)(!(exp) && Debug::printf(_T("%s:%u: verification failed: %s\n"), __TFILE__, __LINE__, #exp) && (TRAP(), 1)))
#endif
#endif
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/shared/mss_const.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2016 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @mss_const.H
/// @This file contains constants for the memory team.
///
// *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com>
// *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: HB:FSP
#ifndef _MSS_CONST_H_
#define _MSS_CONST_H_
#include <cstdint>
namespace mss
{
enum sizes
{
PORTS_PER_MCS = 2,
PORTS_PER_MCBIST = 4,
MCS_PER_MC = 2,
MC_PER_MODULE = 2,
MCBIST_PER_MC = 1,
MAX_DIMM_PER_PORT = 2,
MAX_RANK_PER_DIMM = 4,
MAX_RANKS_DIMM1 = 2, ///< DIMM1 (inner DIMM) can't be a 4R DIMM
MAX_PRIMARY_RANKS_PER_PORT = 4,
MAX_MRANK_PER_PORT = MAX_DIMM_PER_PORT * MAX_RANK_PER_DIMM,
RANK_MID_POINT = 4, ///< Which rank number indicates the switch to the other DIMM
DEFAULT_POLL_LIMIT = 50, ///< the number of poll attempts in the event we can't calculate another
MAX_NUM_IMP = 4, ///< number of impedances valid per slew type
MAX_NUM_CAL_SLEW_RATES = 4, ///< 3V/ns, 4V/ns, 5V/ns, 6V/n
MAX_DQ_BITS = 72, /// TODO RTC:157753 This is Nimbus specific. Should be attribute/trait of processor.
BYTES_PER_GB = 1000000000, ///< Multiplier to go from GB to B
T_PER_MT = 1000000, ///< Multiplier to go from MT/s to T/s
// All need to be attributes? - BRS
WR_LVL_BIG_STEP = 0b0111,
WR_LVL_SMALL_STEP = 0b000,
WR_LVL_PRE_DLY = 0b101010,
WR_LVL_NUM_VALID_SAMPLES = 0x5,
// Attribute? BRS
COARSE_CAL_STEP_SIZE = 0x4,
CONSEQ_PASS = 0x8,
// Largest size a VPD keyword can be
VPD_KEYWORD_MAX = 255,
};
enum times
{
CONVERT_PS_IN_A_NS = 1000, ///< 1000 pico in an nano
CONVERT_PS_IN_A_US = 1000000, ///< 1000000 picos in a micro
DELAY_1NS = 1,
DELAY_10NS = 10 , ///< general purpose 10 ns delay for HW mode
DELAY_100NS = 100, ///< general purpose 100 ns delay for HW mode
DELAY_1US = 1000, ///< general purpose 1 usec delay for HW mode
DELAY_100US = 100000, ///< general purpose 100 usec delay for HW mode
DELAY_1MS = 1000000, ///< general purpose 1 ms delay for HW mode
SEC_IN_HOUR = 60 * 60, ///< seconds in an hour, used for scrub times
BG_SCRUB_IN_HOURS = 12,
CMD_TIMEBASE = 8192, ///< Represents the timebase multiplier for the MCBIST inter cmd gap
};
enum states
{
LOW = 0,
HIGH = 1,
START = 1,
STOP = 0,
START_N = 0,
STOP_N = 1,
ON = 1,
OFF = 0,
ON_N = 0,
OFF_N = 1,
YES = 1,
NO = 0,
YES_N = 0,
NO_N = 1,
INVALID = 0xFF,
NO_CHIP_SELECT_ACTIVE = 0xFF,
// This needs to be an attribute I think - BRS. Used as a boolean.
CAL_ABORT_ON_ERROR = 1,
};
// Static consts describing the bits used in the cal_step_enable attribute
// These are bit positions. 0 is the left most bit.
enum cal_steps
{
EXT_ZQCAL = 0,
WR_LEVEL = 1,
DQS_ALIGN = 2,
RDCLK_ALIGN = 3,
READ_CTR = 4,
READ_CTR_2D_VREF = 5,
WRITE_CTR = 6,
WRITE_CTR_2D_VREF = 7,
COARSE_WR = 8,
COARSE_RD = 9,
};
// Static consts for DDR4 voltages used in p9_mss_volt
enum voltages : uint64_t
{
DDR4_NOMINAL_VOLTAGE = 1200,
DDR4_VPP_VOLTAGE = 2500,
};
enum port_select
{
// Port selects for MCBIST and CCS
// Select for 1 port
PORT0 = 0b1000,
PORT1 = 0b0100,
PORT2 = 0b0010,
PORT3 = 0b0001,
// Selects for 2 port combinations
PORT01 = PORT0 | PORT1,
PORT02 = PORT0 | PORT2,
PORT03 = PORT0 | PORT3,
PORT12 = PORT1 | PORT2,
PORT13 = PORT1 | PORT3,
PORT23 = PORT2 | PORT3,
// Selects for 3 port combinations
PORT012 = PORT0 | PORT1 | PORT2,
PORT013 = PORT0 | PORT1 | PORT3,
PORT023 = PORT0 | PORT2 | PORT3,
PORT123 = PORT1 | PORT2 | PORT3,
// Select all
PORT0123 = PORT0 | PORT1 | PORT2 | PORT3,
// Maybe a better name for disabling all
PORT_NONE = 0b0000,
};
namespace mcbist
{
enum data_mode
{
// MCBIST test data modes
FIXED_DATA_MODE = 0b000,
RAND_FWD_MODE = 0b001,
RAND_REV_MODE = 0b010,
RAND_FWD_MAINT = 0b011,
RAND_REV_MAINT = 0b100,
DATA_EQ_ADDR = 0b101,
ROTATE_LEFT_MODE = 0b110,
ROTATE_RIGHT_MODE = 0b111,
};
// 0:3 Operation Type
enum op_type
{
WRITE = 0b0000, // fast, with no concurrent traffic
READ = 0b0001, // fast, with no concurrent traffic
READ_WRITE = 0b0010,
WRITE_READ = 0b0011,
READ_WRITE_READ = 0b0100,
READ_WRITE_WRITE = 0b0101,
RAND_SEQ = 0b0110,
READ_READ_WRITE = 0b1000,
SCRUB_RRWR = 0b1001,
STEER_RW = 0b1010,
ALTER = 0b1011, // (W)
DISPLAY = 0b1100, // (R, slow)
CCS_EXECUTE = 0b1111,
// if bits 9:11 (Data Mode bits) = 000 (bits 4:8 used to specify which subtest to go to)
// Refresh only cmd if bits 9:11 (Data Mode bits) /= 000
GOTO_SUBTEST_N = 0b0111,
};
enum test_type
{
USER_MODE = 0,
CENSHMOO = 1,
SUREFAIL = 2,
MEMWRITE = 3,
MEMREAD = 4,
CBR_REFRESH = 5,
MCBIST_SHORT = 6,
SHORT_SEQ = 7,
DELTA_I = 8,
DELTA_I_LOOP = 9,
SHORT_RAND = 10,
LONG1 = 11,
BUS_TAT = 12,
SIMPLE_FIX = 13,
SIMPLE_RAND = 14,
SIMPLE_RAND_2W = 15,
SIMPLE_RAND_FIXD = 16,
SIMPLE_RA_RD_WR = 17,
SIMPLE_RA_RD_R = 18,
SIMPLE_RA_FD_R = 19,
SIMPLE_RA_FD_R_INF = 20,
SIMPLE_SA_FD_R = 21,
SIMPLE_RA_FD_W = 22,
INFINITE = 23,
WR_ONLY = 24,
W_ONLY = 25,
R_ONLY = 26,
W_ONLY_RAND = 27,
R_ONLY_RAND = 28,
R_ONLY_MULTI = 29,
SHORT = 30,
SIMPLE_RAND_BARI = 31,
W_R_INFINITE = 32,
W_R_RAND_INFINITE = 33,
R_INFINITE1 = 34,
R_INFINITE_RF = 35,
MARCH = 36,
SIMPLE_FIX_RF = 37,
SHMOO_STRESS = 38,
SIMPLE_RAND_RA = 39,
SIMPLE_FIX_RA = 40,
SIMPLE_FIX_RF_RA = 41,
TEST_RR = 42,
TEST_RF = 43,
W_ONLY_INFINITE_RAND = 44,
MCB_2D_CUP_SEQ = 45,
MCB_2D_CUP_RAND = 46,
SHMOO_STRESS_INFINITE = 47,
HYNIX_1_COL = 48,
RMWFIX = 49,
RMWFIX_I = 50,
W_INFINITE = 51,
R_INFINITE = 52,
};
} // namespace mcbist
enum class shmoo_edge : std::size_t
{
LEFT,
RIGHT
};
} // namespace mss
#endif
<commit_msg>Added Shmoo Wrapper Capabilities<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/shared/mss_const.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2016 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @mss_const.H
/// @This file contains constants for the memory team.
///
// *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com>
// *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: HB:FSP
#ifndef _MSS_CONST_H_
#define _MSS_CONST_H_
#include <cstdint>
namespace mss
{
enum sizes
{
PORTS_PER_MCS = 2,
PORTS_PER_MCBIST = 4,
MCS_PER_MC = 2,
MC_PER_MODULE = 2,
MCBIST_PER_MC = 1,
MAX_DIMM_PER_PORT = 2,
MAX_RANK_PER_DIMM = 4,
MAX_RANKS_DIMM1 = 2, ///< DIMM1 (inner DIMM) can't be a 4R DIMM
MAX_PRIMARY_RANKS_PER_PORT = 4,
MAX_MRANK_PER_PORT = MAX_DIMM_PER_PORT * MAX_RANK_PER_DIMM,
RANK_MID_POINT = 4, ///< Which rank number indicates the switch to the other DIMM
DEFAULT_POLL_LIMIT = 50, ///< the number of poll attempts in the event we can't calculate another
MAX_NUM_IMP = 4, ///< number of impedances valid per slew type
MAX_NUM_CAL_SLEW_RATES = 4, ///< 3V/ns, 4V/ns, 5V/ns, 6V/n
MAX_DQ_BITS = 72, /// TODO RTC:157753 This is Nimbus specific. Should be attribute/trait of processor.
BYTES_PER_GB = 1000000000, ///< Multiplier to go from GB to B
T_PER_MT = 1000000, ///< Multiplier to go from MT/s to T/s
// All need to be attributes? - BRS
WR_LVL_BIG_STEP = 0b0111,
WR_LVL_SMALL_STEP = 0b000,
WR_LVL_PRE_DLY = 0b101010,
WR_LVL_NUM_VALID_SAMPLES = 0x5,
// Attribute? BRS
COARSE_CAL_STEP_SIZE = 0x4,
CONSEQ_PASS = 0x8,
// Largest size a VPD keyword can be
VPD_KEYWORD_MAX = 255,
};
enum times
{
CONVERT_PS_IN_A_NS = 1000, ///< 1000 pico in an nano
CONVERT_PS_IN_A_US = 1000000, ///< 1000000 picos in a micro
DELAY_1NS = 1,
DELAY_10NS = 10 , ///< general purpose 10 ns delay for HW mode
DELAY_100NS = 100, ///< general purpose 100 ns delay for HW mode
DELAY_1US = 1000, ///< general purpose 1 usec delay for HW mode
DELAY_100US = 100000, ///< general purpose 100 usec delay for HW mode
DELAY_1MS = 1000000, ///< general purpose 1 ms delay for HW mode
SEC_IN_HOUR = 60 * 60, ///< seconds in an hour, used for scrub times
BG_SCRUB_IN_HOURS = 12,
CMD_TIMEBASE = 8192, ///< Represents the timebase multiplier for the MCBIST inter cmd gap
};
enum states
{
LOW = 0,
HIGH = 1,
START = 1,
STOP = 0,
START_N = 0,
STOP_N = 1,
ON = 1,
OFF = 0,
ON_N = 0,
OFF_N = 1,
YES = 1,
NO = 0,
YES_N = 0,
NO_N = 1,
INVALID = 0xFF,
NO_CHIP_SELECT_ACTIVE = 0xFF,
// This needs to be an attribute I think - BRS. Used as a boolean.
CAL_ABORT_ON_ERROR = 1,
};
// Static consts describing the bits used in the cal_step_enable attribute
// These are bit positions. 0 is the left most bit.
enum cal_steps
{
EXT_ZQCAL = 0,
WR_LEVEL = 1,
DQS_ALIGN = 2,
RDCLK_ALIGN = 3,
READ_CTR = 4,
READ_CTR_2D_VREF = 5,
WRITE_CTR = 6,
WRITE_CTR_2D_VREF = 7,
COARSE_WR = 8,
COARSE_RD = 9,
};
// Static consts for DDR4 voltages used in p9_mss_volt
enum voltages : uint64_t
{
DDR4_NOMINAL_VOLTAGE = 1200,
DDR4_VPP_VOLTAGE = 2500,
};
enum port_select
{
// Port selects for MCBIST and CCS
// Select for 1 port
PORT0 = 0b1000,
PORT1 = 0b0100,
PORT2 = 0b0010,
PORT3 = 0b0001,
// Selects for 2 port combinations
PORT01 = PORT0 | PORT1,
PORT02 = PORT0 | PORT2,
PORT03 = PORT0 | PORT3,
PORT12 = PORT1 | PORT2,
PORT13 = PORT1 | PORT3,
PORT23 = PORT2 | PORT3,
// Selects for 3 port combinations
PORT012 = PORT0 | PORT1 | PORT2,
PORT013 = PORT0 | PORT1 | PORT3,
PORT023 = PORT0 | PORT2 | PORT3,
PORT123 = PORT1 | PORT2 | PORT3,
// Select all
PORT0123 = PORT0 | PORT1 | PORT2 | PORT3,
// Maybe a better name for disabling all
PORT_NONE = 0b0000,
};
namespace mcbist
{
enum data_mode
{
// MCBIST test data modes
FIXED_DATA_MODE = 0b000,
RAND_FWD_MODE = 0b001,
RAND_REV_MODE = 0b010,
RAND_FWD_MAINT = 0b011,
RAND_REV_MAINT = 0b100,
DATA_EQ_ADDR = 0b101,
ROTATE_LEFT_MODE = 0b110,
ROTATE_RIGHT_MODE = 0b111,
};
// 0:3 Operation Type
enum op_type
{
WRITE = 0b0000, // fast, with no concurrent traffic
READ = 0b0001, // fast, with no concurrent traffic
READ_WRITE = 0b0010,
WRITE_READ = 0b0011,
READ_WRITE_READ = 0b0100,
READ_WRITE_WRITE = 0b0101,
RAND_SEQ = 0b0110,
READ_READ_WRITE = 0b1000,
SCRUB_RRWR = 0b1001,
STEER_RW = 0b1010,
ALTER = 0b1011, // (W)
DISPLAY = 0b1100, // (R, slow)
CCS_EXECUTE = 0b1111,
// if bits 9:11 (Data Mode bits) = 000 (bits 4:8 used to specify which subtest to go to)
// Refresh only cmd if bits 9:11 (Data Mode bits) /= 000
GOTO_SUBTEST_N = 0b0111,
};
enum test_type
{
USER_MODE = 0,
CENSHMOO = 1,
SUREFAIL = 2,
MEMWRITE = 3,
MEMREAD = 4,
CBR_REFRESH = 5,
MCBIST_SHORT = 6,
SHORT_SEQ = 7,
DELTA_I = 8,
DELTA_I_LOOP = 9,
SHORT_RAND = 10,
LONG1 = 11,
BUS_TAT = 12,
SIMPLE_FIX = 13,
SIMPLE_RAND = 14,
SIMPLE_RAND_2W = 15,
SIMPLE_RAND_FIXD = 16,
SIMPLE_RA_RD_WR = 17,
SIMPLE_RA_RD_R = 18,
SIMPLE_RA_FD_R = 19,
SIMPLE_RA_FD_R_INF = 20,
SIMPLE_SA_FD_R = 21,
SIMPLE_RA_FD_W = 22,
INFINITE = 23,
WR_ONLY = 24,
W_ONLY = 25,
R_ONLY = 26,
W_ONLY_RAND = 27,
R_ONLY_RAND = 28,
R_ONLY_MULTI = 29,
SHORT = 30,
SIMPLE_RAND_BARI = 31,
W_R_INFINITE = 32,
W_R_RAND_INFINITE = 33,
R_INFINITE1 = 34,
R_INFINITE_RF = 35,
MARCH = 36,
SIMPLE_FIX_RF = 37,
SHMOO_STRESS = 38,
SIMPLE_RAND_RA = 39,
SIMPLE_FIX_RA = 40,
SIMPLE_FIX_RF_RA = 41,
TEST_RR = 42,
TEST_RF = 43,
W_ONLY_INFINITE_RAND = 44,
MCB_2D_CUP_SEQ = 45,
MCB_2D_CUP_RAND = 46,
SHMOO_STRESS_INFINITE = 47,
HYNIX_1_COL = 48,
RMWFIX = 49,
RMWFIX_I = 50,
W_INFINITE = 51,
R_INFINITE = 52,
};
} // namespace mcbist
enum class shmoo_edge : std::size_t
{
LEFT,
RIGHT
};
enum visual_max : uint64_t
{
MAX_VISUAL_VALUE = 9999
};
} // namespace mss
#endif
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_ddr_phy_reset.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_mss_ddr_phy_reset.C
/// @brief Reset the DDR PHY
///
// *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com>
// *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB
#include <stdint.h>
#include <string.h>
#include <fapi2.H>
#include <mss.H>
#include <p9_mss_ddr_phy_reset.H>
#include <lib/utils/count_dimm.H>
#include <lib/phy/adr32s.H>
#include <lib/workarounds/dp16_workarounds.H>
#include <lib/workarounds/dll_workarounds.H>
#include <lib/fir/check.H>
#include <lib/fir/unmask.H>
using fapi2::TARGET_TYPE_MCBIST;
extern "C"
{
///
/// @brief Perform a phy reset on all the PHY related to this half-chip (mcbist)
/// @param[in] the mcbist representing the PHY
/// @return FAPI2_RC_SUCCESS iff OK
///
fapi2::ReturnCode p9_mss_ddr_phy_reset(const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& i_target)
{
// If there are no DIMM we don't need to bother. In fact, we can't as we didn't setup
// attributes for the PHY, etc.
if (mss::count_dimm(i_target) == 0)
{
FAPI_INF("... skipping ddr_phy_reset %s - no DIMM ...", mss::c_str(i_target));
return fapi2::FAPI2_RC_SUCCESS;
}
FAPI_TRY(mss::change_force_mclk_low(i_target, mss::LOW),
"force_mclk_low (set high) Failed rc = 0x%08X", uint64_t(fapi2::current_err) );
// 1. Drive all control signals to the PHY to their inactive state, idle state, or inactive value.
FAPI_TRY( mss::dp16::reset_sysclk(i_target) );
// (Note: The chip should already be in this state.)
FAPI_DBG("All control signals to the PHYs should be set to their inactive state, idle state, or inactive values");
// 2. Assert reset to PHY for 32 memory clocks
FAPI_TRY( mss::change_resetn(i_target, mss::HIGH), "change_resetn for %s failed", mss::c_str(i_target) );
fapi2::delay(mss::cycles_to_ns(i_target, 32), mss::cycles_to_simcycles(32));
// 3. Deassert reset_n
FAPI_TRY( mss::change_resetn(i_target, mss::LOW), "change_resetn for %s failed", mss::c_str(i_target) );
//
// Flush output drivers
//
// 8. Set FLUSH=1 and INIT_IO=1 in the DDRPHY_ADR_OUTPUT_FORCE_ATEST_CNTL and DDRPHY_DP16_DATA_BIT_DIR1 register
// 9. Wait at least 32 dphy_gckn clock cycles.
// 10. Set FLUSH=0 and INIT_IO=0 in the DDRPHY_ADR_OUTPUT_FORCE_ATEST_CNTL register
FAPI_TRY( mss::flush_output_drivers(i_target), "unable to flush output drivers for %s", mss::c_str(i_target) );
//
// ZCTL Enable
//
// 11. Assert the ZCNTL enable to the internal impedance controller in DDRPHY_PC_RESETS register
// 12. Wait at least 1024 dphy_gckn cycles
// 13. Deassert the ZCNTL impedance controller enable, Check for DONE in DDRPHY_PC_DLL_ZCAL
FAPI_TRY( mss::enable_zctl(i_target), "enable_zctl for %s failed", mss::c_str(i_target) );
//
// DLL calibration
//
// 14. Begin DLL calibrations by setting INIT_RXDLL_CAL_RESET=0 in the DDRPHY_DP16_DLL_CNTL{0:1} registers
// and DDRPHY_ADR_DLL_CNTL registers
// 15. Monitor the DDRPHY_PC_DLL_ZCAL_CAL_STATUS register to determine when calibration is
// complete. One of the 3 bits will be asserted for ADR and DP16.
{
FAPI_INF( "starting DLL calibration %s", mss::c_str(i_target) );
fapi2::ReturnCode l_rc = mss::dll_calibration(i_target);
// Only run DLL workaround if we fail DLL cal
// Note: there is no EC workaround for this workaround
// The designer team informed me that there is no hardware fix in plan for this type of fail as of DD2 - SPG
if( l_rc != fapi2::FAPI2_RC_SUCCESS )
{
FAPI_INF( "%s Applying DLL workaround", mss::c_str(i_target) );
l_rc = mss::workarounds::dll::fix_bad_voltage_settings(i_target);
}
FAPI_TRY( l_rc, "Failed DLL calibration" );
}
//
// Start bang-bang-lock
//
// 16. Take dphy_nclk/SysClk alignment circuits out of reset and put into continuous update mode,
FAPI_INF("set up of phase rotator controls %s", mss::c_str(i_target) );
FAPI_TRY( mss::setup_phase_rotator_control_registers(i_target, mss::ON) );
// 17. Wait at least 5932 dphy_nclk clock cycles to allow the dphy_nclk/SysClk alignment circuit to
// perform initial alignment.
FAPI_INF("Wait at least 5932 memory clock cycles for clock alignment circuit to perform initial alignment %s",
mss::c_str(i_target));
FAPI_TRY( fapi2::delay(mss::cycles_to_ns(i_target, 5932), 2000) );
// 18. Check for LOCK in DDRPHY_DP16_SYSCLK_PR_VALUE registers and DDRPHY_ADR_SYSCLK_PR_VALUE
FAPI_INF("Checking for bang-bang lock %s ...", mss::c_str(i_target));
FAPI_TRY( mss::check_bang_bang_lock(i_target) );
// 19. Write 0b0 into the DDRPHY_PC_RESETS register bit 1. This write de-asserts the SYSCLK_RESET.
FAPI_INF("deassert sysclk reset %s", mss::c_str(i_target));
FAPI_TRY( mss::deassert_sysclk_reset(i_target), "deassert_sysclk_reset failed for %s", mss::c_str(i_target) );
// 20. Write 8020h into the DDRPHY_ADR_SYSCLK_CNTL_PR Registers and
// DDRPHY_DP16_SYSCLK_PR0/1 registers This write takes the dphy_nclk/
// SysClk alignment circuit out of the Continuous Update mode.
FAPI_INF("take sysclk alignment out of cont update mode %s", mss::c_str(i_target));
FAPI_TRY( mss::setup_phase_rotator_control_registers(i_target, mss::OFF),
"set up of phase rotator controls failed (out of cont update) %s", mss::c_str(i_target) );
// 21. Wait at least 32 dphy_nclk clock cycles.
FAPI_DBG("Wait at least 32 memory clock cycles %s", mss::c_str(i_target));
FAPI_TRY( fapi2::delay(mss::cycles_to_ns(i_target, 32), mss::cycles_to_simcycles(32)) );
//
// Done bang-bang-lock
//
// Per J. Bialas, force_mclk_low can be dasserted.
FAPI_TRY(mss::change_force_mclk_low(i_target, mss::HIGH),
"force_mclk_low (set low) Failed rc = 0x%08X", uint64_t(fapi2::current_err) );
// Workarounds
FAPI_TRY( mss::workarounds::dp16::after_phy_reset(i_target) );
// New for Nimbus - perform duty cycle clock distortion calibration (DCD cal)
// Per PHY team's characterization, the DCD cal needs to be run after DLL calibration
FAPI_TRY( mss::adr32s::duty_cycle_distortion_calibration(i_target) );
// mss::check::during_phy_reset checks to see if there are any FIR. We do this 'twice' once here
// (as part of the good-path) and once if we jump to the fapi_try label.
if ((fapi2::current_err = mss::check::during_phy_reset(i_target)) != fapi2::FAPI2_RC_SUCCESS)
{
goto leave_for_real;
}
// Unmask the FIR we want unmasked after phy reset is complete. Note this is the "good path."
// The algorithm is 'good path do after_phy_reset, all paths (error or not) perform the checks
// which are defined in during_phy_reset'. We won't run after_phy_reset (unmask of FIR) unless
// we're done with a success.
FAPI_TRY( mss::unmask::after_phy_reset(i_target) );
// Leave as we're all good and checked the FIR already ...
return fapi2::current_err;
// ... here on a bad-path, check FIR and leave ...
fapi_try_exit:
// mss::check::during_phy_reset handles the error/no error case internally. All we need to do is
// return the ReturnCode it hands us - it's taken care of commiting anything it needed to.
return mss::check::during_phy_reset(i_target);
// ... here if the good-path FIR check found an error. We jumped over the unmasking and are
// returning an error to the caller.
leave_for_real:
return fapi2::current_err;
}
}
<commit_msg>L3 support for ddr_phy_reset, termination_control<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_ddr_phy_reset.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_mss_ddr_phy_reset.C
/// @brief Reset the DDR PHY
///
// *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com>
// *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: FSP:HB
#include <stdint.h>
#include <string.h>
#include <fapi2.H>
#include <mss.H>
#include <p9_mss_ddr_phy_reset.H>
#include <lib/utils/count_dimm.H>
#include <lib/phy/adr32s.H>
#include <lib/workarounds/dp16_workarounds.H>
#include <lib/workarounds/dll_workarounds.H>
#include <lib/fir/check.H>
#include <lib/fir/unmask.H>
using fapi2::TARGET_TYPE_MCBIST;
extern "C"
{
///
/// @brief Perform a phy reset on all the PHY related to this half-chip (mcbist)
/// @param[in] the mcbist representing the PHY
/// @return FAPI2_RC_SUCCESS iff OK
///
fapi2::ReturnCode p9_mss_ddr_phy_reset(const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& i_target)
{
// If there are no DIMM we don't need to bother. In fact, we can't as we didn't setup
// attributes for the PHY, etc.
if (mss::count_dimm(i_target) == 0)
{
FAPI_INF("... skipping ddr_phy_reset %s - no DIMM ...", mss::c_str(i_target));
return fapi2::FAPI2_RC_SUCCESS;
}
FAPI_TRY(mss::change_force_mclk_low(i_target, mss::LOW),
"force_mclk_low (set high) Failed rc = 0x%08X", uint64_t(fapi2::current_err) );
// 1. Drive all control signals to the PHY to their inactive state, idle state, or inactive value.
FAPI_TRY( mss::dp16::reset_sysclk(i_target) );
// (Note: The chip should already be in this state.)
FAPI_DBG("All control signals to the PHYs should be set to their inactive state, idle state, or inactive values");
// 2. Assert reset to PHY for 32 memory clocks
FAPI_TRY( mss::change_resetn(i_target, mss::HIGH), "change_resetn for %s failed", mss::c_str(i_target) );
fapi2::delay(mss::cycles_to_ns(i_target, 32), mss::cycles_to_simcycles(32));
// 3. Deassert reset_n
FAPI_TRY( mss::change_resetn(i_target, mss::LOW), "change_resetn for %s failed", mss::c_str(i_target) );
//
// Flush output drivers
//
// 8. Set FLUSH=1 and INIT_IO=1 in the DDRPHY_ADR_OUTPUT_FORCE_ATEST_CNTL and DDRPHY_DP16_DATA_BIT_DIR1 register
// 9. Wait at least 32 dphy_gckn clock cycles.
// 10. Set FLUSH=0 and INIT_IO=0 in the DDRPHY_ADR_OUTPUT_FORCE_ATEST_CNTL register
FAPI_TRY( mss::flush_output_drivers(i_target), "unable to flush output drivers for %s", mss::c_str(i_target) );
//
// ZCTL Enable
//
// 11. Assert the ZCNTL enable to the internal impedance controller in DDRPHY_PC_RESETS register
// 12. Wait at least 1024 dphy_gckn cycles
// 13. Deassert the ZCNTL impedance controller enable, Check for DONE in DDRPHY_PC_DLL_ZCAL
FAPI_TRY( mss::enable_zctl(i_target), "enable_zctl for %s failed", mss::c_str(i_target) );
//
// DLL calibration
//
// 14. Begin DLL calibrations by setting INIT_RXDLL_CAL_RESET=0 in the DDRPHY_DP16_DLL_CNTL{0:1} registers
// and DDRPHY_ADR_DLL_CNTL registers
// 15. Monitor the DDRPHY_PC_DLL_ZCAL_CAL_STATUS register to determine when calibration is
// complete. One of the 3 bits will be asserted for ADR and DP16.
{
FAPI_INF( "starting DLL calibration %s", mss::c_str(i_target) );
bool l_run_workaround = false;
fapi2::ReturnCode l_rc = mss::dll_calibration(i_target, l_run_workaround);
// Only run DLL workaround if we fail DLL cal
// Note: there is no EC workaround for this workaround
// The designer team informed me that there is no hardware fix in plan for this type of fail as of DD2 - SPG
if( l_run_workaround )
{
FAPI_INF( "%s Applying DLL workaround", mss::c_str(i_target) );
l_rc = mss::workarounds::dll::fix_bad_voltage_settings(i_target);
}
FAPI_TRY( l_rc, "Failed DLL calibration" );
}
//
// Start bang-bang-lock
//
// 16. Take dphy_nclk/SysClk alignment circuits out of reset and put into continuous update mode,
FAPI_INF("set up of phase rotator controls %s", mss::c_str(i_target) );
FAPI_TRY( mss::setup_phase_rotator_control_registers(i_target, mss::ON) );
// 17. Wait at least 5932 dphy_nclk clock cycles to allow the dphy_nclk/SysClk alignment circuit to
// perform initial alignment.
FAPI_INF("Wait at least 5932 memory clock cycles for clock alignment circuit to perform initial alignment %s",
mss::c_str(i_target));
FAPI_TRY( fapi2::delay(mss::cycles_to_ns(i_target, 5932), 2000) );
// 18. Check for LOCK in DDRPHY_DP16_SYSCLK_PR_VALUE registers and DDRPHY_ADR_SYSCLK_PR_VALUE
FAPI_INF("Checking for bang-bang lock %s ...", mss::c_str(i_target));
FAPI_TRY( mss::check_bang_bang_lock(i_target) );
// 19. Write 0b0 into the DDRPHY_PC_RESETS register bit 1. This write de-asserts the SYSCLK_RESET.
FAPI_INF("deassert sysclk reset %s", mss::c_str(i_target));
FAPI_TRY( mss::deassert_sysclk_reset(i_target), "deassert_sysclk_reset failed for %s", mss::c_str(i_target) );
// 20. Write 8020h into the DDRPHY_ADR_SYSCLK_CNTL_PR Registers and
// DDRPHY_DP16_SYSCLK_PR0/1 registers This write takes the dphy_nclk/
// SysClk alignment circuit out of the Continuous Update mode.
FAPI_INF("take sysclk alignment out of cont update mode %s", mss::c_str(i_target));
FAPI_TRY( mss::setup_phase_rotator_control_registers(i_target, mss::OFF),
"set up of phase rotator controls failed (out of cont update) %s", mss::c_str(i_target) );
// 21. Wait at least 32 dphy_nclk clock cycles.
FAPI_DBG("Wait at least 32 memory clock cycles %s", mss::c_str(i_target));
FAPI_TRY( fapi2::delay(mss::cycles_to_ns(i_target, 32), mss::cycles_to_simcycles(32)) );
//
// Done bang-bang-lock
//
// Per J. Bialas, force_mclk_low can be dasserted.
FAPI_TRY(mss::change_force_mclk_low(i_target, mss::HIGH),
"force_mclk_low (set low) Failed rc = 0x%08X", uint64_t(fapi2::current_err) );
// Workarounds
FAPI_TRY( mss::workarounds::dp16::after_phy_reset(i_target) );
// New for Nimbus - perform duty cycle clock distortion calibration (DCD cal)
// Per PHY team's characterization, the DCD cal needs to be run after DLL calibration
FAPI_TRY( mss::adr32s::duty_cycle_distortion_calibration(i_target) );
// mss::check::during_phy_reset checks to see if there are any FIR. We do this 'twice' once here
// (as part of the good-path) and once if we jump to the fapi_try label.
if ((fapi2::current_err = mss::check::during_phy_reset(i_target)) != fapi2::FAPI2_RC_SUCCESS)
{
goto leave_for_real;
}
// Unmask the FIR we want unmasked after phy reset is complete. Note this is the "good path."
// The algorithm is 'good path do after_phy_reset, all paths (error or not) perform the checks
// which are defined in during_phy_reset'. We won't run after_phy_reset (unmask of FIR) unless
// we're done with a success.
FAPI_TRY( mss::unmask::after_phy_reset(i_target) );
// Leave as we're all good and checked the FIR already ...
return fapi2::current_err;
// ... here on a bad-path, check FIR and leave ...
fapi_try_exit:
// mss::check::during_phy_reset handles the error/no error case internally. All we need to do is
// return the ReturnCode it hands us - it's taken care of commiting anything it needed to.
return mss::check::during_phy_reset(i_target);
// ... here if the good-path FIR check found an error. We jumped over the unmasking and are
// returning an error to the caller.
leave_for_real:
return fapi2::current_err;
}
}
<|endoftext|> |
<commit_before>///
/// @file phi_vector.hpp
/// @brief The PhiCache class calculates the partial sieve function
/// (a.k.a. Legendre-sum) using the recursive formula:
/// phi(x, a) = phi(x, a - 1) - phi(x / primes[a], a - 1).
/// phi(x, a) counts the numbers <= x that are not divisible by
/// any of the first a primes. The algorithm used is an
/// optimized version of the algorithm described in Tomás
/// Oliveira e Silva's paper [1]. I have added 5 optimizations
/// to my implementation which significantly speed up the
/// calculation:
///
/// * Cache results of phi(x, a)
/// * Calculate phi(x, a) using formula [2] if a <= 6
/// * Calculate phi(x, a) using pi(x) lookup table
/// * Calculate all phi(x, a) = 1 upfront
/// * Stop recursion at c instead of 1
///
/// [1] Tomás Oliveira e Silva, Computing pi(x): the combinatorial
/// method, Revista do DETUA, vol. 4, no. 6, March 2006, p. 761.
/// http://sweet.ua.pt/tos/bib/5.4.pdf
/// [2] phi(x, a) = (x / pp) * φ(pp) + phi(x % pp, a)
/// with pp = 2 * 3 * ... * prime[a]
///
/// Copyright (C) 2017 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#ifndef PHI_VECTOR_HPP
#define PHI_VECTOR_HPP
#include <PiTable.hpp>
#include <primecount-internal.hpp>
#include <fast_div.hpp>
#include <imath.hpp>
#include <PhiTiny.hpp>
#include <stdint.h>
#include <array>
#include <cstdlib>
#include <vector>
#include <limits>
#ifdef _OPENMP
#include <omp.h>
#endif
namespace {
using namespace std;
using namespace primecount;
/// Cache phi(x, a) results if a < MAX_A
const int MAX_A = 100;
template <typename Primes>
class PhiCache
{
public:
PhiCache(Primes& primes, PiTable& pi)
: primes_(primes),
pi_(pi)
{ }
/// Calculate phi(x, a) using the recursive formula:
/// phi(x, a) = phi(x, a - 1) - phi(x / prime(a), a - 1)
///
template <int SIGN>
int64_t phi(int64_t x, int64_t a)
{
if (x <= prime(a))
return SIGN;
else if (is_phi_tiny(a))
return phi_tiny(x, a) * SIGN;
else if (is_pix(x, a))
return (pi_[x] - a + 1) * SIGN;
else if (is_cached(x, a))
return cache_[a][x] * SIGN;
int64_t sqrtx = isqrt(x);
int64_t pi_sqrtx = a;
int64_t c = PhiTiny::get_c(sqrtx);
int64_t sum = 0;
if (sqrtx < pi_.size() && sqrtx < prime(a))
pi_sqrtx = pi_[sqrtx];
// Move out of the loop the calculations where phi(x2, i) = 1
// phi(x, a) = 1 if prime(a) >= x
// x2 = x / prime(i + 1)
// phi(x2, i) = 1 if prime(i) >= x / prime(i + 1)
// phi(x2, i) = 1 if prime(i) >= sqrt(x)
// phi(x2, i) = 1 if i >= pi(sqrt(x))
// \sum_{i = pi(sqrt(x))}^{a - 1} phi(x2, i) = a - pi(sqrt(x))
//
sum += (pi_sqrtx - a) * SIGN;
sum += phi_tiny(x, c) * SIGN;
for (int64_t i = c; i < pi_sqrtx; i++)
{
int64_t x2 = fast_div(x, prime(i + 1));
if (is_pix(x2, i))
sum += (pi_[x2] - i + 1) * -SIGN;
else
sum += phi<-SIGN>(x2, i);
}
update_cache(x, a, sum);
return sum;
}
private:
using T = uint16_t;
array<vector<T>, MAX_A> cache_;
Primes& primes_;
PiTable& pi_;
int64_t prime(int64_t i) const
{
return primes_[i];
}
void update_cache(uint64_t x, uint64_t a, int64_t sum)
{
if (a < cache_.size() &&
x <= numeric_limits<T>::max())
{
if (x >= cache_[a].size())
cache_[a].resize(x + 1, 0);
cache_[a][x] = (T) abs(sum);
}
}
bool is_pix(int64_t x, int64_t a) const
{
return x < pi_.size() &&
x < isquare(prime(a + 1));
}
bool is_cached(uint64_t x, uint64_t a) const
{
return a < cache_.size() &&
x < cache_[a].size() &&
cache_[a][x];
}
};
/// Returns a vector with phi(x, i - 1) values such that
/// phi[i] = phi(x, i - 1) for 1 <= i <= a.
/// phi(x, a) counts the numbers <= x that are not
/// divisible by any of the first a primes.
///
template <typename Primes>
vector<int64_t> phi_vector(int64_t x,
int64_t a,
Primes& primes,
PiTable& pi,
int threads = 1)
{
int64_t size = a + 1;
int64_t c = PhiTiny::max_a();
if (primes[a] > x)
a = pi[x];
vector<int64_t> phi;
phi.reserve(size);
phi.resize(a + 1, (x > 0) ? -1 : 0);
phi.resize(size, x > 0);
if (x > 0 && a > c)
{
phi[c] = phi_tiny(x, c - 1);
PhiCache<Primes> cache(primes, pi);
int64_t limit = a;
int64_t sqrtx = isqrt(x);
int64_t thread_threshold = ipow(10ll, 10);
threads = ideal_num_threads(threads, x, thread_threshold);
if (sqrtx < pi.size())
limit = min(a, pi[sqrtx] + 1);
#pragma omp parallel for num_threads(threads) schedule(dynamic, 16) firstprivate(cache)
for (int64_t i = c + 1; i <= limit; i++)
phi[i] = cache.template phi<-1>(x / primes[i - 1], i - 2);
// calculate phi(x, a) using partial results
for (int64_t i = c + 1; i <= a; i++)
phi[i] += phi[i - 1];
}
return phi;
}
} // namespace
#endif
<commit_msg>Rename limit to pi_sqrtx<commit_after>///
/// @file phi_vector.hpp
/// @brief The PhiCache class calculates the partial sieve function
/// (a.k.a. Legendre-sum) using the recursive formula:
/// phi(x, a) = phi(x, a - 1) - phi(x / primes[a], a - 1).
/// phi(x, a) counts the numbers <= x that are not divisible by
/// any of the first a primes. The algorithm used is an
/// optimized version of the algorithm described in Tomás
/// Oliveira e Silva's paper [1]. I have added 5 optimizations
/// to my implementation which significantly speed up the
/// calculation:
///
/// * Cache results of phi(x, a)
/// * Calculate phi(x, a) using formula [2] if a <= 6
/// * Calculate phi(x, a) using pi(x) lookup table
/// * Calculate all phi(x, a) = 1 upfront
/// * Stop recursion at c instead of 1
///
/// [1] Tomás Oliveira e Silva, Computing pi(x): the combinatorial
/// method, Revista do DETUA, vol. 4, no. 6, March 2006, p. 761.
/// http://sweet.ua.pt/tos/bib/5.4.pdf
/// [2] phi(x, a) = (x / pp) * φ(pp) + phi(x % pp, a)
/// with pp = 2 * 3 * ... * prime[a]
///
/// Copyright (C) 2017 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#ifndef PHI_VECTOR_HPP
#define PHI_VECTOR_HPP
#include <PiTable.hpp>
#include <primecount-internal.hpp>
#include <fast_div.hpp>
#include <imath.hpp>
#include <PhiTiny.hpp>
#include <stdint.h>
#include <array>
#include <cstdlib>
#include <vector>
#include <limits>
#ifdef _OPENMP
#include <omp.h>
#endif
namespace {
using namespace std;
using namespace primecount;
/// Cache phi(x, a) results if a < MAX_A
const int MAX_A = 100;
template <typename Primes>
class PhiCache
{
public:
PhiCache(Primes& primes, PiTable& pi)
: primes_(primes),
pi_(pi)
{ }
/// Calculate phi(x, a) using the recursive formula:
/// phi(x, a) = phi(x, a - 1) - phi(x / prime(a), a - 1)
///
template <int SIGN>
int64_t phi(int64_t x, int64_t a)
{
if (x <= prime(a))
return SIGN;
else if (is_phi_tiny(a))
return phi_tiny(x, a) * SIGN;
else if (is_pix(x, a))
return (pi_[x] - a + 1) * SIGN;
else if (is_cached(x, a))
return cache_[a][x] * SIGN;
int64_t sqrtx = isqrt(x);
int64_t pi_sqrtx = a;
int64_t c = PhiTiny::get_c(sqrtx);
int64_t sum = 0;
if (sqrtx < pi_.size() && sqrtx < prime(a))
pi_sqrtx = pi_[sqrtx];
// Move out of the loop the calculations where phi(x2, i) = 1
// phi(x, a) = 1 if prime(a) >= x
// x2 = x / prime(i + 1)
// phi(x2, i) = 1 if prime(i) >= x / prime(i + 1)
// phi(x2, i) = 1 if prime(i) >= sqrt(x)
// phi(x2, i) = 1 if i >= pi(sqrt(x))
// \sum_{i = pi(sqrt(x))}^{a - 1} phi(x2, i) = a - pi(sqrt(x))
//
sum += (pi_sqrtx - a) * SIGN;
sum += phi_tiny(x, c) * SIGN;
for (int64_t i = c; i < pi_sqrtx; i++)
{
int64_t x2 = fast_div(x, prime(i + 1));
if (is_pix(x2, i))
sum += (pi_[x2] - i + 1) * -SIGN;
else
sum += phi<-SIGN>(x2, i);
}
update_cache(x, a, sum);
return sum;
}
private:
using T = uint16_t;
array<vector<T>, MAX_A> cache_;
Primes& primes_;
PiTable& pi_;
int64_t prime(int64_t i) const
{
return primes_[i];
}
void update_cache(uint64_t x, uint64_t a, int64_t sum)
{
if (a < cache_.size() &&
x <= numeric_limits<T>::max())
{
if (x >= cache_[a].size())
cache_[a].resize(x + 1, 0);
cache_[a][x] = (T) abs(sum);
}
}
bool is_pix(int64_t x, int64_t a) const
{
return x < pi_.size() &&
x < isquare(prime(a + 1));
}
bool is_cached(uint64_t x, uint64_t a) const
{
return a < cache_.size() &&
x < cache_[a].size() &&
cache_[a][x];
}
};
/// Returns a vector with phi(x, i - 1) values such that
/// phi[i] = phi(x, i - 1) for 1 <= i <= a.
/// phi(x, a) counts the numbers <= x that are not
/// divisible by any of the first a primes.
///
template <typename Primes>
vector<int64_t> phi_vector(int64_t x,
int64_t a,
Primes& primes,
PiTable& pi,
int threads = 1)
{
int64_t size = a + 1;
int64_t c = PhiTiny::max_a();
if (primes[a] > x)
a = pi[x];
vector<int64_t> phi;
phi.reserve(size);
phi.resize(a + 1, (x > 0) ? -1 : 0);
phi.resize(size, x > 0);
if (x > 0 && a > c)
{
phi[c] = phi_tiny(x, c - 1);
PhiCache<Primes> cache(primes, pi);
int64_t sqrtx = isqrt(x);
int64_t pi_sqrtx = a;
int64_t thread_threshold = ipow(10ll, 10);
threads = ideal_num_threads(threads, x, thread_threshold);
if (sqrtx < pi.size())
pi_sqrtx = min(pi[sqrtx] + 1, a);
#pragma omp parallel for num_threads(threads) schedule(dynamic, 16) firstprivate(cache)
for (int64_t i = c + 1; i <= pi_sqrtx; i++)
phi[i] = cache.template phi<-1>(x / primes[i - 1], i - 2);
// calculate phi(x, a) using partial results
for (int64_t i = c + 1; i <= a; i++)
phi[i] += phi[i - 1];
}
return phi;
}
} // namespace
#endif
<|endoftext|> |
<commit_before>#include <common/buffer.h>
#include <common/endian.h>
#include <event/action.h>
#include <event/callback.h>
#include <event/event_system.h>
#include "wanproxy_config.h"
static void usage(void);
int
main(int argc, char *argv[])
{
std::string configfile("");
int ch;
INFO("/wanproxy") << "WANProxy";
INFO("/wanproxy") << "Copyright (c) 2008-2009 WANProxy.org.";
INFO("/wanproxy") << "All rights reserved.";
while ((ch = getopt(argc, argv, "c:")) != -1) {
switch (ch) {
case 'c':
configfile = optarg;
break;
default:
usage();
}
}
if (configfile == "")
usage();
WANProxyConfig config;
if (!config.configure(configfile))
HALT("/wanproxy") << "Could not configure proxies.";
EventSystem::instance()->start();
}
static void
usage(void)
{
INFO("/wanproxy/usage") << "wanproxy -c configfile";
exit(1);
}
<commit_msg>Update year.<commit_after>#include <common/buffer.h>
#include <common/endian.h>
#include <event/action.h>
#include <event/callback.h>
#include <event/event_system.h>
#include "wanproxy_config.h"
static void usage(void);
int
main(int argc, char *argv[])
{
std::string configfile("");
int ch;
INFO("/wanproxy") << "WANProxy";
INFO("/wanproxy") << "Copyright (c) 2008-2010 WANProxy.org.";
INFO("/wanproxy") << "All rights reserved.";
while ((ch = getopt(argc, argv, "c:")) != -1) {
switch (ch) {
case 'c':
configfile = optarg;
break;
default:
usage();
}
}
if (configfile == "")
usage();
WANProxyConfig config;
if (!config.configure(configfile))
HALT("/wanproxy") << "Could not configure proxies.";
EventSystem::instance()->start();
}
static void
usage(void)
{
INFO("/wanproxy/usage") << "wanproxy -c configfile";
exit(1);
}
<|endoftext|> |
<commit_before>#include "tentacle-pseudopod.h"
#include <stddef.h>
Pseudopod::Pseudopod(Stream &input, Print &output, Tentacle& tentacle) {
pb_ostream_from_stream(output, pbOutput);
pb_istream_from_stream(input, pbInput);
this->tentacle = &tentacle;
messagePinActions = new Action[tentacle.getNumPins()];
resetPinActions();
}
bool Pseudopod::shouldBroadcastPins() {
return broadcastPins;
}
int Pseudopod::getBroadcastInterval() {
return broadcastInterval;
}
bool Pseudopod::isConfigured() {
return configured;
}
void Pseudopod::resetPinActions() {
for(int i = 0; i < tentacle->getNumPins(); i++) {
messagePinActions[i] = Action_ignore;
}
}
size_t Pseudopod::sendPins() {
pbOutput.bytes_written = 0;
currentMessage = {};
currentMessage.topic = TentacleMessageTopic_action;
currentMessage.has_topic = true;
currentMessage.response = true;
currentMessage.has_response = true;
currentMessage.pins.funcs.encode = &Pseudopod::pinEncode;
currentMessage.pins.arg = (void*)this;
bool status = pb_encode_delimited(&pbOutput, TentacleMessage_fields, ¤tMessage);
return pbOutput.bytes_written;
}
size_t Pseudopod::sendPins(Action* actions) {
resetPinActions();
for(int i = 0; i < tentacle->getNumPins(); i++) {
messagePinActions[i] = actions[i];
}
return sendPins();
}
size_t Pseudopod::sendConfiguredPins() {
return sendPins(tentacle->getConfiguredPinActions());
}
size_t Pseudopod::authenticate(const char *uuid, const char *token) {
pbOutput.bytes_written = 0;
currentMessage = {};
currentMessage.topic = TentacleMessageTopic_authentication;
currentMessage.has_topic = true;
currentMessage.authentication = {};
currentMessage.has_authentication = true;
strncpy(currentMessage.authentication.uuid, uuid, 36);
currentMessage.authentication.has_uuid = true;
strncpy(currentMessage.authentication.token, token, 40);
currentMessage.authentication.has_token = true;
bool status = pb_encode_delimited(&pbOutput, TentacleMessage_fields, ¤tMessage);
return pbOutput.bytes_written;
}
size_t Pseudopod::requestConfiguration() {
pbOutput.bytes_written = 0;
currentMessage = {};
currentMessage.topic = TentacleMessageTopic_config;
currentMessage.has_topic = true;
bool status = pb_encode_delimited(&pbOutput, TentacleMessage_fields, ¤tMessage);
return pbOutput.bytes_written;
}
size_t Pseudopod::registerDevice() {
return 0;
}
bool Pseudopod::isConnected() {
pbOutput.bytes_written = 0;
currentMessage = {};
currentMessage.topic = TentacleMessageTopic_ping;
currentMessage.has_topic = true;
bool status = pb_encode_delimited(&pbOutput, TentacleMessage_fields, ¤tMessage);
return pbOutput.bytes_written != 0;
}
TentacleMessageTopic Pseudopod::readMessage() {
resetPinActions();
currentMessage = {};
currentMessage.pins.funcs.decode = &Pseudopod::pinDecode;
currentMessage.pins.arg = (void*) this;
bool status = pb_decode_delimited(&pbInput, TentacleMessage_fields, ¤tMessage);
if (currentMessage.topic == TentacleMessageTopic_config) {
for(int i = 0; i < tentacle->getNumPins(); i++) {
pseudopod->tentacle->configurePin(i, messagePinActions[i]);
}
configured = true;
broadcastPins = currentMessage.broadcastPins;
broadcastInterval = currentMessage.broadcastInterval;
}
return currentMessage.topic;
}
bool Pseudopod::pinEncode(pb_ostream_t *stream, const pb_field_t *field, void * const *arg) {
Pseudopod *pseudopod = (Pseudopod*) *arg;
Action action;
Pin pin;
for(int i = 0; i < pseudopod->tentacle->getNumPins(); i++) {
action = pseudopod->messagePinActions[i];
if(action == Action_ignore) {
continue;
}
pin = {};
pin.has_action = true;
pin.action = action;
pin.has_number = true;
pin.number = i;
int value = pseudopod->tentacle->processPin(i);
if(value != -1) {
pin.has_value = true;
pin.value = value;
}
if (!pb_encode_tag_for_field(stream, field)) {
return false;
}
if(!pb_encode_submessage(stream, Pin_fields, &pin)) {
return false;
}
}
return true;
}
bool Pseudopod::pinDecode(pb_istream_t *stream, const pb_field_t *field, void **arg) {
Pseudopod *pseudopod = (Pseudopod*) *arg;
Pin pin = {};
if (!pb_decode(stream, Pin_fields, &pin)) {
return false;
}
TentacleMessage& message = pseudopod->currentMessage;
pseudopod->messagePinActions[pin.number] = pin.action;
if(message.topic == TentacleMessageTopic_action) {
pseudopod->tentacle->processPin(pin.number, pin.value);
}
return true;
}
<commit_msg>fixed something<commit_after>#include "tentacle-pseudopod.h"
#include <stddef.h>
Pseudopod::Pseudopod(Stream &input, Print &output, Tentacle& tentacle) {
pb_ostream_from_stream(output, pbOutput);
pb_istream_from_stream(input, pbInput);
this->tentacle = &tentacle;
messagePinActions = new Action[tentacle.getNumPins()];
resetPinActions();
}
bool Pseudopod::shouldBroadcastPins() {
return broadcastPins;
}
int Pseudopod::getBroadcastInterval() {
return broadcastInterval;
}
bool Pseudopod::isConfigured() {
return configured;
}
void Pseudopod::resetPinActions() {
for(int i = 0; i < tentacle->getNumPins(); i++) {
messagePinActions[i] = Action_ignore;
}
}
size_t Pseudopod::sendPins() {
pbOutput.bytes_written = 0;
currentMessage = {};
currentMessage.topic = TentacleMessageTopic_action;
currentMessage.has_topic = true;
currentMessage.response = true;
currentMessage.has_response = true;
currentMessage.pins.funcs.encode = &Pseudopod::pinEncode;
currentMessage.pins.arg = (void*)this;
bool status = pb_encode_delimited(&pbOutput, TentacleMessage_fields, ¤tMessage);
return pbOutput.bytes_written;
}
size_t Pseudopod::sendPins(Action* actions) {
resetPinActions();
for(int i = 0; i < tentacle->getNumPins(); i++) {
messagePinActions[i] = actions[i];
}
return sendPins();
}
size_t Pseudopod::sendConfiguredPins() {
return sendPins(tentacle->getConfiguredPinActions());
}
size_t Pseudopod::authenticate(const char *uuid, const char *token) {
pbOutput.bytes_written = 0;
currentMessage = {};
currentMessage.topic = TentacleMessageTopic_authentication;
currentMessage.has_topic = true;
currentMessage.authentication = {};
currentMessage.has_authentication = true;
strncpy(currentMessage.authentication.uuid, uuid, 36);
currentMessage.authentication.has_uuid = true;
strncpy(currentMessage.authentication.token, token, 40);
currentMessage.authentication.has_token = true;
bool status = pb_encode_delimited(&pbOutput, TentacleMessage_fields, ¤tMessage);
return pbOutput.bytes_written;
}
size_t Pseudopod::requestConfiguration() {
pbOutput.bytes_written = 0;
currentMessage = {};
currentMessage.topic = TentacleMessageTopic_config;
currentMessage.has_topic = true;
bool status = pb_encode_delimited(&pbOutput, TentacleMessage_fields, ¤tMessage);
return pbOutput.bytes_written;
}
size_t Pseudopod::registerDevice() {
return 0;
}
bool Pseudopod::isConnected() {
pbOutput.bytes_written = 0;
currentMessage = {};
currentMessage.topic = TentacleMessageTopic_ping;
currentMessage.has_topic = true;
bool status = pb_encode_delimited(&pbOutput, TentacleMessage_fields, ¤tMessage);
return pbOutput.bytes_written != 0;
}
TentacleMessageTopic Pseudopod::readMessage() {
resetPinActions();
currentMessage = {};
currentMessage.pins.funcs.decode = &Pseudopod::pinDecode;
currentMessage.pins.arg = (void*) this;
bool status = pb_decode_delimited(&pbInput, TentacleMessage_fields, ¤tMessage);
if (currentMessage.topic == TentacleMessageTopic_config) {
for(int i = 0; i < tentacle->getNumPins(); i++) {
tentacle->configurePin(i, messagePinActions[i]);
}
configured = true;
broadcastPins = currentMessage.broadcastPins;
broadcastInterval = currentMessage.broadcastInterval;
}
return currentMessage.topic;
}
bool Pseudopod::pinEncode(pb_ostream_t *stream, const pb_field_t *field, void * const *arg) {
Pseudopod *pseudopod = (Pseudopod*) *arg;
Action action;
Pin pin;
for(int i = 0; i < pseudopod->tentacle->getNumPins(); i++) {
action = pseudopod->messagePinActions[i];
if(action == Action_ignore) {
continue;
}
pin = {};
pin.has_action = true;
pin.action = action;
pin.has_number = true;
pin.number = i;
int value = pseudopod->tentacle->processPin(i);
if(value != -1) {
pin.has_value = true;
pin.value = value;
}
if (!pb_encode_tag_for_field(stream, field)) {
return false;
}
if(!pb_encode_submessage(stream, Pin_fields, &pin)) {
return false;
}
}
return true;
}
bool Pseudopod::pinDecode(pb_istream_t *stream, const pb_field_t *field, void **arg) {
Pseudopod *pseudopod = (Pseudopod*) *arg;
Pin pin = {};
if (!pb_decode(stream, Pin_fields, &pin)) {
return false;
}
TentacleMessage& message = pseudopod->currentMessage;
pseudopod->messagePinActions[pin.number] = pin.action;
if(message.topic == TentacleMessageTopic_action) {
pseudopod->tentacle->processPin(pin.number, pin.value);
}
return true;
}
<|endoftext|> |
<commit_before>/*
irceditaccountwidget.cpp - IRC Account Widget
Copyright (c) 2003 by Olivier Goffart <ogoffart@tiscalinet.be>
Copyright (c) 2003 by Jason Keirstead <jason@keirstead.org>
Kopete (c) 2003 by the Kopete developers <kopete-devel@kde.org>
*************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
*************************************************************************
*/
#include <kmessagebox.h>
#include <klocale.h>
#include <klistview.h>
#include <qpopupmenu.h>
#include <qpushbutton.h>
#include <kdebug.h>
#include <qlineedit.h>
#include <qspinbox.h>
#include <qcheckbox.h>
#include <kextsock.h>
#include <qconnection.h>
#include "kirc.h"
#include "ircaccount.h"
#include "irceditaccountwidget.h"
IRCEditAccountWidget::IRCEditAccountWidget(IRCProtocol *proto, IRCAccount *ident, QWidget *parent, const char * )
: IRCEditAccountBase(parent), KopeteEditAccountWidget(ident)
{
mProtocol = proto;
m_IRCAccount = (IRCAccount *)ident;
if( m_IRCAccount )
{
QString nickName = m_IRCAccount->accountId().section( '@', 0, 0);
QString serverInfo = m_IRCAccount->accountId().section( '@', 1);
mNickName->setText( nickName );
mServer->setText( serverInfo.section(':', 0, 0) );
mPort->setValue( serverInfo.section(':',1).toUInt() );
mNickName->setDisabled(true);
mServer->setDisabled(true);
mPort->setDisabled(true);
mUserName->setText( m_IRCAccount->userName() );
mAltNickname->setText( m_IRCAccount->altNick() );
partMessage->setText( m_IRCAccount->defaultPart() );
quitMessage->setText( m_IRCAccount->defaultQuit() );
if(account()->rememberPassword()) mPassword->setText( m_IRCAccount->password() );
QStringList cmds = m_IRCAccount->connectCommands();
for( QStringList::Iterator i = cmds.begin(); i != cmds.end(); ++i )
new QListViewItem( commandList, *i );
const QMap< QString, QString > replies = m_IRCAccount->customCtcpReplies();
for( QMap< QString, QString >::ConstIterator it = replies.begin(); it != replies.end(); ++it )
new QListViewItem( ctcpList, it.key(), it.data() );
}
connect( commandList, SIGNAL( contextMenu( KListView *, QListViewItem *, const QPoint & ) ),
this, SLOT( slotContextMenu( KListView *, QListViewItem *, const QPoint & ) ) );
connect( ctcpList, SIGNAL( contextMenu( KListView *, QListViewItem *, const QPoint & ) ),
this, SLOT( slotContextMenu( KListView *, QListViewItem *, const QPoint & ) ) );
connect( addButton, SIGNAL( clicked() ), this, SLOT( slotAddCommand() ) );
connect( addReply, SIGNAL( clicked() ), this, SLOT( slotAddCtcp() ) );
}
IRCEditAccountWidget::~IRCEditAccountWidget()
{
}
void IRCEditAccountWidget::slotContextMenu( KListView *, QListViewItem *item, const QPoint &p )
{
QPopupMenu popup;
popup.insertItem( i18n("Remove Command"), 1 );
if( popup.exec( p ) == 1 )
delete item;
}
void IRCEditAccountWidget::slotAddCommand()
{
if ( !commandEdit->text().isEmpty() )
{
new QListViewItem( commandList, commandEdit->text() );
commandEdit->clear();
}
}
void IRCEditAccountWidget::slotAddCtcp()
{
if ( !newCTCP->text().isEmpty() && !newReply->text().isEmpty() )
{
new QListViewItem( ctcpList, newCTCP->text(), newReply->text() );
newCTCP->clear();
newReply->clear();
}
}
KopeteAccount *IRCEditAccountWidget::apply()
{
QString mAccountId = mNickName->text() + QString::fromLatin1("@") + mServer->text() + QString::fromLatin1(":") + QString::number( mPort->value() );
if( !m_IRCAccount )
m_IRCAccount = new IRCAccount( mProtocol, mAccountId );
// else
// m_IRCAccount->setAccountId( mAccountId );
if (mRememberPassword->isChecked()) {
kdDebug(14120) << k_funcinfo << "Saving password '" << mPassword->text() << "' empty: " << mPassword->text().isEmpty() << " null: " << mPassword->text().isNull() << endl;
m_IRCAccount->setPassword( mPassword->text() );
}
m_IRCAccount->setUserName( mUserName->text() );
m_IRCAccount->setDefaultPart( partMessage->text() );
m_IRCAccount->setDefaultQuit( quitMessage->text() );
m_IRCAccount->setAutoLogin( mAutoConnect->isChecked() );
m_IRCAccount->setAltNick( mAltNickname->text() );
QStringList cmds;
for( QListViewItem *i = commandList->firstChild(); i; i = i->nextSibling() )
cmds.append( i->text(0) );
QMap< QString, QString > replies;
for( QListViewItem *i = ctcpList->firstChild(); i; i = i->nextSibling() )
replies[ i->text(0) ] = i->text(1);
m_IRCAccount->setCustomCtcpReplies( replies );
m_IRCAccount->setConnectCommands( cmds );
return m_IRCAccount;
}
bool IRCEditAccountWidget::validateData()
{
if( mNickName->text().isEmpty() )
KMessageBox::sorry(this, i18n("<qt>You must enter a nickname.</qt>"), i18n("Kopete"));
else if( mServer->text().isEmpty() )
KMessageBox::sorry(this, i18n("<qt>You must enter a server.</qt>"), i18n("Kopete"));
else
{
int error;
QPtrList<KAddressInfo> address = KExtendedSocket::lookup(
mServer->text(), QString::number( mPort->value() ), 0, &error );
address.setAutoDelete(true);
if( !address.isEmpty() )
return true;
KMessageBox::sorry(this, i18n("<qt>The server/port combination you entered is invalid. Please double-check your values.</qt>"), i18n("Kopete"));
}
return false;
}
#include "irceditaccountwidget.moc"
<commit_msg>Don't allow spaces in the user name, the protocol doesn't support it<commit_after>/*
irceditaccountwidget.cpp - IRC Account Widget
Copyright (c) 2003 by Olivier Goffart <ogoffart@tiscalinet.be>
Copyright (c) 2003 by Jason Keirstead <jason@keirstead.org>
Kopete (c) 2003 by the Kopete developers <kopete-devel@kde.org>
*************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
*************************************************************************
*/
#include <kmessagebox.h>
#include <klocale.h>
#include <klistview.h>
#include <qpopupmenu.h>
#include <qpushbutton.h>
#include <kdebug.h>
#include <qlineedit.h>
#include <qspinbox.h>
#include <qcheckbox.h>
#include <kextsock.h>
#include <qconnection.h>
#include <qvalidator.h>
#include "kirc.h"
#include "ircaccount.h"
#include "irceditaccountwidget.h"
IRCEditAccountWidget::IRCEditAccountWidget(IRCProtocol *proto, IRCAccount *ident, QWidget *parent, const char * )
: IRCEditAccountBase(parent), KopeteEditAccountWidget(ident)
{
mProtocol = proto;
m_IRCAccount = (IRCAccount *)ident;
if( m_IRCAccount )
{
QString nickName = m_IRCAccount->accountId().section( '@', 0, 0);
QString serverInfo = m_IRCAccount->accountId().section( '@', 1);
mNickName->setText( nickName );
mServer->setText( serverInfo.section(':', 0, 0) );
mPort->setValue( serverInfo.section(':',1).toUInt() );
mNickName->setDisabled(true);
mServer->setDisabled(true);
mPort->setDisabled(true);
mUserName->setText( m_IRCAccount->userName() );
mUserName->setValidator( new QRegExpValidator( QString::fromLatin1("^[^\\s]*$"), mUserName ) );
mAltNickname->setText( m_IRCAccount->altNick() );
partMessage->setText( m_IRCAccount->defaultPart() );
quitMessage->setText( m_IRCAccount->defaultQuit() );
if(account()->rememberPassword()) mPassword->setText( m_IRCAccount->password() );
QStringList cmds = m_IRCAccount->connectCommands();
for( QStringList::Iterator i = cmds.begin(); i != cmds.end(); ++i )
new QListViewItem( commandList, *i );
const QMap< QString, QString > replies = m_IRCAccount->customCtcpReplies();
for( QMap< QString, QString >::ConstIterator it = replies.begin(); it != replies.end(); ++it )
new QListViewItem( ctcpList, it.key(), it.data() );
}
connect( commandList, SIGNAL( contextMenu( KListView *, QListViewItem *, const QPoint & ) ),
this, SLOT( slotContextMenu( KListView *, QListViewItem *, const QPoint & ) ) );
connect( ctcpList, SIGNAL( contextMenu( KListView *, QListViewItem *, const QPoint & ) ),
this, SLOT( slotContextMenu( KListView *, QListViewItem *, const QPoint & ) ) );
connect( addButton, SIGNAL( clicked() ), this, SLOT( slotAddCommand() ) );
connect( addReply, SIGNAL( clicked() ), this, SLOT( slotAddCtcp() ) );
}
IRCEditAccountWidget::~IRCEditAccountWidget()
{
}
void IRCEditAccountWidget::slotContextMenu( KListView *, QListViewItem *item, const QPoint &p )
{
QPopupMenu popup;
popup.insertItem( i18n("Remove Command"), 1 );
if( popup.exec( p ) == 1 )
delete item;
}
void IRCEditAccountWidget::slotAddCommand()
{
if ( !commandEdit->text().isEmpty() )
{
new QListViewItem( commandList, commandEdit->text() );
commandEdit->clear();
}
}
void IRCEditAccountWidget::slotAddCtcp()
{
if ( !newCTCP->text().isEmpty() && !newReply->text().isEmpty() )
{
new QListViewItem( ctcpList, newCTCP->text(), newReply->text() );
newCTCP->clear();
newReply->clear();
}
}
KopeteAccount *IRCEditAccountWidget::apply()
{
QString mAccountId = mNickName->text() + QString::fromLatin1("@") + mServer->text() + QString::fromLatin1(":") + QString::number( mPort->value() );
if( !m_IRCAccount )
m_IRCAccount = new IRCAccount( mProtocol, mAccountId );
// else
// m_IRCAccount->setAccountId( mAccountId );
if (mRememberPassword->isChecked()) {
kdDebug(14120) << k_funcinfo << "Saving password '" << mPassword->text() << "' empty: " << mPassword->text().isEmpty() << " null: " << mPassword->text().isNull() << endl;
m_IRCAccount->setPassword( mPassword->text() );
}
m_IRCAccount->setUserName( mUserName->text() );
m_IRCAccount->setDefaultPart( partMessage->text() );
m_IRCAccount->setDefaultQuit( quitMessage->text() );
m_IRCAccount->setAutoLogin( mAutoConnect->isChecked() );
m_IRCAccount->setAltNick( mAltNickname->text() );
QStringList cmds;
for( QListViewItem *i = commandList->firstChild(); i; i = i->nextSibling() )
cmds.append( i->text(0) );
QMap< QString, QString > replies;
for( QListViewItem *i = ctcpList->firstChild(); i; i = i->nextSibling() )
replies[ i->text(0) ] = i->text(1);
m_IRCAccount->setCustomCtcpReplies( replies );
m_IRCAccount->setConnectCommands( cmds );
return m_IRCAccount;
}
bool IRCEditAccountWidget::validateData()
{
if( mNickName->text().isEmpty() )
KMessageBox::sorry(this, i18n("<qt>You must enter a nickname.</qt>"), i18n("Kopete"));
else if( mServer->text().isEmpty() )
KMessageBox::sorry(this, i18n("<qt>You must enter a server.</qt>"), i18n("Kopete"));
else
{
int error;
QPtrList<KAddressInfo> address = KExtendedSocket::lookup(
mServer->text(), QString::number( mPort->value() ), 0, &error );
address.setAutoDelete(true);
if( !address.isEmpty() )
return true;
KMessageBox::sorry(this, i18n("<qt>The server/port combination you entered is invalid. Please double-check your values.</qt>"), i18n("Kopete"));
}
return false;
}
#include "irceditaccountwidget.moc"
<|endoftext|> |
<commit_before>/***************************************************************************
dlgjabberservices.cpp - description
-------------------
begin : Mon Dec 9 2002
copyright : (C) 2002 by Till Gerken
email : kopete-devel@kde.org
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include <kmessagebox.h>
#include <klocale.h>
#include <kdebug.h>
#include <qapplication.h>
#include <qpushbutton.h>
#include <qlineedit.h>
#include <qtable.h>
#include <psi/types.h>
#include <psi/tasks.h>
#include "jabbercontact.h"
#include "jabberprotocol.h"
#include "dlgjabberregister.h"
#include "dlgjabberbrowse.h"
#include "dlgjabberservices.h"
#include "dlgjabberservices.moc"
DlgJabberServices::DlgJabberServices(QWidget *parent, const char *name ) : dlgServices(parent,name)
{
if(JabberProtocol::protocol()->isConnected())
{
// pre-populate the server field
leServer->setText(Jid(JabberProtocol::protocol()->myContact->contactId()).host());
}
// disable the left margin
tblServices->setLeftMargin(0);
// no content for now
tblServices->setNumRows(0);
// disable the buttons as long as nothing has been selected
btnRegister->setDisabled(true);
btnBrowse->setDisabled(true);
// allow autostretching
tblServices->setColumnStretchable(0, true);
tblServices->setColumnStretchable(1, true);
// disable user selections
tblServices->setSelectionMode(QTable::NoSelection);
// name table headers
tblServices->horizontalHeader()->setLabel(0, i18n("Name"));
tblServices->horizontalHeader()->setLabel(1, i18n("Address"));
connect(btnQuery, SIGNAL(clicked()), this, SLOT(slotQuery()));
connect(tblServices, SIGNAL(clicked(int, int, int, const QPoint &)), this, SLOT(slotSetSelection(int, int, int, const QPoint &)));
connect(btnRegister, SIGNAL(clicked()), this, SLOT(slotRegister()));
connect(btnBrowse, SIGNAL(clicked()), this, SLOT(slotBrowse()));
serviceTask = 0L;
selectedRow = 0;
}
void DlgJabberServices::slotSetSelection(int row, int, int, const QPoint &)
{
tblServices->clearSelection(true);
#if QT_VERSION >= 0x030100
tblServices->addSelection(QTableSelection(row, 0, row, 1));
#else
QTableSelection selection;
selection.init(row, 0);
selection.expandTo(row, 1);
tblServices->addSelection(selection);
#endif
// query the agent list about the selected item
btnRegister->setDisabled(!serviceTask->agents()[row].canRegister());
btnBrowse->setDisabled(!serviceTask->agents()[row].canSearch());
selectedRow = row;
}
void DlgJabberServices::slotQuery()
{
if(!JabberProtocol::protocol()->isConnected())
{
JabberProtocol::protocol()->errorConnectFirst();
return;
}
// create the jabber task
delete serviceTask;
serviceTask = new Jabber::JT_GetServices(JabberProtocol::protocol()->jabberClient->rootTask());
connect(serviceTask, SIGNAL(finished()), this, SLOT(slotQueryFinished()));
/* populate server field if it is empty */
if(leServer->text().isEmpty())
leServer->setText(Jid(JabberProtocol::protocol()->myContact->contactId()).host());
kdDebug(14130) << "[DlgJabberServices] Trying to fetch a list of services at " << leServer->text() << endl;
serviceTask->get(leServer->text());
serviceTask->go(false);
}
void DlgJabberServices::slotQueryFinished()
{
kdDebug(14130) << "[DlgJabberServices] Query task finished" << endl;
Jabber::JT_GetServices *task = (Jabber::JT_GetServices *)sender();
if(!task->success())
{
KMessageBox::error(this,
i18n("Unable to retrieve the list of services"),
i18n("Jabber Error"));
return;
}
tblServices->setNumRows(task->agents().count());
int row = 0;
for(Jabber::AgentList::const_iterator it = task->agents().begin(); it != task->agents().end(); it++)
{
tblServices->setText(row, 0, (*it).name());
tblServices->setText(row, 1, (*it).jid().userHost());
row++;
}
}
void DlgJabberServices::slotRegister()
{
DlgJabberRegister *registerDialog = new DlgJabberRegister(serviceTask->agents()[selectedRow].jid());
registerDialog->show();
registerDialog->raise();
}
void DlgJabberServices::slotBrowse()
{
DlgJabberBrowse *browseDialog = new DlgJabberBrowse(serviceTask->agents()[selectedRow].jid());
browseDialog->show();
browseDialog->raise();
}
DlgJabberServices::~DlgJabberServices()
{
delete serviceTask;
}
<commit_msg>Maybe parentheses are needed?<commit_after>/***************************************************************************
dlgjabberservices.cpp - description
-------------------
begin : Mon Dec 9 2002
copyright : (C) 2002 by Till Gerken
email : kopete-devel@kde.org
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include <kmessagebox.h>
#include <klocale.h>
#include <kdebug.h>
#include <qapplication.h>
#include <qpushbutton.h>
#include <qlineedit.h>
#include <qtable.h>
#include <psi/types.h>
#include <psi/tasks.h>
#include "jabbercontact.h"
#include "jabberprotocol.h"
#include "dlgjabberregister.h"
#include "dlgjabberbrowse.h"
#include "dlgjabberservices.h"
#include "dlgjabberservices.moc"
DlgJabberServices::DlgJabberServices(QWidget *parent, const char *name ) : dlgServices(parent,name)
{
if(JabberProtocol::protocol()->isConnected())
{
// pre-populate the server field
leServer->setText(Jid(JabberProtocol::protocol()->myContact->contactId()).host());
}
// disable the left margin
tblServices->setLeftMargin(0);
// no content for now
tblServices->setNumRows(0);
// disable the buttons as long as nothing has been selected
btnRegister->setDisabled(true);
btnBrowse->setDisabled(true);
// allow autostretching
tblServices->setColumnStretchable(0, true);
tblServices->setColumnStretchable(1, true);
// disable user selections
tblServices->setSelectionMode(QTable::NoSelection);
// name table headers
tblServices->horizontalHeader()->setLabel(0, i18n("Name"));
tblServices->horizontalHeader()->setLabel(1, i18n("Address"));
connect(btnQuery, SIGNAL(clicked()), this, SLOT(slotQuery()));
connect(tblServices, SIGNAL(clicked(int, int, int, const QPoint &)), this, SLOT(slotSetSelection(int, int, int, const QPoint &)));
connect(btnRegister, SIGNAL(clicked()), this, SLOT(slotRegister()));
connect(btnBrowse, SIGNAL(clicked()), this, SLOT(slotBrowse()));
serviceTask = 0L;
selectedRow = 0;
}
void DlgJabberServices::slotSetSelection(int row, int, int, const QPoint &)
{
tblServices->clearSelection(true);
#if (QT_VERSION >= 0x030100)
tblServices->addSelection(QTableSelection(row, 0, row, 1));
#else
QTableSelection selection;
selection.init(row, 0);
selection.expandTo(row, 1);
tblServices->addSelection(selection);
#endif
// query the agent list about the selected item
btnRegister->setDisabled(!serviceTask->agents()[row].canRegister());
btnBrowse->setDisabled(!serviceTask->agents()[row].canSearch());
selectedRow = row;
}
void DlgJabberServices::slotQuery()
{
if(!JabberProtocol::protocol()->isConnected())
{
JabberProtocol::protocol()->errorConnectFirst();
return;
}
// create the jabber task
delete serviceTask;
serviceTask = new Jabber::JT_GetServices(JabberProtocol::protocol()->jabberClient->rootTask());
connect(serviceTask, SIGNAL(finished()), this, SLOT(slotQueryFinished()));
/* populate server field if it is empty */
if(leServer->text().isEmpty())
leServer->setText(Jid(JabberProtocol::protocol()->myContact->contactId()).host());
kdDebug(14130) << "[DlgJabberServices] Trying to fetch a list of services at " << leServer->text() << endl;
serviceTask->get(leServer->text());
serviceTask->go(false);
}
void DlgJabberServices::slotQueryFinished()
{
kdDebug(14130) << "[DlgJabberServices] Query task finished" << endl;
Jabber::JT_GetServices *task = (Jabber::JT_GetServices *)sender();
if(!task->success())
{
KMessageBox::error(this,
i18n("Unable to retrieve the list of services"),
i18n("Jabber Error"));
return;
}
tblServices->setNumRows(task->agents().count());
int row = 0;
for(Jabber::AgentList::const_iterator it = task->agents().begin(); it != task->agents().end(); it++)
{
tblServices->setText(row, 0, (*it).name());
tblServices->setText(row, 1, (*it).jid().userHost());
row++;
}
}
void DlgJabberServices::slotRegister()
{
DlgJabberRegister *registerDialog = new DlgJabberRegister(serviceTask->agents()[selectedRow].jid());
registerDialog->show();
registerDialog->raise();
}
void DlgJabberServices::slotBrowse()
{
DlgJabberBrowse *browseDialog = new DlgJabberBrowse(serviceTask->agents()[selectedRow].jid());
browseDialog->show();
browseDialog->raise();
}
DlgJabberServices::~DlgJabberServices()
{
delete serviceTask;
}
<|endoftext|> |
<commit_before>/*
Tone.cpp
A Tone Generator Library for the ESP8266
Copyright (c) 2016 Ben Pirt. All rights reserved.
This file is part of the esp8266 core for Arduino environment.
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
*/
#include "Arduino.h"
#include "pins_arduino.h"
#define AVAILABLE_TONE_PINS 1
const uint8_t tone_timers[] = { 1 };
static uint8_t tone_pins[AVAILABLE_TONE_PINS] = { 255, };
static long toggle_counts[AVAILABLE_TONE_PINS] = { 0, };
#define T1INDEX 0
void t1IntHandler();
static int8_t toneBegin(uint8_t _pin) {
_pin = esp8266_pinToGpio[_pin];
int8_t _index = -1;
// if we're already using the pin, reuse it.
for (int i = 0; i < AVAILABLE_TONE_PINS; i++) {
if (tone_pins[i] == _pin) {
return i;
}
}
// search for an unused timer.
for (int i = 0; i < AVAILABLE_TONE_PINS; i++) {
if (tone_pins[i] == 255) {
tone_pins[i] = _pin;
_index = i;
break;
}
}
return _index;
}
// frequency (in hertz) and duration (in milliseconds).
void tone(uint8_t _pin, unsigned int frequency, unsigned long duration) {
_pin = esp8266_pinToGpio[_pin];
int8_t _index;
_index = toneBegin(_pin);
if (_index >= 0) {
// Set the pinMode as OUTPUT
pinMode(_pin, OUTPUT);
// Calculate the toggle count
if (duration > 0) {
toggle_counts[_index] = 2 * frequency * duration / 1000;
} else {
toggle_counts[_index] = -1;
}
// set up the interrupt frequency
switch (tone_timers[_index]) {
case 0:
// Not currently supported
break;
case 1:
timer1_disable();
timer1_isr_init();
timer1_attachInterrupt(t1IntHandler);
timer1_enable(TIM_DIV1, TIM_EDGE, TIM_LOOP);
timer1_write((clockCyclesPerMicrosecond() * 500000) / frequency);
break;
}
}
}
void disableTimer(uint8_t _index) {
tone_pins[_index] = 255;
switch (tone_timers[_index]) {
case 0:
// Not currently supported
break;
case 1:
timer1_disable();
break;
}
}
void noTone(uint8_t _pin) {
_pin = esp8266_pinToGpio[_pin];
for (int i = 0; i < AVAILABLE_TONE_PINS; i++) {
if (tone_pins[i] == _pin) {
tone_pins[i] = 255;
disableTimer(i);
break;
}
}
digitalWrite(_pin, LOW);
}
ICACHE_RAM_ATTR void t1IntHandler() {
if (toggle_counts[T1INDEX] != 0){
// toggle the pin
digitalWrite(tone_pins[T1INDEX], toggle_counts[T1INDEX] % 2);
toggle_counts[T1INDEX]--;
// handle the case of indefinite duration
if (toggle_counts[T1INDEX] < -2){
toggle_counts[T1INDEX] = -1;
}
}else{
disableTimer(T1INDEX);
digitalWrite(tone_pins[T1INDEX], LOW);
}
}
<commit_msg>esp8266_pinToGpio not needed for tone() The '_pin = esp8266_pinToGpio[_pin];' pin remapping is not needed in the tone library - this actually broke the tone support, and only worked with P3 as it remaps to GPIO3.<commit_after>/*
Tone.cpp
A Tone Generator Library for the ESP8266
Copyright (c) 2016 Ben Pirt. All rights reserved.
This file is part of the esp8266 core for Arduino environment.
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
*/
#include "Arduino.h"
#include "pins_arduino.h"
#define AVAILABLE_TONE_PINS 1
const uint8_t tone_timers[] = { 1 };
static uint8_t tone_pins[AVAILABLE_TONE_PINS] = { 255, };
static long toggle_counts[AVAILABLE_TONE_PINS] = { 0, };
#define T1INDEX 0
void t1IntHandler();
static int8_t toneBegin(uint8_t _pin) {
int8_t _index = -1;
// if we're already using the pin, reuse it.
for (int i = 0; i < AVAILABLE_TONE_PINS; i++) {
if (tone_pins[i] == _pin) {
return i;
}
}
// search for an unused timer.
for (int i = 0; i < AVAILABLE_TONE_PINS; i++) {
if (tone_pins[i] == 255) {
tone_pins[i] = _pin;
_index = i;
break;
}
}
return _index;
}
// frequency (in hertz) and duration (in milliseconds).
void tone(uint8_t _pin, unsigned int frequency, unsigned long duration) {
int8_t _index;
_index = toneBegin(_pin);
if (_index >= 0) {
// Set the pinMode as OUTPUT
pinMode(_pin, OUTPUT);
// Calculate the toggle count
if (duration > 0) {
toggle_counts[_index] = 2 * frequency * duration / 1000;
} else {
toggle_counts[_index] = -1;
}
// set up the interrupt frequency
switch (tone_timers[_index]) {
case 0:
// Not currently supported
break;
case 1:
timer1_disable();
timer1_isr_init();
timer1_attachInterrupt(t1IntHandler);
timer1_enable(TIM_DIV1, TIM_EDGE, TIM_LOOP);
timer1_write((clockCyclesPerMicrosecond() * 500000) / frequency);
break;
}
}
}
void disableTimer(uint8_t _index) {
tone_pins[_index] = 255;
switch (tone_timers[_index]) {
case 0:
// Not currently supported
break;
case 1:
timer1_disable();
break;
}
}
void noTone(uint8_t _pin) {
_pin = esp8266_pinToGpio[_pin];
for (int i = 0; i < AVAILABLE_TONE_PINS; i++) {
if (tone_pins[i] == _pin) {
tone_pins[i] = 255;
disableTimer(i);
break;
}
}
digitalWrite(_pin, LOW);
}
ICACHE_RAM_ATTR void t1IntHandler() {
if (toggle_counts[T1INDEX] != 0){
// toggle the pin
digitalWrite(tone_pins[T1INDEX], toggle_counts[T1INDEX] % 2);
toggle_counts[T1INDEX]--;
// handle the case of indefinite duration
if (toggle_counts[T1INDEX] < -2){
toggle_counts[T1INDEX] = -1;
}
}else{
disableTimer(T1INDEX);
digitalWrite(tone_pins[T1INDEX], LOW);
}
}
<|endoftext|> |
<commit_before>/** \brief A MARC-21 filter utility that can remove records based on patterns for MARC subfields.
* \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)
*
* \copyright 2016 Universitätsbiblothek Tübingen. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <memory>
#include <unordered_set>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include "DirectoryEntry.h"
#include "FileUtil.h"
#include "Leader.h"
#include "MarcUtil.h"
#include "MarcXmlWriter.h"
#include "MediaTypeUtil.h"
#include "RegexMatcher.h"
#include "StringUtil.h"
#include "Subfields.h"
#include "util.h"
void Usage() {
std::cerr << "usage: " << progname << " (--drop|--keep|--remove-fields) [--input-format=(marc-xml|marc-21)] [--output-format=(marc-xml|marc-21)] marc_input marc_output field_or_subfieldspec1:regex1 "
<< "[field_or_subfieldspec2:regex2 .. field_or_subfieldspecN:regexN]\n"
<< " where \"field_or_subfieldspec\" must either be a MARC tag or a MARC tag followed by a\n"
<< " single-character subfield code and \"regex\" is a Perl-compatible regular expression.\n"
<< " If you don't specify an output format it will be the same as the input format.\n\n";
std::exit(EXIT_FAILURE);
}
class CompiledPattern {
std::string tag_;
char subfield_code_;
RegexMatcher matcher_;
public:
static const char NO_SUBFIELD_CODE;
public:
CompiledPattern(const std::string &tag, const char subfield_code, const RegexMatcher &matcher)
: tag_(tag), subfield_code_(subfield_code), matcher_(matcher) {}
const std::string &getTag() const { return tag_; }
bool hasSubfieldCode() const { return subfield_code_ != NO_SUBFIELD_CODE; }
char getSubfieldCode() const { return subfield_code_; }
bool fieldMatched(const std::string &field_contents) const;
bool subfieldMatched(const std::string &subfield_contents) const;
};
const char CompiledPattern::NO_SUBFIELD_CODE('\0');
bool CompiledPattern::fieldMatched(const std::string &field_contents) const {
std::string err_msg;
const bool retval = matcher_.matched(field_contents, &err_msg);
if (not retval and not err_msg.empty())
Error("Unexpected error while trying to match a field in CompiledPattern::fieldMatched(): " + err_msg);
return retval;
}
bool CompiledPattern::subfieldMatched(const std::string &subfield_contents) const {
std::string err_msg;
const bool retval = matcher_.matched(subfield_contents, &err_msg);
if (not retval and not err_msg.empty())
Error("Unexpected error while trying to match a subfield in CompiledPattern::subfieldMatched(): " + err_msg);
return retval;
}
// Expects "patterns" to contain strings that look like TTTS:REGEX where TTT are 3 characters specifying a field,
// S is a subfield code and REGEX is a PCRE-style regex supporting UTF8 that should match subfield contents.
// Alteratively a pattern can look like TTT:REGEX where TTT is a tag and we have no subfield code.
bool CompilePatterns(const std::vector<std::string> &patterns, std::vector<CompiledPattern> * const compiled_patterns,
std::string * const err_msg)
{
compiled_patterns->clear();
compiled_patterns->reserve(patterns.size());
for (const auto &pattern : patterns) {
std::string tag;
char subfield_code;
std::string::size_type first_colon_pos = pattern.find(':');
if (first_colon_pos == std::string::npos) {
*err_msg = "missing colon!";
return false;
} else if (first_colon_pos == DirectoryEntry::TAG_LENGTH) {
tag = pattern.substr(0, 3);
subfield_code = CompiledPattern::NO_SUBFIELD_CODE;
} else if (first_colon_pos == DirectoryEntry::TAG_LENGTH + 1) {
tag = pattern.substr(0, 3);
subfield_code = pattern[3];
} else {
*err_msg = "colon in wrong position (" + std::to_string(first_colon_pos) + ")! (Tag length must be "
+ std::to_string(DirectoryEntry::TAG_LENGTH) + ".)";
return false;
}
const std::string regex_string(pattern.substr(first_colon_pos + 1));
RegexMatcher * const new_matcher(RegexMatcher::RegexMatcherFactory(regex_string, err_msg));
if (new_matcher == nullptr) {
*err_msg = "failed to compile regular expression: \"" + regex_string + "\"! (" + *err_msg +")";
return false;
}
compiled_patterns->push_back(CompiledPattern(tag, subfield_code, std::move(*new_matcher)));
delete new_matcher;
}
return true;
}
/** Returns true if we have at least one match. */
bool Matched(const MarcUtil::Record &record, const std::vector<DirectoryEntry> &dir_entries,
const std::vector<std::string> &fields, const std::vector<CompiledPattern> &compiled_patterns,
std::vector<size_t> * const matched_field_indices)
{
matched_field_indices->clear();
bool matched_at_least_one(false);
for (const auto &compiled_pattern : compiled_patterns) {
ssize_t index(record.getFieldIndex(compiled_pattern.getTag()));
if (index == -1)
continue;
for (/* Intentionally empty! */;
static_cast<size_t>(index) < fields.size() and dir_entries[index].getTag() == compiled_pattern.getTag();
++index)
{
if (compiled_pattern.hasSubfieldCode()) {
const Subfields subfields(fields[index]);
const auto begin_end(subfields.getIterators(compiled_pattern.getSubfieldCode()));
for (auto subfield_code_and_value(begin_end.first); subfield_code_and_value != begin_end.second;
++subfield_code_and_value)
{
if (compiled_pattern.subfieldMatched(subfield_code_and_value->second)) {
matched_field_indices->emplace_back(index);
matched_at_least_one = true;
}
}
} else if (compiled_pattern.fieldMatched(fields[index])) {
matched_field_indices->emplace_back(index);
matched_at_least_one = true;
}
}
}
return matched_at_least_one;
}
namespace {
enum class OutputFormat { MARC_XML, MARC_21, SAME_AS_INPUT };
enum class OperationType { KEEP, DROP, REMOVE_FIELDS };
} // unnamed namespace
void Filter(const bool input_is_xml, const OutputFormat output_format, const std::vector<std::string> &patterns,
const OperationType operation_type, File * const input, File * const output)
{
MarcXmlWriter *xml_writer(nullptr);
if ((output_format == OutputFormat::SAME_AS_INPUT and input_is_xml) or output_format == OutputFormat::MARC_XML)
xml_writer = new MarcXmlWriter(output);
std::vector<CompiledPattern> compiled_patterns;
std::string err_msg;
if (not CompilePatterns(patterns, &compiled_patterns, &err_msg))
Error("Error while compiling patterns: " + err_msg);
unsigned total_count(0), kept_count(0), modified_count(0);
while (MarcUtil::Record record = input_is_xml ? MarcUtil::Record::XmlFactory(input)
: MarcUtil::Record::BinaryFactory(input))
{
record.setRecordWillBeWrittenAsXml(input_is_xml);
++total_count;
const std::vector<DirectoryEntry> &dir_entries(record.getDirEntries());
const std::vector<std::string> &fields(record.getFields());
std::vector<size_t> matched_field_indices;
if (Matched(record, dir_entries, fields, compiled_patterns, &matched_field_indices)) {
if (operation_type == OperationType::KEEP) {
xml_writer != nullptr ? record.write(xml_writer) : record.write(output);
++kept_count;
} else if (operation_type == OperationType::REMOVE_FIELDS) {
std::sort(matched_field_indices.begin(), matched_field_indices.end(), std::greater<size_t>());
for (const auto field_index : matched_field_indices)
record.deleteField(field_index);
xml_writer != nullptr ? record.write(xml_writer) : record.write(output);
++modified_count;
}
} else if (operation_type == OperationType::DROP or operation_type == OperationType::REMOVE_FIELDS) {
xml_writer != nullptr ? record.write(xml_writer) : record.write(output);
++kept_count;
}
}
if (not err_msg.empty())
Error(err_msg);
delete xml_writer;
if (operation_type == OperationType::REMOVE_FIELDS)
std::cerr << "Modified " << modified_count << " of " << total_count << " record(s).\n";
else
std::cerr << "Kept " << kept_count << " of " << total_count << " record(s).\n";
}
int main(int argc, char **argv) {
::progname = argv[0];
if (argc < 5)
Usage();
OperationType operation_type;
if (std::strcmp(argv[1], "--keep") == 0)
operation_type = OperationType::KEEP;
else if (std::strcmp(argv[1], "--drop") == 0)
operation_type = OperationType::DROP;
else if (std::strcmp(argv[1], "--remove-fields") == 0)
operation_type = OperationType::REMOVE_FIELDS;
else
Error("expected --keep, --drop or --remove-field as the first argument!");
bool input_is_xml(false), already_determined_input_format(false);
if (std::strcmp("--input-format=marc-xml", argv[2]) == 0) {
input_is_xml = true;
argc -= 1;
argv += 1;
already_determined_input_format = true;
} else if (std::strcmp("--input-format=marc-21", argv[2]) == 0) {
argc -= 1;
argv += 1;
already_determined_input_format = true;
}
OutputFormat output_format(OutputFormat::SAME_AS_INPUT);
if (StringUtil::StartsWith(argv[2], "--output-format=")) {
if (std::strcmp(argv[2] + std::strlen("--output-format="), "marc-xml") == 0)
output_format = OutputFormat::MARC_XML;
else if (std::strcmp(argv[2] + std::strlen("--output-format="), "marc-21") == 0)
output_format = OutputFormat::MARC_21;
else
Error("unknown output format \"" + std::string(argv[2] + 16)
+ "\"! Must be \"marc-xml\" or \"marc-21\".");
++argv, --argc;
}
const std::string input_filename(argv[2]);
// Our input file is possibly a fifo, then avoid reading twice
if (not already_determined_input_format) {
const std::string media_type(MediaTypeUtil::GetFileMediaType(input_filename));
if (unlikely(media_type.empty()))
Error("can't determine media type of \"" + input_filename + "\"!");
if (media_type != "application/xml" and media_type != "application/marc")
Error("\"" + input_filename + "\" is neither XML nor MARC-21 data!");
input_is_xml = (media_type == "application/xml");
}
std::unique_ptr<File> input(FileUtil::OpenInputFileOrDie(input_filename));
std::unique_ptr<File> output(FileUtil::OpenOutputFileOrDie(argv[3]));
std::vector<std::string> patterns;
for (int arg_no(4); arg_no < argc; ++arg_no)
patterns.emplace_back(argv[arg_no]);
try {
Filter(input_is_xml, output_format, patterns, operation_type, input.get(), output.get());
} catch (const std::exception &x) {
Error("caught exception: " + std::string(x.what()));
}
}
<commit_msg>Update marc_filter.cc<commit_after>/** \brief A MARC-21 filter utility that can remove records based on patterns for MARC subfields.
* \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)
*
* \copyright 2016 Universitätsbiblothek Tübingen. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <memory>
#include <unordered_set>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include "DirectoryEntry.h"
#include "FileUtil.h"
#include "Leader.h"
#include "MarcUtil.h"
#include "MarcXmlWriter.h"
#include "MediaTypeUtil.h"
#include "RegexMatcher.h"
#include "StringUtil.h"
#include "Subfields.h"
#include "util.h"
void Usage() {
std::cerr << "usage: " << progname << " (--drop|--keep|--remove-fields) [--input-format=(marc-xml|marc-21)] [--output-format=(marc-xml|marc-21)] marc_input marc_output field_or_subfieldspec1:regex1 "
<< "[field_or_subfieldspec2:regex2 .. field_or_subfieldspecN:regexN]\n"
<< " where \"field_or_subfieldspec\" must either be a MARC tag or a MARC tag followed by a\n"
<< " single-character subfield code and \"regex\" is a Perl-compatible regular expression.\n"
<< " If you don't specify an output format it will be the same as the input format.\n\n";
std::exit(EXIT_FAILURE);
}
class CompiledPattern {
std::string tag_;
char subfield_code_;
RegexMatcher matcher_;
public:
static const char NO_SUBFIELD_CODE;
public:
CompiledPattern(const std::string &tag, const char subfield_code, const RegexMatcher &matcher)
: tag_(tag), subfield_code_(subfield_code), matcher_(matcher) {}
const std::string &getTag() const { return tag_; }
bool hasSubfieldCode() const { return subfield_code_ != NO_SUBFIELD_CODE; }
char getSubfieldCode() const { return subfield_code_; }
bool fieldMatched(const std::string &field_contents) const;
bool subfieldMatched(const std::string &subfield_contents) const;
};
const char CompiledPattern::NO_SUBFIELD_CODE('\0');
bool CompiledPattern::fieldMatched(const std::string &field_contents) const {
std::string err_msg;
const bool retval = matcher_.matched(field_contents, &err_msg);
if (not retval and not err_msg.empty())
Error("Unexpected error while trying to match a field in CompiledPattern::fieldMatched(): " + err_msg);
return retval;
}
bool CompiledPattern::subfieldMatched(const std::string &subfield_contents) const {
std::string err_msg;
const bool retval = matcher_.matched(subfield_contents, &err_msg);
if (not retval and not err_msg.empty())
Error("Unexpected error while trying to match a subfield in CompiledPattern::subfieldMatched(): " + err_msg);
return retval;
}
// Expects "patterns" to contain strings that look like TTTS:REGEX where TTT are 3 characters specifying a field,
// S is a subfield code and REGEX is a PCRE-style regex supporting UTF8 that should match subfield contents.
// Alteratively a pattern can look like TTT:REGEX where TTT is a tag and we have no subfield code.
bool CompilePatterns(const std::vector<std::string> &patterns, std::vector<CompiledPattern> * const compiled_patterns,
std::string * const err_msg)
{
compiled_patterns->clear();
compiled_patterns->reserve(patterns.size());
for (const auto &pattern : patterns) {
std::string tag;
char subfield_code;
std::string::size_type first_colon_pos = pattern.find(':');
if (first_colon_pos == std::string::npos) {
*err_msg = "missing colon!";
return false;
} else if (first_colon_pos == DirectoryEntry::TAG_LENGTH) {
tag = pattern.substr(0, 3);
subfield_code = CompiledPattern::NO_SUBFIELD_CODE;
} else if (first_colon_pos == DirectoryEntry::TAG_LENGTH + 1) {
tag = pattern.substr(0, 3);
subfield_code = pattern[3];
} else {
*err_msg = "colon in wrong position (" + std::to_string(first_colon_pos) + ")! (Tag length must be "
+ std::to_string(DirectoryEntry::TAG_LENGTH) + ".)";
return false;
}
const std::string regex_string(pattern.substr(first_colon_pos + 1));
RegexMatcher * const new_matcher(RegexMatcher::RegexMatcherFactory(regex_string, err_msg));
if (new_matcher == nullptr) {
*err_msg = "failed to compile regular expression: \"" + regex_string + "\"! (" + *err_msg +")";
return false;
}
compiled_patterns->push_back(CompiledPattern(tag, subfield_code, std::move(*new_matcher)));
delete new_matcher;
}
return true;
}
/** Returns true if we have at least one match. */
bool Matched(const MarcUtil::Record &record, const std::vector<DirectoryEntry> &dir_entries,
const std::vector<std::string> &fields, const std::vector<CompiledPattern> &compiled_patterns,
std::vector<size_t> * const matched_field_indices)
{
matched_field_indices->clear();
bool matched_at_least_one(false);
for (const auto &compiled_pattern : compiled_patterns) {
ssize_t index(record.getFieldIndex(compiled_pattern.getTag()));
if (index == -1)
continue;
for (/* Intentionally empty! */;
static_cast<size_t>(index) < fields.size() and dir_entries[index].getTag() == compiled_pattern.getTag();
++index)
{
if (compiled_pattern.hasSubfieldCode()) {
const Subfields subfields(fields[index]);
const auto begin_end(subfields.getIterators(compiled_pattern.getSubfieldCode()));
for (auto subfield_code_and_value(begin_end.first); subfield_code_and_value != begin_end.second;
++subfield_code_and_value)
{
if (compiled_pattern.subfieldMatched(subfield_code_and_value->second)) {
matched_field_indices->emplace_back(index);
matched_at_least_one = true;
}
}
} else if (compiled_pattern.fieldMatched(fields[index])) {
matched_field_indices->emplace_back(index);
matched_at_least_one = true;
}
}
}
return matched_at_least_one;
}
namespace {
enum class OutputFormat { MARC_XML, MARC_21, SAME_AS_INPUT };
enum class OperationType { KEEP, DROP, REMOVE_FIELDS };
} // unnamed namespace
void Filter(const bool input_is_xml, const OutputFormat output_format, const std::vector<std::string> &patterns,
const OperationType operation_type, File * const input, File * const output)
{
MarcXmlWriter *xml_writer(nullptr);
if ((output_format == OutputFormat::SAME_AS_INPUT and input_is_xml) or output_format == OutputFormat::MARC_XML)
xml_writer = new MarcXmlWriter(output);
std::vector<CompiledPattern> compiled_patterns;
std::string err_msg;
if (not CompilePatterns(patterns, &compiled_patterns, &err_msg))
Error("Error while compiling patterns: " + err_msg);
unsigned total_count(0), kept_count(0), modified_count(0);
while (MarcUtil::Record record = input_is_xml ? MarcUtil::Record::XmlFactory(input)
: MarcUtil::Record::BinaryFactory(input))
{
record.setRecordWillBeWrittenAsXml(input_is_xml);
++total_count;
const std::vector<DirectoryEntry> &dir_entries(record.getDirEntries());
const std::vector<std::string> &fields(record.getFields());
std::vector<size_t> matched_field_indices;
if (Matched(record, dir_entries, fields, compiled_patterns, &matched_field_indices)) {
if (operation_type == OperationType::KEEP) {
xml_writer != nullptr ? record.write(xml_writer) : record.write(output);
++kept_count;
} else if (operation_type == OperationType::REMOVE_FIELDS) {
std::sort(matched_field_indices.begin(), matched_field_indices.end(), std::greater<size_t>());
for (const auto field_index : matched_field_indices)
record.deleteField(field_index);
xml_writer != nullptr ? record.write(xml_writer) : record.write(output);
++modified_count;
}
} else if (operation_type == OperationType::DROP or operation_type == OperationType::REMOVE_FIELDS) {
xml_writer != nullptr ? record.write(xml_writer) : record.write(output);
++kept_count;
}
}
if (not err_msg.empty())
Error(err_msg);
delete xml_writer;
if (operation_type == OperationType::REMOVE_FIELDS)
std::cerr << "Modified " << modified_count << " of " << total_count << " record(s).\n";
else
std::cerr << "Kept " << kept_count << " of " << total_count << " record(s).\n";
}
int main(int argc, char **argv) {
::progname = argv[0];
if (argc < 5)
Usage();
OperationType operation_type;
if (std::strcmp(argv[1], "--keep") == 0)
operation_type = OperationType::KEEP;
else if (std::strcmp(argv[1], "--drop") == 0)
operation_type = OperationType::DROP;
else if (std::strcmp(argv[1], "--remove-fields") == 0)
operation_type = OperationType::REMOVE_FIELDS;
else
Error("expected --keep, --drop or --remove-field as the first argument!");
bool input_is_xml(false), already_determined_input_format(false);
if (std::strcmp("--input-format=marc-xml", argv[2]) == 0) {
input_is_xml = true;
--argc, ++argv;
already_determined_input_format = true;
} else if (std::strcmp("--input-format=marc-21", argv[2]) == 0) {
--argc, ++argv;
already_determined_input_format = true;
}
OutputFormat output_format(OutputFormat::SAME_AS_INPUT);
if (StringUtil::StartsWith(argv[2], "--output-format=")) {
if (std::strcmp(argv[2] + std::strlen("--output-format="), "marc-xml") == 0)
output_format = OutputFormat::MARC_XML;
else if (std::strcmp(argv[2] + std::strlen("--output-format="), "marc-21") == 0)
output_format = OutputFormat::MARC_21;
else
Error("unknown output format \"" + std::string(argv[2] + 16)
+ "\"! Must be \"marc-xml\" or \"marc-21\".");
++argv, --argc;
}
const std::string input_filename(argv[2]);
// Our input file is possibly a fifo, then avoid reading twice
if (not already_determined_input_format) {
const std::string media_type(MediaTypeUtil::GetFileMediaType(input_filename));
if (unlikely(media_type.empty()))
Error("can't determine media type of \"" + input_filename + "\"!");
if (media_type != "application/xml" and media_type != "application/marc")
Error("\"" + input_filename + "\" is neither XML nor MARC-21 data!");
input_is_xml = (media_type == "application/xml");
}
std::unique_ptr<File> input(FileUtil::OpenInputFileOrDie(input_filename));
std::unique_ptr<File> output(FileUtil::OpenOutputFileOrDie(argv[3]));
std::vector<std::string> patterns;
for (int arg_no(4); arg_no < argc; ++arg_no)
patterns.emplace_back(argv[arg_no]);
try {
Filter(input_is_xml, output_format, patterns, operation_type, input.get(), output.get());
} catch (const std::exception &x) {
Error("caught exception: " + std::string(x.what()));
}
}
<|endoftext|> |
<commit_before>/* The MIT License (MIT)
Copyright (c) 2016 Guilherme Andrade <nlocks(at)gandrade(dot)net>
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 "erl_nif.h"
#include <cassert>
#include <cstring>
#include <atomic>
#include <chrono>
#include <limits>
static inline ERL_NIF_TERM WrapSuccess(ErlNifEnv* env, ERL_NIF_TERM term) {
return enif_make_tuple2(env, enif_make_atom(env, "ok"), term);
}
static inline ERL_NIF_TERM WrapError(ErlNifEnv* env, ERL_NIF_TERM term) {
return enif_make_tuple2(env, enif_make_atom(env, "error"), term);
}
static inline ERL_NIF_TERM WrapError(ErlNifEnv* env, const char* error) {
return WrapError(env, enif_make_atom(env, error));
}
static inline ERL_NIF_TERM WrapResourceTerm(
ErlNifEnv* env, const char* resourceTypeId, ERL_NIF_TERM resourceTerm)
{
return enif_make_tuple3(env,
enif_make_atom(env, resourceTypeId),
enif_make_uint64(env, static_cast<uint64_t>(resourceTerm)),
resourceTerm);
}
static inline bool UnwrapResourceTerm(
ErlNifEnv* env, ERL_NIF_TERM wrappedResource, ERL_NIF_TERM* resourceTerm)
{
int tupleArity = 0;
const ERL_NIF_TERM *tuple = nullptr;
if (not enif_get_tuple(env, wrappedResource, &tupleArity, &tuple))
return false;
if (tupleArity != 3)
return false;
*resourceTerm = tuple[2];
return true;
}
static uint64_t CurrentTimeMilliseconds() {
std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now();
return std::chrono::duration_cast<std::chrono::milliseconds>(
now.time_since_epoch()).count();
}
struct Ownership;
struct Lock {
std::atomic<Ownership*> ownership;
};
struct Ownership {
ERL_NIF_TERM pid;
Lock* lock = nullptr;
};
#define LOCK_RESOURCE "nlocks.lock"
#define OWNERSHIP_RESOURCE "nlocks.ownership"
static ErlNifResourceType* lockResourceType = nullptr;
static ErlNifResourceType* ownershipResourceType = nullptr;
static void DeleteLockResource(ErlNifEnv* /*env*/, void* resource) {
Lock* lock = static_cast<Lock*>(resource);
assert(lock->ownership == nullptr);
}
static void DeleteOwnershipResource(ErlNifEnv* /*env*/, void* resource) {
Ownership* ownership = static_cast<Ownership*>(resource);
if (ownership->lock != nullptr) {
// process was probably brutally killed; we never released the lock
assert(ownership->lock->ownership == ownership);
ownership->lock->ownership.store(nullptr);
enif_release_resource(ownership->lock);
ownership->lock = nullptr;
}
}
static int load(ErlNifEnv* env, void** /*priv*/, ERL_NIF_TERM /*load_info*/) {
lockResourceType = enif_open_resource_type(
env, nullptr,
LOCK_RESOURCE,
DeleteLockResource,
ERL_NIF_RT_CREATE, nullptr);
ownershipResourceType = enif_open_resource_type(
env, nullptr,
OWNERSHIP_RESOURCE,
DeleteOwnershipResource,
ERL_NIF_RT_CREATE, nullptr);
return 0;
}
//int upgrade(ErlNifEnv* /*env*/, void** /*priv_data*/, void** /*old_priv_data*/, ERL_NIF_TERM /*load_info*/) {
// // TODO
// return 0;
//}
//static void unload(ErlNifEnv* /*env*/, void* /*priv_data*/) {
// // TODO
//}
/****************************************************************/
static ERL_NIF_TERM NewLock(ErlNifEnv* env, int /*argc*/, const ERL_NIF_TERM[] /*argv*/) {
Lock* lock = static_cast<Lock*>(enif_alloc_resource(lockResourceType, sizeof(Lock)));
memset(lock, 0, sizeof(Lock));
ERL_NIF_TERM term = WrapResourceTerm(env, LOCK_RESOURCE, enif_make_resource(env, lock));
enif_release_resource(lock);
return term;
}
// not exported, used internally
static ERL_NIF_TERM AcquireOwnershipRecursive(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {
Lock* lock = nullptr;
Ownership* ownership = nullptr;
uint64_t deadline = 0;
ERL_NIF_TERM errorReturn;
Ownership* currentOwnership = nullptr;
if (not enif_get_resource(env, argv[0], lockResourceType, reinterpret_cast<void**>(&lock))) {
errorReturn = enif_make_badarg(env);
goto give_up;
}
if (not enif_get_resource(env, argv[1], ownershipResourceType, reinterpret_cast<void**>(&ownership))) {
errorReturn = enif_make_badarg(env);
goto give_up;
}
if (not enif_get_uint64(env, argv[2], &deadline)) {
errorReturn = enif_make_badarg(env);
goto give_up;
}
if ((deadline > 0) && (CurrentTimeMilliseconds() >= deadline)) {
errorReturn = WrapError(env, "timeout");
goto give_up;
}
currentOwnership = lock->ownership.load(std::memory_order_relaxed);
if ((currentOwnership == nullptr)
&& lock->ownership.compare_exchange_weak(
currentOwnership, ownership,
std::memory_order_release,
std::memory_order_relaxed))
{
// locked by us
ErlNifPid selfPid;
enif_self(env, &selfPid);
ownership->pid = enif_make_pid(env, &selfPid);
ownership->lock = lock;
enif_keep_resource(lock);
enif_release_resource(ownership);
ERL_NIF_TERM wrappedOwnershipTerm = WrapResourceTerm(env, OWNERSHIP_RESOURCE, argv[1]);
return WrapSuccess(env, wrappedOwnershipTerm);
}
// locked by someone else
return enif_schedule_nif(
env, "AcquireOwnershipRecursive", 0,
AcquireOwnershipRecursive, argc, argv);
give_up:
if (ownership != nullptr)
enif_release_resource(ownership);
return errorReturn;
}
static ERL_NIF_TERM AcquireOwnership(ErlNifEnv* env, int /*argc*/, const ERL_NIF_TERM argv[]) {
ERL_NIF_TERM lockTerm;
Lock* lock = nullptr;
unsigned timeout = 0;
uint64_t deadline = 0;
if (not UnwrapResourceTerm(env, argv[0], &lockTerm))
return enif_make_badarg(env);
if (not enif_get_resource(env, lockTerm, lockResourceType, reinterpret_cast<void**>(&lock)))
return enif_make_badarg(env);
if (not enif_get_uint(env, argv[1], &timeout)) {
if (not enif_is_identical(argv[2], enif_make_atom(env, "infinity")))
return enif_make_badarg(env);
}
else {
uint64_t currentTime = CurrentTimeMilliseconds();
deadline = currentTime + static_cast<uint64_t>(timeout);
}
ErlNifPid self;
enif_self(env, &self);
Ownership* ownership = static_cast<Ownership*>(
enif_alloc_resource(ownershipResourceType, sizeof(Ownership)));
memset(ownership, 0, sizeof(Ownership));
int newArgc = 3;
ERL_NIF_TERM* newArgv = static_cast<ERL_NIF_TERM*>(malloc(sizeof(ERL_NIF_TERM) * newArgc));
newArgv[0] = lockTerm;
newArgv[1] = enif_make_resource(env, ownership);
newArgv[2] = enif_make_uint64(env, deadline);
return enif_schedule_nif(
env, "AcquireOwnershipRecursive", 0,
AcquireOwnershipRecursive, newArgc, newArgv);
}
static ERL_NIF_TERM ReleaseOwnership(ErlNifEnv* env, int /*argc*/, const ERL_NIF_TERM argv[]) {
ERL_NIF_TERM ownershipTerm;
Ownership* ownership = nullptr;
if (not UnwrapResourceTerm(env, argv[0], &ownershipTerm))
return enif_make_badarg(env);
if (not enif_get_resource(env, ownershipTerm, ownershipResourceType, reinterpret_cast<void**>(&ownership)))
return enif_make_badarg(env);
ErlNifPid selfPid;
enif_self(env, &selfPid);
if (not enif_is_identical(enif_make_pid(env, &selfPid), ownership->pid))
return WrapError(env, "not_allowed");
else if (ownership->lock == nullptr)
return WrapError(env, "already_released");
else {
Lock* lock = ownership->lock;
assert(lock->ownership.load() == ownership);
ownership->lock = nullptr;
lock->ownership.store(nullptr);
enif_release_resource(lock);
return enif_make_atom(env, "ok");
}
}
static ErlNifFunc nif_funcs[] = {
{"new", 0, NewLock, 0},
{"acquire_ownership", 2, AcquireOwnership, 0},
{"release_ownership", 1, ReleaseOwnership, 0}
};
//ERL_NIF_INIT(nlocks_nif, nif_funcs, load, nullptr, upgrade, unload)
ERL_NIF_INIT(nlocks, nif_funcs, load, nullptr, nullptr, nullptr)
<commit_msg>Adjust function inlining<commit_after>/* The MIT License (MIT)
Copyright (c) 2016 Guilherme Andrade <nlocks(at)gandrade(dot)net>
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 "erl_nif.h"
#include <cassert>
#include <cstring>
#include <atomic>
#include <chrono>
#include <limits>
static ERL_NIF_TERM MakeNifBoolean(ErlNifEnv* env, bool flag) {
return (flag ? enif_make_atom(env, "true") : enif_make_atom(env, "false"));
}
static ERL_NIF_TERM WrapSuccess(ErlNifEnv* env, ERL_NIF_TERM term) {
return enif_make_tuple2(env, enif_make_atom(env, "ok"), term);
}
static ERL_NIF_TERM WrapError(ErlNifEnv* env, ERL_NIF_TERM term) {
return enif_make_tuple2(env, enif_make_atom(env, "error"), term);
}
static ERL_NIF_TERM WrapError(ErlNifEnv* env, const char* error) {
return WrapError(env, enif_make_atom(env, error));
}
static ERL_NIF_TERM WrapResourceTerm(
ErlNifEnv* env, const char* resourceTypeId, ERL_NIF_TERM resourceTerm)
{
return enif_make_tuple3(env,
enif_make_atom(env, resourceTypeId),
enif_make_uint64(env, static_cast<uint64_t>(resourceTerm)),
resourceTerm);
}
static bool UnwrapResourceTerm(
ErlNifEnv* env, ERL_NIF_TERM wrappedResource, ERL_NIF_TERM* resourceTerm)
{
int tupleArity = 0;
const ERL_NIF_TERM *tuple = nullptr;
if (not enif_get_tuple(env, wrappedResource, &tupleArity, &tuple))
return false;
if (tupleArity != 3)
return false;
*resourceTerm = tuple[2];
return true;
}
static inline uint64_t CurrentTimeMilliseconds() {
std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now();
return std::chrono::duration_cast<std::chrono::milliseconds>(
now.time_since_epoch()).count();
}
struct Ownership;
struct Lock {
std::atomic<Ownership*> ownership;
};
struct Ownership {
ERL_NIF_TERM pid;
Lock* lock = nullptr;
};
#define LOCK_RESOURCE "nlocks.lock"
#define OWNERSHIP_RESOURCE "nlocks.ownership"
static ErlNifResourceType* lockResourceType = nullptr;
static ErlNifResourceType* ownershipResourceType = nullptr;
static void DeleteLockResource(ErlNifEnv* /*env*/, void* resource) {
Lock* lock = static_cast<Lock*>(resource);
assert(lock->ownership == nullptr);
}
static void DeleteOwnershipResource(ErlNifEnv* /*env*/, void* resource) {
Ownership* ownership = static_cast<Ownership*>(resource);
if (ownership->lock != nullptr) {
// process was probably brutally killed; we never released the lock
assert(ownership->lock->ownership == ownership);
ownership->lock->ownership.store(nullptr);
enif_release_resource(ownership->lock);
ownership->lock = nullptr;
}
}
static int load(ErlNifEnv* env, void** /*priv*/, ERL_NIF_TERM /*load_info*/) {
lockResourceType = enif_open_resource_type(
env, nullptr,
LOCK_RESOURCE,
DeleteLockResource,
ERL_NIF_RT_CREATE, nullptr);
ownershipResourceType = enif_open_resource_type(
env, nullptr,
OWNERSHIP_RESOURCE,
DeleteOwnershipResource,
ERL_NIF_RT_CREATE, nullptr);
return 0;
}
//int upgrade(ErlNifEnv* /*env*/, void** /*priv_data*/, void** /*old_priv_data*/, ERL_NIF_TERM /*load_info*/) {
// // TODO
// return 0;
//}
//static void unload(ErlNifEnv* /*env*/, void* /*priv_data*/) {
// // TODO
//}
/****************************************************************/
static ERL_NIF_TERM NewLock(ErlNifEnv* env, int /*argc*/, const ERL_NIF_TERM[] /*argv*/) {
Lock* lock = static_cast<Lock*>(enif_alloc_resource(lockResourceType, sizeof(Lock)));
memset(lock, 0, sizeof(Lock));
ERL_NIF_TERM term = WrapResourceTerm(env, LOCK_RESOURCE, enif_make_resource(env, lock));
enif_release_resource(lock);
return term;
}
// not exported, used internally
static ERL_NIF_TERM AcquireOwnershipRecursive(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {
Lock* lock = nullptr;
Ownership* ownership = nullptr;
uint64_t deadline = 0;
ERL_NIF_TERM errorReturn;
Ownership* currentOwnership = nullptr;
if (not enif_get_resource(env, argv[0], lockResourceType, reinterpret_cast<void**>(&lock))) {
errorReturn = enif_make_badarg(env);
goto give_up;
}
if (not enif_get_resource(env, argv[1], ownershipResourceType, reinterpret_cast<void**>(&ownership))) {
errorReturn = enif_make_badarg(env);
goto give_up;
}
if (not enif_get_uint64(env, argv[2], &deadline)) {
errorReturn = enif_make_badarg(env);
goto give_up;
}
if ((deadline > 0) && (CurrentTimeMilliseconds() >= deadline)) {
errorReturn = WrapError(env, "timeout");
goto give_up;
}
currentOwnership = lock->ownership.load(std::memory_order_relaxed);
if ((currentOwnership == nullptr)
&& lock->ownership.compare_exchange_weak(
currentOwnership, ownership,
std::memory_order_release,
std::memory_order_relaxed))
{
// locked by us
ErlNifPid selfPid;
enif_self(env, &selfPid);
ownership->pid = enif_make_pid(env, &selfPid);
ownership->lock = lock;
enif_keep_resource(lock);
enif_release_resource(ownership);
ERL_NIF_TERM wrappedOwnershipTerm = WrapResourceTerm(env, OWNERSHIP_RESOURCE, argv[1]);
return WrapSuccess(env, wrappedOwnershipTerm);
}
// locked by someone else
return enif_schedule_nif(
env, "AcquireOwnershipRecursive", 0,
AcquireOwnershipRecursive, argc, argv);
give_up:
if (ownership != nullptr)
enif_release_resource(ownership);
return errorReturn;
}
static ERL_NIF_TERM AcquireOwnership(ErlNifEnv* env, int /*argc*/, const ERL_NIF_TERM argv[]) {
ERL_NIF_TERM lockTerm;
Lock* lock = nullptr;
unsigned timeout = 0;
uint64_t deadline = 0;
if (not UnwrapResourceTerm(env, argv[0], &lockTerm))
return enif_make_badarg(env);
if (not enif_get_resource(env, lockTerm, lockResourceType, reinterpret_cast<void**>(&lock)))
return enif_make_badarg(env);
if (not enif_get_uint(env, argv[1], &timeout)) {
if (not enif_is_identical(argv[2], enif_make_atom(env, "infinity")))
return enif_make_badarg(env);
}
else {
uint64_t currentTime = CurrentTimeMilliseconds();
deadline = currentTime + static_cast<uint64_t>(timeout);
}
ErlNifPid self;
enif_self(env, &self);
Ownership* ownership = static_cast<Ownership*>(
enif_alloc_resource(ownershipResourceType, sizeof(Ownership)));
memset(ownership, 0, sizeof(Ownership));
int newArgc = 3;
ERL_NIF_TERM* newArgv = static_cast<ERL_NIF_TERM*>(malloc(sizeof(ERL_NIF_TERM) * newArgc));
newArgv[0] = lockTerm;
newArgv[1] = enif_make_resource(env, ownership);
newArgv[2] = enif_make_uint64(env, deadline);
return enif_schedule_nif(
env, "AcquireOwnershipRecursive", 0,
AcquireOwnershipRecursive, newArgc, newArgv);
}
static ERL_NIF_TERM ReleaseOwnership(ErlNifEnv* env, int /*argc*/, const ERL_NIF_TERM argv[]) {
ERL_NIF_TERM ownershipTerm;
Ownership* ownership = nullptr;
if (not UnwrapResourceTerm(env, argv[0], &ownershipTerm))
return enif_make_badarg(env);
if (not enif_get_resource(env, ownershipTerm, ownershipResourceType, reinterpret_cast<void**>(&ownership)))
return enif_make_badarg(env);
ErlNifPid selfPid;
enif_self(env, &selfPid);
if (not enif_is_identical(enif_make_pid(env, &selfPid), ownership->pid))
return WrapError(env, "not_allowed");
else if (ownership->lock == nullptr)
return WrapError(env, "already_released");
else {
Lock* lock = ownership->lock;
assert(lock->ownership.load() == ownership);
ownership->lock = nullptr;
lock->ownership.store(nullptr);
enif_release_resource(lock);
return enif_make_atom(env, "ok");
}
}
static ErlNifFunc nif_funcs[] = {
{"new", 0, NewLock, 0},
{"acquire_ownership", 2, AcquireOwnership, 0},
{"release_ownership", 1, ReleaseOwnership, 0}
};
//ERL_NIF_INIT(nlocks_nif, nif_funcs, load, nullptr, upgrade, unload)
ERL_NIF_INIT(nlocks, nif_funcs, load, nullptr, nullptr, nullptr)
<|endoftext|> |
<commit_before>/*
* caosVM_core.cpp
* openc2e
*
* Created by Alyssa Milburn on Tue May 25 2004.
* Copyright (c) 2004 Alyssa Milburn. All rights reserved.
*
* 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 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.
*
*/
#include "caosVM.h"
#include "openc2e.h"
#include "World.h"
#include "Engine.h"
#include <iostream>
#include <boost/format.hpp>
using std::cout;
using std::cerr;
using boost::format;
/**
OUTX (command) val (string)
%status maybe
Prints the given string on the output stream, after first quoting it and transforming
escapes in the string to quoted escapes.
*/
void caosVM::c_OUTX() {
VM_PARAM_STRING(val)
std::string oh = "\"";
for (unsigned int i = 0; i < val.size(); i++) {
switch (val[i]) {
case '\r': oh += "\\r"; break;
case '\n': oh += "\\n"; break;
case '\t': oh += "\\t"; break;
case '\\': oh += "\\\\"; break;
case '"': oh += "\\\""; break;
case '\'': oh += "\\'"; break;
default: oh += val[i];
}
}
*outputstream << oh << "\"";
}
/**
OUTS (command) val (string)
%status maybe
Prints the given string to the output stream. Does nothing when run inside a script.
*/
void caosVM::c_OUTS() {
VM_VERIFY_SIZE(1)
VM_PARAM_STRING(val)
*outputstream << val;
}
/**
DDE: PUTS (command) val (bareword)
%status maybe
%pragma variants c1 c2
%pragma implementation caosVM::c_OUTS
*/
/**
OUTV (command) val (decimal)
%status maybe
Prints the given decimal value to the ouput stream. Does nothing when run inside a script.
*/
void caosVM::c_OUTV() {
VM_VERIFY_SIZE(1)
VM_PARAM_VALUE(val)
if (val.hasFloat()) {
*outputstream << boost::format("%0.06f") % val.getFloat();
} else if (val.hasInt()) {
*outputstream << val.getInt();
} else if (val.hasVector()) {
const Vector<float> &v = val.getVector();
*outputstream << boost::format("(%0.6f, %0.6f)") % v.x % v.y;
} else throw badParamException();
}
/**
DDE: PUTV (command) val (integer)
%status maybe
%pragma variants c1 c2
%pragma implementation caosVM::c_OUTV
*/
/**
GAME (variable) name (string)
%status maybe
Returns the game variable with the given name.
*/
void caosVM::v_GAME() {
VM_VERIFY_SIZE(1)
VM_PARAM_STRING(name)
caosVar &i = world.variables[name];
valueStack.push_back(&i);
}
/**
EAME (variable) name (anything)
%status maybe
Returns the temporary game variable with the given name.
*/
void caosVM::v_EAME() {
VM_VERIFY_SIZE(1)
VM_PARAM_VALUE(name)
caosVar &i = engine.eame_variables[name];
valueStack.push_back(&i);
}
/**
DELG (command) name (string)
%status maybe
Deletes the game variable with the given name.
*/
void caosVM::c_DELG() {
VM_PARAM_STRING(name)
std::map<std::string, caosVar>::iterator i = world.variables.find(name);
if (i != world.variables.end())
world.variables.erase(i);
else
std::cerr << "DELG got told to delete '" << name << "' but it doesn't exist!" << std::endl;
}
/**
SCRP (command) family (integer) genus (integer) species (integer) event (integer)
%status done
%pragma noparse
%pragma variants c1 c2 cv c3
Marks the beginning of a normal script applying to the agent with the given classifier
info.
*/
/**
RSCR (command)
%status done
%pragma noparse
%pragma variants c2 cv c3
Marks the beginning of a removal script.
*/
/**
ISCR (command)
%status stub
%pragma variants c2 cv c3
Marks the beginning of an installer script.
*/
void caosVM::c_ISCR() {
VM_VERIFY_SIZE(0)
// STOP
}
/**
ENDM (command)
%status done
%pragma variants c1 c2 cv c3
Marks the end of a script.
*/
void caosVM::c_ENDM() {
stop();
}
/**
RGAM (command)
%status stub
Restore all game variables to their saved or default values.
*/
void caosVM::c_RGAM() {}
/**
MOWS (integer)
%status stub
Returns whether the lawn was cut last Sunday or not, in theory.
How the C2E engine determines this, and whose lawn, exactly, and whether or not it takes into account the fact that the lawn may have been mown on Saturday or Friday, and whether it will cut you any slack if it's winter and the grass isn't growing much, is currently unknown.
In openc2e, currently a no-op (ie, the lawn is never, ever cut properly).
*/
void caosVM::v_MOWS() {
result.setInt(0); // We're too busy coding to mow the lawn.
}
/**
VMNR (integer)
%status maybe
Returns the minor version number of the engine.
*/
void caosVM::v_VMNR() {
result.setInt(1);
}
/**
VMJR (integer)
%status maybe
Returns the major version number of the engine.
*/
void caosVM::v_VMJR() {
result.setInt(0);
}
/**
WOLF (integer) andmask (integer) eormask (integer)
%status stub
*/
void caosVM::v_WOLF() {
VM_PARAM_INTEGER(eormask)
VM_PARAM_INTEGER(andmask)
result.setInt(0); // TODO
}
/**
LANG (string)
%status stub
*/
void caosVM::v_LANG() {
result.setString("en");
}
/**
TOKN (integer) token (bareword)
%status maybe
%pragma variants c1 c2
*/
void caosVM::v_TOKN() {
VM_PARAM_STRING(token)
caos_assert(token.size() == 4);
int *data = (int *)token.c_str();
result.setInt(*data);
}
/* vim: set noet: */
<commit_msg>remove that silly DELG message, since DELGing nonexistant variables is apparently fine<commit_after>/*
* caosVM_core.cpp
* openc2e
*
* Created by Alyssa Milburn on Tue May 25 2004.
* Copyright (c) 2004 Alyssa Milburn. All rights reserved.
*
* 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 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.
*
*/
#include "caosVM.h"
#include "openc2e.h"
#include "World.h"
#include "Engine.h"
#include <iostream>
#include <boost/format.hpp>
using std::cout;
using std::cerr;
using boost::format;
/**
OUTX (command) val (string)
%status maybe
Prints the given string on the output stream, after first quoting it and transforming
escapes in the string to quoted escapes.
*/
void caosVM::c_OUTX() {
VM_PARAM_STRING(val)
std::string oh = "\"";
for (unsigned int i = 0; i < val.size(); i++) {
switch (val[i]) {
case '\r': oh += "\\r"; break;
case '\n': oh += "\\n"; break;
case '\t': oh += "\\t"; break;
case '\\': oh += "\\\\"; break;
case '"': oh += "\\\""; break;
case '\'': oh += "\\'"; break;
default: oh += val[i];
}
}
*outputstream << oh << "\"";
}
/**
OUTS (command) val (string)
%status maybe
Prints the given string to the output stream. Does nothing when run inside a script.
*/
void caosVM::c_OUTS() {
VM_VERIFY_SIZE(1)
VM_PARAM_STRING(val)
*outputstream << val;
}
/**
DDE: PUTS (command) val (bareword)
%status maybe
%pragma variants c1 c2
%pragma implementation caosVM::c_OUTS
*/
/**
OUTV (command) val (decimal)
%status maybe
Prints the given decimal value to the ouput stream. Does nothing when run inside a script.
*/
void caosVM::c_OUTV() {
VM_VERIFY_SIZE(1)
VM_PARAM_VALUE(val)
if (val.hasFloat()) {
*outputstream << boost::format("%0.06f") % val.getFloat();
} else if (val.hasInt()) {
*outputstream << val.getInt();
} else if (val.hasVector()) {
const Vector<float> &v = val.getVector();
*outputstream << boost::format("(%0.6f, %0.6f)") % v.x % v.y;
} else throw badParamException();
}
/**
DDE: PUTV (command) val (integer)
%status maybe
%pragma variants c1 c2
%pragma implementation caosVM::c_OUTV
*/
/**
GAME (variable) name (string)
%status maybe
Returns the game variable with the given name.
*/
void caosVM::v_GAME() {
VM_VERIFY_SIZE(1)
VM_PARAM_STRING(name)
caosVar &i = world.variables[name];
valueStack.push_back(&i);
}
/**
EAME (variable) name (anything)
%status maybe
Returns the temporary game variable with the given name.
*/
void caosVM::v_EAME() {
VM_VERIFY_SIZE(1)
VM_PARAM_VALUE(name)
caosVar &i = engine.eame_variables[name];
valueStack.push_back(&i);
}
/**
DELG (command) name (string)
%status maybe
Deletes the game variable with the given name.
*/
void caosVM::c_DELG() {
VM_PARAM_STRING(name)
std::map<std::string, caosVar>::iterator i = world.variables.find(name);
if (i != world.variables.end())
world.variables.erase(i);
}
/**
SCRP (command) family (integer) genus (integer) species (integer) event (integer)
%status done
%pragma noparse
%pragma variants c1 c2 cv c3
Marks the beginning of a normal script applying to the agent with the given classifier
info.
*/
/**
RSCR (command)
%status done
%pragma noparse
%pragma variants c2 cv c3
Marks the beginning of a removal script.
*/
/**
ISCR (command)
%status stub
%pragma variants c2 cv c3
Marks the beginning of an installer script.
*/
void caosVM::c_ISCR() {
VM_VERIFY_SIZE(0)
// STOP
}
/**
ENDM (command)
%status done
%pragma variants c1 c2 cv c3
Marks the end of a script.
*/
void caosVM::c_ENDM() {
stop();
}
/**
RGAM (command)
%status stub
Restore all game variables to their saved or default values.
*/
void caosVM::c_RGAM() {}
/**
MOWS (integer)
%status stub
Returns whether the lawn was cut last Sunday or not, in theory.
How the C2E engine determines this, and whose lawn, exactly, and whether or not it takes into account the fact that the lawn may have been mown on Saturday or Friday, and whether it will cut you any slack if it's winter and the grass isn't growing much, is currently unknown.
In openc2e, currently a no-op (ie, the lawn is never, ever cut properly).
*/
void caosVM::v_MOWS() {
result.setInt(0); // We're too busy coding to mow the lawn.
}
/**
VMNR (integer)
%status maybe
Returns the minor version number of the engine.
*/
void caosVM::v_VMNR() {
result.setInt(1);
}
/**
VMJR (integer)
%status maybe
Returns the major version number of the engine.
*/
void caosVM::v_VMJR() {
result.setInt(0);
}
/**
WOLF (integer) andmask (integer) eormask (integer)
%status stub
*/
void caosVM::v_WOLF() {
VM_PARAM_INTEGER(eormask)
VM_PARAM_INTEGER(andmask)
result.setInt(0); // TODO
}
/**
LANG (string)
%status stub
*/
void caosVM::v_LANG() {
result.setString("en");
}
/**
TOKN (integer) token (bareword)
%status maybe
%pragma variants c1 c2
*/
void caosVM::v_TOKN() {
VM_PARAM_STRING(token)
caos_assert(token.size() == 4);
int *data = (int *)token.c_str();
result.setInt(*data);
}
/* vim: set noet: */
<|endoftext|> |
<commit_before>
#include <am/hash/fnv.hpp>
#include <am/hash/murmur.hpp>
#include <cstring>
#include <string>
#include <vector>
#include <map>
#include <iostream>
#include <iomanip>
// FIXME: seeds are currently narrowed to HL32
using func_vector_type
= std::vector<
void
(*)(
std::string const&,
am::hash::common_hash_type<am::hash::HL64> const
)
>;
template<
am::hash::HashLength L
>
void
output(
am::hash::common_hash_type<L> const value
) {
std::cout
<< std::setw(static_cast<unsigned>(L) << 1)
<< value
;
}
template<
am::hash::HashLength L
>
using hash_func_type =
am::hash::common_hash_type<L>
(&)(
std::string const&
);
template<
am::hash::HashLength L,
hash_func_type<L>& F
>
void
hash_generic(
std::string const& str,
am::hash::common_hash_type<am::hash::HL64> const
) {
output<L>(F(str));
}
#define FUNC_GENERIC(name__, length__) \
hash_generic< \
am::hash::HashLength:: length__, \
am::hash:: name__ ## _str< \
am::hash::HashLength:: length__, \
std::string \
> \
>
template<
am::hash::HashLength L
>
using seeded_hash_func_type =
am::hash::common_hash_type<L>
(&)(
std::string const&,
am::hash::common_hash_type<L> const
);
template<
am::hash::HashLength L,
seeded_hash_func_type<L>& F
>
void
hash_seeded(
std::string const& str,
am::hash::common_hash_type<am::hash::HL64> const seed
) {
output<L>(F(
str,
static_cast<am::hash::common_hash_type<L>>(seed)
));
}
#define FUNC_SEEDED(name__, length__) \
hash_seeded< \
am::hash::HashLength:: length__, \
am::hash:: name__ ## _str< \
am::hash::HashLength:: length__, \
std::string \
> \
>
// Clang was exploding when FUNC_GENERIC and FUNC_SEEDED were used
// in s_algorithms, so... this stuff
auto const& fnv0_1 = FUNC_GENERIC(fnv0, HL32);
auto const& fnv0_2 = FUNC_GENERIC(fnv0, HL64);
auto const& fnv1_1 = FUNC_GENERIC(fnv1, HL32);
auto const& fnv1_2 = FUNC_GENERIC(fnv1, HL64);
auto const& fnv1a_1 = FUNC_GENERIC(fnv1a, HL32);
auto const& fnv1a_2 = FUNC_GENERIC(fnv1a, HL64);
auto const& murmur2_1 = FUNC_SEEDED(murmur2, HL32);
auto const& murmur2_2 = FUNC_SEEDED(murmur2, HL64);
auto const& murmur2_64b = FUNC_SEEDED(murmur2_64b, HL64);
auto const& murmur3 = FUNC_SEEDED(murmur3, HL32);
using algorithm_map_type
= std::map<
std::string,
func_vector_type
>;
struct AlgorithmConfig final {
std::string const& name;
func_vector_type const& funcs;
am::hash::common_hash_type<am::hash::HL64> const seed;
AlgorithmConfig(
algorithm_map_type::value_type const& pair,
am::hash::common_hash_type<am::hash::HL64> const seed
)
: name(pair.first)
, funcs(pair.second)
, seed(seed)
{}
};
static algorithm_map_type const
s_algorithms{{
{"fnv0", {
&fnv0_1,
&fnv0_2
}},
{"fnv1", {
&fnv1_1,
&fnv1_2
}},
{"fnv1a", {
&fnv1a_1,
&fnv1a_2
}},
{"murmur2", {
&murmur2_1,
&murmur2_2
}},
{"murmur64b", {
&murmur2_64b
}},
{"murmur3", {
&murmur3
}}
}};
static std::vector<AlgorithmConfig>
s_selected{};
bool
select_algorithm(
char const* const name,
am::hash::common_hash_type<am::hash::HL64> const seed
) {
auto const it = s_algorithms.find(name);
if (s_algorithms.end() == it) {
return false;
} else {
s_selected.emplace_back(*it, seed);
return true;
}
}
void
print_help() {
std::cout
<< "usage: util [seed] algo [[seed] algo [...]] - string [...]\n"
<< "valid algorithms are:\n"
;
for (auto const& algo : s_algorithms) {
std::cout << " " << algo.first << '\n';
}
}
signed
main(
int argc,
char* argv[]
) {
if (4 > argc) {
std::cout << "invalid arguments\n";
print_help();
std::cout.flush();
return -1;
}
am::hash::common_hash_type<am::hash::HL64> last_seed{0u};
std::size_t dash_pos = 0u;
for (
std::size_t index = 1;
index < static_cast<std::size_t>(argc);
++index
) {
char const* const arg = argv[index];
// strncmp stops at \0, and we want to know if the entire
// string is equal, not just its first character, so 2 is the
// maximum number of characters to compare
if (0 == std::strncmp("-", arg, 2u)) {
dash_pos = index;
break;
} else if (std::isdigit(arg[0])) {
char* end = argv[index] + std::strlen(arg);
last_seed = std::strtoll(arg, &end, 0);
} else if (!select_algorithm(arg, last_seed)) {
std::cout
<< "invalid algorithm: "
<< arg
<< "\n\n"
;
print_help();
std::cout.flush();
return -2;
}
}
if (0 == dash_pos || s_selected.empty()) {
std::cout << "invalid arguments\n";
print_help();
std::cout.flush();
return -1;
}
std::vector<std::string> strings{
argv + dash_pos + 1,
argv + argc
};
std::cout
<< std::hex
<< std::left
;
for (auto const& string : strings) {
std::cout
<< '\"' << string << "\"\n"
;
for (auto const& config : s_selected) {
std::cout
<< std::setfill(' ')
<< " ["
<< std::setw(9u)
<< config.name
<< "] => "
<< std::setfill('0')
;
for (
auto func_it = config.funcs.cbegin();
config.funcs.cend() != func_it;
++func_it
) {
(*func_it)(string, config.seed);
if (config.funcs.cend() != (func_it + 1)) {
std::cout << ", ";
}
}
std::cout << '\n';
}
}
std::cout.flush();
return 0;
}
<commit_msg>test/hash/util: int -> signed.<commit_after>
#include <am/hash/fnv.hpp>
#include <am/hash/murmur.hpp>
#include <cstring>
#include <string>
#include <vector>
#include <map>
#include <iostream>
#include <iomanip>
// FIXME: seeds are currently narrowed to HL32
using func_vector_type
= std::vector<
void
(*)(
std::string const&,
am::hash::common_hash_type<am::hash::HL64> const
)
>;
template<
am::hash::HashLength L
>
void
output(
am::hash::common_hash_type<L> const value
) {
std::cout
<< std::setw(static_cast<unsigned>(L) << 1)
<< value
;
}
template<
am::hash::HashLength L
>
using hash_func_type =
am::hash::common_hash_type<L>
(&)(
std::string const&
);
template<
am::hash::HashLength L,
hash_func_type<L>& F
>
void
hash_generic(
std::string const& str,
am::hash::common_hash_type<am::hash::HL64> const
) {
output<L>(F(str));
}
#define FUNC_GENERIC(name__, length__) \
hash_generic< \
am::hash::HashLength:: length__, \
am::hash:: name__ ## _str< \
am::hash::HashLength:: length__, \
std::string \
> \
>
template<
am::hash::HashLength L
>
using seeded_hash_func_type =
am::hash::common_hash_type<L>
(&)(
std::string const&,
am::hash::common_hash_type<L> const
);
template<
am::hash::HashLength L,
seeded_hash_func_type<L>& F
>
void
hash_seeded(
std::string const& str,
am::hash::common_hash_type<am::hash::HL64> const seed
) {
output<L>(F(
str,
static_cast<am::hash::common_hash_type<L>>(seed)
));
}
#define FUNC_SEEDED(name__, length__) \
hash_seeded< \
am::hash::HashLength:: length__, \
am::hash:: name__ ## _str< \
am::hash::HashLength:: length__, \
std::string \
> \
>
// Clang was exploding when FUNC_GENERIC and FUNC_SEEDED were used
// in s_algorithms, so... this stuff
auto const& fnv0_1 = FUNC_GENERIC(fnv0, HL32);
auto const& fnv0_2 = FUNC_GENERIC(fnv0, HL64);
auto const& fnv1_1 = FUNC_GENERIC(fnv1, HL32);
auto const& fnv1_2 = FUNC_GENERIC(fnv1, HL64);
auto const& fnv1a_1 = FUNC_GENERIC(fnv1a, HL32);
auto const& fnv1a_2 = FUNC_GENERIC(fnv1a, HL64);
auto const& murmur2_1 = FUNC_SEEDED(murmur2, HL32);
auto const& murmur2_2 = FUNC_SEEDED(murmur2, HL64);
auto const& murmur2_64b = FUNC_SEEDED(murmur2_64b, HL64);
auto const& murmur3 = FUNC_SEEDED(murmur3, HL32);
using algorithm_map_type
= std::map<
std::string,
func_vector_type
>;
struct AlgorithmConfig final {
std::string const& name;
func_vector_type const& funcs;
am::hash::common_hash_type<am::hash::HL64> const seed;
AlgorithmConfig(
algorithm_map_type::value_type const& pair,
am::hash::common_hash_type<am::hash::HL64> const seed
)
: name(pair.first)
, funcs(pair.second)
, seed(seed)
{}
};
static algorithm_map_type const
s_algorithms{{
{"fnv0", {
&fnv0_1,
&fnv0_2
}},
{"fnv1", {
&fnv1_1,
&fnv1_2
}},
{"fnv1a", {
&fnv1a_1,
&fnv1a_2
}},
{"murmur2", {
&murmur2_1,
&murmur2_2
}},
{"murmur64b", {
&murmur2_64b
}},
{"murmur3", {
&murmur3
}}
}};
static std::vector<AlgorithmConfig>
s_selected{};
bool
select_algorithm(
char const* const name,
am::hash::common_hash_type<am::hash::HL64> const seed
) {
auto const it = s_algorithms.find(name);
if (s_algorithms.end() == it) {
return false;
} else {
s_selected.emplace_back(*it, seed);
return true;
}
}
void
print_help() {
std::cout
<< "usage: util [seed] algo [[seed] algo [...]] - string [...]\n"
<< "valid algorithms are:\n"
;
for (auto const& algo : s_algorithms) {
std::cout << " " << algo.first << '\n';
}
}
signed
main(
signed argc,
char* argv[]
) {
if (4 > argc) {
std::cout << "invalid arguments\n";
print_help();
std::cout.flush();
return -1;
}
am::hash::common_hash_type<am::hash::HL64> last_seed{0u};
std::size_t dash_pos = 0u;
for (
std::size_t index = 1;
index < static_cast<std::size_t>(argc);
++index
) {
char const* const arg = argv[index];
// strncmp stops at \0, and we want to know if the entire
// string is equal, not just its first character, so 2 is the
// maximum number of characters to compare
if (0 == std::strncmp("-", arg, 2u)) {
dash_pos = index;
break;
} else if (std::isdigit(arg[0])) {
char* end = argv[index] + std::strlen(arg);
last_seed = std::strtoll(arg, &end, 0);
} else if (!select_algorithm(arg, last_seed)) {
std::cout
<< "invalid algorithm: "
<< arg
<< "\n\n"
;
print_help();
std::cout.flush();
return -2;
}
}
if (0 == dash_pos || s_selected.empty()) {
std::cout << "invalid arguments\n";
print_help();
std::cout.flush();
return -1;
}
std::vector<std::string> strings{
argv + dash_pos + 1,
argv + argc
};
std::cout
<< std::hex
<< std::left
;
for (auto const& string : strings) {
std::cout
<< '\"' << string << "\"\n"
;
for (auto const& config : s_selected) {
std::cout
<< std::setfill(' ')
<< " ["
<< std::setw(9u)
<< config.name
<< "] => "
<< std::setfill('0')
;
for (
auto func_it = config.funcs.cbegin();
config.funcs.cend() != func_it;
++func_it
) {
(*func_it)(string, config.seed);
if (config.funcs.cend() != (func_it + 1)) {
std::cout << ", ";
}
}
std::cout << '\n';
}
}
std::cout.flush();
return 0;
}
<|endoftext|> |
<commit_before>/**
* @file NaoTime.cpp
*
* Class NaoTime provides methods for time information and calculation
*
* @author Oliver Welter
*/
#include "NaoTime.h"
#include "Tools/Debug/Trace.h"
#include "Tools/Debug/NaoTHAssert.h"
#include <iostream>
using namespace naoth;
const unsigned long long NaoTime::startingTimeInMilliSeconds = getSystemTimeInMilliSeconds();
unsigned long long NaoTime::getSystemTimeInMicroSeconds()
{
#ifdef WIN32
LARGE_INTEGER highPerformanceTick;
LARGE_INTEGER freq;
if(QueryPerformanceCounter(&highPerformanceTick) && QueryPerformanceFrequency(&freq))
{
double inSeconds = ((double) highPerformanceTick.LowPart) / ((double) freq.LowPart);
return (unsigned long long) (inSeconds * 1000000.0);
}
#else
#ifdef NAO
struct timespec t;
clock_gettime(CLOCK_MONOTONIC ,&t);
return ((unsigned long long)t.tv_sec) * long_million + ((unsigned long long)t.tv_nsec) / long_thousand;
#else
struct timeval t;
int returnval = gettimeofday(&t, NULL);
if(returnval == 0)
{
return ((unsigned long long)t.tv_sec) * long_million + ((unsigned long long)t.tv_usec);
}
#endif
#endif
return 0;
}//end getSystemTimeInMicroSeconds
unsigned long long NaoTime::getSystemTimeInMilliSeconds()
{
#ifdef WIN32
LARGE_INTEGER highPerformanceTick;
LARGE_INTEGER freq;
if(QueryPerformanceCounter(&highPerformanceTick) && QueryPerformanceFrequency(&freq))
{
double inSeconds = ((double) highPerformanceTick.LowPart) / ((double) freq.LowPart);
return (unsigned long long) (inSeconds * 1000.0);
}
#else
#ifdef NAO
struct timespec t;
clock_gettime(CLOCK_MONOTONIC ,&t);
return ((unsigned long long)t.tv_sec) * long_thousand + ((unsigned long long)t.tv_nsec) / long_million;
#else
struct timeval t;
int returnval = gettimeofday(&t, NULL);
if(returnval == 0)
{
return ((unsigned long long)t.tv_sec) * long_thousand + ((unsigned long long)t.tv_usec) / long_thousand;
}
#endif
#endif
return 0;
}//end getSystemTimeInMilliSeconds
unsigned int NaoTime::getNaoTimeInMilliSeconds()
{
return (unsigned int) (getSystemTimeInMilliSeconds() - startingTimeInMilliSeconds);
}//end getNaoTimeInMilliSeconds
<commit_msg>use real time instead of monotonic since image driver is using it as well<commit_after>/**
* @file NaoTime.cpp
*
* Class NaoTime provides methods for time information and calculation
*
* @author Oliver Welter
*/
#include "NaoTime.h"
#include "Tools/Debug/Trace.h"
#include "Tools/Debug/NaoTHAssert.h"
#include <iostream>
using namespace naoth;
const unsigned long long NaoTime::startingTimeInMilliSeconds = getSystemTimeInMilliSeconds();
unsigned long long NaoTime::getSystemTimeInMicroSeconds()
{
#ifdef WIN32
LARGE_INTEGER highPerformanceTick;
LARGE_INTEGER freq;
if(QueryPerformanceCounter(&highPerformanceTick) && QueryPerformanceFrequency(&freq))
{
double inSeconds = ((double) highPerformanceTick.LowPart) / ((double) freq.LowPart);
return (unsigned long long) (inSeconds * 1000000.0);
}
#else
#ifdef NAO
struct timespec t;
clock_gettime(CLOCK_MONOTONIC ,&t);
return ((unsigned long long)t.tv_sec) * long_million + ((unsigned long long)t.tv_nsec) / long_thousand;
#else
struct timeval t;
int returnval = gettimeofday(&t, NULL);
if(returnval == 0)
{
return ((unsigned long long)t.tv_sec) * long_million + ((unsigned long long)t.tv_usec);
}
#endif
#endif
return 0;
}//end getSystemTimeInMicroSeconds
unsigned long long NaoTime::getSystemTimeInMilliSeconds()
{
#ifdef WIN32
LARGE_INTEGER highPerformanceTick;
LARGE_INTEGER freq;
if(QueryPerformanceCounter(&highPerformanceTick) && QueryPerformanceFrequency(&freq))
{
double inSeconds = ((double) highPerformanceTick.LowPart) / ((double) freq.LowPart);
return (unsigned long long) (inSeconds * 1000.0);
}
#else
#ifdef NAO
struct timespec t;
clock_gettime(CLOCK_REALTIME ,&t);
return ((unsigned long long)t.tv_sec) * long_thousand + ((unsigned long long)t.tv_nsec) / long_million;
#else
struct timeval t;
int returnval = gettimeofday(&t, NULL);
if(returnval == 0)
{
return ((unsigned long long)t.tv_sec) * long_thousand + ((unsigned long long)t.tv_usec) / long_thousand;
}
#endif
#endif
return 0;
}//end getSystemTimeInMilliSeconds
unsigned int NaoTime::getNaoTimeInMilliSeconds()
{
return (unsigned int) (getSystemTimeInMilliSeconds() - startingTimeInMilliSeconds);
}//end getNaoTimeInMilliSeconds
<|endoftext|> |
<commit_before>/**
* \file Gnomonic.hpp
* \brief Header for GeographicLib::Gnomonic class
*
* Copyright (c) Charles Karney (2009, 2010) <charles@karney.com>
* and licensed under the LGPL. For more information, see
* http://geographiclib.sourceforge.net/
**********************************************************************/
#if !defined(GEOGRAPHICLIB_GNOMONIC_HPP)
#define GEOGRAPHICLIB_GNOMONIC_HPP "$Id$"
#include "GeographicLib/Geodesic.hpp"
#include "GeographicLib/Constants.hpp"
namespace GeographicLib {
/**
* \brief %Gnomonic Projection.
*
* %Gnomonic projection centered at an arbitrary position \e C on the
* ellipsoid. The projection of \e P is defined as follows: compute the
* geodesic line from \e C to \e P; compute the reduced length \e m12,
* geodesic scale \e M12, and \e rho = \e m12/\e M12; finally \e x = \e rho
* sin \e azi1; \e y = \e rho cos \e azi1, where \e azi1 is the azimuth of
* the geodesic at \e C. The Forward and Reverse methods also return the
* azimuth \e azi of the geodesic at \e P and reciprocal scale \e rk in the
* azimuthal direction. The scale in the radial direction if 1/\e
* rk<sup>2</sup>.
*
* For a sphere, \e rho is reduces to \e a tan(\e s12/\e a), where \e s12 is
* the length of the geodesic from \e C to \e P, and the gnomonic projection
* has the property that all geodesics appear as straight lines. For an
* ellipsoid, this property holds only for geodesics interesting the centers.
* However geodesics segments close to the center are approximately straight;
* the deviation from straightness is of order \e f (\e r/\e a)<sup>3</sup>
* where \e a and \e f are the major radius and the flattening of the
* ellipsoid and \e r is the maximum distance of the geodesic from the
* center.
*
* The conversions all take place using a GeographicLib::Geodesic object (by
* default GeographicLib::Geodesic::WGS84). For more information on
* geodesics see \ref geodesic.
*
* <b>CAUTION:</b> The definition of this projection for a sphere is
* standard. However, there is no standard for how it should be extended to
* an ellipsoid. The choices are:
* - Declare that the projection is undefined for an ellipsoid.
* - Project to a tangent plane from the center of the ellipsoid. This
* causes great ellipses to appear as straight lines in the projection;
* i.e., it generalizes the spherical great circle to a great ellipse.
* - The projection given here. This causes geodesics close to the center
* point to appear as straight lines in the projection; i.e., it
* generalizes the spherical great circle to a geodesic.
**********************************************************************/
class Gnomonic {
private:
typedef Math::real real;
const Geodesic _earth;
real _a, _f;
static const real eps0, eps;
static const int numit = 10;
public:
/**
* Constructor for Gnomonic setting the Geodesic object to use
* for geodesic calculations. By default this uses the WGS84 ellipsoid.
**********************************************************************/
explicit Gnomonic(const Geodesic& earth = Geodesic::WGS84)
throw()
: _earth(earth)
, _a(_earth.MajorRadius())
, _f(_earth.InverseFlattening() ?
1/std::abs(_earth.InverseFlattening()) : 0)
{}
/**
* Convert from latitude \e lat (degrees) and longitude \e lon (degrees) to
* gnomonic easting \e x (meters) and northing \e y (meters). The center
* of the projection is at latitude \e lat0 (degrees) and longitude \e lon0
* (degrees). Also return the azimuth \e azi (degrees) and the reciprocal
* of the azimuthal scale \e rk. \e lat0 and \e lat should be in the range
* [-90, 90] and \e lon0 and \e lon should be in the range [-180, 360].
* The scale of the projection is 1/\e rk<sup>2</sup> in the "radial"
* direction, \e azi clockwise from true north, and is 1/\e rk in the
* direction perpendicular to this. If the point lies "over the horizon",
* i.e., if \e rk <= 0, then NaNs are returned for \e x and \e y (the
* correct values are returned for \e azi and \e rk). A call to Forward
* followed by a call to Reverse will return the original (\e lat, \e lon)
* (to within roundoff) provided the point in not over the horizon.
**********************************************************************/
void Forward(real lat0, real lon0, real lat, real lon,
real& x, real& y, real& azi, real& rk) const throw();
/**
* Convert from gnomonic easting \e x (meters) and northing \e y (meters)
* to latitude \e lat (degrees) and longitude \e lon (degrees). The center
* of the projection is at latitude \e lat0 (degrees) and longitude \e lon0
* (degrees). Also return the azimuth \e azi (degrees) and the reciprocal
* of the azimuthal scale \e rk. \e lat0 should be in the range [-90, 90]
* and \e lon0 should be in the range [-180, 360]. \e lat will be in the
* range [-90, 90] and \e lon will be in the range [-180, 180). The scale
* of the projection is 1/\e rk<sup>2</sup> in the "radial" direction, \e
* azi clockwise from true north, and is 1/\e rk in the direction
* perpendicular to this. Even though all inputs should return a valid \e
* lat and \e lon, it's possible that the procedure fails to converge for
* very large \e x or \e y; in this case NaNs are returned for all the
* output arguments. A call to Reverse followed by a call to Forward will
* return the original (\e x, \e y) (to roundoff).
**********************************************************************/
void Reverse(real lat0, real lon0, real x, real y,
real& lat, real& lon, real& azi, real& rk) const throw();
/**
* The major radius of the ellipsoid (meters). This is that value of \e a
* inherited from the Geodesic object used in the constructor.
**********************************************************************/
Math::real MajorRadius() const throw() { return _earth.MajorRadius(); }
/**
* The inverse flattening of the ellipsoid. This is that value of \e r
* inherited from the Geodesic object used in the constructor. A value of
* 0 is returned for a sphere (infinite inverse flattening).
**********************************************************************/
Math::real InverseFlattening() const throw()
{ return _earth.InverseFlattening(); }
};
} // namespace GeographicLib
#endif
<commit_msg>More documentation.<commit_after>/**
* \file Gnomonic.hpp
* \brief Header for GeographicLib::Gnomonic class
*
* Copyright (c) Charles Karney (2009, 2010) <charles@karney.com>
* and licensed under the LGPL. For more information, see
* http://geographiclib.sourceforge.net/
**********************************************************************/
#if !defined(GEOGRAPHICLIB_GNOMONIC_HPP)
#define GEOGRAPHICLIB_GNOMONIC_HPP "$Id$"
#include "GeographicLib/Geodesic.hpp"
#include "GeographicLib/Constants.hpp"
namespace GeographicLib {
/**
* \brief %Gnomonic Projection.
*
* %Gnomonic projection centered at an arbitrary position \e C on the
* ellipsoid. The projection of \e P is defined as follows: compute the
* geodesic line from \e C to \e P; compute the reduced length \e m12,
* geodesic scale \e M12, and \e rho = \e m12/\e M12; finally \e x = \e rho
* sin \e azi1; \e y = \e rho cos \e azi1, where \e azi1 is the azimuth of
* the geodesic at \e C. The Forward and Reverse methods also return the
* azimuth \e azi of the geodesic at \e P and reciprocal scale \e rk in the
* azimuthal direction. The scale in the radial direction if 1/\e
* rk<sup>2</sup>.
*
* For a sphere, \e rho is reduces to \e a tan(\e s12/\e a), where \e s12 is
* the length of the geodesic from \e C to \e P, and the gnomonic projection
* has the property that all geodesics appear as straight lines. For an
* ellipsoid, this property holds only for geodesics interesting the centers.
* However geodesics segments close to the center are approximately straight;
* the deviation from straightness is of order \e f (\e r/\e a)<sup>3</sup>
* where \e a and \e f are the major radius and the flattening of the
* ellipsoid and \e r is the maximum distance of the geodesic from the
* center.
*
* The conversions all take place using a GeographicLib::Geodesic object (by
* default GeographicLib::Geodesic::WGS84). For more information on
* geodesics see \ref geodesic.
*
* <b>CAUTION:</b> The definition of this projection for a sphere is
* standard. However, there is no standard for how it should be extended to
* an ellipsoid. The choices are:
* - Declare that the projection is undefined for an ellipsoid.
* - Project to a tangent plane from the center of the ellipsoid. This
* causes great ellipses to appear as straight lines in the projection;
* i.e., it generalizes the spherical great circle to a great ellipse.
* This was proposed by Roy Williams, Geometry of Navigation (Horwood,
* Chichester, 1998).
* - Project to the conformal sphere with a latitude offset so that the
* values of the latitude and longitude match for the center point and
* perform a central projection onto the plane tangent to the conformal
* sphere at the center point. This causes normal sections through the
* center point to appear as straight lines in the projection; i.e., it
* generalizes the spherical great circle to a normal section. This was
* proposed by I. G. Letoval'tsev, Generalization of the Gnomonic
* Projection for a Spheroid and the Principal Geodetic Problems Involved
* in the Alignment of Surface Routes, Geodesy and Aerophotography (5),
* 271-274 (1963).
* - The projection given here. This causes geodesics close to the center
* point to appear as straight lines in the projection; i.e., it
* generalizes the spherical great circle to a geodesic.
**********************************************************************/
class Gnomonic {
private:
typedef Math::real real;
const Geodesic _earth;
real _a, _f;
static const real eps0, eps;
static const int numit = 10;
public:
/**
* Constructor for Gnomonic setting the Geodesic object to use
* for geodesic calculations. By default this uses the WGS84 ellipsoid.
**********************************************************************/
explicit Gnomonic(const Geodesic& earth = Geodesic::WGS84)
throw()
: _earth(earth)
, _a(_earth.MajorRadius())
, _f(_earth.InverseFlattening() ?
1/std::abs(_earth.InverseFlattening()) : 0)
{}
/**
* Convert from latitude \e lat (degrees) and longitude \e lon (degrees) to
* gnomonic easting \e x (meters) and northing \e y (meters). The center
* of the projection is at latitude \e lat0 (degrees) and longitude \e lon0
* (degrees). Also return the azimuth \e azi (degrees) and the reciprocal
* of the azimuthal scale \e rk. \e lat0 and \e lat should be in the range
* [-90, 90] and \e lon0 and \e lon should be in the range [-180, 360].
* The scale of the projection is 1/\e rk<sup>2</sup> in the "radial"
* direction, \e azi clockwise from true north, and is 1/\e rk in the
* direction perpendicular to this. If the point lies "over the horizon",
* i.e., if \e rk <= 0, then NaNs are returned for \e x and \e y (the
* correct values are returned for \e azi and \e rk). A call to Forward
* followed by a call to Reverse will return the original (\e lat, \e lon)
* (to within roundoff) provided the point in not over the horizon.
**********************************************************************/
void Forward(real lat0, real lon0, real lat, real lon,
real& x, real& y, real& azi, real& rk) const throw();
/**
* Convert from gnomonic easting \e x (meters) and northing \e y (meters)
* to latitude \e lat (degrees) and longitude \e lon (degrees). The center
* of the projection is at latitude \e lat0 (degrees) and longitude \e lon0
* (degrees). Also return the azimuth \e azi (degrees) and the reciprocal
* of the azimuthal scale \e rk. \e lat0 should be in the range [-90, 90]
* and \e lon0 should be in the range [-180, 360]. \e lat will be in the
* range [-90, 90] and \e lon will be in the range [-180, 180). The scale
* of the projection is 1/\e rk<sup>2</sup> in the "radial" direction, \e
* azi clockwise from true north, and is 1/\e rk in the direction
* perpendicular to this. Even though all inputs should return a valid \e
* lat and \e lon, it's possible that the procedure fails to converge for
* very large \e x or \e y; in this case NaNs are returned for all the
* output arguments. A call to Reverse followed by a call to Forward will
* return the original (\e x, \e y) (to roundoff).
**********************************************************************/
void Reverse(real lat0, real lon0, real x, real y,
real& lat, real& lon, real& azi, real& rk) const throw();
/**
* The major radius of the ellipsoid (meters). This is that value of \e a
* inherited from the Geodesic object used in the constructor.
**********************************************************************/
Math::real MajorRadius() const throw() { return _earth.MajorRadius(); }
/**
* The inverse flattening of the ellipsoid. This is that value of \e r
* inherited from the Geodesic object used in the constructor. A value of
* 0 is returned for a sphere (infinite inverse flattening).
**********************************************************************/
Math::real InverseFlattening() const throw()
{ return _earth.InverseFlattening(); }
};
} // namespace GeographicLib
#endif
<|endoftext|> |
<commit_before>#include <QtDeclarative>
#include <QEventLoop>
#include <QGLFormat>
#include <QGLFramebufferObject>
#include <QGLWidget>
#include <QImage>
#include <QList>
#include <QPainter>
#include <QResizeEvent>
#include <QSize>
#include <QString>
#include <QVariant>
#include "webvfx/image.h"
#include "webvfx/qml_content.h"
#include "webvfx/webvfx.h"
namespace WebVfx
{
static bool s_QmlContentRegistered = false;
class PixmapProvider : public QDeclarativeImageProvider
{
public:
PixmapProvider(ContentContext* contentContext)
: QDeclarativeImageProvider(QDeclarativeImageProvider::Pixmap)
, contentContext(contentContext)
{
}
QPixmap requestPixmap(const QString& id, QSize* size, const QSize& requestedSize)
{
// URLs are of the form image://webvfx/<name>/<count>
// where <count> is a unique ID to force refresh and is ignored.
QImage image(contentContext->getImage(id.section('/', 0, 0)));
QPixmap pixmap(QPixmap::fromImage(image));
if (size)
*size = pixmap.size();
if (!requestedSize.isEmpty())
return pixmap.scaled(requestedSize, Qt::IgnoreAspectRatio,
Qt::SmoothTransformation);
return pixmap;
}
private:
ContentContext* contentContext;
};
////////////////////
QmlContent::QmlContent(QWidget* parent, const QSize& size, Parameters* parameters)
: QDeclarativeView(parent)
, pageLoadFinished(LoadNotFinished)
, contextLoadFinished(LoadNotFinished)
, contentContext(new ContentContext(this, parameters))
, syncLoop(0)
, multisampleFBO(0)
, resolveFBO(0)
{
if (!s_QmlContentRegistered) {
s_QmlContentRegistered = true;
qmlRegisterType<GraphicsCaptureEffect>("org.webvfx.WebVfx", 1, 0, "Capture");
}
// Add root of our qrc:/ resource path so embedded QML components are available.
engine()->addImportPath(":/");
// Turn off scrollbars
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setInteractive(false);
setResizeMode(QDeclarativeView::SizeRootObjectToView);
setResizeAnchor(QDeclarativeView::AnchorViewCenter);
resize(size);
// We render into FBOs, but need QGLWidget to create a GL context for us
QGLFormat format(QGL::SampleBuffers|QGL::AlphaChannel|QGL::SingleBuffer);
format.setSamples(4);
glWidget = new QGLWidget(format);
setViewport(glWidget);
createFBO(size);
// OpenGL needs this
setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
// Expose context to the QML
rootContext()->setContextProperty("webvfx", contentContext);
// Register image provider for image://webvfx/<name>/<counter>
engine()->addImageProvider(QLatin1String("webvfx"), new PixmapProvider(contentContext));
connect(this, SIGNAL(statusChanged(QDeclarativeView::Status)), SLOT(qmlViewStatusChanged(QDeclarativeView::Status)));
connect(engine(), SIGNAL(warnings(QList<QDeclarativeError>)), SLOT(logWarnings(QList<QDeclarativeError>)));
connect(contentContext, SIGNAL(readyRender(bool)), SLOT(contentContextLoadFinished(bool)));
}
QmlContent::~QmlContent()
{
delete multisampleFBO;
delete resolveFBO;
}
void QmlContent::qmlViewStatusChanged(QDeclarativeView::Status status)
{
if (status != QDeclarativeView::Ready && status != QDeclarativeView::Error)
return;
if (pageLoadFinished == LoadNotFinished)
pageLoadFinished = (status == QDeclarativeView::Ready) ? LoadSucceeded : LoadFailed;
if (syncLoop && (pageLoadFinished == LoadFailed ||
contextLoadFinished != LoadNotFinished))
syncLoop->exit(contextLoadFinished == LoadSucceeded && pageLoadFinished == LoadSucceeded);
}
void QmlContent::contentContextLoadFinished(bool result)
{
if (contextLoadFinished == LoadNotFinished)
contextLoadFinished = result ? LoadSucceeded : LoadFailed;
if (syncLoop && (contextLoadFinished == LoadFailed ||
pageLoadFinished != LoadNotFinished))
syncLoop->exit(contextLoadFinished == LoadSucceeded && pageLoadFinished == LoadSucceeded);
}
void QmlContent::logWarnings(const QList<QDeclarativeError>& warnings)
{
foreach (const QDeclarativeError& warning, warnings) {
log(warning.toString());
}
}
bool QmlContent::loadContent(const QUrl& url)
{
if (syncLoop) {
log("QmlContent::loadContent recursive call detected");
return false;
}
pageLoadFinished = LoadNotFinished;
contextLoadFinished = LoadNotFinished;
QSize originalSize(size());
setSource(url);
// XXX QDeclarativeView::SizeRootObjectToView is broken, so resize after loading
// http://bugreports.qt.nokia.com/browse/QTBUG-15863
setContentSize(originalSize);
bool result = false;
if (pageLoadFinished != LoadFailed
&& (pageLoadFinished == LoadNotFinished
|| contextLoadFinished == LoadNotFinished)) {
// Run a nested event loop which will be exited when both
// qmlViewStatusChanged and contentContextLoadFinished signal,
// returning the result code here.
// http://wiki.forum.nokia.com/index.php/How_to_wait_synchronously_for_a_Signal_in_Qt
// http://qt.gitorious.org/qt/qt/blobs/4.7/src/gui/dialogs/qdialog.cpp#line549
QEventLoop loop;
syncLoop = &loop;
result = loop.exec();
syncLoop = 0;
}
else
result = pageLoadFinished == LoadSucceeded && contextLoadFinished == LoadSucceeded;
logWarnings(errors());
return result;
}
void QmlContent::setContentSize(const QSize& size) {
QSize oldSize(this->size());
if (oldSize != size) {
resize(size);
createFBO(size);
// The resize event is delayed until we are shown.
// Since we are never shown, send the event here.
// Superclass does some calculations in resizeEvent
// (sizing and centering the scene etc.)
QResizeEvent event(size, oldSize);
resizeEvent(&event);
}
}
bool QmlContent::renderContent(double time, Image* renderImage)
{
// Allow the content to render for this time
contentContext->render(time);
if (!renderImage)
return false;
glWidget->makeCurrent();
// Render frame into multisample FBO
QPainter painter(multisampleFBO);
painter.setRenderHint(QPainter::Antialiasing, true);
painter.setRenderHint(QPainter::TextAntialiasing, true);
painter.setRenderHint(QPainter::SmoothPixmapTransform, true);
render(&painter);
painter.end();
// Blit from multisample to resolve FBO.
// Rects are setup so the image is vertically flipped when blitted
// so when we read the pixels back they are the right way up.
// OpenGL does everything "upside down".
QRect srcRect(0, 0, renderImage->width(), renderImage->height());
QRect dstRect(0, renderImage->height(),
renderImage->width(), -renderImage->height());
QGLFramebufferObject::blitFramebuffer(resolveFBO, srcRect,
multisampleFBO, dstRect);
// Read back the pixels from the resolve FBO, in the format our QImage needs
resolveFBO->bind();
glPushClientAttrib(GL_CLIENT_PIXEL_STORE_BIT);
glPixelStorei(GL_PACK_ALIGNMENT, 1);
glPixelStorei(GL_PACK_ROW_LENGTH, renderImage->bytesPerLine() / 3);
glReadPixels(0, 0, renderImage->width(), renderImage->height(),
QSysInfo::ByteOrder == QSysInfo::BigEndian ? GL_BGR : GL_RGB,
GL_UNSIGNED_BYTE, renderImage->pixels());
glPopClientAttrib();
resolveFBO->release();
glWidget->doneCurrent();
return true;
//XXX also check errors() after each render()
}
bool QmlContent::createFBO(const QSize& size)
{
if (!QGLFramebufferObject::hasOpenGLFramebufferObjects()
|| !QGLFramebufferObject::hasOpenGLFramebufferBlit()) {
log("QmlContent: FBOs not fully supported, rendering will fail");
return false;
}
// Create a multisample FBO and an FBO to resolve into
glWidget->makeCurrent();
QGLFramebufferObjectFormat fboFormat;
fboFormat.setSamples(4);
fboFormat.setTextureTarget(GL_TEXTURE_RECTANGLE_ARB);
fboFormat.setAttachment(QGLFramebufferObject::CombinedDepthStencil);
delete multisampleFBO;
multisampleFBO = new QGLFramebufferObject(size, fboFormat);
delete resolveFBO;
resolveFBO = new QGLFramebufferObject(size, GL_TEXTURE_RECTANGLE_ARB);
glWidget->doneCurrent();
return true;
}
}
<commit_msg>Fix QML content on MacOS.<commit_after>#include <QtDeclarative>
#include <QEventLoop>
#include <QGLFormat>
#include <QGLFramebufferObject>
#include <QGLWidget>
#include <QImage>
#include <QList>
#include <QPainter>
#include <QResizeEvent>
#include <QSize>
#include <QString>
#include <QVariant>
#include "webvfx/image.h"
#include "webvfx/qml_content.h"
#include "webvfx/webvfx.h"
namespace WebVfx
{
static bool s_QmlContentRegistered = false;
class PixmapProvider : public QDeclarativeImageProvider
{
public:
PixmapProvider(ContentContext* contentContext)
: QDeclarativeImageProvider(QDeclarativeImageProvider::Pixmap)
, contentContext(contentContext)
{
}
QPixmap requestPixmap(const QString& id, QSize* size, const QSize& requestedSize)
{
// URLs are of the form image://webvfx/<name>/<count>
// where <count> is a unique ID to force refresh and is ignored.
QImage image(contentContext->getImage(id.section('/', 0, 0)));
QPixmap pixmap(QPixmap::fromImage(image));
if (size)
*size = pixmap.size();
if (!requestedSize.isEmpty())
return pixmap.scaled(requestedSize, Qt::IgnoreAspectRatio,
Qt::SmoothTransformation);
return pixmap;
}
private:
ContentContext* contentContext;
};
////////////////////
QmlContent::QmlContent(QWidget* parent, const QSize& size, Parameters* parameters)
: QDeclarativeView(parent)
, pageLoadFinished(LoadNotFinished)
, contextLoadFinished(LoadNotFinished)
, contentContext(new ContentContext(this, parameters))
, syncLoop(0)
, multisampleFBO(0)
, resolveFBO(0)
{
if (!s_QmlContentRegistered) {
s_QmlContentRegistered = true;
qmlRegisterType<GraphicsCaptureEffect>("org.webvfx.WebVfx", 1, 0, "Capture");
}
// Add root of our qrc:/ resource path so embedded QML components are available.
engine()->addImportPath(":/");
// Turn off scrollbars
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setInteractive(false);
setResizeMode(QDeclarativeView::SizeRootObjectToView);
setResizeAnchor(QDeclarativeView::AnchorViewCenter);
resize(size);
// We render into FBOs, but need QGLWidget to create a GL context for us
glWidget = new QGLWidget();
setViewport(glWidget);
createFBO(size);
// OpenGL needs this
setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
// Expose context to the QML
rootContext()->setContextProperty("webvfx", contentContext);
// Register image provider for image://webvfx/<name>/<counter>
engine()->addImageProvider(QLatin1String("webvfx"), new PixmapProvider(contentContext));
connect(this, SIGNAL(statusChanged(QDeclarativeView::Status)), SLOT(qmlViewStatusChanged(QDeclarativeView::Status)));
connect(engine(), SIGNAL(warnings(QList<QDeclarativeError>)), SLOT(logWarnings(QList<QDeclarativeError>)));
connect(contentContext, SIGNAL(readyRender(bool)), SLOT(contentContextLoadFinished(bool)));
}
QmlContent::~QmlContent()
{
delete multisampleFBO;
delete resolveFBO;
}
void QmlContent::qmlViewStatusChanged(QDeclarativeView::Status status)
{
if (status != QDeclarativeView::Ready && status != QDeclarativeView::Error)
return;
if (pageLoadFinished == LoadNotFinished)
pageLoadFinished = (status == QDeclarativeView::Ready) ? LoadSucceeded : LoadFailed;
if (syncLoop && (pageLoadFinished == LoadFailed ||
contextLoadFinished != LoadNotFinished))
syncLoop->exit(contextLoadFinished == LoadSucceeded && pageLoadFinished == LoadSucceeded);
}
void QmlContent::contentContextLoadFinished(bool result)
{
if (contextLoadFinished == LoadNotFinished)
contextLoadFinished = result ? LoadSucceeded : LoadFailed;
if (syncLoop && (contextLoadFinished == LoadFailed ||
pageLoadFinished != LoadNotFinished))
syncLoop->exit(contextLoadFinished == LoadSucceeded && pageLoadFinished == LoadSucceeded);
}
void QmlContent::logWarnings(const QList<QDeclarativeError>& warnings)
{
foreach (const QDeclarativeError& warning, warnings) {
log(warning.toString());
}
}
bool QmlContent::loadContent(const QUrl& url)
{
if (syncLoop) {
log("QmlContent::loadContent recursive call detected");
return false;
}
pageLoadFinished = LoadNotFinished;
contextLoadFinished = LoadNotFinished;
QSize originalSize(size());
setSource(url);
// XXX QDeclarativeView::SizeRootObjectToView is broken, so resize after loading
// http://bugreports.qt.nokia.com/browse/QTBUG-15863
setContentSize(originalSize);
bool result = false;
if (pageLoadFinished != LoadFailed
&& (pageLoadFinished == LoadNotFinished
|| contextLoadFinished == LoadNotFinished)) {
// Run a nested event loop which will be exited when both
// qmlViewStatusChanged and contentContextLoadFinished signal,
// returning the result code here.
// http://wiki.forum.nokia.com/index.php/How_to_wait_synchronously_for_a_Signal_in_Qt
// http://qt.gitorious.org/qt/qt/blobs/4.7/src/gui/dialogs/qdialog.cpp#line549
QEventLoop loop;
syncLoop = &loop;
result = loop.exec();
syncLoop = 0;
}
else
result = pageLoadFinished == LoadSucceeded && contextLoadFinished == LoadSucceeded;
logWarnings(errors());
return result;
}
void QmlContent::setContentSize(const QSize& size) {
QSize oldSize(this->size());
if (oldSize != size) {
resize(size);
createFBO(size);
// The resize event is delayed until we are shown.
// Since we are never shown, send the event here.
// Superclass does some calculations in resizeEvent
// (sizing and centering the scene etc.)
QResizeEvent event(size, oldSize);
resizeEvent(&event);
}
}
bool QmlContent::renderContent(double time, Image* renderImage)
{
// Allow the content to render for this time
contentContext->render(time);
if (!renderImage)
return false;
glWidget->makeCurrent();
// Render frame into multisample FBO
QPainter painter(multisampleFBO);
painter.setRenderHint(QPainter::Antialiasing, true);
painter.setRenderHint(QPainter::TextAntialiasing, true);
painter.setRenderHint(QPainter::SmoothPixmapTransform, true);
render(&painter);
painter.end();
// Blit from multisample to resolve FBO.
// Rects are setup so the image is vertically flipped when blitted
// so when we read the pixels back they are the right way up.
// OpenGL does everything "upside down".
QRect srcRect(0, 0, renderImage->width(), renderImage->height());
QRect dstRect(0, renderImage->height(),
renderImage->width(), -renderImage->height());
QGLFramebufferObject::blitFramebuffer(resolveFBO, srcRect,
multisampleFBO, dstRect);
// Read back the pixels from the resolve FBO, in the format our QImage needs
resolveFBO->bind();
glPushClientAttrib(GL_CLIENT_PIXEL_STORE_BIT);
glPixelStorei(GL_PACK_ALIGNMENT, 1);
glPixelStorei(GL_PACK_ROW_LENGTH, renderImage->bytesPerLine() / 3);
glReadPixels(0, 0, renderImage->width(), renderImage->height(),
QSysInfo::ByteOrder == QSysInfo::BigEndian ? GL_BGR : GL_RGB,
GL_UNSIGNED_BYTE, renderImage->pixels());
glPopClientAttrib();
resolveFBO->release();
glWidget->doneCurrent();
return true;
//XXX also check errors() after each render()
}
bool QmlContent::createFBO(const QSize& size)
{
if (!QGLFramebufferObject::hasOpenGLFramebufferObjects()
|| !QGLFramebufferObject::hasOpenGLFramebufferBlit()) {
log("QmlContent: FBOs not fully supported, rendering will fail");
return false;
}
// Create a multisample FBO and an FBO to resolve into
glWidget->makeCurrent();
QGLFramebufferObjectFormat fboFormat;
fboFormat.setSamples(4);
fboFormat.setTextureTarget(GL_TEXTURE_RECTANGLE_ARB);
fboFormat.setAttachment(QGLFramebufferObject::CombinedDepthStencil);
delete multisampleFBO;
multisampleFBO = new QGLFramebufferObject(size, fboFormat);
delete resolveFBO;
resolveFBO = new QGLFramebufferObject(size, GL_TEXTURE_RECTANGLE_ARB);
glWidget->doneCurrent();
return true;
}
}
<|endoftext|> |
<commit_before>/* -*- c-basic-offset: 2 -*- */
/*
Copyright(C) 2011 Kentoku SHIBA
Copyright(C) 2011-2012 Kouhei Sutou <kou@clear-code.com>
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
*/
#include <mrn_mysql.h>
#include "mrn_index_table_name.hpp"
namespace mrn {
IndexTableName::IndexTableName(const char *table_name,
const char *mysql_index_name)
: table_name_(table_name),
mysql_index_name_(mysql_index_name) {
uchar encoded_mysql_index_name_multibyte[MRN_MAX_KEY_SIZE];
const uchar *mysql_index_name_multibyte =
reinterpret_cast<const uchar *>(mysql_index_name_);
encode(encoded_mysql_index_name_multibyte,
encoded_mysql_index_name_multibyte + MRN_MAX_KEY_SIZE,
mysql_index_name_multibyte,
mysql_index_name_multibyte + strlen(mysql_index_name_));
snprintf(name_, MRN_MAX_KEY_SIZE,
"%s-%s", table_name_, encoded_mysql_index_name_multibyte);
length_ = strlen(name_);
}
const char *IndexTableName::c_str() {
return name_;
}
size_t IndexTableName::length() {
return length_;
}
uint IndexTableName::encode(uchar *encoded_start,
uchar *encoded_end,
const uchar *mysql_string_start,
const uchar *mysql_string_end) {
MRN_DBUG_ENTER_METHOD();
int res1, res2;
my_wc_t wc;
my_charset_conv_mb_wc mb_wc = system_charset_info->cset->mb_wc;
my_charset_conv_wc_mb wc_mb = my_charset_filename.cset->wc_mb;
DBUG_PRINT("info", ("mroonga: in=%s", mysql_string_start));
encoded_end--;
uchar *encoded;
const uchar *mysql_string;
for (encoded = encoded_start, mysql_string = mysql_string_start;
mysql_string < mysql_string_end && encoded < encoded_end;
mysql_string += res1, encoded += res2)
{
if ((res1 = (*mb_wc)(NULL, &wc, mysql_string, mysql_string_end)) > 0)
{
if ((res2 = (*wc_mb)(NULL, wc, encoded, encoded_end)) <= 0)
{
break;
}
} else if (res1 == MY_CS_ILSEQ)
{
*encoded = *mysql_string;
res1 = 1;
res2 = 1;
} else {
break;
}
}
*encoded = '\0';
DBUG_PRINT("info", ("mroonga: out=%s", encoded_start));
DBUG_RETURN(encoded - encoded_start);
}
}
<commit_msg>Use meaningful name<commit_after>/* -*- c-basic-offset: 2 -*- */
/*
Copyright(C) 2011 Kentoku SHIBA
Copyright(C) 2011-2012 Kouhei Sutou <kou@clear-code.com>
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
*/
#include <mrn_mysql.h>
#include "mrn_index_table_name.hpp"
namespace mrn {
IndexTableName::IndexTableName(const char *table_name,
const char *mysql_index_name)
: table_name_(table_name),
mysql_index_name_(mysql_index_name) {
uchar encoded_mysql_index_name_multibyte[MRN_MAX_KEY_SIZE];
const uchar *mysql_index_name_multibyte =
reinterpret_cast<const uchar *>(mysql_index_name_);
encode(encoded_mysql_index_name_multibyte,
encoded_mysql_index_name_multibyte + MRN_MAX_KEY_SIZE,
mysql_index_name_multibyte,
mysql_index_name_multibyte + strlen(mysql_index_name_));
snprintf(name_, MRN_MAX_KEY_SIZE,
"%s-%s", table_name_, encoded_mysql_index_name_multibyte);
length_ = strlen(name_);
}
const char *IndexTableName::c_str() {
return name_;
}
size_t IndexTableName::length() {
return length_;
}
uint IndexTableName::encode(uchar *encoded_start,
uchar *encoded_end,
const uchar *mysql_string_start,
const uchar *mysql_string_end) {
MRN_DBUG_ENTER_METHOD();
int mb_wc_converted_length = 0;
int wc_mb_converted_length = 0;
my_wc_t wc;
my_charset_conv_mb_wc mb_wc = system_charset_info->cset->mb_wc;
my_charset_conv_wc_mb wc_mb = my_charset_filename.cset->wc_mb;
DBUG_PRINT("info", ("mroonga: in=%s", mysql_string_start));
encoded_end--;
uchar *encoded;
const uchar *mysql_string;
for (encoded = encoded_start,
mysql_string = mysql_string_start;
mysql_string < mysql_string_end &&
encoded < encoded_end;
mysql_string += mb_wc_converted_length,
encoded += wc_mb_converted_length)
{
mb_wc_converted_length =
(*mb_wc)(NULL, &wc, mysql_string, mysql_string_end);
if (mb_wc_converted_length > 0)
{
wc_mb_converted_length = (*wc_mb)(NULL, wc, encoded, encoded_end);
if (wc_mb_converted_length <= 0)
{
break;
}
} else if (mb_wc_converted_length == MY_CS_ILSEQ)
{
*encoded = *mysql_string;
mb_wc_converted_length = 1;
wc_mb_converted_length = 1;
} else {
break;
}
}
*encoded = '\0';
DBUG_PRINT("info", ("mroonga: out=%s", encoded_start));
DBUG_RETURN(encoded - encoded_start);
}
}
<|endoftext|> |
<commit_before>#pragma once
// https://infektor.net/posts/2017-03-31-range-based-enumerate.html
#include <iterator>
#include <utility>
// ----------------------------------------------------------------------
namespace acmacs
{
namespace _enumerate_internal
{
template <typename Iterator, typename index_type> struct enumerate_iterator
{
using iterator = Iterator;
//using index_type = typename std::iterator_traits<iterator>::difference_type;
using reference = typename std::iterator_traits<iterator>::reference;
inline enumerate_iterator(index_type aIndex, iterator aIterator) : index(aIndex), iter(aIterator) {}
inline enumerate_iterator& operator++() { ++index; ++iter; return *this; }
inline bool operator!=(const enumerate_iterator &other) const { return iter != other.iter; }
inline std::pair<index_type&, reference> operator*() { return {index, *iter}; }
private:
index_type index;
iterator iter;
};
// ----------------------------------------------------------------------
template <typename Iterator, typename index_type> struct enumerate_range
{
// using index_type = typename std::iterator_traits<Iterator>::difference_type;
using iterator = enumerate_iterator<Iterator, index_type>;
inline enumerate_range(Iterator aFirst, Iterator aLast, index_type aInitial) : first(aFirst), last(aLast), initial(aInitial) {}
inline iterator begin() const { return iterator(initial, first); }
inline iterator end() const { return iterator(0, last); }
private:
Iterator first;
Iterator last;
index_type initial;
};
} // namespace _enumerate_internal
// ----------------------------------------------------------------------
template <typename Iterator, typename index_type> inline auto enumerate(Iterator first, Iterator last, index_type initial = 0)
{
return _enumerate_internal::enumerate_range<Iterator, index_type>(first, last, initial);
}
template <typename Container> inline auto enumerate(Container& content, size_t initial = 0)
{
using iter_type = decltype(std::begin(content));
return _enumerate_internal::enumerate_range<iter_type, size_t>(std::begin(content), std::end(content), initial);
}
template <typename Container> inline auto enumerate(const Container& content, size_t initial = 0)
{
using iter_type = decltype(std::begin(content));
return _enumerate_internal::enumerate_range<iter_type, size_t>(std::begin(content), std::end(content), initial);
}
} // namespace acmacs
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>minor fix<commit_after>#pragma once
// https://infektor.net/posts/2017-03-31-range-based-enumerate.html
#include <iterator>
#include <utility>
// ----------------------------------------------------------------------
namespace acmacs
{
namespace _enumerate_internal
{
template <typename Iterator, typename index_type> struct enumerate_iterator
{
using iterator = Iterator;
//using index_type = typename std::iterator_traits<iterator>::difference_type;
using reference = typename std::iterator_traits<iterator>::reference;
inline enumerate_iterator(index_type aIndex, iterator aIterator) : index(aIndex), iter(aIterator) {}
inline enumerate_iterator& operator++() { ++index; ++iter; return *this; }
inline bool operator!=(const enumerate_iterator &other) const { return iter != other.iter; }
inline std::pair<index_type, reference> operator*() { return {index, *iter}; }
private:
index_type index;
iterator iter;
};
// ----------------------------------------------------------------------
template <typename Iterator, typename index_type> struct enumerate_range
{
// using index_type = typename std::iterator_traits<Iterator>::difference_type;
using iterator = enumerate_iterator<Iterator, index_type>;
inline enumerate_range(Iterator aFirst, Iterator aLast, index_type aInitial) : first(aFirst), last(aLast), initial(aInitial) {}
inline iterator begin() const { return iterator(initial, first); }
inline iterator end() const { return iterator(0, last); }
private:
Iterator first;
Iterator last;
index_type initial;
};
} // namespace _enumerate_internal
// ----------------------------------------------------------------------
template <typename Iterator, typename index_type> inline auto enumerate(Iterator first, Iterator last, index_type initial = 0)
{
return _enumerate_internal::enumerate_range<Iterator, index_type>(first, last, initial);
}
template <typename Container> inline auto enumerate(Container& content, size_t initial = 0)
{
using iter_type = decltype(std::begin(content));
return _enumerate_internal::enumerate_range<iter_type, size_t>(std::begin(content), std::end(content), initial);
}
template <typename Container> inline auto enumerate(const Container& content, size_t initial = 0)
{
using iter_type = decltype(std::begin(content));
return _enumerate_internal::enumerate_range<iter_type, size_t>(std::begin(content), std::end(content), initial);
}
} // namespace acmacs
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2012 The WebM 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 <climits>
#include <vector>
#include "third_party/googletest/src/include/gtest/gtest.h"
#include "test/codec_factory.h"
#include "test/encode_test_driver.h"
#include "test/i420_video_source.h"
#include "test/util.h"
namespace {
class CpuSpeedTest : public ::libvpx_test::EncoderTest,
public ::libvpx_test::CodecTestWith2Params<
libvpx_test::TestMode, int> {
protected:
CpuSpeedTest()
: EncoderTest(GET_PARAM(0)),
encoding_mode_(GET_PARAM(1)),
set_cpu_used_(GET_PARAM(2)) {}
virtual ~CpuSpeedTest() {}
virtual void SetUp() {
InitializeConfig();
SetMode(encoding_mode_);
if (encoding_mode_ != ::libvpx_test::kRealTime) {
cfg_.g_lag_in_frames = 25;
cfg_.rc_end_usage = VPX_VBR;
} else {
cfg_.g_lag_in_frames = 0;
cfg_.rc_end_usage = VPX_CBR;
}
}
virtual void PreEncodeFrameHook(::libvpx_test::VideoSource *video,
::libvpx_test::Encoder *encoder) {
if (video->frame() == 1) {
encoder->Control(VP8E_SET_CPUUSED, set_cpu_used_);
if (encoding_mode_ != ::libvpx_test::kRealTime) {
encoder->Control(VP8E_SET_ENABLEAUTOALTREF, 1);
encoder->Control(VP8E_SET_ARNR_MAXFRAMES, 7);
encoder->Control(VP8E_SET_ARNR_STRENGTH, 5);
encoder->Control(VP8E_SET_ARNR_TYPE, 3);
}
}
}
virtual void FramePktHook(const vpx_codec_cx_pkt_t *pkt) {
if (pkt->data.frame.flags & VPX_FRAME_IS_KEY) {
}
}
::libvpx_test::TestMode encoding_mode_;
int set_cpu_used_;
};
TEST_P(CpuSpeedTest, TestQ0) {
// Validate that this non multiple of 64 wide clip encodes and decodes
// without a mismatch when passing in a very low max q. This pushes
// the encoder to producing lots of big partitions which will likely
// extend into the border and test the border condition.
cfg_.rc_2pass_vbr_minsection_pct = 5;
cfg_.rc_2pass_vbr_minsection_pct = 2000;
cfg_.rc_target_bitrate = 400;
cfg_.rc_max_quantizer = 0;
cfg_.rc_min_quantizer = 0;
::libvpx_test::I420VideoSource video("hantro_odd.yuv", 208, 144, 30, 1, 0,
20);
ASSERT_NO_FATAL_FAILURE(RunLoop(&video));
}
TEST_P(CpuSpeedTest, TestEncodeHighBitrate) {
// Validate that this non multiple of 64 wide clip encodes and decodes
// without a mismatch when passing in a very low max q. This pushes
// the encoder to producing lots of big partitions which will likely
// extend into the border and test the border condition.
cfg_.rc_2pass_vbr_minsection_pct = 5;
cfg_.rc_2pass_vbr_minsection_pct = 2000;
cfg_.rc_target_bitrate = 12000;
cfg_.rc_max_quantizer = 10;
cfg_.rc_min_quantizer = 0;
::libvpx_test::I420VideoSource video("hantro_odd.yuv", 208, 144, 30, 1, 0,
20);
ASSERT_NO_FATAL_FAILURE(RunLoop(&video));
}
TEST_P(CpuSpeedTest, TestLowBitrate) {
// Validate that this clip encodes and decodes without a mismatch
// when passing in a very high min q. This pushes the encoder to producing
// lots of small partitions which might will test the other condition.
cfg_.rc_2pass_vbr_minsection_pct = 5;
cfg_.rc_2pass_vbr_minsection_pct = 2000;
cfg_.rc_target_bitrate = 200;
cfg_.rc_min_quantizer = 40;
::libvpx_test::I420VideoSource video("hantro_odd.yuv", 208, 144, 30, 1, 0,
20);
ASSERT_NO_FATAL_FAILURE(RunLoop(&video));
}
using std::tr1::make_tuple;
#define VP9_FACTORY \
static_cast<const libvpx_test::CodecFactory*> (&libvpx_test::kVP9)
VP9_INSTANTIATE_TEST_CASE(
CpuSpeedTest,
::testing::Values(::libvpx_test::kTwoPassGood, ::libvpx_test::kOnePassGood,
::libvpx_test::kRealTime),
::testing::Range(0, 8));
} // namespace
<commit_msg>Verify that the ouput of q0 is lossless in cpu speed test.<commit_after>/*
* Copyright (c) 2012 The WebM 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 <climits>
#include <vector>
#include "third_party/googletest/src/include/gtest/gtest.h"
#include "test/codec_factory.h"
#include "test/encode_test_driver.h"
#include "test/i420_video_source.h"
#include "test/util.h"
namespace {
const int kMaxPSNR = 100;
class CpuSpeedTest : public ::libvpx_test::EncoderTest,
public ::libvpx_test::CodecTestWith2Params<
libvpx_test::TestMode, int> {
protected:
CpuSpeedTest()
: EncoderTest(GET_PARAM(0)),
encoding_mode_(GET_PARAM(1)),
set_cpu_used_(GET_PARAM(2)),
min_psnr_(kMaxPSNR) {}
virtual ~CpuSpeedTest() {}
virtual void SetUp() {
InitializeConfig();
SetMode(encoding_mode_);
if (encoding_mode_ != ::libvpx_test::kRealTime) {
cfg_.g_lag_in_frames = 25;
cfg_.rc_end_usage = VPX_VBR;
} else {
cfg_.g_lag_in_frames = 0;
cfg_.rc_end_usage = VPX_CBR;
}
}
virtual void BeginPassHook(unsigned int /*pass*/) {
min_psnr_ = kMaxPSNR;
}
virtual void PreEncodeFrameHook(::libvpx_test::VideoSource *video,
::libvpx_test::Encoder *encoder) {
if (video->frame() == 1) {
encoder->Control(VP8E_SET_CPUUSED, set_cpu_used_);
if (encoding_mode_ != ::libvpx_test::kRealTime) {
encoder->Control(VP8E_SET_ENABLEAUTOALTREF, 1);
encoder->Control(VP8E_SET_ARNR_MAXFRAMES, 7);
encoder->Control(VP8E_SET_ARNR_STRENGTH, 5);
encoder->Control(VP8E_SET_ARNR_TYPE, 3);
}
}
}
virtual void FramePktHook(const vpx_codec_cx_pkt_t *pkt) {
if (pkt->data.frame.flags & VPX_FRAME_IS_KEY) {
}
}
virtual void PSNRPktHook(const vpx_codec_cx_pkt_t *pkt) {
if (pkt->data.psnr.psnr[0] < min_psnr_)
min_psnr_ = pkt->data.psnr.psnr[0];
}
::libvpx_test::TestMode encoding_mode_;
int set_cpu_used_;
double min_psnr_;
};
TEST_P(CpuSpeedTest, TestQ0) {
// Validate that this non multiple of 64 wide clip encodes and decodes
// without a mismatch when passing in a very low max q. This pushes
// the encoder to producing lots of big partitions which will likely
// extend into the border and test the border condition.
cfg_.rc_2pass_vbr_minsection_pct = 5;
cfg_.rc_2pass_vbr_minsection_pct = 2000;
cfg_.rc_target_bitrate = 400;
cfg_.rc_max_quantizer = 0;
cfg_.rc_min_quantizer = 0;
::libvpx_test::I420VideoSource video("hantro_odd.yuv", 208, 144, 30, 1, 0,
20);
init_flags_ = VPX_CODEC_USE_PSNR;
ASSERT_NO_FATAL_FAILURE(RunLoop(&video));
EXPECT_GE(min_psnr_, kMaxPSNR);
}
TEST_P(CpuSpeedTest, TestEncodeHighBitrate) {
// Validate that this non multiple of 64 wide clip encodes and decodes
// without a mismatch when passing in a very low max q. This pushes
// the encoder to producing lots of big partitions which will likely
// extend into the border and test the border condition.
cfg_.rc_2pass_vbr_minsection_pct = 5;
cfg_.rc_2pass_vbr_minsection_pct = 2000;
cfg_.rc_target_bitrate = 12000;
cfg_.rc_max_quantizer = 10;
cfg_.rc_min_quantizer = 0;
::libvpx_test::I420VideoSource video("hantro_odd.yuv", 208, 144, 30, 1, 0,
20);
ASSERT_NO_FATAL_FAILURE(RunLoop(&video));
}
TEST_P(CpuSpeedTest, TestLowBitrate) {
// Validate that this clip encodes and decodes without a mismatch
// when passing in a very high min q. This pushes the encoder to producing
// lots of small partitions which might will test the other condition.
cfg_.rc_2pass_vbr_minsection_pct = 5;
cfg_.rc_2pass_vbr_minsection_pct = 2000;
cfg_.rc_target_bitrate = 200;
cfg_.rc_min_quantizer = 40;
::libvpx_test::I420VideoSource video("hantro_odd.yuv", 208, 144, 30, 1, 0,
20);
ASSERT_NO_FATAL_FAILURE(RunLoop(&video));
}
using std::tr1::make_tuple;
#define VP9_FACTORY \
static_cast<const libvpx_test::CodecFactory*> (&libvpx_test::kVP9)
VP9_INSTANTIATE_TEST_CASE(
CpuSpeedTest,
::testing::Values(::libvpx_test::kTwoPassGood, ::libvpx_test::kOnePassGood,
::libvpx_test::kRealTime),
::testing::Range(0, 8));
} // namespace
<|endoftext|> |
<commit_before>#pragma once
#include <string>
#include <variant>
#include <functional>
#include <iostream>
#include <fstream>
#include "acmacs-base/filesystem.hh"
// ----------------------------------------------------------------------
namespace acmacs::file
{
enum class ForceCompression { No, Yes };
enum class BackupFile { No, Yes };
// ----------------------------------------------------------------------
inline bool exists(std::string aFilename) { return fs::exists(aFilename); }
std::string decompress_if_necessary(std::string_view aSource);
// ----------------------------------------------------------------------
class file_error : public std::runtime_error { public: using std::runtime_error::runtime_error; };
class not_opened : public file_error { public: not_opened(std::string aMsg) : file_error("cannot open " + aMsg) {} };
class cannot_read : public file_error { public: cannot_read(std::string aMsg) : file_error("cannot read " + aMsg) {} };
class not_found : public file_error { public: not_found(std::string aFilename) : file_error("not found: " + aFilename) {} };
class read_access
{
public:
read_access() = default;
read_access(std::string aFilename);
~read_access();
read_access(const read_access&) = delete;
read_access(read_access&&);
read_access& operator=(const read_access&) = delete;
read_access& operator=(read_access&&);
operator std::string() const { return decompress_if_necessary({mapped, len}); }
size_t size() const { return len; }
const char* data() const { return mapped; }
bool valid() const { return mapped != nullptr; }
private:
int fd = -1;
size_t len = 0;
char* mapped = nullptr;
}; // class read_access
inline read_access read(std::string aFilename) { return {aFilename}; }
std::string read_from_file_descriptor(int fd, size_t chunk_size = 1024);
inline std::string read_stdin() { return read_from_file_descriptor(0); }
void write(std::string aFilename, std::string_view aData, ForceCompression aForceCompression = ForceCompression::No, BackupFile aBackupFile = BackupFile::Yes);
inline void write(std::string_view aFilename, std::string_view aData, ForceCompression aForceCompression = ForceCompression::No, BackupFile aBackupFile = BackupFile::Yes) { write(std::string(aFilename), aData, aForceCompression, aBackupFile); }
void backup(std::string aFilename);
// ----------------------------------------------------------------------
class temp
{
public:
temp(std::string prefix, std::string suffix);
temp(std::string suffix);
~temp();
inline temp& operator = (temp&& aFrom) noexcept { name = std::move(aFrom.name); fd = aFrom.fd; aFrom.name.clear(); return *this; }
inline operator std::string() const { return name; }
inline operator int() const { return fd; }
private:
std::string name;
int fd;
std::string make_template(std::string prefix);
}; // class temp
class ifstream
{
public:
ifstream(std::string filename) : backend_(std::cin)
{
if (filename != "-")
backend_ = std::ifstream(filename);
}
ifstream(std::string_view filename) : ifstream(std::string(filename)) {}
std::istream& stream()
{
return std::visit([](auto&& stream) -> std::istream& { return stream; }, backend_);
}
operator std::istream&() { return stream(); }
std::string read() { return {std::istreambuf_iterator<char>(stream()), {}}; }
private:
std::variant<std::reference_wrapper<std::istream>,std::ifstream> backend_;
};
class ofstream
{
public:
ofstream(std::string filename) : backend_(std::cout)
{
if (filename == "=")
backend_ = std::cerr;
else if (filename != "-")
backend_ = std::ofstream(filename);
}
ofstream(std::string_view filename) : ofstream(std::string(filename)) {}
std::ostream& stream()
{
return std::visit([](auto&& stream) -> std::ostream& { return stream; }, backend_);
}
operator std::ostream&() { return stream(); }
private:
std::variant<std::reference_wrapper<std::ostream>,std::ofstream> backend_;
};
} // namespace acmacs::file
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>minor improvement<commit_after>#pragma once
#include <string>
#include <variant>
#include <functional>
#include <iostream>
#include <fstream>
#include "acmacs-base/filesystem.hh"
// ----------------------------------------------------------------------
namespace acmacs::file
{
enum class ForceCompression { No, Yes };
enum class BackupFile { No, Yes };
// ----------------------------------------------------------------------
inline bool exists(std::string aFilename) { return fs::exists(aFilename); }
std::string decompress_if_necessary(std::string_view aSource);
// ----------------------------------------------------------------------
class file_error : public std::runtime_error { public: using std::runtime_error::runtime_error; };
class not_opened : public file_error { public: not_opened(std::string aMsg) : file_error("cannot open " + aMsg) {} };
class cannot_read : public file_error { public: cannot_read(std::string aMsg) : file_error("cannot read " + aMsg) {} };
class not_found : public file_error { public: not_found(std::string aFilename) : file_error("not found: " + aFilename) {} };
class read_access
{
public:
read_access() = default;
read_access(std::string aFilename);
~read_access();
read_access(const read_access&) = delete;
read_access(read_access&&);
read_access& operator=(const read_access&) = delete;
read_access& operator=(read_access&&);
operator std::string() const { return decompress_if_necessary({mapped, len}); }
size_t size() const { return len; }
const char* data() const { return mapped; }
bool valid() const { return mapped != nullptr; }
private:
int fd = -1;
size_t len = 0;
char* mapped = nullptr;
}; // class read_access
inline read_access read(std::string aFilename) { return {aFilename}; }
std::string read_from_file_descriptor(int fd, size_t chunk_size = 1024);
inline std::string read_stdin() { return read_from_file_descriptor(0); }
void write(std::string aFilename, std::string_view aData, ForceCompression aForceCompression = ForceCompression::No, BackupFile aBackupFile = BackupFile::Yes);
inline void write(std::string_view aFilename, std::string_view aData, ForceCompression aForceCompression = ForceCompression::No, BackupFile aBackupFile = BackupFile::Yes) { write(std::string(aFilename), aData, aForceCompression, aBackupFile); }
void backup(std::string aFilename);
// ----------------------------------------------------------------------
class temp
{
public:
temp(std::string prefix, std::string suffix);
temp(std::string suffix);
~temp();
inline temp& operator = (temp&& aFrom) noexcept { name = std::move(aFrom.name); fd = aFrom.fd; aFrom.name.clear(); return *this; }
inline operator std::string() const { return name; }
inline operator int() const { return fd; }
private:
std::string name;
int fd;
std::string make_template(std::string prefix);
}; // class temp
class ifstream
{
public:
ifstream(std::string filename) : backend_(std::cin)
{
if (filename != "-")
backend_ = std::ifstream(filename);
}
ifstream(std::string_view filename) : ifstream(std::string(filename)) {}
std::istream& stream()
{
return std::visit([](auto&& stream) -> std::istream& { return stream; }, backend_);
}
operator std::istream&() { return stream(); }
std::string read() { return {std::istreambuf_iterator<char>(stream()), {}}; }
private:
std::variant<std::reference_wrapper<std::istream>,std::ifstream> backend_;
};
class ofstream
{
public:
ofstream(std::string filename) : backend_(std::cout)
{
if (filename == "=")
backend_ = std::cerr;
else if (filename != "-")
backend_ = std::ofstream(filename);
}
ofstream(std::string_view filename) : ofstream(std::string(filename)) {}
std::ostream& stream()
{
return std::visit([](auto&& stream) -> std::ostream& { return stream; }, backend_);
}
std::ostream& operator*() { return stream(); }
operator std::ostream&() { return stream(); }
private:
std::variant<std::reference_wrapper<std::ostream>,std::ofstream> backend_;
};
} // namespace acmacs::file
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|endoftext|> |
<commit_before>/**
* This file is part of the CernVM file system
*/
#include "sync_item.h"
#include <errno.h>
#include "sync_mediator.h"
using namespace std; // NOLINT
namespace publish {
SyncItem::SyncItem() :
union_engine_(NULL),
whiteout_(false),
scratch_type_(static_cast<SyncItemType>(0)),
rdonly_type_(static_cast<SyncItemType>(0))
{
}
SyncItem::SyncItem(const string &relative_parent_path,
const string &filename,
const SyncItemType entry_type,
const SyncUnion *union_engine) :
union_engine_(union_engine),
whiteout_(false),
relative_parent_path_(relative_parent_path),
filename_(filename),
scratch_type_(entry_type),
rdonly_type_(GetRdOnlyFiletype())
{
content_hash_.algorithm = shash::kAny;
}
SyncItemType SyncItem::GetRdOnlyFiletype() const {
StatRdOnly();
if (rdonly_stat_.error_code == ENOENT) return kItemNew;
if (S_ISDIR(rdonly_stat_.stat.st_mode)) return kItemDir;
if (S_ISREG(rdonly_stat_.stat.st_mode)) return kItemFile;
if (S_ISLNK(rdonly_stat_.stat.st_mode)) return kItemSymlink;
PrintWarning("'" + GetRelativePath() + "' has an unsupported file type!");
abort();
}
void SyncItem::MarkAsWhiteout(const std::string &actual_filename) {
// Mark the file as whiteout entry and strip the whiteout prefix
whiteout_ = true;
filename_ = actual_filename;
// Find the entry in the repository
StatRdOnly(true); // <== refreshing the stat (filename might have changed)
if (rdonly_stat_.error_code != 0) {
PrintWarning("'" + GetRelativePath() + "' should be deleted, but was not "
"found in repository.");
abort();
return;
}
// What is deleted?
rdonly_type_ = GetRdOnlyFiletype();
scratch_type_ = GetRdOnlyFiletype();
}
unsigned int SyncItem::GetRdOnlyLinkcount() const {
StatRdOnly();
return rdonly_stat_.stat.st_nlink;
}
uint64_t SyncItem::GetRdOnlyInode() const {
StatRdOnly();
return rdonly_stat_.stat.st_ino;
}
unsigned int SyncItem::GetUnionLinkcount() const {
StatUnion();
return union_stat_.stat.st_nlink;
}
uint64_t SyncItem::GetUnionInode() const {
StatUnion();
return union_stat_.stat.st_ino;
}
void SyncItem::StatGeneric(const string &path,
EntryStat *info,
const bool refresh) {
if (info->obtained && !refresh) return;
int retval = platform_lstat(path.c_str(), &info->stat);
info->error_code = (retval != 0) ? errno : 0;
info->obtained = true;
}
bool SyncItem::IsOpaqueDirectory() const {
if (!IsDirectory()) {
return false;
}
return union_engine_->IsOpaqueDirectory(*this);
}
catalog::DirectoryEntryBase SyncItem::CreateBasicCatalogDirent() const {
catalog::DirectoryEntryBase dirent;
// inode and parent inode is determined at runtime of client
dirent.inode_ = catalog::DirectoryEntry::kInvalidInode;
dirent.parent_inode_ = catalog::DirectoryEntry::kInvalidInode;
dirent.linkcount_ = this->GetUnionStat().st_nlink; // TODO: is this a good idea here?
dirent.mode_ = this->GetUnionStat().st_mode;
dirent.uid_ = this->GetUnionStat().st_uid;
dirent.gid_ = this->GetUnionStat().st_gid;
dirent.size_ = this->GetUnionStat().st_size;
dirent.mtime_ = this->GetUnionStat().st_mtime;
dirent.checksum_ = this->GetContentHash();
dirent.name_.Assign(filename_.data(), filename_.length());
if (this->IsSymlink()) {
char slnk[PATH_MAX+1];
const ssize_t length = readlink((this->GetUnionPath()).c_str(), slnk, PATH_MAX);
assert(length >= 0);
dirent.symlink_.Assign(slnk, length);
}
return dirent;
}
std::string SyncItem::GetRdOnlyPath() const {
const string relative_path = GetRelativePath().empty() ?
"" : "/" + GetRelativePath();
return union_engine_->rdonly_path() + relative_path;
}
std::string SyncItem::GetUnionPath() const {
const string relative_path = GetRelativePath().empty() ?
"" : "/" + GetRelativePath();
return union_engine_->union_path() + relative_path;
}
std::string SyncItem::GetScratchPath() const {
const string relative_path = GetRelativePath().empty() ?
"" : "/" + GetRelativePath();
return union_engine_->scratch_path() + relative_path;
}
} // namespace sync
<commit_msg>add verbosity to error message<commit_after>/**
* This file is part of the CernVM file system
*/
#include "sync_item.h"
#include <errno.h>
#include "sync_mediator.h"
using namespace std; // NOLINT
namespace publish {
SyncItem::SyncItem() :
union_engine_(NULL),
whiteout_(false),
scratch_type_(static_cast<SyncItemType>(0)),
rdonly_type_(static_cast<SyncItemType>(0))
{
}
SyncItem::SyncItem(const string &relative_parent_path,
const string &filename,
const SyncItemType entry_type,
const SyncUnion *union_engine) :
union_engine_(union_engine),
whiteout_(false),
relative_parent_path_(relative_parent_path),
filename_(filename),
scratch_type_(entry_type),
rdonly_type_(GetRdOnlyFiletype())
{
content_hash_.algorithm = shash::kAny;
}
SyncItemType SyncItem::GetRdOnlyFiletype() const {
StatRdOnly();
if (rdonly_stat_.error_code == ENOENT) return kItemNew;
if (S_ISDIR(rdonly_stat_.stat.st_mode)) return kItemDir;
if (S_ISREG(rdonly_stat_.stat.st_mode)) return kItemFile;
if (S_ISLNK(rdonly_stat_.stat.st_mode)) return kItemSymlink;
PrintWarning("'" + GetRelativePath() + "' has an unsupported file type "
"(st_mode: " + StringifyInt(rdonly_stat_.stat.st_mode) +
" errno: " + StringifyInt(rdonly_stat_.error_code) + ")");
abort();
}
void SyncItem::MarkAsWhiteout(const std::string &actual_filename) {
// Mark the file as whiteout entry and strip the whiteout prefix
whiteout_ = true;
filename_ = actual_filename;
// Find the entry in the repository
StatRdOnly(true); // <== refreshing the stat (filename might have changed)
if (rdonly_stat_.error_code != 0) {
PrintWarning("'" + GetRelativePath() + "' should be deleted, but was not "
"found in repository.");
abort();
return;
}
// What is deleted?
rdonly_type_ = GetRdOnlyFiletype();
scratch_type_ = GetRdOnlyFiletype();
}
unsigned int SyncItem::GetRdOnlyLinkcount() const {
StatRdOnly();
return rdonly_stat_.stat.st_nlink;
}
uint64_t SyncItem::GetRdOnlyInode() const {
StatRdOnly();
return rdonly_stat_.stat.st_ino;
}
unsigned int SyncItem::GetUnionLinkcount() const {
StatUnion();
return union_stat_.stat.st_nlink;
}
uint64_t SyncItem::GetUnionInode() const {
StatUnion();
return union_stat_.stat.st_ino;
}
void SyncItem::StatGeneric(const string &path,
EntryStat *info,
const bool refresh) {
if (info->obtained && !refresh) return;
int retval = platform_lstat(path.c_str(), &info->stat);
info->error_code = (retval != 0) ? errno : 0;
info->obtained = true;
}
bool SyncItem::IsOpaqueDirectory() const {
if (!IsDirectory()) {
return false;
}
return union_engine_->IsOpaqueDirectory(*this);
}
catalog::DirectoryEntryBase SyncItem::CreateBasicCatalogDirent() const {
catalog::DirectoryEntryBase dirent;
// inode and parent inode is determined at runtime of client
dirent.inode_ = catalog::DirectoryEntry::kInvalidInode;
dirent.parent_inode_ = catalog::DirectoryEntry::kInvalidInode;
dirent.linkcount_ = this->GetUnionStat().st_nlink; // TODO: is this a good idea here?
dirent.mode_ = this->GetUnionStat().st_mode;
dirent.uid_ = this->GetUnionStat().st_uid;
dirent.gid_ = this->GetUnionStat().st_gid;
dirent.size_ = this->GetUnionStat().st_size;
dirent.mtime_ = this->GetUnionStat().st_mtime;
dirent.checksum_ = this->GetContentHash();
dirent.name_.Assign(filename_.data(), filename_.length());
if (this->IsSymlink()) {
char slnk[PATH_MAX+1];
const ssize_t length = readlink((this->GetUnionPath()).c_str(), slnk, PATH_MAX);
assert(length >= 0);
dirent.symlink_.Assign(slnk, length);
}
return dirent;
}
std::string SyncItem::GetRdOnlyPath() const {
const string relative_path = GetRelativePath().empty() ?
"" : "/" + GetRelativePath();
return union_engine_->rdonly_path() + relative_path;
}
std::string SyncItem::GetUnionPath() const {
const string relative_path = GetRelativePath().empty() ?
"" : "/" + GetRelativePath();
return union_engine_->union_path() + relative_path;
}
std::string SyncItem::GetScratchPath() const {
const string relative_path = GetRelativePath().empty() ?
"" : "/" + GetRelativePath();
return union_engine_->scratch_path() + relative_path;
}
} // namespace sync
<|endoftext|> |
<commit_before>//---------------------------------------------------------------------------//
/*
Copyright (c) 2012, Stuart R. Slattery
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 University of Wisconsin - Madison nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
//---------------------------------------------------------------------------//
/*!
* \file DTK_GeometryManager_def.hpp
* \author Stuart R. Slattery
* \brief Geometry manager definition.
*/
//---------------------------------------------------------------------------//
#ifndef DTK_GEOMETRYMANAGER_DEF_HPP
#define DTK_GEOMETRYMANAGER_DEF_HPP
#include "DTK_Assertion.hpp"
#include "DataTransferKit_config.hpp"
#include <Teuchos_CommHelpers.hpp>
namespace DataTransferKit
{
//---------------------------------------------------------------------------//
/*!
* \brief Constructor. If Design-By-Contract is enabled, the constructor will
* validate the geometry description to the domain model. This requires a few
* global communications.
*
* \param geometry The geometry that this object is managing. This geometry
* must have GeometryTraits.
*
* \param geom_gids The global ordinals for the geometry this object is
* managing.
*
* \param comm The communicator over which the geometry is defined.
*
* \param dim The dimension of the geometry.
*/
template<class Geometry,class GlobalOrdinal>
GeometryManager<Geometry,GlobalOrdinal>::GeometryManager(
const Teuchos::ArrayRCP<Geometry>& geometry,
const Teuchos::ArrayRCP<GlobalOrdinal>& geom_gids,
const RCP_Comm& comm, const int dim )
: d_geometry( geometry )
, d_geom_gids( geom_gids )
, d_comm( comm )
, d_dim( dim )
{
testPrecondition( d_geometry.size() == d_geom_gids.size() );
// If we're checking with Design-by-Contract, validate the geometry to the
// domain model.
#if HAVE_DTK_DBC
validate();
#endif
}
//---------------------------------------------------------------------------//
/*!
* \brief Destructor.
*/
template<class Geometry,class GlobalOrdinal>
GeometryManager<Geometry,GlobalOrdinal>::~GeometryManager()
{ /* ... */ }
//---------------------------------------------------------------------------//
/*!
* \brief Get the global number of objects owned by this manager.
*
* \return The global number of objects owned by this manager.
*/
template<class Geometry,class GlobalOrdinal>
const typename Teuchos::ArrayRCP<Geometry>::size_type
GeometryManager<Geometry,GlobalOrdinal>::globalNumGeometry() const
{
typename Teuchos::ArrayRCP<Geometry>::size_type global_size =
d_geometry.size();
typename Teuchos::ArrayRCP<Geometry>::size_type global_size_copy =
d_geometry.size();
Teuchos::reduceAll<int,typename Teuchos::ArrayRCP<Geometry>::size_type>(
*d_comm, Teuchos::REDUCE_SUM, 1, &global_size, &global_size_copy );
return global_size_copy;
}
//---------------------------------------------------------------------------//
/*!
* \brief Get the bounding boxes for the objects owned by this manager.
*
* \return The bounding boxes for the geometry owned by this manager.
*/
template<class Geometry,class GlobalOrdinal>
Teuchos::Array<BoundingBox>
GeometryManager<Geometry,GlobalOrdinal>::boundingBoxes() const
{
Teuchos::Array<BoundingBox> boxes( d_geometry.size() );
Teuchos::Array<BoundingBox>::iterator box_iterator;
typename Teuchos::ArrayRCP<Geometry>::const_iterator geom_iterator;
for ( geom_iterator = d_geometry.begin(), box_iterator = boxes.begin();
geom_iterator != d_geometry.end();
++geom_iterator, ++box_iterator )
{
*box_iterator = GT::boundingBox( *geom_iterator );
}
return boxes;
}
//---------------------------------------------------------------------------//
/*!
* \brief Get the local bounding box for the objects owned by this manager.
*/
template<class Geometry,class GlobalOrdinal>
BoundingBox GeometryManager<Geometry,GlobalOrdinal>::localBoundingBox() const
{
double global_x_min = Teuchos::ScalarTraits<double>::rmax();
double global_y_min = Teuchos::ScalarTraits<double>::rmax();
double global_z_min = Teuchos::ScalarTraits<double>::rmax();
double global_x_max = -Teuchos::ScalarTraits<double>::rmax();
double global_y_max = -Teuchos::ScalarTraits<double>::rmax();
double global_z_max = -Teuchos::ScalarTraits<double>::rmax();
// Get the local bounding boxes compute the local bounding box.
BoundingBox local_box;
Teuchos::Tuple<double,6> box_bounds;
Teuchos::Array<BoundingBox> boxes = boundingBoxes();
Teuchos::Array<BoundingBox>::const_iterator box_iterator;
for ( box_iterator = boxes.begin();
box_iterator != boxes.end();
++box_iterator )
{
box_bounds = box_iterator->getBounds();
if ( box_bounds[0] < global_x_min )
{
global_x_min = box_bounds[0];
}
if ( box_bounds[1] < global_y_min )
{
global_y_min = box_bounds[1];
}
if ( box_bounds[2] < global_z_min )
{
global_z_min = box_bounds[2];
}
if ( box_bounds[3] > global_x_max )
{
global_x_max = box_bounds[3];
}
if ( box_bounds[4] > global_y_max )
{
global_y_max = box_bounds[4];
}
if ( box_bounds[5] > global_z_max )
{
global_z_max = box_bounds[5];
}
}
return BoundingBox( global_x_min, global_y_min, global_z_min,
global_x_max, global_y_max, global_z_max );
}
//---------------------------------------------------------------------------//
/*!
* \brief Get the global bounding box for the objects owned by this manager.
*/
template<class Geometry,class GlobalOrdinal>
BoundingBox GeometryManager<Geometry,GlobalOrdinal>::globalBoundingBox() const
{
Teuchos::Tuple<double,6> local_bounds( Teuchos::ScalarTraits<double>::rmax(),
Teuchos::ScalarTraits<double>::rmax(),
Teuchos::ScalarTraits<double>::rmax(),
-Teuchos::ScalarTraits<double>::rmax(),
-Teuchos::ScalarTraits<double>::rmax(),
-Teuchos::ScalarTraits<double>::rmax() );
if ( d_geometry->size() > 0 )
{
BoundingBox local_box = localBoundingBox();
local_bounds = local_box.getBounds();
}
double global_x_min, global_y_min, global_z_min;
double global_x_max, global_y_max, global_z_max;
Teuchos::reduceAll<int,double>( *d_comm,
Teuchos::REDUCE_MIN,
1,
&local_bounds[0],
&global_x_min );
Teuchos::reduceAll<int,double>( *d_comm,
Teuchos::REDUCE_MIN,
1,
&local_bounds[1],
&global_y_min );
Teuchos::reduceAll<int,double>( *d_comm,
Teuchos::REDUCE_MIN,
1,
&local_bounds[2],
&global_z_min );
Teuchos::reduceAll<int,double>( *d_comm,
Teuchos::REDUCE_MAX,
1,
&local_bounds[3],
&global_x_max );
Teuchos::reduceAll<int,double>( *d_comm,
Teuchos::REDUCE_MAX,
1,
&local_bounds[4],
&global_y_max );
Teuchos::reduceAll<int,double>( *d_comm,
Teuchos::REDUCE_MAX,
1,
&local_bounds[5],
&global_z_max );
return BoundingBox( global_x_min, global_y_min, global_z_min,
global_x_max, global_y_max, global_z_max );
}
//---------------------------------------------------------------------------//
/*!
* \brief Validate the geometry to the domain model.
*/
template<class Geometry,class GlobalOrdinal>
void GeometryManager<Geometry,GlobalOrdinal>::validate()
{
// Dimensions greater than 3 are not valid.
testPrecondition( 0 <= d_dim && d_dim <= 3 );
// Check that all local geometries have the same dimension.
typename Teuchos::ArrayRCP<Geometry>::const_iterator geom_iterator;
for ( geom_iterator = d_geometry.begin();
geom_iterator != d_geometry.end();
++geom_iterator )
{
testPrecondition( GT::dim( *geom_iterator ) == d_dim );
}
// Check that the geometry dimension is the same on every node.
Teuchos::Array<int> local_dims( d_comm->getSize(), 0 );
Teuchos::Array<int> local_dims_copy( d_comm->getSize(), 0 );
local_dims[ d_comm->getRank() ] = d_dim;
Teuchos::reduceAll<int,int>( *d_comm, Teuchos::REDUCE_SUM,
local_dims.size(),
&local_dims[0], &local_dims_copy[0] );
Teuchos::Array<int>::iterator unique_bound;
std::sort( local_dims_copy.begin(), local_dims_copy.end() );
unique_bound =
std::unique( local_dims_copy.begin(), local_dims_copy.end() );
int unique_dim = std::distance( local_dims_copy.begin(), unique_bound );
testPrecondition( 1 == unique_dim );
local_dims_copy.clear();
}
//---------------------------------------------------------------------------//
} // end namespace DataTransferKit
#endif // end DTK_GEOMETRYMANAGER_DEF_HPP
//---------------------------------------------------------------------------//
// end DTK_GeometryManager_def.hpp
//---------------------------------------------------------------------------//
<commit_msg>fixing compile error in geometry manager global bounding box<commit_after>//---------------------------------------------------------------------------//
/*
Copyright (c) 2012, Stuart R. Slattery
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 University of Wisconsin - Madison nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
//---------------------------------------------------------------------------//
/*!
* \file DTK_GeometryManager_def.hpp
* \author Stuart R. Slattery
* \brief Geometry manager definition.
*/
//---------------------------------------------------------------------------//
#ifndef DTK_GEOMETRYMANAGER_DEF_HPP
#define DTK_GEOMETRYMANAGER_DEF_HPP
#include "DTK_Assertion.hpp"
#include "DataTransferKit_config.hpp"
#include <Teuchos_CommHelpers.hpp>
namespace DataTransferKit
{
//---------------------------------------------------------------------------//
/*!
* \brief Constructor. If Design-By-Contract is enabled, the constructor will
* validate the geometry description to the domain model. This requires a few
* global communications.
*
* \param geometry The geometry that this object is managing. This geometry
* must have GeometryTraits.
*
* \param geom_gids The global ordinals for the geometry this object is
* managing.
*
* \param comm The communicator over which the geometry is defined.
*
* \param dim The dimension of the geometry.
*/
template<class Geometry,class GlobalOrdinal>
GeometryManager<Geometry,GlobalOrdinal>::GeometryManager(
const Teuchos::ArrayRCP<Geometry>& geometry,
const Teuchos::ArrayRCP<GlobalOrdinal>& geom_gids,
const RCP_Comm& comm, const int dim )
: d_geometry( geometry )
, d_geom_gids( geom_gids )
, d_comm( comm )
, d_dim( dim )
{
testPrecondition( d_geometry.size() == d_geom_gids.size() );
// If we're checking with Design-by-Contract, validate the geometry to the
// domain model.
#if HAVE_DTK_DBC
validate();
#endif
}
//---------------------------------------------------------------------------//
/*!
* \brief Destructor.
*/
template<class Geometry,class GlobalOrdinal>
GeometryManager<Geometry,GlobalOrdinal>::~GeometryManager()
{ /* ... */ }
//---------------------------------------------------------------------------//
/*!
* \brief Get the global number of objects owned by this manager.
*
* \return The global number of objects owned by this manager.
*/
template<class Geometry,class GlobalOrdinal>
const typename Teuchos::ArrayRCP<Geometry>::size_type
GeometryManager<Geometry,GlobalOrdinal>::globalNumGeometry() const
{
typename Teuchos::ArrayRCP<Geometry>::size_type global_size =
d_geometry.size();
typename Teuchos::ArrayRCP<Geometry>::size_type global_size_copy =
d_geometry.size();
Teuchos::reduceAll<int,typename Teuchos::ArrayRCP<Geometry>::size_type>(
*d_comm, Teuchos::REDUCE_SUM, 1, &global_size, &global_size_copy );
return global_size_copy;
}
//---------------------------------------------------------------------------//
/*!
* \brief Get the bounding boxes for the objects owned by this manager.
*
* \return The bounding boxes for the geometry owned by this manager.
*/
template<class Geometry,class GlobalOrdinal>
Teuchos::Array<BoundingBox>
GeometryManager<Geometry,GlobalOrdinal>::boundingBoxes() const
{
Teuchos::Array<BoundingBox> boxes( d_geometry.size() );
Teuchos::Array<BoundingBox>::iterator box_iterator;
typename Teuchos::ArrayRCP<Geometry>::const_iterator geom_iterator;
for ( geom_iterator = d_geometry.begin(), box_iterator = boxes.begin();
geom_iterator != d_geometry.end();
++geom_iterator, ++box_iterator )
{
*box_iterator = GT::boundingBox( *geom_iterator );
}
return boxes;
}
//---------------------------------------------------------------------------//
/*!
* \brief Get the local bounding box for the objects owned by this manager.
*/
template<class Geometry,class GlobalOrdinal>
BoundingBox GeometryManager<Geometry,GlobalOrdinal>::localBoundingBox() const
{
double global_x_min = Teuchos::ScalarTraits<double>::rmax();
double global_y_min = Teuchos::ScalarTraits<double>::rmax();
double global_z_min = Teuchos::ScalarTraits<double>::rmax();
double global_x_max = -Teuchos::ScalarTraits<double>::rmax();
double global_y_max = -Teuchos::ScalarTraits<double>::rmax();
double global_z_max = -Teuchos::ScalarTraits<double>::rmax();
// Get the local bounding boxes compute the local bounding box.
BoundingBox local_box;
Teuchos::Tuple<double,6> box_bounds;
Teuchos::Array<BoundingBox> boxes = boundingBoxes();
Teuchos::Array<BoundingBox>::const_iterator box_iterator;
for ( box_iterator = boxes.begin();
box_iterator != boxes.end();
++box_iterator )
{
box_bounds = box_iterator->getBounds();
if ( box_bounds[0] < global_x_min )
{
global_x_min = box_bounds[0];
}
if ( box_bounds[1] < global_y_min )
{
global_y_min = box_bounds[1];
}
if ( box_bounds[2] < global_z_min )
{
global_z_min = box_bounds[2];
}
if ( box_bounds[3] > global_x_max )
{
global_x_max = box_bounds[3];
}
if ( box_bounds[4] > global_y_max )
{
global_y_max = box_bounds[4];
}
if ( box_bounds[5] > global_z_max )
{
global_z_max = box_bounds[5];
}
}
return BoundingBox( global_x_min, global_y_min, global_z_min,
global_x_max, global_y_max, global_z_max );
}
//---------------------------------------------------------------------------//
/*!
* \brief Get the global bounding box for the objects owned by this manager.
*/
template<class Geometry,class GlobalOrdinal>
BoundingBox GeometryManager<Geometry,GlobalOrdinal>::globalBoundingBox() const
{
Teuchos::Tuple<double,6> local_bounds =
Teuchos::tuple( Teuchos::ScalarTraits<double>::rmax(),
Teuchos::ScalarTraits<double>::rmax(),
Teuchos::ScalarTraits<double>::rmax(),
-Teuchos::ScalarTraits<double>::rmax(),
-Teuchos::ScalarTraits<double>::rmax(),
-Teuchos::ScalarTraits<double>::rmax() );
if ( d_geometry.size() > 0 )
{
BoundingBox local_box = localBoundingBox();
local_bounds = local_box.getBounds();
}
double global_x_min, global_y_min, global_z_min;
double global_x_max, global_y_max, global_z_max;
Teuchos::reduceAll<int,double>( *d_comm,
Teuchos::REDUCE_MIN,
1,
&local_bounds[0],
&global_x_min );
Teuchos::reduceAll<int,double>( *d_comm,
Teuchos::REDUCE_MIN,
1,
&local_bounds[1],
&global_y_min );
Teuchos::reduceAll<int,double>( *d_comm,
Teuchos::REDUCE_MIN,
1,
&local_bounds[2],
&global_z_min );
Teuchos::reduceAll<int,double>( *d_comm,
Teuchos::REDUCE_MAX,
1,
&local_bounds[3],
&global_x_max );
Teuchos::reduceAll<int,double>( *d_comm,
Teuchos::REDUCE_MAX,
1,
&local_bounds[4],
&global_y_max );
Teuchos::reduceAll<int,double>( *d_comm,
Teuchos::REDUCE_MAX,
1,
&local_bounds[5],
&global_z_max );
return BoundingBox( global_x_min, global_y_min, global_z_min,
global_x_max, global_y_max, global_z_max );
}
//---------------------------------------------------------------------------//
/*!
* \brief Validate the geometry to the domain model.
*/
template<class Geometry,class GlobalOrdinal>
void GeometryManager<Geometry,GlobalOrdinal>::validate()
{
// Dimensions greater than 3 are not valid.
testPrecondition( 0 <= d_dim && d_dim <= 3 );
// Check that all local geometries have the same dimension.
typename Teuchos::ArrayRCP<Geometry>::const_iterator geom_iterator;
for ( geom_iterator = d_geometry.begin();
geom_iterator != d_geometry.end();
++geom_iterator )
{
testPrecondition( GT::dim( *geom_iterator ) == d_dim );
}
// Check that the geometry dimension is the same on every node.
Teuchos::Array<int> local_dims( d_comm->getSize(), 0 );
Teuchos::Array<int> local_dims_copy( d_comm->getSize(), 0 );
local_dims[ d_comm->getRank() ] = d_dim;
Teuchos::reduceAll<int,int>( *d_comm, Teuchos::REDUCE_SUM,
local_dims.size(),
&local_dims[0], &local_dims_copy[0] );
Teuchos::Array<int>::iterator unique_bound;
std::sort( local_dims_copy.begin(), local_dims_copy.end() );
unique_bound =
std::unique( local_dims_copy.begin(), local_dims_copy.end() );
int unique_dim = std::distance( local_dims_copy.begin(), unique_bound );
testPrecondition( 1 == unique_dim );
local_dims_copy.clear();
}
//---------------------------------------------------------------------------//
} // end namespace DataTransferKit
#endif // end DTK_GEOMETRYMANAGER_DEF_HPP
//---------------------------------------------------------------------------//
// end DTK_GeometryManager_def.hpp
//---------------------------------------------------------------------------//
<|endoftext|> |
<commit_before>/*
Copyright 2019 Alain Dargelas
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.
*/
/*
* File: ModuleDefinition.cpp
* Author: alain
*
* Created on October 20, 2017, 10:29 PM
*/
#include <Surelog/Design/FileContent.h>
#include <Surelog/Design/ModPort.h>
#include <Surelog/Design/ModuleDefinition.h>
namespace SURELOG {
VObjectType ModuleDefinition::getType() const {
return (m_fileContents.size()) ? m_fileContents[0]->Type(m_nodeIds[0])
: VObjectType::slN_input_gate_instance;
}
ModuleDefinition::ModuleDefinition(const FileContent* fileContent,
NodeId nodeId, const std::string_view name)
: DesignComponent(fileContent, nullptr), m_name(name), m_udpDefn(nullptr) {
if (fileContent) {
addFileContent(fileContent, nodeId);
}
}
bool ModuleDefinition::isInstance() const {
const VObjectType type = getType();
return ((type == VObjectType::slN_input_gate_instance) ||
(type == VObjectType::slModule_declaration) ||
(type == VObjectType::slUdp_declaration));
}
ModuleDefinition* ModuleDefinitionFactory::newModuleDefinition(
const FileContent* fileContent, NodeId nodeId, std::string_view name) {
return new ModuleDefinition(fileContent, nodeId, name);
}
unsigned int ModuleDefinition::getSize() const {
unsigned int size = 0;
for (unsigned int i = 0; i < m_fileContents.size(); i++) {
NodeId end = m_nodeIds[i];
NodeId begin = m_fileContents[i]->Child(end);
size += (RawNodeId)(end - begin);
}
return size;
}
void ModuleDefinition::insertModPort(const std::string& modport,
const Signal& signal, NodeId nodeId) {
ModPortSignalMap::iterator itr = m_modportSignalMap.find(modport);
if (itr == m_modportSignalMap.end()) {
ModPort modp(this, modport, m_fileContents[0], nodeId);
modp.addSignal(signal);
m_modportSignalMap.insert(std::make_pair(modport, modp));
} else {
(*itr).second.addSignal(signal);
}
}
const Signal* ModuleDefinition::getModPortSignal(const std::string& modport,
NodeId port) const {
ModPortSignalMap::const_iterator itr = m_modportSignalMap.find(modport);
if (itr == m_modportSignalMap.end()) {
return nullptr;
} else {
for (auto& sig : (*itr).second.getPorts()) {
if (sig.getNodeId() == port) {
return &sig;
}
}
}
return nullptr;
}
ModPort* ModuleDefinition::getModPort(const std::string& modport) {
ModPortSignalMap::iterator itr = m_modportSignalMap.find(modport);
if (itr == m_modportSignalMap.end()) {
return nullptr;
} else {
return &(*itr).second;
}
}
void ModuleDefinition::insertModPort(const std::string& modport,
ClockingBlock& cb) {
ModPortClockingBlockMap::iterator itr =
m_modportClockingBlockMap.find(modport);
if (itr == m_modportClockingBlockMap.end()) {
std::vector<ClockingBlock> cbs;
cbs.push_back(cb);
m_modportClockingBlockMap.insert(std::make_pair(modport, cbs));
} else {
(*itr).second.push_back(cb);
}
}
const ClockingBlock* ModuleDefinition::getModPortClockingBlock(
const std::string& modport, NodeId port) const {
auto itr = m_modportClockingBlockMap.find(modport);
if (itr == m_modportClockingBlockMap.end()) {
return nullptr;
} else {
for (auto& cb : (*itr).second) {
if (cb.getNodeId() == port) {
return &cb;
}
}
}
return nullptr;
}
ClassDefinition* ModuleDefinition::getClassDefinition(const std::string& name) {
auto itr = m_classDefinitions.find(name);
if (itr == m_classDefinitions.end()) {
return nullptr;
} else {
return (*itr).second;
}
}
} // namespace SURELOG
<commit_msg>Prefer empty() to size() when quering containers.<commit_after>/*
Copyright 2019 Alain Dargelas
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.
*/
/*
* File: ModuleDefinition.cpp
* Author: alain
*
* Created on October 20, 2017, 10:29 PM
*/
#include <Surelog/Design/FileContent.h>
#include <Surelog/Design/ModPort.h>
#include <Surelog/Design/ModuleDefinition.h>
namespace SURELOG {
VObjectType ModuleDefinition::getType() const {
return (m_fileContents.empty()) ? VObjectType::slN_input_gate_instance
: m_fileContents[0]->Type(m_nodeIds[0]);
}
ModuleDefinition::ModuleDefinition(const FileContent* fileContent,
NodeId nodeId, const std::string_view name)
: DesignComponent(fileContent, nullptr), m_name(name), m_udpDefn(nullptr) {
if (fileContent) {
addFileContent(fileContent, nodeId);
}
}
bool ModuleDefinition::isInstance() const {
const VObjectType type = getType();
return ((type == VObjectType::slN_input_gate_instance) ||
(type == VObjectType::slModule_declaration) ||
(type == VObjectType::slUdp_declaration));
}
ModuleDefinition* ModuleDefinitionFactory::newModuleDefinition(
const FileContent* fileContent, NodeId nodeId, std::string_view name) {
return new ModuleDefinition(fileContent, nodeId, name);
}
unsigned int ModuleDefinition::getSize() const {
unsigned int size = 0;
for (unsigned int i = 0; i < m_fileContents.size(); i++) {
NodeId end = m_nodeIds[i];
NodeId begin = m_fileContents[i]->Child(end);
size += (RawNodeId)(end - begin);
}
return size;
}
void ModuleDefinition::insertModPort(const std::string& modport,
const Signal& signal, NodeId nodeId) {
ModPortSignalMap::iterator itr = m_modportSignalMap.find(modport);
if (itr == m_modportSignalMap.end()) {
ModPort modp(this, modport, m_fileContents[0], nodeId);
modp.addSignal(signal);
m_modportSignalMap.insert(std::make_pair(modport, modp));
} else {
(*itr).second.addSignal(signal);
}
}
const Signal* ModuleDefinition::getModPortSignal(const std::string& modport,
NodeId port) const {
ModPortSignalMap::const_iterator itr = m_modportSignalMap.find(modport);
if (itr == m_modportSignalMap.end()) {
return nullptr;
} else {
for (auto& sig : (*itr).second.getPorts()) {
if (sig.getNodeId() == port) {
return &sig;
}
}
}
return nullptr;
}
ModPort* ModuleDefinition::getModPort(const std::string& modport) {
ModPortSignalMap::iterator itr = m_modportSignalMap.find(modport);
if (itr == m_modportSignalMap.end()) {
return nullptr;
} else {
return &(*itr).second;
}
}
void ModuleDefinition::insertModPort(const std::string& modport,
ClockingBlock& cb) {
ModPortClockingBlockMap::iterator itr =
m_modportClockingBlockMap.find(modport);
if (itr == m_modportClockingBlockMap.end()) {
std::vector<ClockingBlock> cbs;
cbs.push_back(cb);
m_modportClockingBlockMap.insert(std::make_pair(modport, cbs));
} else {
(*itr).second.push_back(cb);
}
}
const ClockingBlock* ModuleDefinition::getModPortClockingBlock(
const std::string& modport, NodeId port) const {
auto itr = m_modportClockingBlockMap.find(modport);
if (itr == m_modportClockingBlockMap.end()) {
return nullptr;
} else {
for (auto& cb : (*itr).second) {
if (cb.getNodeId() == port) {
return &cb;
}
}
}
return nullptr;
}
ClassDefinition* ModuleDefinition::getClassDefinition(const std::string& name) {
auto itr = m_classDefinitions.find(name);
if (itr == m_classDefinitions.end()) {
return nullptr;
} else {
return (*itr).second;
}
}
} // namespace SURELOG
<|endoftext|> |
<commit_before>#include <plugins/interactive/PluginInteractive.h>
namespace beliefstate {
namespace plugins {
PluginInteractive::PluginInteractive() {
this->addDependency("ros");
m_imsServer = NULL;
}
PluginInteractive::~PluginInteractive() {
if(m_imsServer) {
delete m_imsServer;
}
for(list<InteractiveObject*>::iterator itIO = m_lstInteractiveObjects.begin();
itIO != m_lstInteractiveObjects.end();
itIO++) {
delete *itIO;
}
}
Result PluginInteractive::init(int argc, char** argv) {
Result resInit = defaultResult();
// Initialize server
m_imsServer = new InteractiveMarkerServer("interactive", "", false);
// Just for development: Add objects
InteractiveObject* ioNew = this->addInteractiveObject("object0");
ioNew->addMenuEntry("Pick up", "pickup");
ioNew->removeMenuEntry("pickup");
return resInit;
}
InteractiveObject* PluginInteractive::updatePoseForInteractiveObject(string strName, geometry_msgs::Pose posUpdate) {
InteractiveObject* ioUpdate = this->interactiveObjectForName(strName);
if(!ioUpdate) {
ioUpdate = this->addInteractiveObject(strName);
}
ioUpdate->setPose(posUpdate);
return ioUpdate;
}
InteractiveObject* PluginInteractive::addInteractiveObject(string strName) {
return this->addInteractiveObject(new InteractiveObject(strName));
}
InteractiveObject* PluginInteractive::addInteractiveObject(InteractiveObject* ioAdd) {
m_lstInteractiveObjects.push_back(ioAdd);
ioAdd->insertIntoServer(m_imsServer);
return ioAdd;
}
InteractiveObject* PluginInteractive::interactiveObjectForName(string strName) {
for(list<InteractiveObject*>::iterator itIO = m_lstInteractiveObjects.begin();
itIO != m_lstInteractiveObjects.end();
itIO++) {
InteractiveObject* ioCurrent = *itIO;
if(ioCurrent->name() == strName) {
return ioCurrent;
}
}
return NULL;
}
Result PluginInteractive::deinit() {
return defaultResult();
}
Result PluginInteractive::cycle() {
Result resCycle = defaultResult();
this->deployCycleData(resCycle);
return resCycle;
}
void PluginInteractive::consumeEvent(Event evEvent) {
this->info("Consume event!");
}
}
extern "C" plugins::PluginInteractive* createInstance() {
return new plugins::PluginInteractive();
}
extern "C" void destroyInstance(plugins::PluginInteractive* icDestroy) {
delete icDestroy;
}
}
<commit_msg>Subscribe to internal events; also, infrastructure for interpreting object add events and updating their pose is prepared<commit_after>#include <plugins/interactive/PluginInteractive.h>
namespace beliefstate {
namespace plugins {
PluginInteractive::PluginInteractive() {
this->addDependency("ros");
m_imsServer = NULL;
}
PluginInteractive::~PluginInteractive() {
if(m_imsServer) {
delete m_imsServer;
}
for(list<InteractiveObject*>::iterator itIO = m_lstInteractiveObjects.begin();
itIO != m_lstInteractiveObjects.end();
itIO++) {
delete *itIO;
}
}
Result PluginInteractive::init(int argc, char** argv) {
Result resInit = defaultResult();
// Initialize server
m_imsServer = new InteractiveMarkerServer("interactive_beliefstate", "", false);
// Subscribe to internal events
this->setSubscribedToEvent("symbolic-add-object", true);
this->setSubscribedToEvent("symbolic-update-object-pose", true);
// Just for development: Add objects
InteractiveObject* ioNew = this->addInteractiveObject("object0");
ioNew->addMenuEntry("Pick up", "pickup");
ioNew->removeMenuEntry("pickup");
return resInit;
}
InteractiveObject* PluginInteractive::updatePoseForInteractiveObject(string strName, geometry_msgs::Pose posUpdate) {
InteractiveObject* ioUpdate = this->interactiveObjectForName(strName);
if(!ioUpdate) {
ioUpdate = this->addInteractiveObject(strName);
}
ioUpdate->setPose(posUpdate);
return ioUpdate;
}
InteractiveObject* PluginInteractive::addInteractiveObject(string strName) {
return this->addInteractiveObject(new InteractiveObject(strName));
}
InteractiveObject* PluginInteractive::addInteractiveObject(InteractiveObject* ioAdd) {
m_lstInteractiveObjects.push_back(ioAdd);
ioAdd->insertIntoServer(m_imsServer);
return ioAdd;
}
InteractiveObject* PluginInteractive::interactiveObjectForName(string strName) {
for(list<InteractiveObject*>::iterator itIO = m_lstInteractiveObjects.begin();
itIO != m_lstInteractiveObjects.end();
itIO++) {
InteractiveObject* ioCurrent = *itIO;
if(ioCurrent->name() == strName) {
return ioCurrent;
}
}
return NULL;
}
Result PluginInteractive::deinit() {
return defaultResult();
}
Result PluginInteractive::cycle() {
Result resCycle = defaultResult();
this->deployCycleData(resCycle);
return resCycle;
}
void PluginInteractive::consumeEvent(Event evEvent) {
if(evEvent.strEventName == "symbolic-add-object") {
this->warn("Adding objects via events not yet implemented.");
} else if(evEvent.strEventName == "symbolic-update-object-pose") {
this->warn("Updating object poses via events not yet implemented.");
}
}
}
extern "C" plugins::PluginInteractive* createInstance() {
return new plugins::PluginInteractive();
}
extern "C" void destroyInstance(plugins::PluginInteractive* icDestroy) {
delete icDestroy;
}
}
<|endoftext|> |
<commit_before><commit_msg>Fixed parallelized mean computation + removed unnecessary recomputation of results in opencv/superpixels/mean<commit_after><|endoftext|> |
<commit_before>/*******************************************************
* Copyright (c) 2015, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#include <gtest/gtest.h>
#include <arrayfire.h>
#include <af/dim4.hpp>
#include <af/defines.h>
#include <af/traits.hpp>
#include <vector>
#include <iostream>
#include <complex>
#include <string>
#include <testHelpers.hpp>
using std::vector;
using std::string;
using std::cout;
using std::endl;
using std::abs;
using af::cfloat;
using af::cdouble;
template<typename T>
class svd : public ::testing::Test
{
};
typedef ::testing::Types<float, double, cfloat, cdouble> TestTypes;
TYPED_TEST_CASE(svd, TestTypes);
template<typename T>
inline double get_val(T val)
{
return val;
}
template<> inline double get_val<cfloat>(cfloat val)
{
return abs(val);
}
template<> double get_val<cdouble>(cdouble val)
{
return abs(val);
}
template<typename T>
void svdTest(const int M, const int N)
{
if (noDoubleTests<T>()) return;
if (noLAPACKTests()) return;
af::dtype ty = (af::dtype)af::dtype_traits<T>::af_type;
af::array A = af::randu(M, N, ty);
//! [ex_svd_reg]
af::array U, S, Vt;
af::svd(U, S, Vt, A);
const int MN = std::min(M, N);
af::array UU = U(af::span, af::seq(MN));
af::array SS = af::diag(S, 0, false).as(ty);
af::array VV = Vt(af::seq(MN), af::span);
af::array AA = matmul(UU, SS, VV);
//! [ex_svd_reg]
std::vector<T> hA(M * N);
std::vector<T> hAA(M * N);
A.host(&hA[0]);
AA.host(&hAA[0]);
for (int i = 0; i < M * N; i++) {
#if defined(OS_MAC)
ASSERT_NEAR(get_val(hA[i]), get_val(hAA[i]), 2E-3);
#else
ASSERT_NEAR(get_val(hA[i]), get_val(hAA[i]), 1E-3);
#endif
}
}
TYPED_TEST(svd, Square)
{
svdTest<TypeParam>(500, 500);
}
TYPED_TEST(svd, Rect0)
{
svdTest<TypeParam>(500, 300);
}
TYPED_TEST(svd, Rect1)
{
svdTest<TypeParam>(300, 500);
}
<commit_msg>Increase `svd_dense` test thresholds on macOS.<commit_after>/*******************************************************
* Copyright (c) 2015, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#include <gtest/gtest.h>
#include <arrayfire.h>
#include <af/dim4.hpp>
#include <af/defines.h>
#include <af/traits.hpp>
#include <vector>
#include <iostream>
#include <complex>
#include <string>
#include <testHelpers.hpp>
using std::vector;
using std::string;
using std::cout;
using std::endl;
using std::abs;
using af::cfloat;
using af::cdouble;
template<typename T>
class svd : public ::testing::Test
{
};
typedef ::testing::Types<float, double, cfloat, cdouble> TestTypes;
TYPED_TEST_CASE(svd, TestTypes);
template<typename T>
inline double get_val(T val)
{
return val;
}
template<> inline double get_val<cfloat>(cfloat val)
{
return abs(val);
}
template<> double get_val<cdouble>(cdouble val)
{
return abs(val);
}
template<typename T>
void svdTest(const int M, const int N)
{
if (noDoubleTests<T>()) return;
if (noLAPACKTests()) return;
af::dtype ty = (af::dtype)af::dtype_traits<T>::af_type;
af::array A = af::randu(M, N, ty);
//! [ex_svd_reg]
af::array U, S, Vt;
af::svd(U, S, Vt, A);
const int MN = std::min(M, N);
af::array UU = U(af::span, af::seq(MN));
af::array SS = af::diag(S, 0, false).as(ty);
af::array VV = Vt(af::seq(MN), af::span);
af::array AA = matmul(UU, SS, VV);
//! [ex_svd_reg]
std::vector<T> hA(M * N);
std::vector<T> hAA(M * N);
A.host(&hA[0]);
AA.host(&hAA[0]);
for (int i = 0; i < M * N; i++) {
#if defined(OS_MAC)
ASSERT_NEAR(get_val(hA[i]), get_val(hAA[i]), 3E-3);
#else
ASSERT_NEAR(get_val(hA[i]), get_val(hAA[i]), 1E-3);
#endif
}
}
TYPED_TEST(svd, Square)
{
svdTest<TypeParam>(500, 500);
}
TYPED_TEST(svd, Rect0)
{
svdTest<TypeParam>(500, 300);
}
TYPED_TEST(svd, Rect1)
{
svdTest<TypeParam>(300, 500);
}
<|endoftext|> |
<commit_before>#include <imap.hpp>
#include "helpers.hpp"
#include <cctype>
#include <iterator>
#include <string>
#include <vector>
#include "catch.hpp"
using iter::imap;
using Vec = const std::vector<int>;
namespace {
int plusone(int i) {
return i + 1;
}
class PlusOner {
public:
int operator()(int i) {
return i + 1;
}
};
int power(int b, int e) {
int acc = 1;
for (int i = 0; i < e; ++i) {
acc *= b;
}
return acc;
}
}
TEST_CASE("imap: works with lambda, callable, and function", "[imap]") {
Vec ns = {10, 20, 30};
std::vector<int> v;
SECTION("with lambda") {
auto im = imap([](int i) { return i + 1; }, ns);
v.assign(std::begin(im), std::end(im));
}
SECTION("with callable") {
SECTION("Normal call") {
auto im = imap(PlusOner{}, ns);
v.assign(std::begin(im), std::end(im));
}
SECTION("Pipe") {
auto im = ns | imap(PlusOner{});
v.assign(std::begin(im), std::end(im));
}
}
SECTION("with function") {
auto im = imap(PlusOner{}, ns);
v.assign(std::begin(im), std::end(im));
}
Vec vc = {11, 21, 31};
REQUIRE(v == vc);
}
// TODO enable once zip supports const
#if 0
TEST_CASE("imap: supports const iteration", "[imap][const]") {
Vec ns = {10, 20, 30};
const auto m = imap(PlusOner{}, ns);
Vec v(std::begin(m), std::end(m));
Vec vc = {11, 21, 31};
REQUIRE(v == vc);
}
TEST_CASE("imap: const iterators can be compared to non-const iterators", "[imap][const]") {
auto m = imap(PlusOner{}, Vec{});
const auto& cm = m;
(void)(std::begin(m) == std::end(cm));
}
#endif
TEST_CASE("imap: Works with different begin and end types", "[imap]") {
CharRange cr{'d'};
auto m = imap([](char c) { return std::toupper(c); }, cr);
Vec v(m.begin(), m.end());
Vec vc{'A', 'B', 'C'};
REQUIRE(v == vc);
}
TEST_CASE("imap: works with multiple sequences", "[imap]") {
Vec bases = {0, 1, 2, 3};
Vec exps = {1, 2, 3, 4};
auto im = imap(power, bases, exps);
Vec v(std::begin(im), std::end(im));
Vec vc = {0, 1, 8, 81};
REQUIRE(v == vc);
}
TEST_CASE("imap: terminates on shortest squence", "[imap]") {
Vec ns1 = {1, 2, 3, 4};
Vec ns2 = {2, 4, 6, 8, 10};
Vec vc = {3, 6, 9, 12};
SECTION("shortest sequence first") {
auto im = imap([](int a, int b) { return a + b; }, ns1, ns2);
Vec v(std::begin(im), std::end(im));
REQUIRE(v == vc);
}
SECTION("shortest sequence second") {
auto im = imap([](int a, int b) { return a + b; }, ns2, ns1);
Vec v(std::begin(im), std::end(im));
REQUIRE(v == vc);
}
}
TEST_CASE("imap: operator->", "[imap]") {
std::vector<std::string> vs = {"ab", "abcd", "abcdefg"};
{
auto m = imap([](std::string& s) { return s; }, vs);
auto it = std::begin(m);
REQUIRE(it->size() == 2);
}
{
auto m = imap([](std::string& s) -> std::string& { return s; }, vs);
auto it = std::begin(m);
REQUIRE(it->size() == 2);
}
}
TEST_CASE("imap: empty sequence gives nothing", "[imap]") {
Vec v{};
auto im = imap(plusone, v);
REQUIRE(std::begin(im) == std::end(im));
}
TEST_CASE("imap: binds to lvalues, moves rvalues", "[imap]") {
itertest::BasicIterable<int> bi{1, 2};
SECTION("binds to lvalues") {
imap(plusone, bi);
REQUIRE_FALSE(bi.was_moved_from());
}
SECTION("moves rvalues") {
imap(plusone, std::move(bi));
REQUIRE(bi.was_moved_from());
}
}
TEST_CASE("imap: doesn't move or copy elements of iterable", "[imap]") {
constexpr itertest::SolidInt arr[] = {{1}, {0}, {2}};
for (auto&& i :
imap([](const itertest::SolidInt& si) { return si.getint(); }, arr)) {
(void)i;
}
}
TEST_CASE("imap: postfix ++", "[imap]") {
Vec ns = {10, 20};
auto im = imap(plusone, ns);
auto it = std::begin(im);
it++;
REQUIRE((*it) == 21);
it++;
REQUIRE(it == std::end(im));
}
TEST_CASE("imap: iterator meets requirements", "[imap]") {
std::string s{};
auto c = imap([](char) { return 1; }, s);
REQUIRE(itertest::IsIterator<decltype(std::begin(c))>::value);
}
template <typename T, typename U>
using ImpT = decltype(imap(std::declval<T>(), std::declval<U>()));
TEST_CASE("imap: has correct ctor and assign ops", "[imap]") {
using T1 = ImpT<bool (*)(char c), std::string&>;
auto lam = [](char) { return false; };
using T2 = ImpT<decltype(lam), std::string>;
REQUIRE(itertest::IsMoveConstructibleOnly<T1>::value);
REQUIRE(itertest::IsMoveConstructibleOnly<T2>::value);
}
<commit_msg>Tests imap with pointer-to-member<commit_after>#include <imap.hpp>
#include "helpers.hpp"
#include <cctype>
#include <iterator>
#include <string>
#include <vector>
#include "catch.hpp"
using iter::imap;
using Vec = const std::vector<int>;
namespace {
int plusone(int i) {
return i + 1;
}
class PlusOner {
public:
int operator()(int i) {
return i + 1;
}
};
int power(int b, int e) {
int acc = 1;
for (int i = 0; i < e; ++i) {
acc *= b;
}
return acc;
}
}
TEST_CASE("imap: works with lambda, callable, and function", "[imap]") {
Vec ns = {10, 20, 30};
std::vector<int> v;
SECTION("with lambda") {
auto im = imap([](int i) { return i + 1; }, ns);
v.assign(std::begin(im), std::end(im));
}
SECTION("with callable") {
SECTION("Normal call") {
auto im = imap(PlusOner{}, ns);
v.assign(std::begin(im), std::end(im));
}
SECTION("Pipe") {
auto im = ns | imap(PlusOner{});
v.assign(std::begin(im), std::end(im));
}
}
SECTION("with function") {
auto im = imap(PlusOner{}, ns);
v.assign(std::begin(im), std::end(im));
}
Vec vc = {11, 21, 31};
REQUIRE(v == vc);
}
TEST_CASE("imap: works with pointer to member", "[imap]") {
using itertest::Point;
std::vector<Point> ps = {{3, 6}, {20, 25}};
std::vector<int> v;
SECTION("with pointer to member function") {
auto im = imap(&Point::get_y, ps);
v.assign(std::begin(im), std::end(im));
}
SECTION("with pointer to data member") {
auto im = imap(&Point::y, ps);
v.assign(std::begin(im), std::end(im));
}
Vec vc = {6, 25};
REQUIRE(v == vc);
}
TEST_CASE("imap: works with pointer to member function taking argument") {
using itertest::Point;
std::vector<Point> ps = {{10, 20}, {6, 8}, {3, 15}};
std::vector<std::string> strs = {"a", "point", "pos"};
auto im = imap(&Point::prefix, ps, strs);
std::vector<std::string> v(std::begin(im), std::end(im));
const std::vector<std::string> vc = {
"a(10, 20)", "point(6, 8)", "pos(3, 15)"};
REQUIRE(v == vc);
}
// TODO enable once zip supports const
#if 0
TEST_CASE("imap: supports const iteration", "[imap][const]") {
Vec ns = {10, 20, 30};
const auto m = imap(PlusOner{}, ns);
Vec v(std::begin(m), std::end(m));
Vec vc = {11, 21, 31};
REQUIRE(v == vc);
}
TEST_CASE("imap: const iterators can be compared to non-const iterators", "[imap][const]") {
auto m = imap(PlusOner{}, Vec{});
const auto& cm = m;
(void)(std::begin(m) == std::end(cm));
}
#endif
TEST_CASE("imap: Works with different begin and end types", "[imap]") {
CharRange cr{'d'};
auto m = imap([](char c) { return std::toupper(c); }, cr);
Vec v(m.begin(), m.end());
Vec vc{'A', 'B', 'C'};
REQUIRE(v == vc);
}
TEST_CASE("imap: works with multiple sequences", "[imap]") {
Vec bases = {0, 1, 2, 3};
Vec exps = {1, 2, 3, 4};
auto im = imap(power, bases, exps);
Vec v(std::begin(im), std::end(im));
Vec vc = {0, 1, 8, 81};
REQUIRE(v == vc);
}
TEST_CASE("imap: terminates on shortest squence", "[imap]") {
Vec ns1 = {1, 2, 3, 4};
Vec ns2 = {2, 4, 6, 8, 10};
Vec vc = {3, 6, 9, 12};
SECTION("shortest sequence first") {
auto im = imap([](int a, int b) { return a + b; }, ns1, ns2);
Vec v(std::begin(im), std::end(im));
REQUIRE(v == vc);
}
SECTION("shortest sequence second") {
auto im = imap([](int a, int b) { return a + b; }, ns2, ns1);
Vec v(std::begin(im), std::end(im));
REQUIRE(v == vc);
}
}
TEST_CASE("imap: operator->", "[imap]") {
std::vector<std::string> vs = {"ab", "abcd", "abcdefg"};
{
auto m = imap([](std::string& s) { return s; }, vs);
auto it = std::begin(m);
REQUIRE(it->size() == 2);
}
{
auto m = imap([](std::string& s) -> std::string& { return s; }, vs);
auto it = std::begin(m);
REQUIRE(it->size() == 2);
}
}
TEST_CASE("imap: empty sequence gives nothing", "[imap]") {
Vec v{};
auto im = imap(plusone, v);
REQUIRE(std::begin(im) == std::end(im));
}
TEST_CASE("imap: binds to lvalues, moves rvalues", "[imap]") {
itertest::BasicIterable<int> bi{1, 2};
SECTION("binds to lvalues") {
imap(plusone, bi);
REQUIRE_FALSE(bi.was_moved_from());
}
SECTION("moves rvalues") {
imap(plusone, std::move(bi));
REQUIRE(bi.was_moved_from());
}
}
TEST_CASE("imap: doesn't move or copy elements of iterable", "[imap]") {
constexpr itertest::SolidInt arr[] = {{1}, {0}, {2}};
for (auto&& i :
imap([](const itertest::SolidInt& si) { return si.getint(); }, arr)) {
(void)i;
}
}
TEST_CASE("imap: postfix ++", "[imap]") {
Vec ns = {10, 20};
auto im = imap(plusone, ns);
auto it = std::begin(im);
it++;
REQUIRE((*it) == 21);
it++;
REQUIRE(it == std::end(im));
}
TEST_CASE("imap: iterator meets requirements", "[imap]") {
std::string s{};
auto c = imap([](char) { return 1; }, s);
REQUIRE(itertest::IsIterator<decltype(std::begin(c))>::value);
}
template <typename T, typename U>
using ImpT = decltype(imap(std::declval<T>(), std::declval<U>()));
TEST_CASE("imap: has correct ctor and assign ops", "[imap]") {
using T1 = ImpT<bool (*)(char c), std::string&>;
auto lam = [](char) { return false; };
using T2 = ImpT<decltype(lam), std::string>;
REQUIRE(itertest::IsMoveConstructibleOnly<T1>::value);
REQUIRE(itertest::IsMoveConstructibleOnly<T2>::value);
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2016+ AzerothCore <www.azerothcore.org>, released under GNU AGPL v3 license: https://github.com/azerothcore/azerothcore-wotlk/blob/master/LICENSE-AGPL3
*/
#include "Chat.h"
#include "ScriptMgr.h"
#include "Language.h"
#include "Player.h"
#include "PlayerCommand.h"
bool PlayerCommand::Learn(ChatHandler* handler, Player* targetPlayer, uint32 spell, char const* all)
{
if (!spell)
return false;
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spell);
if (!spellInfo)
{
handler->PSendSysMessage(LANG_COMMAND_NOSPELLFOUND);
handler->SetSentErrorMessage(true);
return false;
}
if (!SpellMgr::IsSpellValid(spellInfo))
{
handler->PSendSysMessage(LANG_COMMAND_SPELL_BROKEN, spell);
handler->SetSentErrorMessage(true);
return false;
}
if (handler->GetSession())
{
SpellScriptsBounds bounds = sObjectMgr->GetSpellScriptsBounds(spell);
uint32 spellDifficultyId = sSpellMgr->GetSpellDifficultyId(spell);
if (handler->GetSession() && handler->GetSession()->GetSecurity() < SEC_ADMINISTRATOR && (bounds.first != bounds.second || spellDifficultyId))
{
handler->PSendSysMessage("Spell %u cannot be learnt using a command!", spell);
handler->SetSentErrorMessage(true);
return false;
}
}
bool allRanks = all ? (strncmp(all, "all", 3) == 0) : false;
if (!allRanks && targetPlayer->HasSpell(spell))
{
if (targetPlayer == handler->GetSession()->GetPlayer())
handler->SendSysMessage(LANG_YOU_KNOWN_SPELL);
else
handler->PSendSysMessage(LANG_TARGET_KNOWN_SPELL, handler->GetNameLink(targetPlayer).c_str());
handler->SetSentErrorMessage(true);
return false;
}
if (allRanks)
targetPlayer->learnSpellHighRank(spell);
else
targetPlayer->learnSpell(spell);
uint32 firstSpell = sSpellMgr->GetFirstSpellInChain(spell);
if (GetTalentSpellCost(firstSpell))
targetPlayer->SendTalentsInfoData(false);
return true;
}
bool PlayerCommand::UnLearn(ChatHandler* handler, Player* target, uint32 spellId, char const* allStr)
{
if (!spellId)
return false;
bool allRanks = allStr ? (strncmp(allStr, "all", 3) == 0) : false;
if (allRanks)
spellId = sSpellMgr->GetFirstSpellInChain (spellId);
if (target->HasSpell(spellId))
target->removeSpell(spellId, SPEC_MASK_ALL, false);
else
handler->SendSysMessage(LANG_FORGET_SPELL);
if (GetTalentSpellCost(spellId))
target->SendTalentsInfoData(false);
return true;
}
<commit_msg>fix(Core/CS): Fixed learn command using null session when send over SOAP (#3595)<commit_after>/*
* Copyright (C) 2016+ AzerothCore <www.azerothcore.org>, released under GNU AGPL v3 license: https://github.com/azerothcore/azerothcore-wotlk/blob/master/LICENSE-AGPL3
*/
#include "Chat.h"
#include "ScriptMgr.h"
#include "Language.h"
#include "Player.h"
#include "PlayerCommand.h"
bool PlayerCommand::Learn(ChatHandler* handler, Player* targetPlayer, uint32 spell, char const* all)
{
if (!spell)
return false;
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spell);
if (!spellInfo)
{
handler->PSendSysMessage(LANG_COMMAND_NOSPELLFOUND);
handler->SetSentErrorMessage(true);
return false;
}
if (!SpellMgr::IsSpellValid(spellInfo))
{
handler->PSendSysMessage(LANG_COMMAND_SPELL_BROKEN, spell);
handler->SetSentErrorMessage(true);
return false;
}
if (handler->GetSession())
{
SpellScriptsBounds bounds = sObjectMgr->GetSpellScriptsBounds(spell);
uint32 spellDifficultyId = sSpellMgr->GetSpellDifficultyId(spell);
if (handler->GetSession() && handler->GetSession()->GetSecurity() < SEC_ADMINISTRATOR && (bounds.first != bounds.second || spellDifficultyId))
{
handler->PSendSysMessage("Spell %u cannot be learnt using a command!", spell);
handler->SetSentErrorMessage(true);
return false;
}
}
bool allRanks = all ? (strncmp(all, "all", 3) == 0) : false;
if (!allRanks && targetPlayer->HasSpell(spell))
{
if (handler->GetSession() && targetPlayer == handler->GetSession()->GetPlayer())
handler->SendSysMessage(LANG_YOU_KNOWN_SPELL);
else
handler->PSendSysMessage(LANG_TARGET_KNOWN_SPELL, handler->GetNameLink(targetPlayer).c_str());
handler->SetSentErrorMessage(true);
return false;
}
if (allRanks)
targetPlayer->learnSpellHighRank(spell);
else
targetPlayer->learnSpell(spell);
uint32 firstSpell = sSpellMgr->GetFirstSpellInChain(spell);
if (GetTalentSpellCost(firstSpell))
targetPlayer->SendTalentsInfoData(false);
return true;
}
bool PlayerCommand::UnLearn(ChatHandler* handler, Player* target, uint32 spellId, char const* allStr)
{
if (!spellId)
return false;
bool allRanks = allStr ? (strncmp(allStr, "all", 3) == 0) : false;
if (allRanks)
spellId = sSpellMgr->GetFirstSpellInChain (spellId);
if (target->HasSpell(spellId))
target->removeSpell(spellId, SPEC_MASK_ALL, false);
else
handler->SendSysMessage(LANG_FORGET_SPELL);
if (GetTalentSpellCost(spellId))
target->SendTalentsInfoData(false);
return true;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) The Shogun Machine Learning Toolbox
* Written (w) 2014 Wu Lin
* Written (W) 2013 Roman Votyakov
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*
* The views and conclusions contained in the software and documentation are those
* of the authors and should not be interpreted as representing official policies,
* either expressed or implied, of the Shogun Development Team.
*
* Code adapted from
* Gaussian Process Machine Learning Toolbox
* http://www.gaussianprocess.org/gpml/code/matlab/doc/
* and
* https://gist.github.com/yorkerlin/8a36e8f9b298aa0246a4
*/
#include <shogun/lib/config.h>
#ifdef HAVE_EIGEN3
#include <shogun/machine/GaussianProcessMachine.h>
#include <shogun/mathematics/Math.h>
#include <shogun/kernel/Kernel.h>
#include <shogun/machine/gp/SingleFITCLaplacianBase.h>
#include <shogun/mathematics/eigen3.h>
using namespace shogun;
using namespace Eigen;
CGaussianProcessMachine::CGaussianProcessMachine()
{
init();
}
CGaussianProcessMachine::CGaussianProcessMachine(CInferenceMethod* method)
{
init();
set_inference_method(method);
}
void CGaussianProcessMachine::init()
{
m_method=NULL;
SG_ADD((CSGObject**) &m_method, "inference_method", "Inference method",
MS_AVAILABLE);
}
CGaussianProcessMachine::~CGaussianProcessMachine()
{
SG_UNREF(m_method);
}
SGVector<float64_t> CGaussianProcessMachine::get_posterior_means(CFeatures* data)
{
REQUIRE(m_method, "Inference method should not be NULL\n")
CFeatures* feat;
// use inducing features for FITC inference method
if (m_method->get_inference_type()==INF_FITC_REGRESSION ||
m_method->get_inference_type()==INF_FITC_LAPLACIAN_SINGLE)
{
CSingleFITCLaplacianBase* fitc_method=
dynamic_cast<CSingleFITCLaplacianBase *>(m_method);
REQUIRE(fitc_method, "Inference method %s does not support FITC inference\n",
m_method->get_name());
feat=fitc_method->get_inducing_features();
}
else
feat=m_method->get_features();
// get kernel and compute kernel matrix: K(feat, data)*scale^2
CKernel* training_kernel=m_method->get_kernel();
CKernel* kernel=CKernel::obtain_from_generic(training_kernel->clone());
SG_UNREF(training_kernel);
kernel->init(feat, data);
// get kernel matrix and create eigen representation of it
SGMatrix<float64_t> k_trts=kernel->get_kernel_matrix();
Map<MatrixXd> eigen_Ks(k_trts.matrix, k_trts.num_rows, k_trts.num_cols);
// compute Ks=Ks*scale^2
eigen_Ks*=CMath::sq(m_method->get_scale());
// cleanup
SG_UNREF(feat);
SG_UNREF(kernel);
// get alpha and create eigen representation of it
SGVector<float64_t> alpha=m_method->get_alpha();
Map<VectorXd> eigen_alpha(alpha.vector, alpha.vlen);
// get mean and create eigen representation of it
CMeanFunction* mean_function=m_method->get_mean();
SGVector<float64_t> mean=mean_function->get_mean_vector(data);
Map<VectorXd> eigen_mean(mean.vector, mean.vlen);
SG_UNREF(mean_function);
const index_t C=alpha.vlen/k_trts.num_rows;
const index_t n=k_trts.num_rows;
const index_t m=k_trts.num_cols;
// compute mean: mu=Ks'*alpha+m
SGVector<float64_t> mu(C*m);
Map<MatrixXd> eigen_mu_matrix(mu.vector,C,m);
for(index_t bl=0; bl<C; bl++)
eigen_mu_matrix.block(bl,0,1,m)=(eigen_Ks.adjoint()*eigen_alpha.block(bl*n,0,n,1)+eigen_mean).transpose();
return mu;
}
SGVector<float64_t> CGaussianProcessMachine::get_posterior_variances(
CFeatures* data)
{
REQUIRE(m_method, "Inference method should not be NULL\n")
CFeatures* feat;
// use inducing features for FITC inference method
if (m_method->get_inference_type()==INF_FITC_REGRESSION ||
m_method->get_inference_type()==INF_FITC_LAPLACIAN_SINGLE)
{
CSingleFITCLaplacianBase* fitc_method=
dynamic_cast<CSingleFITCLaplacianBase *>(m_method);
REQUIRE(fitc_method, "Inference method %s must support FITC inference\n",
m_method->get_name());
feat=fitc_method->get_inducing_features();
}
else
feat=m_method->get_features();
SG_REF(data);
// get kernel and compute kernel matrix: K(data, data)*scale^2
CKernel* training_kernel=m_method->get_kernel();
CKernel* kernel=CKernel::obtain_from_generic(training_kernel->clone());
SG_UNREF(training_kernel);
kernel->init(data, data);
// get kernel matrix and create eigen representation of it
SGVector<float64_t> k_tsts=kernel->get_kernel_diagonal();
Map<VectorXd> eigen_Kss_diag(k_tsts.vector, k_tsts.vlen);
// compute Kss=Kss*scale^2
eigen_Kss_diag*=CMath::sq(m_method->get_scale());
// compute kernel matrix: K(feat, data)*scale^2
kernel->init(feat, data);
// get kernel matrix and create eigen representation of it
SGMatrix<float64_t> k_trts=kernel->get_kernel_matrix();
Map<MatrixXd> eigen_Ks(k_trts.matrix, k_trts.num_rows, k_trts.num_cols);
// compute Ks=Ks*scale^2
eigen_Ks*=CMath::sq(m_method->get_scale());
// cleanup
SG_UNREF(kernel);
SG_UNREF(feat);
SG_UNREF(data);
// get shogun representation of cholesky and create eigen representation
SGMatrix<float64_t> L=m_method->get_cholesky();
Map<MatrixXd> eigen_L(L.matrix, L.num_rows, L.num_cols);
SGVector<float64_t> alpha=m_method->get_alpha();
const index_t n=k_trts.num_rows;
const index_t m=k_tsts.vlen;
const index_t C=alpha.vlen/n;
// result variance vector
SGVector<float64_t> s2(m*C*C);
Map<VectorXd> eigen_s2(s2.vector, s2.vlen);
if (eigen_L.isUpperTriangular())
{
if (alpha.vlen==L.num_rows)
{
//binary case
// get shogun of diagonal sigma vector and create eigen representation
SGVector<float64_t> sW=m_method->get_diagonal_vector();
Map<VectorXd> eigen_sW(sW.vector, sW.vlen);
// solve L' * V = sW * Ks and compute V.^2
MatrixXd eigen_V=eigen_L.triangularView<Upper>().adjoint().solve(
eigen_sW.asDiagonal()*eigen_Ks);
MatrixXd eigen_sV=eigen_V.cwiseProduct(eigen_V);
eigen_s2=eigen_Kss_diag-eigen_sV.colwise().sum().adjoint();
}
else
{
if (m_method->supports_multiclass())
{
//multiclass case
//see the reference code of the gist link, which is based on the algorithm 3.4 of the GPML textbook
Map<MatrixXd> &eigen_M=eigen_L;
eigen_s2.fill(0);
SGMatrix<float64_t> E=m_method->get_multiclass_E();
Map<MatrixXd> eigen_E(E.matrix, E.num_rows, E.num_cols);
ASSERT(E.num_cols==alpha.vlen);
for(index_t bl_i=0; bl_i<C; bl_i++)
{
//n by m
MatrixXd bi=eigen_E.block(0,bl_i*n,n,n)*eigen_Ks;
MatrixXd c_cav=eigen_M.triangularView<Upper>().adjoint().solve(bi);
c_cav=eigen_M.triangularView<Upper>().solve(c_cav);
for(index_t bl_j=0; bl_j<C; bl_j++)
{
MatrixXd bj=eigen_E.block(0,bl_j*n,n,n)*eigen_Ks;
for (index_t idx_m=0; idx_m<m; idx_m++)
eigen_s2[bl_j+(bl_i+idx_m*C)*C]=(bj.block(0,idx_m,n,1).array()*c_cav.block(0,idx_m,n,1).array()).sum();
}
for (index_t idx_m=0; idx_m<m; idx_m++)
eigen_s2[bl_i+(bl_i+idx_m*C)*C]+=eigen_Kss_diag(idx_m)-(eigen_Ks.block(0,idx_m,n,1).array()*bi.block(0,idx_m,n,1).array()).sum();
}
}
else
{
SG_ERROR("Unsupported inference method!\n");
return s2;
}
}
}
else
{
// M = Ks .* (L * Ks)
MatrixXd eigen_M=eigen_Ks.cwiseProduct(eigen_L*eigen_Ks);
eigen_s2=eigen_Kss_diag+eigen_M.colwise().sum().adjoint();
}
return s2;
}
#endif /* HAVE_EIGEN3 */
<commit_msg>bug fix<commit_after>/*
* Copyright (c) The Shogun Machine Learning Toolbox
* Written (w) 2014 Wu Lin
* Written (W) 2013 Roman Votyakov
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*
* The views and conclusions contained in the software and documentation are those
* of the authors and should not be interpreted as representing official policies,
* either expressed or implied, of the Shogun Development Team.
*
* Code adapted from
* Gaussian Process Machine Learning Toolbox
* http://www.gaussianprocess.org/gpml/code/matlab/doc/
* and
* https://gist.github.com/yorkerlin/8a36e8f9b298aa0246a4
*/
#include <shogun/lib/config.h>
#ifdef HAVE_EIGEN3
#include <shogun/machine/GaussianProcessMachine.h>
#include <shogun/mathematics/Math.h>
#include <shogun/kernel/Kernel.h>
#include <shogun/machine/gp/SingleFITCLaplacianBase.h>
#include <shogun/mathematics/eigen3.h>
using namespace shogun;
using namespace Eigen;
CGaussianProcessMachine::CGaussianProcessMachine()
{
init();
}
CGaussianProcessMachine::CGaussianProcessMachine(CInferenceMethod* method)
{
init();
set_inference_method(method);
}
void CGaussianProcessMachine::init()
{
m_method=NULL;
SG_ADD((CSGObject**) &m_method, "inference_method", "Inference method",
MS_AVAILABLE);
}
CGaussianProcessMachine::~CGaussianProcessMachine()
{
SG_UNREF(m_method);
}
SGVector<float64_t> CGaussianProcessMachine::get_posterior_means(CFeatures* data)
{
REQUIRE(m_method, "Inference method should not be NULL\n")
CFeatures* feat;
// use inducing features for FITC inference method
if (m_method->get_inference_type()==INF_FITC_REGRESSION ||
m_method->get_inference_type()==INF_FITC_LAPLACIAN_SINGLE)
{
CSingleFITCLaplacianBase* fitc_method=
dynamic_cast<CSingleFITCLaplacianBase *>(m_method);
REQUIRE(fitc_method, "Inference method %s does not support FITC inference\n",
m_method->get_name());
feat=fitc_method->get_inducing_features();
}
else
feat=m_method->get_features();
// get kernel and compute kernel matrix: K(feat, data)*scale^2
CKernel* training_kernel=m_method->get_kernel();
CKernel* kernel=CKernel::obtain_from_generic(training_kernel->clone());
SG_UNREF(training_kernel);
kernel->init(feat, data);
// get kernel matrix and create eigen representation of it
SGMatrix<float64_t> k_trts=kernel->get_kernel_matrix();
Map<MatrixXd> eigen_Ks(k_trts.matrix, k_trts.num_rows, k_trts.num_cols);
// compute Ks=Ks*scale^2
eigen_Ks*=CMath::sq(m_method->get_scale());
// cleanup
SG_UNREF(feat);
SG_UNREF(kernel);
// get alpha and create eigen representation of it
SGVector<float64_t> alpha=m_method->get_alpha();
Map<VectorXd> eigen_alpha(alpha.vector, alpha.vlen);
// get mean and create eigen representation of it
CMeanFunction* mean_function=m_method->get_mean();
SGVector<float64_t> mean=mean_function->get_mean_vector(data);
Map<VectorXd> eigen_mean(mean.vector, mean.vlen);
SG_UNREF(mean_function);
const index_t C=alpha.vlen/k_trts.num_rows;
const index_t n=k_trts.num_rows;
const index_t m=k_trts.num_cols;
// compute mean: mu=Ks'*alpha+m
SGVector<float64_t> mu(C*m);
Map<MatrixXd> eigen_mu_matrix(mu.vector,C,m);
for(index_t bl=0; bl<C; bl++)
eigen_mu_matrix.block(bl,0,1,m)=(eigen_Ks.adjoint()*eigen_alpha.block(bl*n,0,n,1)+eigen_mean).transpose();
return mu;
}
SGVector<float64_t> CGaussianProcessMachine::get_posterior_variances(
CFeatures* data)
{
REQUIRE(m_method, "Inference method should not be NULL\n")
CFeatures* feat;
bool is_FITC=false;
// use inducing features for FITC inference method
if (m_method->get_inference_type()==INF_FITC_REGRESSION ||
m_method->get_inference_type()==INF_FITC_LAPLACIAN_SINGLE)
{
CSingleFITCLaplacianBase* fitc_method=
dynamic_cast<CSingleFITCLaplacianBase *>(m_method);
REQUIRE(fitc_method, "Inference method %s must support FITC inference\n",
m_method->get_name());
feat=fitc_method->get_inducing_features();
is_FITC=true;
}
else
feat=m_method->get_features();
SG_REF(data);
// get kernel and compute kernel matrix: K(data, data)*scale^2
CKernel* training_kernel=m_method->get_kernel();
CKernel* kernel=CKernel::obtain_from_generic(training_kernel->clone());
SG_UNREF(training_kernel);
kernel->init(data, data);
// get kernel matrix and create eigen representation of it
SGVector<float64_t> k_tsts=kernel->get_kernel_diagonal();
Map<VectorXd> eigen_Kss_diag(k_tsts.vector, k_tsts.vlen);
// compute Kss=Kss*scale^2
eigen_Kss_diag*=CMath::sq(m_method->get_scale());
// compute kernel matrix: K(feat, data)*scale^2
kernel->init(feat, data);
// get kernel matrix and create eigen representation of it
SGMatrix<float64_t> k_trts=kernel->get_kernel_matrix();
Map<MatrixXd> eigen_Ks(k_trts.matrix, k_trts.num_rows, k_trts.num_cols);
// compute Ks=Ks*scale^2
eigen_Ks*=CMath::sq(m_method->get_scale());
// cleanup
SG_UNREF(kernel);
SG_UNREF(feat);
SG_UNREF(data);
// get shogun representation of cholesky and create eigen representation
SGMatrix<float64_t> L=m_method->get_cholesky();
Map<MatrixXd> eigen_L(L.matrix, L.num_rows, L.num_cols);
SGVector<float64_t> alpha=m_method->get_alpha();
const index_t n=k_trts.num_rows;
const index_t m=k_tsts.vlen;
const index_t C=alpha.vlen/n;
// result variance vector
SGVector<float64_t> s2(m*C*C);
Map<VectorXd> eigen_s2(s2.vector, s2.vlen);
if (eigen_L.isUpperTriangular() && !is_FITC)
{
if (alpha.vlen==L.num_rows)
{
//binary case
// get shogun of diagonal sigma vector and create eigen representation
SGVector<float64_t> sW=m_method->get_diagonal_vector();
Map<VectorXd> eigen_sW(sW.vector, sW.vlen);
// solve L' * V = sW * Ks and compute V.^2
MatrixXd eigen_V=eigen_L.triangularView<Upper>().adjoint().solve(
eigen_sW.asDiagonal()*eigen_Ks);
MatrixXd eigen_sV=eigen_V.cwiseProduct(eigen_V);
eigen_s2=eigen_Kss_diag-eigen_sV.colwise().sum().adjoint();
}
else
{
if (m_method->supports_multiclass())
{
//multiclass case
//see the reference code of the gist link, which is based on the algorithm 3.4 of the GPML textbook
Map<MatrixXd> &eigen_M=eigen_L;
eigen_s2.fill(0);
SGMatrix<float64_t> E=m_method->get_multiclass_E();
Map<MatrixXd> eigen_E(E.matrix, E.num_rows, E.num_cols);
ASSERT(E.num_cols==alpha.vlen);
for(index_t bl_i=0; bl_i<C; bl_i++)
{
//n by m
MatrixXd bi=eigen_E.block(0,bl_i*n,n,n)*eigen_Ks;
MatrixXd c_cav=eigen_M.triangularView<Upper>().adjoint().solve(bi);
c_cav=eigen_M.triangularView<Upper>().solve(c_cav);
for(index_t bl_j=0; bl_j<C; bl_j++)
{
MatrixXd bj=eigen_E.block(0,bl_j*n,n,n)*eigen_Ks;
for (index_t idx_m=0; idx_m<m; idx_m++)
eigen_s2[bl_j+(bl_i+idx_m*C)*C]=(bj.block(0,idx_m,n,1).array()*c_cav.block(0,idx_m,n,1).array()).sum();
}
for (index_t idx_m=0; idx_m<m; idx_m++)
eigen_s2[bl_i+(bl_i+idx_m*C)*C]+=eigen_Kss_diag(idx_m)-(eigen_Ks.block(0,idx_m,n,1).array()*bi.block(0,idx_m,n,1).array()).sum();
}
}
else
{
SG_ERROR("Unsupported inference method!\n");
return s2;
}
}
}
else
{
// M = Ks .* (L * Ks)
MatrixXd eigen_M=eigen_Ks.cwiseProduct(eigen_L*eigen_Ks);
eigen_s2=eigen_Kss_diag+eigen_M.colwise().sum().adjoint();
}
return s2;
}
#endif /* HAVE_EIGEN3 */
<|endoftext|> |
<commit_before>/*
* linuxWaitingSlot.cpp
*
* Created on: 12. 10. 2017
* Author: ondra
*/
#include <fcntl.h>
#include <sys/socket.h>
#include <unistd.h>
#include "../exceptions.h"
#include "../mt.h"
#include "netEventDispatcher.h"
#include "../defer.h"
namespace simpleServer {
using ondra_shared::defer;
static LinuxEventDispatcher::Task empty_task([](AsyncState){},asyncOK);
LinuxEventDispatcher::LinuxEventDispatcher() {
int fds[2];
if (pipe2(fds, O_CLOEXEC)!=0) {
int err = errno;
throw SystemException(err,"Failed to call pipe2 (LinuxEventDispatcher)");
}
intrHandle = fds[1];
intrWaitHandle = fds[0];
addIntrWaitHandle();
exitFlag = false;
}
LinuxEventDispatcher::~LinuxEventDispatcher() noexcept {
close(intrHandle);
close(intrWaitHandle);
}
LinuxEventDispatcher::Task LinuxEventDispatcher::runQueue() {
std::lock_guard<std::mutex> _(queueLock);
char b;
::read(intrWaitHandle, &b, 1);
if (!queue.empty()) {
const RegReq &r = queue.front();
if (r.ares.socket == 0 && r.ares.socket == 0) {
return Task(r.extra.completionFn,asyncOK);
} else if (r.extra.completionFn == nullptr) {
return findAndCancel(r.ares);
} else {
addResource(r);
queue.pop();
}
}
return Task();
}
LinuxEventDispatcher::Task LinuxEventDispatcher::findAndCancel(const AsyncResource &res) {
CompletionFn curFn = nullptr;
int cnt = (int)fdmap.size();
for (int i = 0; i < cnt; i++) {
if (fdmap[i].fd == res.socket && fdmap[i].events == res.op) {
if (curFn ==nullptr) curFn = fdextramap[i].completionFn;
else {
CompletionFn otherFn = fdextramap[i].completionFn;
curFn = [curFn,otherFn](AsyncState st) {
curFn(st);
otherFn(st);
};
}
deleteResource(i);
--i;
--cnt;
}
}
return Task(curFn,asyncCancel);
}
void LinuxEventDispatcher::addIntrWaitHandle() {
RegReq rq;
rq.ares = AsyncResource(intrWaitHandle, POLLIN);
rq.extra.completionFn = empty_task;
rq.extra.timeout = TimePoint::max();
addResource(rq);
}
void LinuxEventDispatcher::runAsync(const AsyncResource &resource, int timeout, const CompletionFn &complfn) {
if (exitFlag || complfn == nullptr) {
defer >> std::bind(complfn, asyncCancel);
return;
}
RegReq req;
req.ares = resource;
req.extra.completionFn = complfn;
if (timeout < 0) req.extra.timeout = TimePoint::max();
else req.extra.timeout = TimePoint::clock::now() + std::chrono::milliseconds(timeout);
std::lock_guard<std::mutex> _(queueLock);
queue.push(req);
sendIntr();
}
void LinuxEventDispatcher::runAsync(const CustomFn &completion) {
if (exitFlag || completion == nullptr) {
defer >> completion;
return;
}
RegReq req;
req.extra.completionFn = [fn=CustomFn(completion)](AsyncState){fn();};
std::lock_guard<std::mutex> _(queueLock);
queue.push(req);
sendIntr();
}
void LinuxEventDispatcher::addResource(const RegReq &req) {
pollfd pfd;
pfd.events = req.ares.op;
pfd.fd = req.ares.socket;
pfd.revents = 0;
fdmap.push_back(pfd);
fdextramap.push_back(req.extra);
if (req.extra.timeout < nextTimeout) nextTimeout = req.extra.timeout;
}
void LinuxEventDispatcher::deleteResource(int index) {
int last = fdmap.size()-1;
if (index < last) {
std::swap(fdmap[index],fdmap[last]);
std::swap(fdextramap[index],fdextramap[last]);
}
fdmap.resize(last);
fdextramap.resize(last);
}
LinuxEventDispatcher::Task LinuxEventDispatcher::checkEvents(const TimePoint &now, bool finish) {
int sz = static_cast<int>(fdmap.size());
if (last_checked >= sz) {
if (finish) return Task();
last_checked = 0;
nextTimeout = TimePoint::max();
}
while (last_checked < sz) {
int idx = last_checked++;
if (fdmap[idx].revents) {
if (fdmap[idx].fd == intrWaitHandle) {
Task t = runQueue();
fdmap[idx].revents = 0;
if (t != nullptr) return t;
} else {
Task t(fdextramap[idx].completionFn, asyncOK);
deleteResource(idx);
--last_checked;
return t;
}
} else if (fdextramap[idx].timeout<=now) {
Task t(fdextramap[idx].completionFn, asyncTimeout);
deleteResource(idx);
--last_checked;
return t;
} else if (fdextramap[idx].timeout<nextTimeout) {
nextTimeout = fdextramap[idx].timeout;
}
}
return Task();
}
///returns true, if the listener doesn't contain any asynchronous task
bool LinuxEventDispatcher::empty() const {
return fdmap.empty();
}
void LinuxEventDispatcher::stop() {
exitFlag = true;
sendIntr();
}
unsigned int LinuxEventDispatcher::getPendingCount() const {
return fdmap.size();
}
void LinuxEventDispatcher::cancel(const AsyncResource& resource) {
RegReq req;
req.ares = resource;
req.extra.completionFn = nullptr;
std::lock_guard<std::mutex> _(queueLock);
queue.push(req);
sendIntr();
}
LinuxEventDispatcher::Task LinuxEventDispatcher::cleanup() {
if (!fdmap.empty()) {
int idx = fdmap.size()-1;
Task t(fdextramap[idx].completionFn, asyncCancel);
deleteResource(idx);
return t;
} else {
return Task();
}
}
LinuxEventDispatcher::Task LinuxEventDispatcher::wait() {
if (exitFlag) {
return cleanup();
}
TimePoint now = std::chrono::steady_clock::now();
Task x = checkEvents(now,true);
if (x != nullptr) return x;
auto int_ms = std::chrono::duration_cast<std::chrono::milliseconds>(nextTimeout - now);
int r = poll(fdmap.data(),fdmap.size(),int_ms.count());
if (r < 0) {
int e = errno;
if (e != EINTR && e != EAGAIN)
throw SystemException(e, "Failed to call poll()");
} else {
now = std::chrono::steady_clock::now();
x = checkEvents(now,false);
if (x != nullptr) return x;
}
return empty_task;
}
void LinuxEventDispatcher::sendIntr() {
unsigned char b = 1;
int r = ::write(intrHandle, &b, 1);
if (r < 0) {
throw SystemException(errno);
}
}
PStreamEventDispatcher AbstractStreamEventDispatcher::create() {
return new LinuxEventDispatcher;
}
} /* namespace simpleServer */
<commit_msg>ignore result of read operation<commit_after>/*
* linuxWaitingSlot.cpp
*
* Created on: 12. 10. 2017
* Author: ondra
*/
#include <fcntl.h>
#include <sys/socket.h>
#include <unistd.h>
#include "../exceptions.h"
#include "../mt.h"
#include "netEventDispatcher.h"
#include "../defer.h"
namespace simpleServer {
using ondra_shared::defer;
static LinuxEventDispatcher::Task empty_task([](AsyncState){},asyncOK);
LinuxEventDispatcher::LinuxEventDispatcher() {
int fds[2];
if (pipe2(fds, O_CLOEXEC)!=0) {
int err = errno;
throw SystemException(err,"Failed to call pipe2 (LinuxEventDispatcher)");
}
intrHandle = fds[1];
intrWaitHandle = fds[0];
addIntrWaitHandle();
exitFlag = false;
}
LinuxEventDispatcher::~LinuxEventDispatcher() noexcept {
close(intrHandle);
close(intrWaitHandle);
}
template<typename T>
void ignore_variable(T) {}
LinuxEventDispatcher::Task LinuxEventDispatcher::runQueue() {
std::lock_guard<std::mutex> _(queueLock);
char b;
ignore_variable(::read(intrWaitHandle, &b, 1));
if (!queue.empty()) {
const RegReq &r = queue.front();
if (r.ares.socket == 0 && r.ares.socket == 0) {
return Task(r.extra.completionFn,asyncOK);
} else if (r.extra.completionFn == nullptr) {
return findAndCancel(r.ares);
} else {
addResource(r);
queue.pop();
}
}
return Task();
}
LinuxEventDispatcher::Task LinuxEventDispatcher::findAndCancel(const AsyncResource &res) {
CompletionFn curFn = nullptr;
int cnt = (int)fdmap.size();
for (int i = 0; i < cnt; i++) {
if (fdmap[i].fd == res.socket && fdmap[i].events == res.op) {
if (curFn ==nullptr) curFn = fdextramap[i].completionFn;
else {
CompletionFn otherFn = fdextramap[i].completionFn;
curFn = [curFn,otherFn](AsyncState st) {
curFn(st);
otherFn(st);
};
}
deleteResource(i);
--i;
--cnt;
}
}
return Task(curFn,asyncCancel);
}
void LinuxEventDispatcher::addIntrWaitHandle() {
RegReq rq;
rq.ares = AsyncResource(intrWaitHandle, POLLIN);
rq.extra.completionFn = empty_task;
rq.extra.timeout = TimePoint::max();
addResource(rq);
}
void LinuxEventDispatcher::runAsync(const AsyncResource &resource, int timeout, const CompletionFn &complfn) {
if (exitFlag || complfn == nullptr) {
defer >> std::bind(complfn, asyncCancel);
return;
}
RegReq req;
req.ares = resource;
req.extra.completionFn = complfn;
if (timeout < 0) req.extra.timeout = TimePoint::max();
else req.extra.timeout = TimePoint::clock::now() + std::chrono::milliseconds(timeout);
std::lock_guard<std::mutex> _(queueLock);
queue.push(req);
sendIntr();
}
void LinuxEventDispatcher::runAsync(const CustomFn &completion) {
if (exitFlag || completion == nullptr) {
defer >> completion;
return;
}
RegReq req;
req.extra.completionFn = [fn=CustomFn(completion)](AsyncState){fn();};
std::lock_guard<std::mutex> _(queueLock);
queue.push(req);
sendIntr();
}
void LinuxEventDispatcher::addResource(const RegReq &req) {
pollfd pfd;
pfd.events = req.ares.op;
pfd.fd = req.ares.socket;
pfd.revents = 0;
fdmap.push_back(pfd);
fdextramap.push_back(req.extra);
if (req.extra.timeout < nextTimeout) nextTimeout = req.extra.timeout;
}
void LinuxEventDispatcher::deleteResource(int index) {
int last = fdmap.size()-1;
if (index < last) {
std::swap(fdmap[index],fdmap[last]);
std::swap(fdextramap[index],fdextramap[last]);
}
fdmap.resize(last);
fdextramap.resize(last);
}
LinuxEventDispatcher::Task LinuxEventDispatcher::checkEvents(const TimePoint &now, bool finish) {
int sz = static_cast<int>(fdmap.size());
if (last_checked >= sz) {
if (finish) return Task();
last_checked = 0;
nextTimeout = TimePoint::max();
}
while (last_checked < sz) {
int idx = last_checked++;
if (fdmap[idx].revents) {
if (fdmap[idx].fd == intrWaitHandle) {
Task t = runQueue();
fdmap[idx].revents = 0;
if (t != nullptr) return t;
} else {
Task t(fdextramap[idx].completionFn, asyncOK);
deleteResource(idx);
--last_checked;
return t;
}
} else if (fdextramap[idx].timeout<=now) {
Task t(fdextramap[idx].completionFn, asyncTimeout);
deleteResource(idx);
--last_checked;
return t;
} else if (fdextramap[idx].timeout<nextTimeout) {
nextTimeout = fdextramap[idx].timeout;
}
}
return Task();
}
///returns true, if the listener doesn't contain any asynchronous task
bool LinuxEventDispatcher::empty() const {
return fdmap.empty();
}
void LinuxEventDispatcher::stop() {
exitFlag = true;
sendIntr();
}
unsigned int LinuxEventDispatcher::getPendingCount() const {
return fdmap.size();
}
void LinuxEventDispatcher::cancel(const AsyncResource& resource) {
RegReq req;
req.ares = resource;
req.extra.completionFn = nullptr;
std::lock_guard<std::mutex> _(queueLock);
queue.push(req);
sendIntr();
}
LinuxEventDispatcher::Task LinuxEventDispatcher::cleanup() {
if (!fdmap.empty()) {
int idx = fdmap.size()-1;
Task t(fdextramap[idx].completionFn, asyncCancel);
deleteResource(idx);
return t;
} else {
return Task();
}
}
LinuxEventDispatcher::Task LinuxEventDispatcher::wait() {
if (exitFlag) {
return cleanup();
}
TimePoint now = std::chrono::steady_clock::now();
Task x = checkEvents(now,true);
if (x != nullptr) return x;
auto int_ms = std::chrono::duration_cast<std::chrono::milliseconds>(nextTimeout - now);
int r = poll(fdmap.data(),fdmap.size(),int_ms.count());
if (r < 0) {
int e = errno;
if (e != EINTR && e != EAGAIN)
throw SystemException(e, "Failed to call poll()");
} else {
now = std::chrono::steady_clock::now();
x = checkEvents(now,false);
if (x != nullptr) return x;
}
return empty_task;
}
void LinuxEventDispatcher::sendIntr() {
unsigned char b = 1;
int r = ::write(intrHandle, &b, 1);
if (r < 0) {
throw SystemException(errno);
}
}
PStreamEventDispatcher AbstractStreamEventDispatcher::create() {
return new LinuxEventDispatcher;
}
} /* namespace simpleServer */
<|endoftext|> |
<commit_before>#include "wled.h"
/*
* Adalight and TPM2 handler
*/
enum class AdaState {
Header_A,
Header_d,
Header_a,
Header_CountHi,
Header_CountLo,
Header_CountCheck,
Data_Red,
Data_Green,
Data_Blue,
TPM2_Header_Type,
TPM2_Header_CountHi,
TPM2_Header_CountLo,
};
void handleSerial()
{
if (pinManager.isPinAllocated(3)) return;
#ifdef WLED_ENABLE_ADALIGHT
static auto state = AdaState::Header_A;
static uint16_t count = 0;
static uint16_t pixel = 0;
static byte check = 0x00;
static byte red = 0x00;
static byte green = 0x00;
while (Serial.available() > 0)
{
yield();
byte next = Serial.peek();
switch (state) {
case AdaState::Header_A:
if (next == 'A') state = AdaState::Header_d;
else if (next == 0xC9) { //TPM2 start byte
state = AdaState::TPM2_Header_Type;
}
else if (next == 'I') {
handleImprovPacket();
return;
} else if (next == 'v') {
Serial.print("WLED"); Serial.write(' '); Serial.println(VERSION);
} else if (next == '{') { //JSON API
bool verboseResponse = false;
#ifdef WLED_USE_DYNAMIC_JSON
DynamicJsonDocument doc(JSON_BUFFER_SIZE);
#else
if (!requestJSONBufferLock(16)) return;
#endif
Serial.setTimeout(100);
DeserializationError error = deserializeJson(doc, Serial);
if (error) {
releaseJSONBufferLock();
return;
}
verboseResponse = deserializeState(doc.as<JsonObject>());
//only send response if TX pin is unused for other purposes
if (verboseResponse && !pinManager.isPinAllocated(1)) {
doc.clear();
JsonObject state = doc.createNestedObject("state");
serializeState(state);
JsonObject info = doc.createNestedObject("info");
serializeInfo(info);
serializeJson(doc, Serial);
Serial.println();
}
releaseJSONBufferLock();
}
break;
case AdaState::Header_d:
if (next == 'd') state = AdaState::Header_a;
else state = AdaState::Header_A;
break;
case AdaState::Header_a:
if (next == 'a') state = AdaState::Header_CountHi;
else state = AdaState::Header_A;
break;
case AdaState::Header_CountHi:
pixel = 0;
count = next * 0x100;
check = next;
state = AdaState::Header_CountLo;
break;
case AdaState::Header_CountLo:
count += next + 1;
check = check ^ next ^ 0x55;
state = AdaState::Header_CountCheck;
break;
case AdaState::Header_CountCheck:
if (check == next) state = AdaState::Data_Red;
else state = AdaState::Header_A;
break;
case AdaState::TPM2_Header_Type:
state = AdaState::Header_A; //(unsupported) TPM2 command or invalid type
if (next == 0xDA) state = AdaState::TPM2_Header_CountHi; //TPM2 data
else if (next == 0xAA) Serial.write(0xAC); //TPM2 ping
break;
case AdaState::TPM2_Header_CountHi:
pixel = 0;
count = (next * 0x100) /3;
state = AdaState::TPM2_Header_CountLo;
break;
case AdaState::TPM2_Header_CountLo:
count += next /3;
state = AdaState::Data_Red;
break;
case AdaState::Data_Red:
red = next;
state = AdaState::Data_Green;
break;
case AdaState::Data_Green:
green = next;
state = AdaState::Data_Blue;
break;
case AdaState::Data_Blue:
byte blue = next;
if (!realtimeOverride) setRealtimePixel(pixel++, red, green, blue, 0);
if (--count > 0) state = AdaState::Data_Red;
else {
if (!realtimeMode && bri == 0) strip.setBrightness(briLast);
realtimeLock(realtimeTimeoutMs, REALTIME_MODE_ADALIGHT);
if (!realtimeOverride) strip.show();
state = AdaState::Header_A;
}
break;
}
Serial.read(); //discard the byte
}
#endif
}
<commit_msg>Update wled_serial.cpp<commit_after>#include "wled.h"
/*
* Adalight and TPM2 handler
*/
enum class AdaState {
Header_A,
Header_d,
Header_a,
Header_CountHi,
Header_CountLo,
Header_CountCheck,
Data_Red,
Data_Green,
Data_Blue,
TPM2_Header_Type,
TPM2_Header_CountHi,
TPM2_Header_CountLo,
};
void update_baud_rate(int rate){
if (!pinManager.isPinAllocated(1)){
Serial.print("ATTENTION! Baud rate is changing to "); Serial.println(rate);
delay(100);
Serial.end();
Serial.begin(rate);
}
}
void handleSerial()
{
if (pinManager.isPinAllocated(3)) return;
#ifdef WLED_ENABLE_ADALIGHT
static auto state = AdaState::Header_A;
static uint16_t count = 0;
static uint16_t pixel = 0;
static byte check = 0x00;
static byte red = 0x00;
static byte green = 0x00;
uint16_t nBytes = 0;
while (Serial.available() > 0)
{
yield();
byte next = Serial.peek();
switch (state) {
case AdaState::Header_A:
if (next == 'A') state = AdaState::Header_d;
else if (next == 0xC9) { //TPM2 start byte
state = AdaState::TPM2_Header_Type;
}
else if (next == 'I') {
handleImprovPacket();
return;
} else if (next == 'v') {
Serial.print("WLED"); Serial.write(' '); Serial.println(VERSION);
} else if ( next == 0xB0 ){ update_baud_rate( 115200 );
} else if ( next == 0xB1 ){ update_baud_rate( 230400 );
} else if ( next == 0xB2 ){ update_baud_rate( 460800 );
} else if ( next == 0xB3 ){ update_baud_rate( 500000 );
} else if ( next == 0xB4 ){ update_baud_rate( 576000 );
} else if ( next == 0xB5 ){ update_baud_rate( 921600 );
} else if ( next == 0xB6 ){ update_baud_rate( 1000000 );
} else if ( next == 0xB7 ){ update_baud_rate( 1500000 );
} else if (next == 'l'){ // LED Data return in JSON blob. Slow, but easy to use on the other end.
if (!pinManager.isPinAllocated(1)){
uint16_t used = strip.getLengthTotal();
Serial.print("[");
for (uint16_t i=0; i<used; i+=1){
Serial.print(strip.getPixelColor(i));
if (i != used-1) {Serial.print(",");}}
Serial.println("]");}
} else if (next == 'L'){ // LED Data returned as bytes. Faster, and slightly less easy to use on the other end.
if (!pinManager.isPinAllocated(1)){
// first byte sent back denotes number of color bytes. 0x00 RGB, 0x01 RGBW, 0x02 ??? etc
if (strip.isRgbw){ // alternate idea, merge the white channel down into RGB like recent websocket update. or perhaps 0x02 should be merged white chanel
Serial.write(0x01);
nBytes = 4;}
else{
Serial.write(0x00);
nBytes = 3;}
uint16_t used = strip.getLengthTotal();
for (uint16_t i=0; i<used; i+=1){
uint32_t thing = strip.getPixelColor(i);
Serial.write((byte *) &thing, nBytes);}
Serial.println();}
} else if (next == '{') { //JSON API
bool verboseResponse = false;
#ifdef WLED_USE_DYNAMIC_JSON
DynamicJsonDocument doc(JSON_BUFFER_SIZE);
#else
if (!requestJSONBufferLock(16)) return;
#endif
Serial.setTimeout(100);
DeserializationError error = deserializeJson(doc, Serial);
if (error) {
releaseJSONBufferLock();
return;
}
verboseResponse = deserializeState(doc.as<JsonObject>());
//only send response if TX pin is unused for other purposes
if (verboseResponse && !pinManager.isPinAllocated(1)) {
doc.clear();
JsonObject state = doc.createNestedObject("state");
serializeState(state);
JsonObject info = doc.createNestedObject("info");
serializeInfo(info);
serializeJson(doc, Serial);
Serial.println();
}
releaseJSONBufferLock();
}
break;
case AdaState::Header_d:
if (next == 'd') state = AdaState::Header_a;
else state = AdaState::Header_A;
break;
case AdaState::Header_a:
if (next == 'a') state = AdaState::Header_CountHi;
else state = AdaState::Header_A;
break;
case AdaState::Header_CountHi:
pixel = 0;
count = next * 0x100;
check = next;
state = AdaState::Header_CountLo;
break;
case AdaState::Header_CountLo:
count += next + 1;
check = check ^ next ^ 0x55;
state = AdaState::Header_CountCheck;
break;
case AdaState::Header_CountCheck:
if (check == next) state = AdaState::Data_Red;
else state = AdaState::Header_A;
break;
case AdaState::TPM2_Header_Type:
state = AdaState::Header_A; //(unsupported) TPM2 command or invalid type
if (next == 0xDA) state = AdaState::TPM2_Header_CountHi; //TPM2 data
else if (next == 0xAA) Serial.write(0xAC); //TPM2 ping
break;
case AdaState::TPM2_Header_CountHi:
pixel = 0;
count = (next * 0x100) /3;
state = AdaState::TPM2_Header_CountLo;
break;
case AdaState::TPM2_Header_CountLo:
count += next /3;
state = AdaState::Data_Red;
break;
case AdaState::Data_Red:
red = next;
state = AdaState::Data_Green;
break;
case AdaState::Data_Green:
green = next;
state = AdaState::Data_Blue;
break;
case AdaState::Data_Blue:
byte blue = next;
if (!realtimeOverride) setRealtimePixel(pixel++, red, green, blue, 0);
if (--count > 0) state = AdaState::Data_Red;
else {
if (!realtimeMode && bri == 0) strip.setBrightness(briLast);
realtimeLock(realtimeTimeoutMs, REALTIME_MODE_ADALIGHT);
if (!realtimeOverride) strip.show();
state = AdaState::Header_A;
}
break;
}
Serial.read(); //discard the byte
}
#endif
}
<|endoftext|> |
<commit_before>// This file is part of the AliceVision project.
// 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 https://mozilla.org/MPL/2.0/.
#include <aliceVision/feature/imageDescriberCommon.hpp>
#include <aliceVision/sfm/sfm.hpp>
#include <aliceVision/sfm/pipeline/regionsIO.hpp>
#include <aliceVision/system/Timer.hpp>
#include <aliceVision/system/Logger.hpp>
#include <aliceVision/system/cmdline.hpp>
#include <dependencies/stlplus3/filesystemSimplified/file_system.hpp>
#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>
#include <cstdlib>
using namespace aliceVision;
using namespace aliceVision::camera;
using namespace aliceVision::sfm;
using namespace aliceVision::feature;
using namespace std;
namespace po = boost::program_options;
/**
* @brief Retrieve the view id in the sfmData from the image filename.
*
* @param[in] sfm_data the SfM scene
* @param[in] initialName the image name to find (filename or path)
* @param[out] out_viewId the id found
* @return if a view is found
*/
bool retrieveViewIdFromImageName(
const SfMData & sfm_data,
const std::string& initialName,
IndexT& out_viewId)
{
out_viewId = UndefinedIndexT;
bool isName = (initialName == stlplus::filename_part(initialName));
/// List views filenames and find the one that correspond to the user ones:
for(Views::const_iterator it = sfm_data.GetViews().begin();
it != sfm_data.GetViews().end(); ++it)
{
const View * v = it->second.get();
std::string filename;
if(isName)
filename = stlplus::filename_part(v->getImagePath());
else if(stlplus::is_full_path(v->getImagePath()))
filename = v->getImagePath();
else
filename = v->getImagePath();
if (filename == initialName)
{
if(out_viewId == UndefinedIndexT)
out_viewId = v->getViewId();
else
std::cout<<"Error: Two pictures named :" << initialName << " !" << std::endl;
}
}
return out_viewId != UndefinedIndexT;
}
int main(int argc, char **argv)
{
// command-line parameters
std::string verboseLevel = system::EVerboseLevel_enumToString(system::Logger::getDefaultVerboseLevel());
std::string sfmDataFilename;
std::string featuresFolder;
std::string matchesFolder;
std::string outputSfM;
// user optional parameters
std::string outputSfMViewsAndPoses;
std::string extraInfoFolder;
std::string describerTypesName = feature::EImageDescriberType_enumToString(feature::EImageDescriberType::SIFT);
std::string outInterFileExtension = ".ply";
std::pair<std::string,std::string> initialPairString("","");
int minInputTrackLength = 2;
int maxNbMatches = 0;
std::size_t minNbObservationsForTriangulation = 2;
bool refineIntrinsics = true;
bool useLocalBundleAdjustment = false;
std::size_t localBundelAdjustementGraphDistanceLimit = 1;
std::string localizerEstimatorName = robustEstimation::ERobustEstimator_enumToString(robustEstimation::ERobustEstimator::ACRANSAC);
po::options_description allParams(
"Sequential/Incremental reconstruction\n"
"Perform incremental SfM (Initial Pair Essential + Resection)\n"
"AliceVision incrementalSfM");
po::options_description requiredParams("Required parameters");
requiredParams.add_options()
("input,i", po::value<std::string>(&sfmDataFilename)->required(),
"SfMData file.")
("output,o", po::value<std::string>(&outputSfM)->required(),
"Path to the output SfMData file.")
("featuresFolder,f", po::value<std::string>(&featuresFolder)->required(),
"Path to a folder containing the extracted features.")
("matchesFolder,m", po::value<std::string>(&matchesFolder)->required(),
"Path to a folder in which computed matches are stored.");
po::options_description optionalParams("Optional parameters");
optionalParams.add_options()
("outputViewsAndPoses", po::value<std::string>(&outputSfMViewsAndPoses)->default_value(outputSfMViewsAndPoses),
"Path to the output SfMData file (with only views and poses).")
("extraInfoFolder", po::value<std::string>(&extraInfoFolder)->default_value(extraInfoFolder),
"Folder for intermediate reconstruction files and additional reconstruction information files.")
("describerTypes,d", po::value<std::string>(&describerTypesName)->default_value(describerTypesName),
feature::EImageDescriberType_informations().c_str())
("interFileExtension", po::value<std::string>(&outInterFileExtension)->default_value(outInterFileExtension),
"Extension of the intermediate file export.")
("minInputTrackLength", po::value<int>(&minInputTrackLength)->default_value(minInputTrackLength),
"Minimum track length in input of SfM.")
("maxNumberOfMatches", po::value<int>(&maxNbMatches)->default_value(maxNbMatches),
"Maximum number of matches per image pair (and per feature type). "
"This can be useful to have a quick reconstruction overview. 0 means no limit.")
("minNumberOfObservationsForTriangulation", po::value<std::size_t>(&minNbObservationsForTriangulation)->default_value(minNbObservationsForTriangulation),
"Minimum number of observations to triangulate a point.\n"
"Set it to 3 (or more) reduces drastically the noise in the point cloud, but the number of final poses is a little bit reduced (from 1.5% to 11% on the tested datasets).\n"
"Note: set it to 0 or 1 to use the old triangulation algorithm (using 2 views only) during resection.")
("initialPairA", po::value<std::string>(&initialPairString.first)->default_value(initialPairString.first),
"filename of the first image (without path).")
("initialPairB", po::value<std::string>(&initialPairString.second)->default_value(initialPairString.second),
"filename of the second image (without path).")
("refineIntrinsics", po::value<bool>(&refineIntrinsics)->default_value(refineIntrinsics),
"Refine intrinsic parameters.")
("useLocalBA,l", po::value<bool>(&useLocalBundleAdjustment)->default_value(useLocalBundleAdjustment),
"Enable/Disable the Local bundle adjustment strategy.\n"
"It reduces the reconstruction time, especially for big datasets (500+ images).")
("localBAGraphDistance", po::value<std::size_t>(&localBundelAdjustementGraphDistanceLimit)->default_value(localBundelAdjustementGraphDistanceLimit),
"Graph-distance limit setting the Active region in the Local Bundle Adjustment strategy.")
("localizerEstimator", po::value<std::string>(&localizerEstimatorName)->default_value(localizerEstimatorName),
"Estimator type used to localize cameras (acransac (default), ransac, lsmeds, loransac, maxconsensus)");
po::options_description logParams("Log parameters");
logParams.add_options()
("verboseLevel,v", po::value<std::string>(&verboseLevel)->default_value(verboseLevel),
"verbosity level (fatal, error, warning, info, debug, trace).");
allParams.add(requiredParams).add(optionalParams).add(logParams);
po::variables_map vm;
try
{
po::store(po::parse_command_line(argc, argv, allParams), vm);
if(vm.count("help") || (argc == 1))
{
ALICEVISION_COUT(allParams);
return EXIT_SUCCESS;
}
po::notify(vm);
}
catch(boost::program_options::required_option& e)
{
ALICEVISION_CERR("ERROR: " << e.what());
ALICEVISION_COUT("Usage:\n\n" << allParams);
return EXIT_FAILURE;
}
catch(boost::program_options::error& e)
{
ALICEVISION_CERR("ERROR: " << e.what());
ALICEVISION_COUT("Usage:\n\n" << allParams);
return EXIT_FAILURE;
}
ALICEVISION_COUT("Program called with the following parameters:");
ALICEVISION_COUT(vm);
// set verbose level
system::Logger::get()->setLogLevel(verboseLevel);
// load input SfMData scene
SfMData sfmData;
if(!Load(sfmData, sfmDataFilename, ESfMData::ALL))
{
ALICEVISION_LOG_ERROR("Error: The input SfMData file '" + sfmDataFilename + "' cannot be read.");
return EXIT_FAILURE;
}
// get imageDescriber type
const std::vector<feature::EImageDescriberType> describerTypes = feature::EImageDescriberType_stringToEnums(describerTypesName);
// features reading
feature::FeaturesPerView featuresPerView;
if(!sfm::loadFeaturesPerView(featuresPerView, sfmData, featuresFolder, describerTypes))
{
ALICEVISION_LOG_ERROR("Invalid features.");
return EXIT_FAILURE;
}
// matches reading
matching::PairwiseMatches pairwiseMatches;
if(!sfm::loadPairwiseMatches(pairwiseMatches, sfmData, matchesFolder, describerTypes, "f", maxNbMatches))
{
ALICEVISION_LOG_ERROR("Unable to load matches file from '" + matchesFolder + "'.");
return EXIT_FAILURE;
}
if(extraInfoFolder.empty())
{
namespace bfs = boost::filesystem;
extraInfoFolder = bfs::path(outputSfM).parent_path().string();
}
if (!stlplus::folder_exists(extraInfoFolder))
stlplus::folder_create(extraInfoFolder);
// sequential reconstruction process
aliceVision::system::Timer timer;
ReconstructionEngine_sequentialSfM sfmEngine(
sfmData,
extraInfoFolder,
stlplus::create_filespec(extraInfoFolder, "sfm_log.html"));
// configure the featuresPerView & the matches_provider
sfmEngine.setFeatures(&featuresPerView);
sfmEngine.setMatches(&pairwiseMatches);
// configure reconstruction parameters
sfmEngine.Set_bFixedIntrinsics(!refineIntrinsics);
sfmEngine.setMinInputTrackLength(minInputTrackLength);
sfmEngine.setIntermediateFileExtension(outInterFileExtension);
sfmEngine.setUseLocalBundleAdjustmentStrategy(useLocalBundleAdjustment);
sfmEngine.setLocalBundleAdjustmentGraphDistance(localBundelAdjustementGraphDistanceLimit);
sfmEngine.setLocalizerEstimator(robustEstimation::ERobustEstimator_stringToEnum(localizerEstimatorName));
if(minNbObservationsForTriangulation < 2)
{
// allows to use to the old triangulatation algorithm (using 2 views only) during resection.
minNbObservationsForTriangulation = 0;
// ALICEVISION_LOG_ERROR("The value associated to the argument '--minNbObservationsForTriangulation' must be >= 2 ");
// return EXIT_FAILURE;
}
sfmEngine.setNbOfObservationsForTriangulation(minNbObservationsForTriangulation);
// handle Initial pair parameter
if(!initialPairString.first.empty() && !initialPairString.second.empty())
{
if(initialPairString.first == initialPairString.second)
{
ALICEVISION_LOG_ERROR("Invalid image names. You cannot use the same image to initialize a pair.");
return EXIT_FAILURE;
}
Pair initialPairIndex;
if(!retrieveViewIdFromImageName(sfmData, initialPairString.first, initialPairIndex.first)
|| !retrieveViewIdFromImageName(sfmData, initialPairString.second, initialPairIndex.second))
{
ALICEVISION_LOG_ERROR("Could not find the initial pairs (" + initialPairString.first + ", " + initialPairString.second + ") !");
return EXIT_FAILURE;
}
sfmEngine.setInitialPair(initialPairIndex);
}
if(!sfmEngine.Process())
return EXIT_FAILURE;
// get the color for the 3D points
if(!sfmEngine.Colorize())
ALICEVISION_LOG_ERROR("Colorize failed !");
sfmEngine.Get_SfMData().addFeaturesFolder(featuresFolder);
sfmEngine.Get_SfMData().addMatchesFolder(matchesFolder);
ALICEVISION_LOG_INFO("Structure from motion took (s): " + std::to_string(timer.elapsed()));
ALICEVISION_LOG_INFO("Generating HTML report...");
Generate_SfM_Report(sfmEngine.Get_SfMData(), stlplus::create_filespec(extraInfoFolder, "sfm_report.html"));
// export to disk computed scene (data & visualizable results)
ALICEVISION_LOG_INFO("Export SfMData to disk: " + outputSfM);
Save(sfmEngine.Get_SfMData(), stlplus::create_filespec(extraInfoFolder, "cloud_and_poses", outInterFileExtension), ESfMData(VIEWS | EXTRINSICS | INTRINSICS | STRUCTURE));
Save(sfmEngine.Get_SfMData(), outputSfM, ESfMData(ALL));
if(!outputSfMViewsAndPoses.empty())
Save(sfmEngine.Get_SfMData(), outputSfMViewsAndPoses, ESfMData(VIEWS | EXTRINSICS | INTRINSICS));
return EXIT_SUCCESS;
}
<commit_msg>[software] `incrementalSfM` : Add results log<commit_after>// This file is part of the AliceVision project.
// 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 https://mozilla.org/MPL/2.0/.
#include <aliceVision/feature/imageDescriberCommon.hpp>
#include <aliceVision/sfm/sfm.hpp>
#include <aliceVision/sfm/pipeline/regionsIO.hpp>
#include <aliceVision/system/Timer.hpp>
#include <aliceVision/system/Logger.hpp>
#include <aliceVision/system/cmdline.hpp>
#include <dependencies/stlplus3/filesystemSimplified/file_system.hpp>
#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>
#include <cstdlib>
using namespace aliceVision;
using namespace aliceVision::camera;
using namespace aliceVision::sfm;
using namespace aliceVision::feature;
using namespace std;
namespace po = boost::program_options;
/**
* @brief Retrieve the view id in the sfmData from the image filename.
*
* @param[in] sfm_data the SfM scene
* @param[in] initialName the image name to find (filename or path)
* @param[out] out_viewId the id found
* @return if a view is found
*/
bool retrieveViewIdFromImageName(
const SfMData & sfm_data,
const std::string& initialName,
IndexT& out_viewId)
{
out_viewId = UndefinedIndexT;
bool isName = (initialName == stlplus::filename_part(initialName));
/// List views filenames and find the one that correspond to the user ones:
for(Views::const_iterator it = sfm_data.GetViews().begin();
it != sfm_data.GetViews().end(); ++it)
{
const View * v = it->second.get();
std::string filename;
if(isName)
filename = stlplus::filename_part(v->getImagePath());
else if(stlplus::is_full_path(v->getImagePath()))
filename = v->getImagePath();
else
filename = v->getImagePath();
if (filename == initialName)
{
if(out_viewId == UndefinedIndexT)
out_viewId = v->getViewId();
else
std::cout<<"Error: Two pictures named :" << initialName << " !" << std::endl;
}
}
return out_viewId != UndefinedIndexT;
}
int main(int argc, char **argv)
{
// command-line parameters
std::string verboseLevel = system::EVerboseLevel_enumToString(system::Logger::getDefaultVerboseLevel());
std::string sfmDataFilename;
std::string featuresFolder;
std::string matchesFolder;
std::string outputSfM;
// user optional parameters
std::string outputSfMViewsAndPoses;
std::string extraInfoFolder;
std::string describerTypesName = feature::EImageDescriberType_enumToString(feature::EImageDescriberType::SIFT);
std::string outInterFileExtension = ".ply";
std::pair<std::string,std::string> initialPairString("","");
int minInputTrackLength = 2;
int maxNbMatches = 0;
std::size_t minNbObservationsForTriangulation = 2;
bool refineIntrinsics = true;
bool useLocalBundleAdjustment = false;
std::size_t localBundelAdjustementGraphDistanceLimit = 1;
std::string localizerEstimatorName = robustEstimation::ERobustEstimator_enumToString(robustEstimation::ERobustEstimator::ACRANSAC);
po::options_description allParams(
"Sequential/Incremental reconstruction\n"
"Perform incremental SfM (Initial Pair Essential + Resection)\n"
"AliceVision incrementalSfM");
po::options_description requiredParams("Required parameters");
requiredParams.add_options()
("input,i", po::value<std::string>(&sfmDataFilename)->required(),
"SfMData file.")
("output,o", po::value<std::string>(&outputSfM)->required(),
"Path to the output SfMData file.")
("featuresFolder,f", po::value<std::string>(&featuresFolder)->required(),
"Path to a folder containing the extracted features.")
("matchesFolder,m", po::value<std::string>(&matchesFolder)->required(),
"Path to a folder in which computed matches are stored.");
po::options_description optionalParams("Optional parameters");
optionalParams.add_options()
("outputViewsAndPoses", po::value<std::string>(&outputSfMViewsAndPoses)->default_value(outputSfMViewsAndPoses),
"Path to the output SfMData file (with only views and poses).")
("extraInfoFolder", po::value<std::string>(&extraInfoFolder)->default_value(extraInfoFolder),
"Folder for intermediate reconstruction files and additional reconstruction information files.")
("describerTypes,d", po::value<std::string>(&describerTypesName)->default_value(describerTypesName),
feature::EImageDescriberType_informations().c_str())
("interFileExtension", po::value<std::string>(&outInterFileExtension)->default_value(outInterFileExtension),
"Extension of the intermediate file export.")
("minInputTrackLength", po::value<int>(&minInputTrackLength)->default_value(minInputTrackLength),
"Minimum track length in input of SfM.")
("maxNumberOfMatches", po::value<int>(&maxNbMatches)->default_value(maxNbMatches),
"Maximum number of matches per image pair (and per feature type). "
"This can be useful to have a quick reconstruction overview. 0 means no limit.")
("minNumberOfObservationsForTriangulation", po::value<std::size_t>(&minNbObservationsForTriangulation)->default_value(minNbObservationsForTriangulation),
"Minimum number of observations to triangulate a point.\n"
"Set it to 3 (or more) reduces drastically the noise in the point cloud, but the number of final poses is a little bit reduced (from 1.5% to 11% on the tested datasets).\n"
"Note: set it to 0 or 1 to use the old triangulation algorithm (using 2 views only) during resection.")
("initialPairA", po::value<std::string>(&initialPairString.first)->default_value(initialPairString.first),
"filename of the first image (without path).")
("initialPairB", po::value<std::string>(&initialPairString.second)->default_value(initialPairString.second),
"filename of the second image (without path).")
("refineIntrinsics", po::value<bool>(&refineIntrinsics)->default_value(refineIntrinsics),
"Refine intrinsic parameters.")
("useLocalBA,l", po::value<bool>(&useLocalBundleAdjustment)->default_value(useLocalBundleAdjustment),
"Enable/Disable the Local bundle adjustment strategy.\n"
"It reduces the reconstruction time, especially for big datasets (500+ images).")
("localBAGraphDistance", po::value<std::size_t>(&localBundelAdjustementGraphDistanceLimit)->default_value(localBundelAdjustementGraphDistanceLimit),
"Graph-distance limit setting the Active region in the Local Bundle Adjustment strategy.")
("localizerEstimator", po::value<std::string>(&localizerEstimatorName)->default_value(localizerEstimatorName),
"Estimator type used to localize cameras (acransac (default), ransac, lsmeds, loransac, maxconsensus)");
po::options_description logParams("Log parameters");
logParams.add_options()
("verboseLevel,v", po::value<std::string>(&verboseLevel)->default_value(verboseLevel),
"verbosity level (fatal, error, warning, info, debug, trace).");
allParams.add(requiredParams).add(optionalParams).add(logParams);
po::variables_map vm;
try
{
po::store(po::parse_command_line(argc, argv, allParams), vm);
if(vm.count("help") || (argc == 1))
{
ALICEVISION_COUT(allParams);
return EXIT_SUCCESS;
}
po::notify(vm);
}
catch(boost::program_options::required_option& e)
{
ALICEVISION_CERR("ERROR: " << e.what());
ALICEVISION_COUT("Usage:\n\n" << allParams);
return EXIT_FAILURE;
}
catch(boost::program_options::error& e)
{
ALICEVISION_CERR("ERROR: " << e.what());
ALICEVISION_COUT("Usage:\n\n" << allParams);
return EXIT_FAILURE;
}
ALICEVISION_COUT("Program called with the following parameters:");
ALICEVISION_COUT(vm);
// set verbose level
system::Logger::get()->setLogLevel(verboseLevel);
// load input SfMData scene
SfMData sfmData;
if(!Load(sfmData, sfmDataFilename, ESfMData::ALL))
{
ALICEVISION_LOG_ERROR("Error: The input SfMData file '" + sfmDataFilename + "' cannot be read.");
return EXIT_FAILURE;
}
// get imageDescriber type
const std::vector<feature::EImageDescriberType> describerTypes = feature::EImageDescriberType_stringToEnums(describerTypesName);
// features reading
feature::FeaturesPerView featuresPerView;
if(!sfm::loadFeaturesPerView(featuresPerView, sfmData, featuresFolder, describerTypes))
{
ALICEVISION_LOG_ERROR("Invalid features.");
return EXIT_FAILURE;
}
// matches reading
matching::PairwiseMatches pairwiseMatches;
if(!sfm::loadPairwiseMatches(pairwiseMatches, sfmData, matchesFolder, describerTypes, "f", maxNbMatches))
{
ALICEVISION_LOG_ERROR("Unable to load matches file from '" + matchesFolder + "'.");
return EXIT_FAILURE;
}
if(extraInfoFolder.empty())
{
namespace bfs = boost::filesystem;
extraInfoFolder = bfs::path(outputSfM).parent_path().string();
}
if (!stlplus::folder_exists(extraInfoFolder))
stlplus::folder_create(extraInfoFolder);
// sequential reconstruction process
aliceVision::system::Timer timer;
ReconstructionEngine_sequentialSfM sfmEngine(
sfmData,
extraInfoFolder,
stlplus::create_filespec(extraInfoFolder, "sfm_log.html"));
// configure the featuresPerView & the matches_provider
sfmEngine.setFeatures(&featuresPerView);
sfmEngine.setMatches(&pairwiseMatches);
// configure reconstruction parameters
sfmEngine.Set_bFixedIntrinsics(!refineIntrinsics);
sfmEngine.setMinInputTrackLength(minInputTrackLength);
sfmEngine.setIntermediateFileExtension(outInterFileExtension);
sfmEngine.setUseLocalBundleAdjustmentStrategy(useLocalBundleAdjustment);
sfmEngine.setLocalBundleAdjustmentGraphDistance(localBundelAdjustementGraphDistanceLimit);
sfmEngine.setLocalizerEstimator(robustEstimation::ERobustEstimator_stringToEnum(localizerEstimatorName));
if(minNbObservationsForTriangulation < 2)
{
// allows to use to the old triangulatation algorithm (using 2 views only) during resection.
minNbObservationsForTriangulation = 0;
// ALICEVISION_LOG_ERROR("The value associated to the argument '--minNbObservationsForTriangulation' must be >= 2 ");
// return EXIT_FAILURE;
}
sfmEngine.setNbOfObservationsForTriangulation(minNbObservationsForTriangulation);
// handle Initial pair parameter
if(!initialPairString.first.empty() && !initialPairString.second.empty())
{
if(initialPairString.first == initialPairString.second)
{
ALICEVISION_LOG_ERROR("Invalid image names. You cannot use the same image to initialize a pair.");
return EXIT_FAILURE;
}
Pair initialPairIndex;
if(!retrieveViewIdFromImageName(sfmData, initialPairString.first, initialPairIndex.first)
|| !retrieveViewIdFromImageName(sfmData, initialPairString.second, initialPairIndex.second))
{
ALICEVISION_LOG_ERROR("Could not find the initial pairs (" + initialPairString.first + ", " + initialPairString.second + ") !");
return EXIT_FAILURE;
}
sfmEngine.setInitialPair(initialPairIndex);
}
if(!sfmEngine.Process())
return EXIT_FAILURE;
// get the color for the 3D points
if(!sfmEngine.Colorize())
ALICEVISION_LOG_ERROR("Colorize failed !");
sfmEngine.Get_SfMData().addFeaturesFolder(featuresFolder);
sfmEngine.Get_SfMData().addMatchesFolder(matchesFolder);
ALICEVISION_LOG_INFO("Structure from motion took (s): " + std::to_string(timer.elapsed()));
ALICEVISION_LOG_INFO("Generating HTML report...");
Generate_SfM_Report(sfmEngine.Get_SfMData(), stlplus::create_filespec(extraInfoFolder, "sfm_report.html"));
// export to disk computed scene (data & visualizable results)
ALICEVISION_LOG_INFO("Export SfMData to disk: " + outputSfM);
Save(sfmEngine.Get_SfMData(), stlplus::create_filespec(extraInfoFolder, "cloud_and_poses", outInterFileExtension), ESfMData(VIEWS | EXTRINSICS | INTRINSICS | STRUCTURE));
Save(sfmEngine.Get_SfMData(), outputSfM, ESfMData(ALL));
if(!outputSfMViewsAndPoses.empty())
Save(sfmEngine.Get_SfMData(), outputSfMViewsAndPoses, ESfMData(VIEWS | EXTRINSICS | INTRINSICS));
ALICEVISION_LOG_INFO("Structure from Motion results:" << std::endl
<< "\t- # input images: " << sfmEngine.Get_SfMData().GetViews().size() << std::endl
<< "\t- # cameras calibrated: " << sfmEngine.Get_SfMData().GetPoses().size() << std::endl
<< "\t- # landmarks: " << sfmEngine.Get_SfMData().GetLandmarks().size());
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>#pragma once
template<class T>
struct LuaResultTraits {};
template<>
struct LuaResultTraits<unsigned long> {
typedef unsigned long type;
};
template<>
struct LuaResultTraits<unsigned long long> {
typedef unsigned long long type;
};
template<>
struct LuaResultTraits<int> {
typedef int type;
};
template<>
struct LuaResultTraits<double> {
typedef double type;
};
template<>
struct LuaResultTraits<void> {
typedef void type;
};
template<>
struct LuaResultTraits<char*> {
typedef const char* type;
};
template<>
struct LuaResultTraits<const char*> {
typedef const char* type;
};
template<>
struct LuaResultTraits<bool> {
typedef bool type;
};
template<>
struct LuaResultTraits<float> {
typedef float type;
};<commit_msg>多余的文件<commit_after><|endoftext|> |
<commit_before>/****************************************************************************
*
* Copyright (C) 2018-2019 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 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.
*
****************************************************************************/
/**
* @file test_microbench_uorb.cpp
* Tests for microbench uORB functionality.
*/
#include <unit_test.h>
#include <time.h>
#include <stdlib.h>
#include <unistd.h>
#include <drivers/drv_hrt.h>
#include <perf/perf_counter.h>
#include <px4_platform_common/px4_config.h>
#include <px4_platform_common/micro_hal.h>
#include <uORB/Subscription.hpp>
#include <uORB/topics/sensor_accel.h>
#include <uORB/topics/sensor_gyro.h>
#include <uORB/topics/vehicle_local_position.h>
#include <uORB/topics/vehicle_status.h>
namespace MicroBenchORB
{
#ifdef __PX4_NUTTX
#include <nuttx/irq.h>
static irqstate_t flags;
#endif
void lock()
{
#ifdef __PX4_NUTTX
flags = px4_enter_critical_section();
#endif
}
void unlock()
{
#ifdef __PX4_NUTTX
px4_leave_critical_section(flags);
#endif
}
#define PERF(name, op, count) do { \
px4_usleep(1000); \
reset(); \
perf_counter_t p = perf_alloc(PC_ELAPSED, name); \
for (int i = 0; i < count; i++) { \
px4_usleep(1); \
lock(); \
perf_begin(p); \
op; \
perf_end(p); \
unlock(); \
reset(); \
} \
perf_print_counter(p); \
perf_free(p); \
} while (0)
class MicroBenchORB : public UnitTest
{
public:
virtual bool run_tests();
private:
bool time_px4_uorb();
bool time_px4_uorb_direct();
void reset();
vehicle_status_s status;
vehicle_local_position_s lpos;
sensor_gyro_s gyro;
};
bool MicroBenchORB::run_tests()
{
ut_run_test(time_px4_uorb);
ut_run_test(time_px4_uorb_direct);
return (_tests_failed == 0);
}
template<typename T>
T random(T min, T max)
{
const T scale = rand() / (T) RAND_MAX; /* [0, 1.0] */
return min + scale * (max - min); /* [min, max] */
}
void MicroBenchORB::reset()
{
srand(time(nullptr));
// initialize with random data
status.timestamp = rand();
status.mission_failure = rand();
lpos.timestamp = rand();
lpos.dist_bottom_valid = rand();
gyro.timestamp = rand();
}
ut_declare_test_c(test_microbench_uorb, MicroBenchORB)
bool MicroBenchORB::time_px4_uorb()
{
int fd_status = orb_subscribe(ORB_ID(vehicle_status));
int fd_lpos = orb_subscribe(ORB_ID(vehicle_local_position));
int fd_gyro = orb_subscribe(ORB_ID(sensor_gyro));
int ret = 0;
bool updated = false;
uint64_t time = 0;
PERF("orb_check vehicle_status", ret = orb_check(fd_status, &updated), 100);
PERF("orb_copy vehicle_status", ret = orb_copy(ORB_ID(vehicle_status), fd_status, &status), 100);
printf("\n");
PERF("orb_check vehicle_local_position", ret = orb_check(fd_lpos, &updated), 100);
PERF("orb_copy vehicle_local_position", ret = orb_copy(ORB_ID(vehicle_local_position), fd_lpos, &lpos), 100);
printf("\n");
PERF("orb_check sensor_gyro", ret = orb_check(fd_gyro, &updated), 100);
PERF("orb_copy sensor_gyro", ret = orb_copy(ORB_ID(sensor_gyro), fd_gyro, &gyro), 100);
printf("\n");
PERF("orb_exists sensor_accel 0", ret = orb_exists(ORB_ID(sensor_accel), 0), 100);
PERF("orb_exists sensor_accel 1", ret = orb_exists(ORB_ID(sensor_accel), 1), 100);
PERF("orb_exists sensor_accel 2", ret = orb_exists(ORB_ID(sensor_accel), 2), 100);
PERF("orb_exists sensor_accel 3", ret = orb_exists(ORB_ID(sensor_accel), 3), 100);
PERF("orb_exists sensor_accel 4", ret = orb_exists(ORB_ID(sensor_accel), 4), 100);
PERF("orb_exists sensor_accel 5", ret = orb_exists(ORB_ID(sensor_accel), 5), 100);
PERF("orb_exists sensor_accel 6", ret = orb_exists(ORB_ID(sensor_accel), 6), 100);
PERF("orb_exists sensor_accel 7", ret = orb_exists(ORB_ID(sensor_accel), 7), 100);
PERF("orb_exists sensor_accel 8", ret = orb_exists(ORB_ID(sensor_accel), 8), 100);
PERF("orb_exists sensor_accel 9", ret = orb_exists(ORB_ID(sensor_accel), 9), 100);
PERF("orb_exists sensor_accel 10", ret = orb_exists(ORB_ID(sensor_accel), 10), 100);
orb_unsubscribe(fd_status);
orb_unsubscribe(fd_lpos);
orb_unsubscribe(fd_gyro);
return true;
}
bool MicroBenchORB::time_px4_uorb_direct()
{
bool ret = false;
bool updated = false;
uint64_t time = 0;
uORB::Subscription vstatus{ORB_ID(vehicle_status)};
PERF("uORB::Subscription orb_check vehicle_status", ret = vstatus.updated(), 100);
PERF("uORB::Subscription orb_copy vehicle_status", ret = vstatus.copy(&status), 100);
printf("\n");
uORB::Subscription local_pos{ORB_ID(vehicle_local_position)};
PERF("uORB::Subscription orb_check vehicle_local_position", ret = local_pos.updated(), 100);
PERF("uORB::Subscription orb_copy vehicle_local_position", ret = local_pos.copy(&lpos), 100);
{
printf("\n");
uORB::Subscription sens_gyro0{ORB_ID(sensor_gyro), 0};
PERF("uORB::Subscription orb_check sensor_gyro:0", ret = sens_gyro0.updated(), 100);
PERF("uORB::Subscription orb_copy sensor_gyro:0", ret = sens_gyro0.copy(&gyro), 100);
}
{
printf("\n");
uORB::Subscription sens_gyro1{ORB_ID(sensor_gyro), 1};
PERF("uORB::Subscription orb_check sensor_gyro:1", ret = sens_gyro1.updated(), 100);
PERF("uORB::Subscription orb_copy sensor_gyro:1", ret = sens_gyro1.copy(&gyro), 100);
}
{
printf("\n");
uORB::Subscription sens_gyro2{ORB_ID(sensor_gyro), 2};
PERF("uORB::Subscription orb_check sensor_gyro:2", ret = sens_gyro2.updated(), 100);
PERF("uORB::Subscription orb_copy sensor_gyro:2", ret = sens_gyro2.copy(&gyro), 100);
}
{
printf("\n");
uORB::Subscription sens_gyro3{ORB_ID(sensor_gyro), 3};
PERF("uORB::Subscription orb_check sensor_gyro:3", ret = sens_gyro3.updated(), 100);
PERF("uORB::Subscription orb_copy sensor_gyro:3", ret = sens_gyro3.copy(&gyro), 100);
}
return true;
}
} // namespace MicroBenchORB
<commit_msg>tests: microbench uorb add sensor_gyro_fifo copy<commit_after>/****************************************************************************
*
* Copyright (C) 2018-2019 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 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.
*
****************************************************************************/
/**
* @file test_microbench_uorb.cpp
* Tests for microbench uORB functionality.
*/
#include <unit_test.h>
#include <time.h>
#include <stdlib.h>
#include <unistd.h>
#include <drivers/drv_hrt.h>
#include <perf/perf_counter.h>
#include <px4_platform_common/px4_config.h>
#include <px4_platform_common/micro_hal.h>
#include <uORB/Subscription.hpp>
#include <uORB/topics/sensor_accel.h>
#include <uORB/topics/sensor_gyro.h>
#include <uORB/topics/sensor_gyro_fifo.h>
#include <uORB/topics/vehicle_local_position.h>
#include <uORB/topics/vehicle_status.h>
namespace MicroBenchORB
{
#ifdef __PX4_NUTTX
#include <nuttx/irq.h>
static irqstate_t flags;
#endif
void lock()
{
#ifdef __PX4_NUTTX
flags = px4_enter_critical_section();
#endif
}
void unlock()
{
#ifdef __PX4_NUTTX
px4_leave_critical_section(flags);
#endif
}
#define PERF(name, op, count) do { \
px4_usleep(1000); \
reset(); \
perf_counter_t p = perf_alloc(PC_ELAPSED, name); \
for (int i = 0; i < count; i++) { \
px4_usleep(1); \
lock(); \
perf_begin(p); \
op; \
perf_end(p); \
unlock(); \
reset(); \
} \
perf_print_counter(p); \
perf_free(p); \
} while (0)
class MicroBenchORB : public UnitTest
{
public:
virtual bool run_tests();
private:
bool time_px4_uorb();
bool time_px4_uorb_direct();
void reset();
vehicle_status_s status;
vehicle_local_position_s lpos;
sensor_gyro_s gyro;
sensor_gyro_fifo_s gyro_fifo;
};
bool MicroBenchORB::run_tests()
{
ut_run_test(time_px4_uorb);
ut_run_test(time_px4_uorb_direct);
return (_tests_failed == 0);
}
template<typename T>
T random(T min, T max)
{
const T scale = rand() / (T) RAND_MAX; /* [0, 1.0] */
return min + scale * (max - min); /* [min, max] */
}
void MicroBenchORB::reset()
{
srand(time(nullptr));
// initialize with random data
status.timestamp = rand();
status.mission_failure = rand();
lpos.timestamp = rand();
lpos.dist_bottom_valid = rand();
gyro.timestamp = rand();
gyro_fifo.timestamp = rand();
}
ut_declare_test_c(test_microbench_uorb, MicroBenchORB)
bool MicroBenchORB::time_px4_uorb()
{
int fd_status = orb_subscribe(ORB_ID(vehicle_status));
int fd_lpos = orb_subscribe(ORB_ID(vehicle_local_position));
int fd_gyro = orb_subscribe(ORB_ID(sensor_gyro));
int fd_gyro_fifo = orb_subscribe(ORB_ID(sensor_gyro_fifo));
int ret = 0;
bool updated = false;
uint64_t time = 0;
PERF("orb_check vehicle_status", ret = orb_check(fd_status, &updated), 100);
PERF("orb_copy vehicle_status", ret = orb_copy(ORB_ID(vehicle_status), fd_status, &status), 100);
printf("\n");
PERF("orb_check vehicle_local_position", ret = orb_check(fd_lpos, &updated), 100);
PERF("orb_copy vehicle_local_position", ret = orb_copy(ORB_ID(vehicle_local_position), fd_lpos, &lpos), 100);
printf("\n");
PERF("orb_check sensor_gyro", ret = orb_check(fd_gyro, &updated), 100);
PERF("orb_copy sensor_gyro", ret = orb_copy(ORB_ID(sensor_gyro), fd_gyro, &gyro), 100);
printf("\n");
PERF("orb_check sensor_gyro_fifo", ret = orb_check(fd_gyro_fifo, &updated), 100);
PERF("orb_copy sensor_gyro_fifo", ret = orb_copy(ORB_ID(sensor_gyro_fifo), fd_gyro_fifo, &gyro_fifo), 100);
printf("\n");
PERF("orb_exists sensor_accel 0", ret = orb_exists(ORB_ID(sensor_accel), 0), 100);
PERF("orb_exists sensor_accel 1", ret = orb_exists(ORB_ID(sensor_accel), 1), 100);
PERF("orb_exists sensor_accel 2", ret = orb_exists(ORB_ID(sensor_accel), 2), 100);
PERF("orb_exists sensor_accel 3", ret = orb_exists(ORB_ID(sensor_accel), 3), 100);
PERF("orb_exists sensor_accel 4", ret = orb_exists(ORB_ID(sensor_accel), 4), 100);
PERF("orb_exists sensor_accel 5", ret = orb_exists(ORB_ID(sensor_accel), 5), 100);
PERF("orb_exists sensor_accel 6", ret = orb_exists(ORB_ID(sensor_accel), 6), 100);
PERF("orb_exists sensor_accel 7", ret = orb_exists(ORB_ID(sensor_accel), 7), 100);
PERF("orb_exists sensor_accel 8", ret = orb_exists(ORB_ID(sensor_accel), 8), 100);
PERF("orb_exists sensor_accel 9", ret = orb_exists(ORB_ID(sensor_accel), 9), 100);
PERF("orb_exists sensor_accel 10", ret = orb_exists(ORB_ID(sensor_accel), 10), 100);
orb_unsubscribe(fd_status);
orb_unsubscribe(fd_lpos);
orb_unsubscribe(fd_gyro);
orb_unsubscribe(fd_gyro_fifo);
return true;
}
bool MicroBenchORB::time_px4_uorb_direct()
{
bool ret = false;
bool updated = false;
uint64_t time = 0;
uORB::Subscription vstatus{ORB_ID(vehicle_status)};
PERF("uORB::Subscription orb_check vehicle_status", ret = vstatus.updated(), 100);
PERF("uORB::Subscription orb_copy vehicle_status", ret = vstatus.copy(&status), 100);
printf("\n");
uORB::Subscription local_pos{ORB_ID(vehicle_local_position)};
PERF("uORB::Subscription orb_check vehicle_local_position", ret = local_pos.updated(), 100);
PERF("uORB::Subscription orb_copy vehicle_local_position", ret = local_pos.copy(&lpos), 100);
{
printf("\n");
uORB::Subscription sens_gyro0{ORB_ID(sensor_gyro), 0};
PERF("uORB::Subscription orb_check sensor_gyro:0", ret = sens_gyro0.updated(), 100);
PERF("uORB::Subscription orb_copy sensor_gyro:0", ret = sens_gyro0.copy(&gyro), 100);
}
{
printf("\n");
uORB::Subscription sens_gyro1{ORB_ID(sensor_gyro), 1};
PERF("uORB::Subscription orb_check sensor_gyro:1", ret = sens_gyro1.updated(), 100);
PERF("uORB::Subscription orb_copy sensor_gyro:1", ret = sens_gyro1.copy(&gyro), 100);
}
{
printf("\n");
uORB::Subscription sens_gyro2{ORB_ID(sensor_gyro), 2};
PERF("uORB::Subscription orb_check sensor_gyro:2", ret = sens_gyro2.updated(), 100);
PERF("uORB::Subscription orb_copy sensor_gyro:2", ret = sens_gyro2.copy(&gyro), 100);
}
{
printf("\n");
uORB::Subscription sens_gyro3{ORB_ID(sensor_gyro), 3};
PERF("uORB::Subscription orb_check sensor_gyro:3", ret = sens_gyro3.updated(), 100);
PERF("uORB::Subscription orb_copy sensor_gyro:3", ret = sens_gyro3.copy(&gyro), 100);
}
{
printf("\n");
uORB::Subscription sens_gyro_fifo0{ORB_ID(sensor_gyro_fifo), 0};
PERF("uORB::Subscription orb_check sensor_gyro_fifo:0", ret = sens_gyro_fifo0.updated(), 100);
PERF("uORB::Subscription orb_copy sensor_gyro_fifo:0", ret = sens_gyro_fifo0.copy(&gyro_fifo), 100);
}
return true;
}
} // namespace MicroBenchORB
<|endoftext|> |
<commit_before>#include "stan/math/functions/lmgamma.hpp"
#include <gtest/gtest.h>
TEST(MathsSpecialFunctions, lmgamma) {
unsigned int k = 1;
double x = 2.5;
double result = k * (k - 1) * log(boost::math::constants::pi<double>()) / 4.0;
result += lgamma(x); // j = 1
EXPECT_FLOAT_EQ(result, stan::math::lmgamma(k,x));
k = 2;
x = 3.0;
result = k * (k - 1) * log(boost::math::constants::pi<double>()) / 4.0;
result += lgamma(x); // j = 1
result += lgamma(x + (1.0 - 2.0)/2.0); // j = 2
EXPECT_FLOAT_EQ(result, stan::math::lmgamma(k,x));
}
<commit_msg>added NaN test for lmgamma<commit_after>#include <stan/math/functions/lmgamma.hpp>
#include <boost/math/special_functions/fpclassify.hpp>
#include <gtest/gtest.h>
TEST(MathFunctions, lmgamma) {
unsigned int k = 1;
double x = 2.5;
double result = k * (k - 1) * log(boost::math::constants::pi<double>()) / 4.0;
result += lgamma(x); // j = 1
EXPECT_FLOAT_EQ(result, stan::math::lmgamma(k,x));
k = 2;
x = 3.0;
result = k * (k - 1) * log(boost::math::constants::pi<double>()) / 4.0;
result += lgamma(x); // j = 1
result += lgamma(x + (1.0 - 2.0)/2.0); // j = 2
EXPECT_FLOAT_EQ(result, stan::math::lmgamma(k,x));
}
TEST(MathFunctions, lmgamma_nan) {
double nan = std::numeric_limits<double>::quiet_NaN();
EXPECT_PRED1(boost::math::isnan<double>,
stan::math::lmgamma(2, nan));
}
<|endoftext|> |
<commit_before>
//Copyright (c) 2012 Jonathan Topf
//
//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.
#if defined __APPLE__
#include <maya/OpenMayaMac.h>
#endif
#include <maya/MIOStream.h>
#include <maya/MSimple.h>
#include <maya/MGlobal.h>
#include <maya/MSelectionList.h>
#include <maya/MDagPath.h>
#include <maya/MSelectionList.h>
#include <maya/MFnMesh.h>
#include <maya/MItMeshPolygon.h>
#include <maya/MPointArray.h>
#include <maya/MFloatArray.h>
#include <maya/MFloatVectorArray.h>
#include <maya/MArgList.h>
#include <maya/MString.h>
#include <fstream>
// Use a Maya macro to setup a simple helloWorld class
// with methods for initialization, etc.
//
const MString Version("0.1.1");
DeclareSimpleCommand( ms_export_obj, "mayaseed", Version.asChar());
// All we need to do is supply the doIt method
// which in this case is only a Hello World example
//
MStatus ms_export_obj::doIt( const MArgList& args)
{
MString mesh_name;
MString file_path;
//get the args
for (unsigned int i = 0; i < args.length(); i++)
{
MGlobal::displayInfo(args.asString(i));
if (args.asString(i) == "-mesh")
{
mesh_name = args.asString(i+1);
} else if (args.asString(i) == "-filePath")
{
file_path = args.asString(i+1);
}
}
MString display_info;
display_info.format("Exporting ^1s using ms_export_obj", mesh_name);
MGlobal::displayInfo(display_info);
MSelectionList sel;
sel.add(mesh_name);
MDagPath mesh_dag_path;
sel.getDagPath(0, mesh_dag_path);
MFnMesh mesh(mesh_dag_path);
MItMeshPolygon iter_polys(mesh.object());
//open file for writing
std::ofstream out_file;
out_file.open(file_path.asChar(), ios::trunc); // open file for writing and overwrite previous contents
out_file << "# File generated by ms_obj_xport version: " << Version.asChar() << "\n\n";
//write points to file
MPointArray point_array;
mesh.getPoints(point_array);
for (unsigned int i=0; i < point_array.length(); i++)
{
MPoint point(point_array[i]);
out_file << "v " << point.x << " " << point.y << " " << point.z << "\n";
}
//write uvs to disk
MFloatArray u_array;
MFloatArray v_array;
mesh.getUVs(u_array, v_array);
for (unsigned int i=0; i < u_array.length(); i++)
{
out_file << "vt " << u_array[i] << " " << v_array[i] << "\n";
}
MFloatVectorArray normal_array;
mesh.getNormals(normal_array, MSpace::kTransform);
//write normals
for (unsigned int i=0; i < normal_array.length(); i++)
{
out_file << "vn " << normal_array[i].x << " " << normal_array[i].y << " " << normal_array[i].z << "\n";
}
//itterate over polys
while (!iter_polys.isDone())
{
out_file << "f ";
//create values to store temporary poly info
int vert_count = iter_polys.polygonVertexCount();
for (int i=0; i < vert_count; i++)
{
int uv_index;
iter_polys.getUVIndex(i, uv_index);
out_file << (iter_polys.vertexIndex(i)+1) << "/" << (uv_index+1) << "/" << (iter_polys.normalIndex(i)+1) << " ";
}
out_file << "\n";
iter_polys.next();
}
out_file.close();
return MS::kSuccess;
}
<commit_msg>minor code tweak.<commit_after>
//Copyright (c) 2012 Jonathan Topf
//
//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.
#if defined __APPLE__
#include <maya/OpenMayaMac.h>
#endif
#include <maya/MIOStream.h>
#include <maya/MSimple.h>
#include <maya/MGlobal.h>
#include <maya/MSelectionList.h>
#include <maya/MDagPath.h>
#include <maya/MSelectionList.h>
#include <maya/MFnMesh.h>
#include <maya/MItMeshPolygon.h>
#include <maya/MPointArray.h>
#include <maya/MFloatArray.h>
#include <maya/MFloatVectorArray.h>
#include <maya/MArgList.h>
#include <maya/MString.h>
#include <fstream>
// Use a Maya macro to setup a simple helloWorld class
// with methods for initialization, etc.
//
const MString Version("0.1.1");
DeclareSimpleCommand( ms_export_obj, "mayaseed", Version.asChar());
// All we need to do is supply the doIt method
// which in this case is only a Hello World example
//
MStatus ms_export_obj::doIt( const MArgList& args)
{
MString mesh_name;
MString file_path;
//get the args
for (unsigned int i = 0; i < args.length(); i++)
{
MGlobal::displayInfo(args.asString(i));
if (args.asString(i) == "-mesh")
{
mesh_name = args.asString(i+1);
} else if (args.asString(i) == "-filePath")
{
file_path = args.asString(i+1);
}
}
MString display_info;
display_info.format("Exporting ^1s using ms_export_obj", mesh_name);
MGlobal::displayInfo(display_info);
MSelectionList sel;
sel.add(mesh_name);
MDagPath mesh_dag_path;
sel.getDagPath(0, mesh_dag_path);
MFnMesh mesh(mesh_dag_path);
MItMeshPolygon iter_polys(mesh.object());
//open file for writing
std::ofstream out_file;
out_file.open(file_path.asChar(), ios::trunc); // open file for writing and overwrite previous contents
out_file << "# File generated by ms_obj_xport version: " << Version.asChar() << "\n\n";
//write points to file
MPointArray point_array;
mesh.getPoints(point_array);
for (unsigned int i=0; i < point_array.length(); i++)
{
MPoint point(point_array[i]);
out_file << "v " << point.x << " " << point.y << " " << point.z << "\n";
}
//write uvs to disk
MFloatArray u_array;
MFloatArray v_array;
mesh.getUVs(u_array, v_array);
for (unsigned int i=0; i < u_array.length(); i++)
{
out_file << "vt " << u_array[i] << " " << v_array[i] << "\n";
}
MFloatVectorArray normal_array;
mesh.getNormals(normal_array, MSpace::kTransform);
//write normals
for (unsigned int i=0; i < normal_array.length(); i++)
{
out_file << "vn " << normal_array[i].x << " " << normal_array[i].y << " " << normal_array[i].z << "\n";
}
//itterate over polys
while (!iter_polys.isDone())
{
out_file << "f ";
//create values to store temporary poly info
unsigned int vert_count = iter_polys.polygonVertexCount();
for (unsigned int i=0; i < vert_count; i++)
{
int uv_index;
iter_polys.getUVIndex(i, uv_index);
out_file << (iter_polys.vertexIndex(i)+1) << "/" << (uv_index+1) << "/" << (iter_polys.normalIndex(i)+1) << " ";
}
out_file << "\n";
iter_polys.next();
}
out_file.close();
return MS::kSuccess;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: textproperties.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: pjunck $ $Date: 2004-11-03 10:32:41 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* 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
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _SDR_PROPERTIES_TEXTPROPERTIES_HXX
#define _SDR_PROPERTIES_TEXTPROPERTIES_HXX
#ifndef _SDR_PROPERTIES_ATTRIBUTEPROPERTIES_HXX
#include <svx/sdr/properties/attributeproperties.hxx>
#endif
//////////////////////////////////////////////////////////////////////////////
namespace sdr
{
namespace properties
{
class TextProperties : public AttributeProperties
{
protected:
// create a new itemset
virtual SfxItemSet& CreateObjectSpecificItemSet(SfxItemPool& rPool);
// Do the ItemChange, may do special handling
virtual void ItemChange(const sal_uInt16 nWhich, const SfxPoolItem* pNewItem = 0);
// react on ItemSet changes
virtual void ItemSetChanged(const SfxItemSet& rSet);
public:
// basic constructor
TextProperties(SdrObject& rObj);
// constructor for copying, but using new object
TextProperties(const TextProperties& rProps, SdrObject& rObj);
// destructor
virtual ~TextProperties();
// Clone() operator, normally just calls the local copy constructor
virtual BaseProperties& Clone(SdrObject& rObj) const;
// set a new StyleSheet and broadcast
virtual void SetStyleSheet(SfxStyleSheet* pNewStyleSheet, sal_Bool bDontRemoveHardAttr);
// pre/post-process saving
//BFS01virtual void PreProcessSave();
// force default attributes for a specific object type, called from
// DefaultProperties::GetObjectItemSet() if a new ItemSet is created
virtual void ForceDefaultAttributes();
// force all attributes which come from styles to hard attributes
// to be able to live without the style.
virtual void ForceStyleToHardAttributes(sal_Bool bPseudoSheetsOnly = sal_False);
// This is the notifyer from SfxListener
virtual void Notify(SfxBroadcaster& rBC, const SfxHint& rHint);
};
} // end of namespace properties
} // end of namespace sdr
//////////////////////////////////////////////////////////////////////////////
#endif //_SDR_PROPERTIES_TEXTPROPERTIES_HXX
// eof
<commit_msg>INTEGRATION: CWS visibility01 (1.3.26); FILE MERGED 2004/11/19 12:54:56 mmeeks 1.3.26.1: Issue number: #i35758# Submitted by: mnicel Reviewed by: mmeeks<commit_after>/*************************************************************************
*
* $RCSfile: textproperties.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: kz $ $Date: 2005-01-21 16:25:02 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* 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
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _SDR_PROPERTIES_TEXTPROPERTIES_HXX
#define _SDR_PROPERTIES_TEXTPROPERTIES_HXX
#ifndef _SDR_PROPERTIES_ATTRIBUTEPROPERTIES_HXX
#include <svx/sdr/properties/attributeproperties.hxx>
#endif
#ifndef INCLUDED_SVXDLLAPI_H
#include "svx/svxdllapi.h"
#endif
//////////////////////////////////////////////////////////////////////////////
namespace sdr
{
namespace properties
{
class SVX_DLLPUBLIC TextProperties : public AttributeProperties
{
protected:
// create a new itemset
virtual SfxItemSet& CreateObjectSpecificItemSet(SfxItemPool& rPool);
// Do the ItemChange, may do special handling
virtual void ItemChange(const sal_uInt16 nWhich, const SfxPoolItem* pNewItem = 0);
// react on ItemSet changes
virtual void ItemSetChanged(const SfxItemSet& rSet);
public:
// basic constructor
TextProperties(SdrObject& rObj);
// constructor for copying, but using new object
TextProperties(const TextProperties& rProps, SdrObject& rObj);
// destructor
virtual ~TextProperties();
// Clone() operator, normally just calls the local copy constructor
virtual BaseProperties& Clone(SdrObject& rObj) const;
// set a new StyleSheet and broadcast
virtual void SetStyleSheet(SfxStyleSheet* pNewStyleSheet, sal_Bool bDontRemoveHardAttr);
// pre/post-process saving
//BFS01virtual void PreProcessSave();
// force default attributes for a specific object type, called from
// DefaultProperties::GetObjectItemSet() if a new ItemSet is created
virtual void ForceDefaultAttributes();
// force all attributes which come from styles to hard attributes
// to be able to live without the style.
virtual void ForceStyleToHardAttributes(sal_Bool bPseudoSheetsOnly = sal_False);
// This is the notifyer from SfxListener
virtual void Notify(SfxBroadcaster& rBC, const SfxHint& rHint);
};
} // end of namespace properties
} // end of namespace sdr
//////////////////////////////////////////////////////////////////////////////
#endif //_SDR_PROPERTIES_TEXTPROPERTIES_HXX
// eof
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: SvXMLAutoCorrectExport.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: hr $ $Date: 2001-07-11 11:44:36 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* 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
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): Martin Gallwey (gallwey@sun.com)
*
*
************************************************************************/
#ifndef _SV_XMLAUTOCORRECTEXPORT_HXX
#define _SV_XMLAUTOCORRECTEXPORT_HXX
#ifndef _XMLOFF_XMLICTXT_HXX
#include <xmloff/xmlictxt.hxx>
#endif
#ifndef _XMLOFF_XMLEXP_HXX
#include <xmloff/xmlexp.hxx>
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include <xmloff/nmspmap.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include <xmloff/xmlnmspe.hxx>
#endif
#ifndef _MySVXACORR_HXX
#include "svxacorr.hxx"
#endif
class SvXMLAutoCorrectExport : public SvXMLExport
{
private:
const SvxAutocorrWordList *pAutocorr_List;
public:
SvXMLAutoCorrectExport( const SvxAutocorrWordList * pNewAutocorr_List, const rtl::OUString &rFileName,
com::sun::star::uno::Reference< com::sun::star::xml::sax::XDocumentHandler> &rHandler);
virtual ~SvXMLAutoCorrectExport ( void ) {}
sal_uInt32 exportDoc(enum ::xmloff::token::XMLTokenEnum eClass);
void _ExportAutoStyles() {}
void _ExportMasterStyles () {}
void _ExportContent() {}
};
class SvStringsISortDtor;
class SvXMLExceptionListExport : public SvXMLExport
{
private:
const SvStringsISortDtor & rList;
public:
SvXMLExceptionListExport( const SvStringsISortDtor &rNewList, const rtl::OUString &rFileName,
com::sun::star::uno::Reference< com::sun::star::xml::sax::XDocumentHandler> &rHandler);
virtual ~SvXMLExceptionListExport ( void ) {}
sal_uInt32 exportDoc(enum ::xmloff::token::XMLTokenEnum eClass);
void _ExportAutoStyles() {}
void _ExportMasterStyles () {}
void _ExportContent() {}
};
#endif
<commit_msg>INTEGRATION: CWS binfilter (1.5.338); FILE MERGED 2003/07/08 17:22:12 aw 1.5.338.1: #110680#<commit_after>/*************************************************************************
*
* $RCSfile: SvXMLAutoCorrectExport.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: rt $ $Date: 2004-05-03 13:26:50 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* 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
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): Martin Gallwey (gallwey@sun.com)
*
*
************************************************************************/
#ifndef _SV_XMLAUTOCORRECTEXPORT_HXX
#define _SV_XMLAUTOCORRECTEXPORT_HXX
#ifndef _XMLOFF_XMLICTXT_HXX
#include <xmloff/xmlictxt.hxx>
#endif
#ifndef _XMLOFF_XMLEXP_HXX
#include <xmloff/xmlexp.hxx>
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include <xmloff/nmspmap.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include <xmloff/xmlnmspe.hxx>
#endif
#ifndef _MySVXACORR_HXX
#include "svxacorr.hxx"
#endif
class SvXMLAutoCorrectExport : public SvXMLExport
{
private:
const SvxAutocorrWordList *pAutocorr_List;
public:
// #110680#
SvXMLAutoCorrectExport(
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory,
const SvxAutocorrWordList * pNewAutocorr_List,
const rtl::OUString &rFileName,
com::sun::star::uno::Reference< com::sun::star::xml::sax::XDocumentHandler> &rHandler);
virtual ~SvXMLAutoCorrectExport ( void ) {}
sal_uInt32 exportDoc(enum ::xmloff::token::XMLTokenEnum eClass);
void _ExportAutoStyles() {}
void _ExportMasterStyles () {}
void _ExportContent() {}
};
class SvStringsISortDtor;
class SvXMLExceptionListExport : public SvXMLExport
{
private:
const SvStringsISortDtor & rList;
public:
// #110680#
SvXMLExceptionListExport(
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory,
const SvStringsISortDtor &rNewList,
const rtl::OUString &rFileName,
com::sun::star::uno::Reference< com::sun::star::xml::sax::XDocumentHandler> &rHandler);
virtual ~SvXMLExceptionListExport ( void ) {}
sal_uInt32 exportDoc(enum ::xmloff::token::XMLTokenEnum eClass);
void _ExportAutoStyles() {}
void _ExportMasterStyles () {}
void _ExportContent() {}
};
#endif
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "maemorunconfiguration.h"
#include "maemodeployables.h"
#include "maemodeploystep.h"
#include "maemodeviceconfiglistmodel.h"
#include "maemoglobal.h"
#include "maemoqemumanager.h"
#include "maemoremotemountsmodel.h"
#include "maemorunconfigurationwidget.h"
#include "maemotoolchain.h"
#include "qtoutputformatter.h"
#include <coreplugin/icore.h>
#include <coreplugin/messagemanager.h>
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/session.h>
#include <qt4projectmanager/qt4buildconfiguration.h>
#include <qt4projectmanager/qt4project.h>
#include <utils/qtcassert.h>
#include <utils/qtcprocess.h>
#include <QtCore/QStringBuilder>
namespace Qt4ProjectManager {
namespace Internal {
namespace {
const bool DefaultUseRemoteGdbValue = false;
} // anonymous namespace
using namespace ProjectExplorer;
MaemoRunConfiguration::MaemoRunConfiguration(Qt4Target *parent,
const QString &proFilePath)
: RunConfiguration(parent, QLatin1String(MAEMO_RC_ID))
, m_proFilePath(proFilePath)
, m_useRemoteGdb(DefaultUseRemoteGdbValue)
, m_baseEnvironmentBase(SystemEnvironmentBase)
, m_validParse(parent->qt4Project()->validParse(m_proFilePath))
{
init();
}
MaemoRunConfiguration::MaemoRunConfiguration(Qt4Target *parent,
MaemoRunConfiguration *source)
: RunConfiguration(parent, source)
, m_proFilePath(source->m_proFilePath)
, m_gdbPath(source->m_gdbPath)
, m_arguments(source->m_arguments)
, m_useRemoteGdb(source->useRemoteGdb())
, m_baseEnvironmentBase(source->m_baseEnvironmentBase)
, m_systemEnvironment(source->m_systemEnvironment)
, m_userEnvironmentChanges(source->m_userEnvironmentChanges)
, m_validParse(source->m_validParse)
{
init();
}
void MaemoRunConfiguration::init()
{
setDefaultDisplayName(defaultDisplayName());
setUseCppDebugger(true);
setUseQmlDebugger(false);
m_remoteMounts = new MaemoRemoteMountsModel(this);
connect(target(),
SIGNAL(activeDeployConfigurationChanged(ProjectExplorer::DeployConfiguration*)),
this, SLOT(handleDeployConfigChanged()));
handleDeployConfigChanged();
Qt4Project *pro = qt4Target()->qt4Project();
connect(pro, SIGNAL(proFileUpdated(Qt4ProjectManager::Internal::Qt4ProFileNode*,bool)),
this, SLOT(proFileUpdate(Qt4ProjectManager::Internal::Qt4ProFileNode*,bool)));
connect(pro, SIGNAL(proFileInvalidated(Qt4ProjectManager::Internal::Qt4ProFileNode *)),
this, SLOT(proFileInvalidated(Qt4ProjectManager::Internal::Qt4ProFileNode*)));
}
MaemoRunConfiguration::~MaemoRunConfiguration()
{
}
Qt4Target *MaemoRunConfiguration::qt4Target() const
{
return static_cast<Qt4Target *>(target());
}
Qt4BuildConfiguration *MaemoRunConfiguration::activeQt4BuildConfiguration() const
{
return static_cast<Qt4BuildConfiguration *>(activeBuildConfiguration());
}
bool MaemoRunConfiguration::isEnabled(ProjectExplorer::BuildConfiguration *config) const
{
if (!m_validParse)
return false;
return true;
}
QWidget *MaemoRunConfiguration::createConfigurationWidget()
{
return new MaemoRunConfigurationWidget(this);
}
ProjectExplorer::OutputFormatter *MaemoRunConfiguration::createOutputFormatter() const
{
return new QtOutputFormatter(qt4Target()->qt4Project());
}
void MaemoRunConfiguration::handleParseState(bool success)
{
bool enabled = isEnabled();
m_validParse = success;
if (enabled != isEnabled()) {
emit isEnabledChanged(!enabled);
}
}
void MaemoRunConfiguration::proFileInvalidated(Qt4ProjectManager::Internal::Qt4ProFileNode *pro)
{
if (m_proFilePath != pro->path())
return;
qDebug()<<"proFileInvalidated";
handleParseState(false);
}
void MaemoRunConfiguration::proFileUpdate(Qt4ProjectManager::Internal::Qt4ProFileNode *pro, bool success)
{
if (m_proFilePath == pro->path()) {
handleParseState(success);
emit targetInformationChanged();
}
}
QVariantMap MaemoRunConfiguration::toMap() const
{
QVariantMap map(RunConfiguration::toMap());
map.insert(ArgumentsKey, m_arguments);
const QDir dir = QDir(target()->project()->projectDirectory());
map.insert(ProFileKey, dir.relativeFilePath(m_proFilePath));
map.insert(UseRemoteGdbKey, useRemoteGdb());
map.insert(BaseEnvironmentBaseKey, m_baseEnvironmentBase);
map.insert(UserEnvironmentChangesKey,
Utils::EnvironmentItem::toStringList(m_userEnvironmentChanges));
map.unite(m_remoteMounts->toMap());
return map;
}
bool MaemoRunConfiguration::fromMap(const QVariantMap &map)
{
if (!RunConfiguration::fromMap(map))
return false;
m_arguments = map.value(ArgumentsKey).toString();
const QDir dir = QDir(target()->project()->projectDirectory());
m_proFilePath = dir.filePath(map.value(ProFileKey).toString());
m_useRemoteGdb = map.value(UseRemoteGdbKey, DefaultUseRemoteGdbValue).toBool();
m_userEnvironmentChanges =
Utils::EnvironmentItem::fromStringList(map.value(UserEnvironmentChangesKey)
.toStringList());
m_baseEnvironmentBase = static_cast<BaseEnvironmentBase> (map.value(BaseEnvironmentBaseKey,
SystemEnvironmentBase).toInt());
m_remoteMounts->fromMap(map);
m_validParse = qt4Target()->qt4Project()->validParse(m_proFilePath);
setDefaultDisplayName(defaultDisplayName());
return true;
}
QString MaemoRunConfiguration::defaultDisplayName()
{
if (!m_proFilePath.isEmpty())
return (QFileInfo(m_proFilePath).completeBaseName());
//: Maemo run configuration default display name
return tr("Run on Maemo device");
}
MaemoDeviceConfig MaemoRunConfiguration::deviceConfig() const
{
return deployStep()->deviceConfigModel()->current();
}
const MaemoToolChain *MaemoRunConfiguration::toolchain() const
{
Qt4BuildConfiguration *qt4bc(activeQt4BuildConfiguration());
QTC_ASSERT(qt4bc, return 0);
MaemoToolChain *tc = dynamic_cast<MaemoToolChain *>(qt4bc->toolChain());
QTC_ASSERT(tc != 0, return 0);
return tc;
}
const QString MaemoRunConfiguration::gdbCmd() const
{
if (const MaemoToolChain *tc = toolchain())
return QDir::toNativeSeparators(tc->targetRoot() + QLatin1String("/bin/gdb"));
return QString();
}
MaemoDeployStep *MaemoRunConfiguration::deployStep() const
{
MaemoDeployStep * const step
= MaemoGlobal::buildStep<MaemoDeployStep>(target()->activeDeployConfiguration());
Q_ASSERT_X(step, Q_FUNC_INFO,
"Impossible: Maemo build configuration without deploy step.");
return step;
}
QString MaemoRunConfiguration::maddeRoot() const
{
if (const MaemoToolChain *tc = toolchain())
return tc->maddeRoot();
return QString();
}
const QString MaemoRunConfiguration::sysRoot() const
{
if (const MaemoToolChain *tc = toolchain())
return tc->sysrootRoot();
return QString();
}
const QString MaemoRunConfiguration::targetRoot() const
{
if (const MaemoToolChain *tc = toolchain())
return tc->targetRoot();
return QString();
}
const QString MaemoRunConfiguration::arguments() const
{
return m_arguments;
}
const QString MaemoRunConfiguration::dumperLib() const
{
Qt4BuildConfiguration *qt4bc(activeQt4BuildConfiguration());
return qt4bc->qtVersion()->debuggingHelperLibrary();
}
QString MaemoRunConfiguration::localDirToMountForRemoteGdb() const
{
const QString projectDir
= QDir::fromNativeSeparators(QDir::cleanPath(activeBuildConfiguration()
->target()->project()->projectDirectory()));
const QString execDir
= QDir::fromNativeSeparators(QFileInfo(localExecutableFilePath()).path());
const int length = qMin(projectDir.length(), execDir.length());
int lastSeparatorPos = 0;
for (int i = 0; i < length; ++i) {
if (projectDir.at(i) != execDir.at(i))
return projectDir.left(lastSeparatorPos);
if (projectDir.at(i) == QLatin1Char('/'))
lastSeparatorPos = i;
}
return projectDir.length() == execDir.length()
? projectDir : projectDir.left(lastSeparatorPos);
}
QString MaemoRunConfiguration::remoteProjectSourcesMountPoint() const
{
return MaemoGlobal::homeDirOnDevice(deviceConfig().server.uname)
+ QLatin1String("/gdbSourcesDir_")
+ QFileInfo(localExecutableFilePath()).fileName();
}
QString MaemoRunConfiguration::localExecutableFilePath() const
{
TargetInformation ti = qt4Target()->qt4Project()->rootProjectNode()
->targetInformation(m_proFilePath);
if (!ti.valid)
return QString();
return QDir::cleanPath(ti.workingDir + QLatin1Char('/') + ti.target);
}
QString MaemoRunConfiguration::remoteExecutableFilePath() const
{
return deployStep()->deployables()
->remoteExecutableFilePath(localExecutableFilePath());
}
MaemoPortList MaemoRunConfiguration::freePorts() const
{
const MaemoDeviceConfig &devConfig = deviceConfig();
const Qt4BuildConfiguration * const qt4bc = activeQt4BuildConfiguration();
if (devConfig.type == MaemoDeviceConfig::Simulator && qt4bc) {
MaemoQemuRuntime rt;
const int id = qt4bc->qtVersion()->uniqueId();
if (MaemoQemuManager::instance().runtimeForQtVersion(id, &rt))
return rt.m_freePorts;
}
return devConfig.freePorts();
}
bool MaemoRunConfiguration::useRemoteGdb() const
{
return m_useRemoteGdb && toolchain()->allowsRemoteMounts();
}
void MaemoRunConfiguration::setArguments(const QString &args)
{
m_arguments = args;
}
MaemoRunConfiguration::DebuggingType MaemoRunConfiguration::debuggingType() const
{
if (!toolchain() || !toolchain()->allowsQmlDebugging())
return DebugCppOnly;
if (useCppDebugger()) {
if (useQmlDebugger())
return DebugCppAndQml;
return DebugCppOnly;
}
return DebugQmlOnly;
}
int MaemoRunConfiguration::portsUsedByDebuggers() const
{
switch (debuggingType()) {
case DebugCppOnly:
case DebugQmlOnly:
return 1;
case DebugCppAndQml:
default:
return 2;
}
}
void MaemoRunConfiguration::updateDeviceConfigurations()
{
emit deviceConfigurationChanged(target());
}
void MaemoRunConfiguration::handleDeployConfigChanged()
{
const QList<DeployConfiguration *> &deployConfigs
= target()->deployConfigurations();
DeployConfiguration * const activeDeployConf
= target()->activeDeployConfiguration();
for (int i = 0; i < deployConfigs.count(); ++i) {
MaemoDeployStep * const step
= MaemoGlobal::buildStep<MaemoDeployStep>(deployConfigs.at(i));
MaemoDeviceConfigListModel * const devConfigModel
= step->deviceConfigModel();
if (deployConfigs.at(i) == activeDeployConf) {
connect(devConfigModel, SIGNAL(currentChanged()), this,
SLOT(updateDeviceConfigurations()));
connect(devConfigModel, SIGNAL(modelReset()), this,
SLOT(updateDeviceConfigurations()));
} else {
disconnect(devConfigModel, 0, this,
SLOT(updateDeviceConfigurations()));
}
}
updateDeviceConfigurations();
}
QString MaemoRunConfiguration::baseEnvironmentText() const
{
if (m_baseEnvironmentBase == CleanEnvironmentBase)
return tr("Clean Environment");
else if (m_baseEnvironmentBase == SystemEnvironmentBase)
return tr("System Environment");
return QString();
}
MaemoRunConfiguration::BaseEnvironmentBase MaemoRunConfiguration::baseEnvironmentBase() const
{
return m_baseEnvironmentBase;
}
void MaemoRunConfiguration::setBaseEnvironmentBase(BaseEnvironmentBase env)
{
if (m_baseEnvironmentBase != env) {
m_baseEnvironmentBase = env;
emit baseEnvironmentChanged();
}
}
Utils::Environment MaemoRunConfiguration::environment() const
{
Utils::Environment env = baseEnvironment();
env.modify(userEnvironmentChanges());
return env;
}
Utils::Environment MaemoRunConfiguration::baseEnvironment() const
{
return (m_baseEnvironmentBase == SystemEnvironmentBase ? systemEnvironment()
: Utils::Environment());
}
QList<Utils::EnvironmentItem> MaemoRunConfiguration::userEnvironmentChanges() const
{
return m_userEnvironmentChanges;
}
void MaemoRunConfiguration::setUserEnvironmentChanges(
const QList<Utils::EnvironmentItem> &diff)
{
if (m_userEnvironmentChanges != diff) {
m_userEnvironmentChanges = diff;
emit userEnvironmentChangesChanged(diff);
}
}
Utils::Environment MaemoRunConfiguration::systemEnvironment() const
{
return m_systemEnvironment;
}
void MaemoRunConfiguration::setSystemEnvironment(const Utils::Environment &environment)
{
if (m_systemEnvironment.size() == 0 || m_systemEnvironment != environment) {
m_systemEnvironment = environment;
emit systemEnvironmentChanged();
}
}
} // namespace Internal
} // namespace Qt4ProjectManager
<commit_msg>Remove debug output<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "maemorunconfiguration.h"
#include "maemodeployables.h"
#include "maemodeploystep.h"
#include "maemodeviceconfiglistmodel.h"
#include "maemoglobal.h"
#include "maemoqemumanager.h"
#include "maemoremotemountsmodel.h"
#include "maemorunconfigurationwidget.h"
#include "maemotoolchain.h"
#include "qtoutputformatter.h"
#include <coreplugin/icore.h>
#include <coreplugin/messagemanager.h>
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/session.h>
#include <qt4projectmanager/qt4buildconfiguration.h>
#include <qt4projectmanager/qt4project.h>
#include <utils/qtcassert.h>
#include <utils/qtcprocess.h>
#include <QtCore/QStringBuilder>
namespace Qt4ProjectManager {
namespace Internal {
namespace {
const bool DefaultUseRemoteGdbValue = false;
} // anonymous namespace
using namespace ProjectExplorer;
MaemoRunConfiguration::MaemoRunConfiguration(Qt4Target *parent,
const QString &proFilePath)
: RunConfiguration(parent, QLatin1String(MAEMO_RC_ID))
, m_proFilePath(proFilePath)
, m_useRemoteGdb(DefaultUseRemoteGdbValue)
, m_baseEnvironmentBase(SystemEnvironmentBase)
, m_validParse(parent->qt4Project()->validParse(m_proFilePath))
{
init();
}
MaemoRunConfiguration::MaemoRunConfiguration(Qt4Target *parent,
MaemoRunConfiguration *source)
: RunConfiguration(parent, source)
, m_proFilePath(source->m_proFilePath)
, m_gdbPath(source->m_gdbPath)
, m_arguments(source->m_arguments)
, m_useRemoteGdb(source->useRemoteGdb())
, m_baseEnvironmentBase(source->m_baseEnvironmentBase)
, m_systemEnvironment(source->m_systemEnvironment)
, m_userEnvironmentChanges(source->m_userEnvironmentChanges)
, m_validParse(source->m_validParse)
{
init();
}
void MaemoRunConfiguration::init()
{
setDefaultDisplayName(defaultDisplayName());
setUseCppDebugger(true);
setUseQmlDebugger(false);
m_remoteMounts = new MaemoRemoteMountsModel(this);
connect(target(),
SIGNAL(activeDeployConfigurationChanged(ProjectExplorer::DeployConfiguration*)),
this, SLOT(handleDeployConfigChanged()));
handleDeployConfigChanged();
Qt4Project *pro = qt4Target()->qt4Project();
connect(pro, SIGNAL(proFileUpdated(Qt4ProjectManager::Internal::Qt4ProFileNode*,bool)),
this, SLOT(proFileUpdate(Qt4ProjectManager::Internal::Qt4ProFileNode*,bool)));
connect(pro, SIGNAL(proFileInvalidated(Qt4ProjectManager::Internal::Qt4ProFileNode *)),
this, SLOT(proFileInvalidated(Qt4ProjectManager::Internal::Qt4ProFileNode*)));
}
MaemoRunConfiguration::~MaemoRunConfiguration()
{
}
Qt4Target *MaemoRunConfiguration::qt4Target() const
{
return static_cast<Qt4Target *>(target());
}
Qt4BuildConfiguration *MaemoRunConfiguration::activeQt4BuildConfiguration() const
{
return static_cast<Qt4BuildConfiguration *>(activeBuildConfiguration());
}
bool MaemoRunConfiguration::isEnabled(ProjectExplorer::BuildConfiguration *config) const
{
if (!m_validParse)
return false;
return true;
}
QWidget *MaemoRunConfiguration::createConfigurationWidget()
{
return new MaemoRunConfigurationWidget(this);
}
ProjectExplorer::OutputFormatter *MaemoRunConfiguration::createOutputFormatter() const
{
return new QtOutputFormatter(qt4Target()->qt4Project());
}
void MaemoRunConfiguration::handleParseState(bool success)
{
bool enabled = isEnabled();
m_validParse = success;
if (enabled != isEnabled()) {
emit isEnabledChanged(!enabled);
}
}
void MaemoRunConfiguration::proFileInvalidated(Qt4ProjectManager::Internal::Qt4ProFileNode *pro)
{
if (m_proFilePath != pro->path())
return;
handleParseState(false);
}
void MaemoRunConfiguration::proFileUpdate(Qt4ProjectManager::Internal::Qt4ProFileNode *pro, bool success)
{
if (m_proFilePath == pro->path()) {
handleParseState(success);
emit targetInformationChanged();
}
}
QVariantMap MaemoRunConfiguration::toMap() const
{
QVariantMap map(RunConfiguration::toMap());
map.insert(ArgumentsKey, m_arguments);
const QDir dir = QDir(target()->project()->projectDirectory());
map.insert(ProFileKey, dir.relativeFilePath(m_proFilePath));
map.insert(UseRemoteGdbKey, useRemoteGdb());
map.insert(BaseEnvironmentBaseKey, m_baseEnvironmentBase);
map.insert(UserEnvironmentChangesKey,
Utils::EnvironmentItem::toStringList(m_userEnvironmentChanges));
map.unite(m_remoteMounts->toMap());
return map;
}
bool MaemoRunConfiguration::fromMap(const QVariantMap &map)
{
if (!RunConfiguration::fromMap(map))
return false;
m_arguments = map.value(ArgumentsKey).toString();
const QDir dir = QDir(target()->project()->projectDirectory());
m_proFilePath = dir.filePath(map.value(ProFileKey).toString());
m_useRemoteGdb = map.value(UseRemoteGdbKey, DefaultUseRemoteGdbValue).toBool();
m_userEnvironmentChanges =
Utils::EnvironmentItem::fromStringList(map.value(UserEnvironmentChangesKey)
.toStringList());
m_baseEnvironmentBase = static_cast<BaseEnvironmentBase> (map.value(BaseEnvironmentBaseKey,
SystemEnvironmentBase).toInt());
m_remoteMounts->fromMap(map);
m_validParse = qt4Target()->qt4Project()->validParse(m_proFilePath);
setDefaultDisplayName(defaultDisplayName());
return true;
}
QString MaemoRunConfiguration::defaultDisplayName()
{
if (!m_proFilePath.isEmpty())
return (QFileInfo(m_proFilePath).completeBaseName());
//: Maemo run configuration default display name
return tr("Run on Maemo device");
}
MaemoDeviceConfig MaemoRunConfiguration::deviceConfig() const
{
return deployStep()->deviceConfigModel()->current();
}
const MaemoToolChain *MaemoRunConfiguration::toolchain() const
{
Qt4BuildConfiguration *qt4bc(activeQt4BuildConfiguration());
QTC_ASSERT(qt4bc, return 0);
MaemoToolChain *tc = dynamic_cast<MaemoToolChain *>(qt4bc->toolChain());
QTC_ASSERT(tc != 0, return 0);
return tc;
}
const QString MaemoRunConfiguration::gdbCmd() const
{
if (const MaemoToolChain *tc = toolchain())
return QDir::toNativeSeparators(tc->targetRoot() + QLatin1String("/bin/gdb"));
return QString();
}
MaemoDeployStep *MaemoRunConfiguration::deployStep() const
{
MaemoDeployStep * const step
= MaemoGlobal::buildStep<MaemoDeployStep>(target()->activeDeployConfiguration());
Q_ASSERT_X(step, Q_FUNC_INFO,
"Impossible: Maemo build configuration without deploy step.");
return step;
}
QString MaemoRunConfiguration::maddeRoot() const
{
if (const MaemoToolChain *tc = toolchain())
return tc->maddeRoot();
return QString();
}
const QString MaemoRunConfiguration::sysRoot() const
{
if (const MaemoToolChain *tc = toolchain())
return tc->sysrootRoot();
return QString();
}
const QString MaemoRunConfiguration::targetRoot() const
{
if (const MaemoToolChain *tc = toolchain())
return tc->targetRoot();
return QString();
}
const QString MaemoRunConfiguration::arguments() const
{
return m_arguments;
}
const QString MaemoRunConfiguration::dumperLib() const
{
Qt4BuildConfiguration *qt4bc(activeQt4BuildConfiguration());
return qt4bc->qtVersion()->debuggingHelperLibrary();
}
QString MaemoRunConfiguration::localDirToMountForRemoteGdb() const
{
const QString projectDir
= QDir::fromNativeSeparators(QDir::cleanPath(activeBuildConfiguration()
->target()->project()->projectDirectory()));
const QString execDir
= QDir::fromNativeSeparators(QFileInfo(localExecutableFilePath()).path());
const int length = qMin(projectDir.length(), execDir.length());
int lastSeparatorPos = 0;
for (int i = 0; i < length; ++i) {
if (projectDir.at(i) != execDir.at(i))
return projectDir.left(lastSeparatorPos);
if (projectDir.at(i) == QLatin1Char('/'))
lastSeparatorPos = i;
}
return projectDir.length() == execDir.length()
? projectDir : projectDir.left(lastSeparatorPos);
}
QString MaemoRunConfiguration::remoteProjectSourcesMountPoint() const
{
return MaemoGlobal::homeDirOnDevice(deviceConfig().server.uname)
+ QLatin1String("/gdbSourcesDir_")
+ QFileInfo(localExecutableFilePath()).fileName();
}
QString MaemoRunConfiguration::localExecutableFilePath() const
{
TargetInformation ti = qt4Target()->qt4Project()->rootProjectNode()
->targetInformation(m_proFilePath);
if (!ti.valid)
return QString();
return QDir::cleanPath(ti.workingDir + QLatin1Char('/') + ti.target);
}
QString MaemoRunConfiguration::remoteExecutableFilePath() const
{
return deployStep()->deployables()
->remoteExecutableFilePath(localExecutableFilePath());
}
MaemoPortList MaemoRunConfiguration::freePorts() const
{
const MaemoDeviceConfig &devConfig = deviceConfig();
const Qt4BuildConfiguration * const qt4bc = activeQt4BuildConfiguration();
if (devConfig.type == MaemoDeviceConfig::Simulator && qt4bc) {
MaemoQemuRuntime rt;
const int id = qt4bc->qtVersion()->uniqueId();
if (MaemoQemuManager::instance().runtimeForQtVersion(id, &rt))
return rt.m_freePorts;
}
return devConfig.freePorts();
}
bool MaemoRunConfiguration::useRemoteGdb() const
{
return m_useRemoteGdb && toolchain()->allowsRemoteMounts();
}
void MaemoRunConfiguration::setArguments(const QString &args)
{
m_arguments = args;
}
MaemoRunConfiguration::DebuggingType MaemoRunConfiguration::debuggingType() const
{
if (!toolchain() || !toolchain()->allowsQmlDebugging())
return DebugCppOnly;
if (useCppDebugger()) {
if (useQmlDebugger())
return DebugCppAndQml;
return DebugCppOnly;
}
return DebugQmlOnly;
}
int MaemoRunConfiguration::portsUsedByDebuggers() const
{
switch (debuggingType()) {
case DebugCppOnly:
case DebugQmlOnly:
return 1;
case DebugCppAndQml:
default:
return 2;
}
}
void MaemoRunConfiguration::updateDeviceConfigurations()
{
emit deviceConfigurationChanged(target());
}
void MaemoRunConfiguration::handleDeployConfigChanged()
{
const QList<DeployConfiguration *> &deployConfigs
= target()->deployConfigurations();
DeployConfiguration * const activeDeployConf
= target()->activeDeployConfiguration();
for (int i = 0; i < deployConfigs.count(); ++i) {
MaemoDeployStep * const step
= MaemoGlobal::buildStep<MaemoDeployStep>(deployConfigs.at(i));
MaemoDeviceConfigListModel * const devConfigModel
= step->deviceConfigModel();
if (deployConfigs.at(i) == activeDeployConf) {
connect(devConfigModel, SIGNAL(currentChanged()), this,
SLOT(updateDeviceConfigurations()));
connect(devConfigModel, SIGNAL(modelReset()), this,
SLOT(updateDeviceConfigurations()));
} else {
disconnect(devConfigModel, 0, this,
SLOT(updateDeviceConfigurations()));
}
}
updateDeviceConfigurations();
}
QString MaemoRunConfiguration::baseEnvironmentText() const
{
if (m_baseEnvironmentBase == CleanEnvironmentBase)
return tr("Clean Environment");
else if (m_baseEnvironmentBase == SystemEnvironmentBase)
return tr("System Environment");
return QString();
}
MaemoRunConfiguration::BaseEnvironmentBase MaemoRunConfiguration::baseEnvironmentBase() const
{
return m_baseEnvironmentBase;
}
void MaemoRunConfiguration::setBaseEnvironmentBase(BaseEnvironmentBase env)
{
if (m_baseEnvironmentBase != env) {
m_baseEnvironmentBase = env;
emit baseEnvironmentChanged();
}
}
Utils::Environment MaemoRunConfiguration::environment() const
{
Utils::Environment env = baseEnvironment();
env.modify(userEnvironmentChanges());
return env;
}
Utils::Environment MaemoRunConfiguration::baseEnvironment() const
{
return (m_baseEnvironmentBase == SystemEnvironmentBase ? systemEnvironment()
: Utils::Environment());
}
QList<Utils::EnvironmentItem> MaemoRunConfiguration::userEnvironmentChanges() const
{
return m_userEnvironmentChanges;
}
void MaemoRunConfiguration::setUserEnvironmentChanges(
const QList<Utils::EnvironmentItem> &diff)
{
if (m_userEnvironmentChanges != diff) {
m_userEnvironmentChanges = diff;
emit userEnvironmentChangesChanged(diff);
}
}
Utils::Environment MaemoRunConfiguration::systemEnvironment() const
{
return m_systemEnvironment;
}
void MaemoRunConfiguration::setSystemEnvironment(const Utils::Environment &environment)
{
if (m_systemEnvironment.size() == 0 || m_systemEnvironment != environment) {
m_systemEnvironment = environment;
emit systemEnvironmentChanged();
}
}
} // namespace Internal
} // namespace Qt4ProjectManager
<|endoftext|> |
<commit_before>#include "RuleMatching.h"
#include "hext/Rule.h"
#include "NodeUtil.h"
namespace hext {
void SaveMatchingNodesRecursive(const Rule * rule,
const GumboNode * node,
std::vector<MatchingNodes>& result)
{
assert(node);
if( !node )
return;
const GumboNode * next_node = node;
while( next_node )
{
MatchingNodes sub;
next_node = MatchRuleGroup(rule, next_node, sub);
if( sub.size() )
result.push_back(std::move(sub));
}
next_node = node;
do
{
if( next_node->type == GUMBO_NODE_ELEMENT &&
next_node->v.element.children.length )
{
auto next_node_first_child = static_cast<const GumboNode *>(
next_node->v.element.children.data[0]);
SaveMatchingNodesRecursive(rule, next_node_first_child, result);
}
}
while( (next_node = NextNode(next_node)) );
}
const GumboNode * MatchRuleGroup(const Rule * rule,
const GumboNode * node,
MatchingNodes& result)
{
if( !rule || !node )
return nullptr;
auto first_rule = rule;
MatchingNodes sub;
while( rule && node )
{
if( rule->is_optional() )
{
// Optional rules can be matched anywhere up to the next match of a
// mandatory rule
// Flag to tell whether the next mandatory rule falls into the current
// result set or the next one.
bool has_wrapped = false;
// Get the next mandatory rule within (rule,rule-end)
auto stop_rule = FindMandatoryRule(rule->next(), nullptr);
if( !stop_rule )
{
// Get the next mandatory rule within [first_rule, rule)
stop_rule = FindMandatoryRule(first_rule, rule);
// if there are no mandatory rules at all
if( stop_rule == rule )
stop_rule = nullptr;
has_wrapped = true;
}
// If there are no mandatory rules, match until end
if( !stop_rule )
{
node = MatchRange(rule, nullptr, node, nullptr, sub);
std::move(sub.begin(), sub.end(), std::back_inserter(result));
return node ? NextNode(node) : nullptr;
}
// else match until the match of the next mandatory rule
else
{
// If the stop_rule is not included in this match_group
if( has_wrapped )
{
// Match the next node, but discard the result.
// TODO: This is obviously wasteful.
MatchingNodes discard;
auto stop_node = MatchRuleOnce(stop_rule, node, nullptr, discard);
// Match until the last rule: either there are only optional rules
// following, or no rules.
node = MatchRange(rule, nullptr, node, stop_node, sub);
// If there was no match found for the mandatory rule, then matching
// is done.
if( !stop_node )
node = nullptr;
std::move(sub.begin(), sub.end(), std::back_inserter(result));
return node ? NextNode(node) : nullptr;
}
else
{
// Match the next mandatory rule
auto stop_node = MatchRuleOnce(stop_rule, node, nullptr, sub);
if( !stop_node )
{
// Here, the stop rule is mandatory, and is part of the current
// result set, but was not matched, so we can abort.
return nullptr;
}
else
{
node = MatchRange(rule, stop_rule, node, stop_node, sub);
// Also include the already matched stop_rule
sub.push_back({stop_rule, stop_node});
rule = stop_rule->next();
node = NextNode(stop_node);
}
}
}
}
else // rule is mandatory
{
node = MatchRuleOnce(rule, node, nullptr, sub);
// If a mandatory rule isn't found, abort immediately
if( !node )
return nullptr;
sub.push_back({rule, node});
node = NextNode(node);
rule = rule->next();
}
}
// Optional rules can be skipped
while( rule && rule->is_optional() )
rule = rule->next();
if( !rule )
{
// Here, all rules (at least all mandatory rules) were matched.
std::move(sub.begin(), sub.end(), std::back_inserter(result));
return node ? NextNode(node) : nullptr;
}
return nullptr;
}
bool RuleMatchesNodeRecursive(const Rule * rule,
const GumboNode * node,
MatchingNodes& result)
{
if( !rule || !node )
return false;
if( !rule->matches(node) )
return false;
if( !rule->child() )
return true;
if( node->type != GUMBO_NODE_ELEMENT || !node->v.element.children.length )
return false;
auto first_child = static_cast<const GumboNode *>(
node->v.element.children.data[0]);
bool matched = false;
auto next_node = first_child;
do
{
MatchingNodes sub;
next_node = MatchRuleGroup(rule->child(), next_node, sub);
if( sub.size() )
{
std::move(sub.begin(), sub.end(), std::back_inserter(result));
matched = true;
}
}
while( next_node );
return matched;
}
const GumboNode * MatchRuleOnce(const Rule * rule,
const GumboNode * begin,
const GumboNode * end,
MatchingNodes& result)
{
assert(rule);
if( !rule )
return end;
while( begin && begin != end )
{
if( RuleMatchesNodeRecursive(rule, begin, result) )
return begin;
begin = NextNode(begin);
}
return end;
}
const GumboNode * MatchRange(const Rule * r_begin,
const Rule * r_end,
const GumboNode * n_begin,
const GumboNode * n_end,
MatchingNodes& result)
{
while( n_begin && n_begin != n_end &&
r_begin && r_begin != r_end )
{
auto matching_node = MatchRuleOnce(r_begin, n_begin, n_end, result);
if( matching_node && matching_node != n_end )
{
result.push_back({r_begin, matching_node});
n_begin = NextNode(matching_node);
}
r_begin = r_begin->next();
}
return n_begin;
}
const Rule * FindMandatoryRule(const Rule * begin, const Rule * end)
{
while( begin && begin != end )
{
if( !begin->is_optional() )
return begin;
begin = begin->next();
}
return end;
}
} // namespace hext
<commit_msg>RuleMatching: fix MatchRange to return last matched node<commit_after>#include "RuleMatching.h"
#include "hext/Rule.h"
#include "NodeUtil.h"
namespace hext {
void SaveMatchingNodesRecursive(const Rule * rule,
const GumboNode * node,
std::vector<MatchingNodes>& result)
{
assert(node);
if( !node )
return;
const GumboNode * next_node = node;
while( next_node )
{
MatchingNodes sub;
next_node = MatchRuleGroup(rule, next_node, sub);
if( sub.size() )
result.push_back(std::move(sub));
}
next_node = node;
do
{
if( next_node->type == GUMBO_NODE_ELEMENT &&
next_node->v.element.children.length )
{
auto next_node_first_child = static_cast<const GumboNode *>(
next_node->v.element.children.data[0]);
SaveMatchingNodesRecursive(rule, next_node_first_child, result);
}
}
while( (next_node = NextNode(next_node)) );
}
const GumboNode * MatchRuleGroup(const Rule * rule,
const GumboNode * node,
MatchingNodes& result)
{
if( !rule || !node )
return nullptr;
auto first_rule = rule;
MatchingNodes sub;
while( rule && node )
{
if( rule->is_optional() )
{
// Optional rules can be matched anywhere up to the next match of a
// mandatory rule
// Flag to tell whether the next mandatory rule falls into the current
// result set or the next one.
bool has_wrapped = false;
// Get the next mandatory rule within (rule,rule-end)
auto stop_rule = FindMandatoryRule(rule->next(), nullptr);
if( !stop_rule )
{
// Get the next mandatory rule within [first_rule, rule)
stop_rule = FindMandatoryRule(first_rule, rule);
// if there are no mandatory rules at all
if( stop_rule == rule )
stop_rule = nullptr;
has_wrapped = true;
}
// If there are no mandatory rules, match until end
if( !stop_rule )
{
node = MatchRange(rule, nullptr, node, nullptr, sub);
std::move(sub.begin(), sub.end(), std::back_inserter(result));
return node ? NextNode(node) : nullptr;
}
// else match until the match of the next mandatory rule
else
{
// If the stop_rule is not included in this match_group
if( has_wrapped )
{
// Match the next node, but discard the result.
// TODO: This is obviously wasteful.
MatchingNodes discard;
auto stop_node = MatchRuleOnce(stop_rule, node, nullptr, discard);
// Match until the last rule: either there are only optional rules
// following, or no rules.
node = MatchRange(rule, nullptr, node, stop_node, sub);
// If there was no match found for the mandatory rule, then matching
// is done.
if( !stop_node )
node = nullptr;
std::move(sub.begin(), sub.end(), std::back_inserter(result));
return node ? NextNode(node) : nullptr;
}
else
{
// Match the next mandatory rule
auto stop_node = MatchRuleOnce(stop_rule, node, nullptr, sub);
if( !stop_node )
{
// Here, the stop rule is mandatory, and is part of the current
// result set, but was not matched, so we can abort.
return nullptr;
}
else
{
node = MatchRange(rule, stop_rule, node, stop_node, sub);
// Also include the already matched stop_rule
sub.push_back({stop_rule, stop_node});
rule = stop_rule->next();
node = NextNode(stop_node);
}
}
}
}
else // rule is mandatory
{
node = MatchRuleOnce(rule, node, nullptr, sub);
// If a mandatory rule isn't found, abort immediately
if( !node )
return nullptr;
sub.push_back({rule, node});
node = NextNode(node);
rule = rule->next();
}
}
// Optional rules can be skipped
while( rule && rule->is_optional() )
rule = rule->next();
if( !rule )
{
// Here, all rules (at least all mandatory rules) were matched.
std::move(sub.begin(), sub.end(), std::back_inserter(result));
return node ? NextNode(node) : nullptr;
}
return nullptr;
}
bool RuleMatchesNodeRecursive(const Rule * rule,
const GumboNode * node,
MatchingNodes& result)
{
if( !rule || !node )
return false;
if( !rule->matches(node) )
return false;
if( !rule->child() )
return true;
if( node->type != GUMBO_NODE_ELEMENT || !node->v.element.children.length )
return false;
auto first_child = static_cast<const GumboNode *>(
node->v.element.children.data[0]);
bool matched = false;
auto next_node = first_child;
do
{
MatchingNodes sub;
next_node = MatchRuleGroup(rule->child(), next_node, sub);
if( sub.size() )
{
std::move(sub.begin(), sub.end(), std::back_inserter(result));
matched = true;
}
}
while( next_node );
return matched;
}
const GumboNode * MatchRuleOnce(const Rule * rule,
const GumboNode * begin,
const GumboNode * end,
MatchingNodes& result)
{
assert(rule);
if( !rule )
return end;
while( begin && begin != end )
{
if( RuleMatchesNodeRecursive(rule, begin, result) )
return begin;
begin = NextNode(begin);
}
return end;
}
const GumboNode * MatchRange(const Rule * r_begin,
const Rule * r_end,
const GumboNode * n_begin,
const GumboNode * n_end,
MatchingNodes& result)
{
assert(n_begin);
if( !n_begin )
return nullptr;
const GumboNode * matching_node = nullptr;
while( r_begin && r_begin != r_end )
{
matching_node = MatchRuleOnce(r_begin, n_begin, n_end, result);
if( matching_node && matching_node != n_end )
{
result.push_back({r_begin, matching_node});
n_begin = NextNode(matching_node);
}
r_begin = r_begin->next();
}
return matching_node;
}
const Rule * FindMandatoryRule(const Rule * begin, const Rule * end)
{
while( begin && begin != end )
{
if( !begin->is_optional() )
return begin;
begin = begin->next();
}
return end;
}
} // namespace hext
<|endoftext|> |
<commit_before>#include "parser.h"
#include "_parser.h"
#include <QScriptValueIterator>
int i = 0;
QCoreApplication *qCoreApplication = new QCoreApplication(i, nullptr);
QScriptEngine *engine = new QScriptEngine();
namespace QJSTP
{
namespace Parser
{
QScriptValue parse(QString str)
{
uint beg = 0;
skipWhitespaces(str, beg);
return parser[typeOf(str, beg)](str, beg);
}
QString stringify(QScriptValue obj)
{
if (obj.isArray()) {
return stringifyArr(obj);
}
else if (obj.isObject()) {
return stringifyObj(obj);
}
else {
return obj.toString();
}
}
QString dump(QScriptValue obj)
{
}
QScriptValue interprete(QString str)
{
QScriptValue result = engine->evaluate("(" + str + ")");
postprocess(result);
return result;
}
QString serialize(QScriptValue obj)
{
}
QScriptValue deserialize(QString str)
{
}
QScriptValue dataToObject(QScriptValue data, QScriptValue metadata)
{
}
QScriptValue objectToData(QScriptValue obj, QScriptValue metadata)
{
}
QScriptValue parseUndefined(QString &str, uint &beg)
{
if (str[beg] == ',' || str[beg] == ']') {
return QScriptValue::UndefinedValue;
}
if (str.mid(beg, 9) == "undefined") {
beg += 9;
return QScriptValue(QScriptValue::UndefinedValue);
}
return parseError(str, beg);
}
QScriptValue parseNull(QString &str, uint &beg)
{
if (str.mid(beg, 4) == "null") {
beg += 4;
return QScriptValue::NullValue;
}
return parseError(str, beg);
}
QScriptValue parseBool(QString &str, uint &beg)
{
if (str.mid(beg, 4) == "true") {
beg += 4;
return QScriptValue(true);
}
if (str.mid(beg, 5) == "false") {
beg += 5;
return QScriptValue(false);
}
return parseError(str, beg);
}
QScriptValue parseNumber(QString &str, uint &beg)
{
uint size = 0;
bool isIntPart = true;
if (str[beg] == '+' || str[beg] == '-') ++size;
while (!str[beg + size].isSpace() && size < str.length() - beg && str[beg + size] != ',') {
if (str[beg + size].isNumber()) {
++size;
} else if (str[beg + size] == '.' && isIntPart) {
isIntPart = false;
++size;
} else {
break;
}
}
if (size > 0) {
beg += size;
return QScriptValue(str.mid(beg - size, size).toDouble());
}
return parseError(str, beg);
}
QScriptValue parseString(QString &str, uint &beg)
{
uint size = 1;
QCharRef begSymbol = str[beg];
++beg;
while (true) {
if (size == str.length() - beg) {
size = -1;
break;
}
if (str[beg + size] == begSymbol && str[beg + size - 1] != '\\') { break; }
++size;
}
if (size > 0) {
beg += size + 1;
return QScriptValue(str.mid(beg - size - 1, size));
}
return parseError(str, beg);
}
QScriptValue parseArray(QString &str, uint &beg)
{
QScriptValue result = engine->newArray();
skipWhitespaces(str, beg);
quint32 index = 0;
while (beg < str.length()) {
if (str[beg] == ']') {
++beg;
return result;
}
++beg;
skipWhitespaces(str, beg);
result.setProperty(index++, parser[typeOf(str, beg)](str, beg));
skipWhitespaces(str, beg);
}
return parseError(str, beg);
}
QScriptValue parseObject(QString &str, uint &beg)
{
QScriptValue result = engine->newObject();
skipWhitespaces(str, beg);
while (beg < str.length()) {
if (str[beg] == '}') {
++beg;
return result;
}
else {
++beg;
skipWhitespaces(str, beg);
}
QString token = getTokenName(str, beg);
result.setProperty(token, parser[typeOf(str, beg)](str, beg));
skipWhitespaces(str, beg);
}
return result;
}
QScriptValue parseError(QString &str, uint &beg)
{
}
QScriptValue parseFunction(QString &str, uint &beg)
{
}
Type typeOf(QString &str, uint &beg)
{
skipWhitespaces(str, beg);
if (str[beg] == ',' || str[beg] == ']' || str[beg] == 'u')
return UNDEFINED;
if (str[beg] == 'n')
return NUL;
if (str[beg].isDigit() || str[beg] == '.' || str[beg] == '-' || str[beg] == '+')
return NUMBER;
if (str[beg] == 'f' && str[beg + 1] == 'u')
return FUNCTION;
if ((str[beg] == 'f' && str[beg + 1] == 'a') || str[beg] == 't')
return BOOL;
if (str[beg] == '\"' || str[beg] == '\'')
return STRING;
if (str[beg] == '[')
return ARRAY;
if (str[beg] == '{')
return OBJECT;
return ERROR;
}
void skipWhitespaces(QString &str, uint &beg)
{
while (str[beg].isSpace()) { ++beg; }
}
QString getTokenName(QString &str, uint &beg)
{
skipWhitespaces(str, beg);
uint size = 0;
for (size = 0; size < str.length() - beg && !str[beg + size].isSpace() && str[beg + size] != ':'; ++size);
uint tmp = beg;
beg += size;
skipWhitespaces(str, beg);
++beg;
return QString(str.mid(tmp, size));
}
QString stringifyObj(QScriptValue obj)
{
QString str;
QScriptValueIterator current(obj);
str = "{";
if (current.hasNext()) {
current.next();
str += (current.name() + ":" + stringify(current.value()));
}
while (current.hasNext()) {
current.next();
str += "," + current.name() + ":" + stringify(current.value());
}
str += "}";
return str;
}
QString stringifyArr(QScriptValue obj)
{
QString str;
str = "[";
if (obj.property("length").toNumber() != 0) {
str += stringify(obj.property(0));
}
for (int i = 1; i < obj.property("length").toNumber(); ++i) {
QScriptValue current = obj.property(i);
str += ",";
if (!current.isUndefined()) {
str += stringify(current);
}
}
str += "]";
return str;
}
void postprocess(QScriptValue value)
{
if (value.isObject()) {
QScriptValueIterator current(value);
if (current.hasNext()) {
current.next();
postprocess(current.value());
}
}
else if (value.isArray()) {
for (int i = 1; i < value.property("length").toNumber(); ++i) {
if (!value.property(i).isValid()) {
value.setProperty(i, QScriptValue::UndefinedValue);
}
}
}
}
}
}
<commit_msg>Fixed parsing of empty arrays and objects<commit_after>#include "parser.h"
#include "_parser.h"
#include <QScriptValueIterator>
int i = 0;
QCoreApplication *qCoreApplication = new QCoreApplication(i, nullptr);
QScriptEngine *engine = new QScriptEngine();
namespace QJSTP
{
namespace Parser
{
QScriptValue parse(QString str)
{
uint beg = 0;
skipWhitespaces(str, beg);
return parser[typeOf(str, beg)](str, beg);
}
QString stringify(QScriptValue obj)
{
if (obj.isArray()) {
return stringifyArr(obj);
}
else if (obj.isObject()) {
return stringifyObj(obj);
}
else {
return obj.toString();
}
}
QString dump(QScriptValue obj)
{
}
QScriptValue interprete(QString str)
{
QScriptValue result = engine->evaluate("(" + str + ")");
postprocess(result);
return result;
}
QString serialize(QScriptValue obj)
{
}
QScriptValue deserialize(QString str)
{
}
QScriptValue dataToObject(QScriptValue data, QScriptValue metadata)
{
}
QScriptValue objectToData(QScriptValue obj, QScriptValue metadata)
{
}
QScriptValue parseUndefined(QString &str, uint &beg)
{
if (str[beg] == ',' || str[beg] == ']') {
return QScriptValue::UndefinedValue;
}
if (str.mid(beg, 9) == "undefined") {
beg += 9;
return QScriptValue(QScriptValue::UndefinedValue);
}
return parseError(str, beg);
}
QScriptValue parseNull(QString &str, uint &beg)
{
if (str.mid(beg, 4) == "null") {
beg += 4;
return QScriptValue::NullValue;
}
return parseError(str, beg);
}
QScriptValue parseBool(QString &str, uint &beg)
{
if (str.mid(beg, 4) == "true") {
beg += 4;
return QScriptValue(true);
}
if (str.mid(beg, 5) == "false") {
beg += 5;
return QScriptValue(false);
}
return parseError(str, beg);
}
QScriptValue parseNumber(QString &str, uint &beg)
{
uint size = 0;
bool isIntPart = true;
if (str[beg] == '+' || str[beg] == '-') ++size;
while (!str[beg + size].isSpace() && size < str.length() - beg && str[beg + size] != ',') {
if (str[beg + size].isNumber()) {
++size;
} else if (str[beg + size] == '.' && isIntPart) {
isIntPart = false;
++size;
} else {
break;
}
}
if (size > 0) {
beg += size;
return QScriptValue(str.mid(beg - size, size).toDouble());
}
return parseError(str, beg);
}
QScriptValue parseString(QString &str, uint &beg)
{
uint size = 1;
QCharRef begSymbol = str[beg];
++beg;
while (true) {
if (size == str.length() - beg) {
size = -1;
break;
}
if (str[beg + size] == begSymbol && str[beg + size - 1] != '\\') { break; }
++size;
}
if (size > 0) {
beg += size + 1;
return QScriptValue(str.mid(beg - size - 1, size));
}
return parseError(str, beg);
}
QScriptValue parseArray(QString &str, uint &beg)
{
QScriptValue result = engine->newArray();
skipWhitespaces(str, beg);
quint32 index = 0;
++beg;
skipWhitespaces(str, beg);
if (str[beg] == ']') {
++beg;
return result;
}
while (beg < str.length()) {
skipWhitespaces(str, beg);
result.setProperty(index++, parser[typeOf(str, beg)](str, beg));
skipWhitespaces(str, beg);
if (str[beg] == ']') {
++beg;
return result;
};
++beg;
}
return parseError(str, beg);
}
QScriptValue parseObject(QString &str, uint &beg)
{
QScriptValue result = engine->newObject();
++beg;
skipWhitespaces(str, beg);
if (str[beg] == '}') {
++beg;
return result;
}
while (beg < str.length()) {
skipWhitespaces(str, beg);
QString token = getTokenName(str, beg);
result.setProperty(token, parser[typeOf(str, beg)](str, beg));
skipWhitespaces(str, beg);
if (str[beg] == '}') {
++beg;
return result;
}
++beg;
}
return result;
}
QScriptValue parseError(QString &str, uint &beg)
{
}
QScriptValue parseFunction(QString &str, uint &beg)
{
}
Type typeOf(QString &str, uint &beg)
{
skipWhitespaces(str, beg);
if (str[beg] == ',' || str[beg] == ']' || str[beg] == 'u')
return UNDEFINED;
if (str[beg] == 'n')
return NUL;
if (str[beg].isDigit() || str[beg] == '.' || str[beg] == '-' || str[beg] == '+')
return NUMBER;
if (str[beg] == 'f' && str[beg + 1] == 'u')
return FUNCTION;
if ((str[beg] == 'f' && str[beg + 1] == 'a') || str[beg] == 't')
return BOOL;
if (str[beg] == '\"' || str[beg] == '\'')
return STRING;
if (str[beg] == '[')
return ARRAY;
if (str[beg] == '{')
return OBJECT;
return ERROR;
}
void skipWhitespaces(QString &str, uint &beg)
{
while (str[beg].isSpace()) { ++beg; }
}
QString getTokenName(QString &str, uint &beg)
{
skipWhitespaces(str, beg);
uint size = 0;
for (size = 0; size < str.length() - beg && !str[beg + size].isSpace() && str[beg + size] != ':'; ++size);
uint tmp = beg;
beg += size;
skipWhitespaces(str, beg);
++beg;
return QString(str.mid(tmp, size));
}
QString stringifyObj(QScriptValue obj)
{
QString str;
QScriptValueIterator current(obj);
str = "{";
if (current.hasNext()) {
current.next();
str += (current.name() + ":" + stringify(current.value()));
}
while (current.hasNext()) {
current.next();
str += "," + current.name() + ":" + stringify(current.value());
}
str += "}";
return str;
}
QString stringifyArr(QScriptValue obj)
{
QString str;
str = "[";
if (obj.property("length").toNumber() != 0) {
str += stringify(obj.property(0));
}
for (int i = 1; i < obj.property("length").toNumber(); ++i) {
QScriptValue current = obj.property(i);
str += ",";
if (!current.isUndefined()) {
str += stringify(current);
}
}
str += "]";
return str;
}
void postprocess(QScriptValue value)
{
if (value.isObject()) {
QScriptValueIterator current(value);
if (current.hasNext()) {
current.next();
postprocess(current.value());
}
}
else if (value.isArray()) {
for (int i = 1; i < value.property("length").toNumber(); ++i) {
if (!value.property(i).isValid()) {
value.setProperty(i, QScriptValue::UndefinedValue);
}
}
}
}
}
}
<|endoftext|> |
<commit_before>/*
kopeteprotocol.cpp - Kopete Protocol
Copyright (c) 2002 by Duncan Mac-Vicar Prett <duncan@kde.org>
Copyright (c) 2002 by Martijn Klingens <klingens@kde.org>
Kopete (c) 2002 by the Kopete developers <kopete-devel@kde.org>
*************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
*************************************************************************
*/
#include "kopeteprotocol.h"
#include "kopete.h"
#include "kopetemessagemanagerfactory.h"
KopeteProtocol::KopeteProtocol(QObject *parent, const char *name)
: KopetePlugin( parent, name )
{
}
KopeteProtocol::~KopeteProtocol()
{
}
bool KopeteProtocol::unload()
{
KopeteMessageManagerFactory::factory()->cleanSessions(this);
return KopetePlugin::unload();
}
QString KopeteProtocol::statusIcon() const
{
return m_statusIcon;
}
void KopeteProtocol::setStatusIcon( const QString &icon )
{
if( icon != m_statusIcon )
{
m_statusIcon = icon;
emit( statusIconChanged( this, icon ) );
}
}
KActionMenu* KopeteProtocol::protocolActions()
{
return 0L;
}
// vim: set noet ts=4 sts=4 sw=4:
<commit_msg>why this wasn't any longer in my source file, i don't know, but things compile better if it's there :)<commit_after>/*
kopeteprotocol.cpp - Kopete Protocol
Copyright (c) 2002 by Duncan Mac-Vicar Prett <duncan@kde.org>
Copyright (c) 2002 by Martijn Klingens <klingens@kde.org>
Kopete (c) 2002 by the Kopete developers <kopete-devel@kde.org>
*************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
*************************************************************************
*/
#include "kopeteprotocol.h"
#include "kopete.h"
#include "kopetemessagemanagerfactory.h"
KopeteProtocol::KopeteProtocol(QObject *parent, const char *name)
: KopetePlugin( parent, name )
{
}
KopeteProtocol::~KopeteProtocol()
{
}
bool KopeteProtocol::unload()
{
KopeteMessageManagerFactory::factory()->cleanSessions(this);
return KopetePlugin::unload();
}
QString KopeteProtocol::statusIcon() const
{
return m_statusIcon;
}
void KopeteProtocol::setStatusIcon( const QString &icon )
{
if( icon != m_statusIcon )
{
m_statusIcon = icon;
emit( statusIconChanged( this, icon ) );
}
}
KActionMenu* KopeteProtocol::protocolActions()
{
return 0L;
}
#include "kopeteprotocol.moc"
// vim: set noet ts=4 sts=4 sw=4:
<|endoftext|> |
<commit_before>
/*
* iterator_test.cpp
*
* Tests basic iterator operations
*
* by Ziqi Wang
*/
#include "test_suite.h"
/*
* ForwardIteratorTest() - Tests forward iterator functionalities
*/
void ForwardIteratorTest(TreeType *t, int key_num) {
printf("========== Forward Iteration Test ==========\n");
auto it = t->Begin();
long i = 0;
while(it.IsEnd() == false) {
assert(it->first == it->second);
assert(it->first == i);
i++;
it++;
}
assert(i == (key_num));
auto it2 = t->Begin(key_num - 1);
auto it3 = it2;
it2++;
assert(it2.IsEnd() == true);
assert(it3->first == (key_num - 1));
auto it4 = t->Begin(key_num + 1);
assert(it4.IsEnd() == true);
return;
}
/*
* BackwardIteratorTest() - Tests backward iteration
*/
void BackwardIteratorTest(TreeType *t, int key_num) {
auto it = t->Begin(key_num - 1);
auto it2 = t->Begin(key_num);
// Since they all points to the same key == (key_num - 1)
assert(it == it2);
assert(it.IsEnd() == true);
assert(it.IsBegin() == false);
// This does not test Begin()
long int key = key_num - 1;
while(it.IsBegin() == false) {
assert(it->first == it->second);
assert(it->first == key);
key--;
it--;
}
// Test for Begin()
assert(it->first == it->second);
assert(it->first == key);
return;
}
<commit_msg>Fixing assertion<commit_after>
/*
* iterator_test.cpp
*
* Tests basic iterator operations
*
* by Ziqi Wang
*/
#include "test_suite.h"
/*
* ForwardIteratorTest() - Tests forward iterator functionalities
*/
void ForwardIteratorTest(TreeType *t, int key_num) {
printf("========== Forward Iteration Test ==========\n");
auto it = t->Begin();
long i = 0;
while(it.IsEnd() == false) {
assert(it->first == it->second);
assert(it->first == i);
i++;
it++;
}
assert(i == (key_num));
auto it2 = t->Begin(key_num - 1);
auto it3 = it2;
it2++;
assert(it2.IsEnd() == true);
assert(it3->first == (key_num - 1));
auto it4 = t->Begin(key_num + 1);
assert(it4.IsEnd() == true);
return;
}
/*
* BackwardIteratorTest() - Tests backward iteration
*/
void BackwardIteratorTest(TreeType *t, int key_num) {
printf("========== Backward Iteration Test ==========\n");
auto it = t->Begin(key_num - 1);
assert(it.IsEnd() == false);
assert(it.IsBegin() == false);
// This does not test Begin()
long int key = key_num - 1;
while(it.IsBegin() == false) {
assert(it->first == it->second);
assert(it->first == key);
key--;
it--;
}
// Test for Begin()
assert(it->first == it->second);
assert(it->first == key);
return;
}
<|endoftext|> |
<commit_before>#include <audio_system.h>
#include <sound.h>
#include <stream.h>
#include <thread>
#include <chrono>
#include <iostream>
using namespace KameMix;
using std::cout;
void onSoundFinished(Sound *sound, void *udata)
{
cout << "sound finished\n";
}
void onStreamFinished(Stream *stream, void *udata)
{
cout << "stream finished\n";
}
int main(int argc, char *argv[])
{
if (!AudioSystem::init()) {
cout << "AudioSystem::init failed\n";
return 1;
}
cout << "Initialized KameMix\n";
AudioSystem::setSoundFinished(onSoundFinished, nullptr);
AudioSystem::setStreamFinished(onStreamFinished, nullptr);
//Group effect_group(0.25f);
//Listener listener(0, 0);
Sound spell1("sound/spell1_0.wav");
if (!spell1.isLoaded()) {
cout << "Couldn't load 'spell1_0.wav'\n";
}
Sound spell3("sound/spell3.wav");
if (!spell3.isLoaded()) {
cout << "Couldn't load 'spell3.wav'\n";
}
Sound cow("sound/Mudchute_cow_1.ogg");
if (!cow.isLoaded()) {
cout << "Couldn't load 'Mudchute_cow_1.ogg'\n";
}
Stream duck("sound/Mudchute_duck_2.ogg");
if (!duck.isLoaded()) {
cout << "Couldn't load 'Mudchute_duck_2.ogg'\n";
}
Sound music1("sound/dark fallout.ogg");
if (!music1.isLoaded()) {
cout << "Couldn't load 'a new beginning.ogg'\n";
}
Stream music2("sound/a new beginning.ogg");
if (!music2.isLoaded()) {
cout << "Couldn't load 'dark fallout.ogg'\n";
}
spell1.play(5);
cout << "play spell1 5 times\n";
spell3.play(5);
cout << "play spell3 5 times\n";
cow.play(5);
cout << "play cow 5 times\n";
duck.play(5);
cout << "play duck 5 times\n";
//AudioSystem::setMasterVolume(.5f);
double time_ms = 0.0;
int count = 0;
while (true) {
AudioSystem::update();
std::this_thread::sleep_for(std::chrono::milliseconds(17));
time_ms += 17;
if (time_ms > 5000 && count == 0) {
cout << "play music1\n";
time_ms = 0.0;
count++;
music1.play(0, false);
} else if (time_ms > 10000 && count == 1) {
cout << "Fadeout music1 over 10 secs\n";
time_ms = 0.0;
count++;
music1.fadeout(10.0f);
} else if (time_ms > 10000 && count == 2) {
cout << "Fadein music2 over 10 secs, and play 15 secs total\n";
time_ms = 0.0;
count++;
music2.fadein(0, 10.0f, false);
} else if (time_ms > 15000 && count == 3) {
cout << "stop music2\n";
time_ms = 0.0;
count++;
music2.stop();
} else if (count == 4) {
if (AudioSystem::numberPlaying() == 0) {
cout << "Test complete\n";
break;
}
}
}
AudioSystem::shutdown();
cout << "Shutdown KameMix\n";
return 0;
}
<commit_msg>Exit early if a sound isn't loaded<commit_after>#include <audio_system.h>
#include <sound.h>
#include <stream.h>
#include <thread>
#include <chrono>
#include <iostream>
using namespace KameMix;
using std::cout;
void onSoundFinished(Sound *sound, void *udata)
{
cout << "sound finished\n";
}
void onStreamFinished(Stream *stream, void *udata)
{
cout << "stream finished\n";
}
int main(int argc, char *argv[])
{
if (!AudioSystem::init()) {
cout << "AudioSystem::init failed\n";
return 1;
}
cout << "Initialized KameMix\n";
AudioSystem::setSoundFinished(onSoundFinished, nullptr);
AudioSystem::setStreamFinished(onStreamFinished, nullptr);
//Group effect_group(0.25f);
//Listener listener(0, 0);
Sound spell1("sound/spell1_0.wav");
if (!spell1.isLoaded()) {
cout << "Couldn't load 'spell1_0.wav'\n";
return EXIT_FAILURE;
}
Sound spell3("sound/spell3.wav");
if (!spell3.isLoaded()) {
cout << "Couldn't load 'spell3.wav'\n";
return EXIT_FAILURE;
}
Sound cow("sound/Mudchute_cow_1.ogg");
if (!cow.isLoaded()) {
cout << "Couldn't load 'Mudchute_cow_1.ogg'\n";
return EXIT_FAILURE;
}
Stream duck("sound/Mudchute_duck_2.ogg");
if (!duck.isLoaded()) {
cout << "Couldn't load 'Mudchute_duck_2.ogg'\n";
return EXIT_FAILURE;
}
Sound music1("sound/dark fallout.ogg");
if (!music1.isLoaded()) {
cout << "Couldn't load 'a new beginning.ogg'\n";
return EXIT_FAILURE;
}
Stream music2("sound/a new beginning.ogg");
if (!music2.isLoaded()) {
cout << "Couldn't load 'dark fallout.ogg'\n";
return EXIT_FAILURE;
}
spell1.play(5);
cout << "play spell1 5 times\n";
spell3.play(5);
cout << "play spell3 5 times\n";
cow.play(5);
cout << "play cow 5 times\n";
duck.play(5);
cout << "play duck 5 times\n";
double time_ms = 0.0;
int count = 0;
while (true) {
AudioSystem::update();
std::this_thread::sleep_for(std::chrono::milliseconds(17));
time_ms += 17;
if (time_ms > 5000 && count == 0) {
cout << "play music1\n";
time_ms = 0.0;
count++;
music1.play(0, false);
} else if (time_ms > 10000 && count == 1) {
cout << "Fadeout music1 over 10 secs\n";
time_ms = 0.0;
count++;
music1.fadeout(10.0f);
} else if (time_ms > 10000 && count == 2) {
cout << "Fadein music2 over 10 secs, and play 15 secs total\n";
time_ms = 0.0;
count++;
music2.fadein(0, 10.0f, false);
} else if (time_ms > 15000 && count == 3) {
cout << "stop music2\n";
time_ms = 0.0;
count++;
music2.stop();
} else if (count == 4) {
if (AudioSystem::numberPlaying() == 0) {
cout << "Test complete\n";
break;
}
}
}
AudioSystem::shutdown();
cout << "Shutdown KameMix\n";
return 0;
}
<|endoftext|> |
<commit_before><commit_msg>Fix vsm options serialization.<commit_after><|endoftext|> |
<commit_before>#include <execution_policy>
#include <iostream>
int main()
{
bulk_async(std::seq, [](std::sequential_agent& self)
{
std::cout << "self.index(): " << self.index() << std::endl;
}).wait();
std::mutex mut;
bulk_invoke(std::con(10), [&mut](std::concurrent_agent& self)
{
mut.lock();
std::cout << "self.index(): " << self.index() << " arriving at barrier" << std::endl;
mut.unlock();
self.wait();
mut.lock();
std::cout << "self.index(): " << self.index() << " departing barrier" << std::endl;
mut.unlock();
});
bulk_async(std::seq(3, std::seq(2)), [](std::sequential_group<std::sequential_agent>& self)
{
std::cout << "index: (" << self.index() << ", " << self.inner().index() << ")" << std::endl;
}).wait();
bulk_invoke(std::seq(4, std::seq(3, std::seq(2))), [](std::sequential_group<std::sequential_group<std::sequential_agent>>& self)
{
std::cout << "index: (" << self.index() << ", " << self.inner().index() << ", " << self.inner().inner().index() << ")" << std::endl;
});
bulk_invoke(std::con(2, std::seq(2, std::con(2))), [&mut](std::concurrent_group<std::sequential_group<std::concurrent_agent>>& self)
{
// the first agent in the first subgroup waits at the top-level barrier
if(self.inner().index() == 0 && self.inner().inner().index() == 0)
{
mut.lock();
std::cout << "(" << self.index() << ", " << self.inner().index() << ", " << self.inner().inner().index() << ") arriving at top-level barrier" << std::endl;
mut.unlock();
self.wait();
mut.lock();
std::cout << "(" << self.index() << ", " << self.inner().index() << ", " << self.inner().inner().index() << ") departing top-level barrier" << std::endl;
mut.unlock();
}
// every agent waits at the inner most barrier
mut.lock();
std::cout << " (" << self.index() << ", " << self.inner().index() << ", " << self.inner().inner().index() << ") arriving at bottom-level barrier" << std::endl;
mut.unlock();
self.inner().inner().wait();
mut.lock();
std::cout << " (" << self.index() << ", " << self.inner().index() << ", " << self.inner().inner().index() << ") departing bottom-level barrier" << std::endl;
mut.unlock();
});
return 0;
}
<commit_msg>Eliminate superfluous test<commit_after><|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: typemanager.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: vg $ $Date: 2007-10-15 12:45:01 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* 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
*
************************************************************************/
#ifndef _RTL_ALLOC_H_
#include <rtl/alloc.h>
#endif
#ifndef _OSL_FILE_HXX_
#include <osl/file.hxx>
#endif
#ifndef _CODEMAKER_TYPEMANAGER_HXX_
#include <codemaker/typemanager.hxx>
#endif
using namespace rtl;
TypeManager::TypeManager()
{
m_pImpl = new TypeManagerImpl();
acquire();
}
TypeManager::~TypeManager()
{
release();
}
sal_Int32 TypeManager::acquire()
{
return osl_incrementInterlockedCount(&m_pImpl->m_refCount);
}
sal_Int32 TypeManager::release()
{
sal_Int32 refCount = 0;
if (0 == (refCount = osl_decrementInterlockedCount(&m_pImpl->m_refCount)) )
{
delete m_pImpl;
}
return refCount;;
}
RegistryTypeManager::RegistryTypeManager()
{
m_pImpl = new RegistryTypeManagerImpl();
acquire();
}
RegistryTypeManager::~RegistryTypeManager()
{
release();
}
void RegistryTypeManager::acquire()
{
TypeManager::acquire();
}
void RegistryTypeManager::release()
{
if (0 == TypeManager::release())
{
if (m_pImpl->m_pMergedRegistry)
{
if (m_pImpl->m_pMergedRegistry->isValid())
{
m_pImpl->m_pMergedRegistry->destroy(OUString());
}
delete m_pImpl->m_pMergedRegistry;
}
if (m_pImpl->m_registries.size() > 0)
{
freeRegistries();
}
delete m_pImpl;
}
}
sal_Bool RegistryTypeManager::init(sal_Bool bMerged, const StringVector& regFiles)
{
m_pImpl->m_isMerged = bMerged && (regFiles.size() > 1);
if (regFiles.empty())
return sal_False;
StringVector::const_iterator iter = regFiles.begin();
Registry tmpReg;
while (iter != regFiles.end())
{
if (!tmpReg.open( convertToFileUrl(*iter), REG_READONLY))
m_pImpl->m_registries.push_back(new Registry(tmpReg));
else
{
freeRegistries();
return sal_False;
}
iter++;
}
if (m_pImpl->m_isMerged)
{
Registry *pTmpReg = new Registry;
OUString tmpName;
osl::FileBase::createTempFile(0, 0, &tmpName);
if (!pTmpReg->create(tmpName))
{
RegistryKey rootKey;
RegError ret = REG_NO_ERROR;
OUString aRoot( RTL_CONSTASCII_USTRINGPARAM("/") );
iter = regFiles.begin();
pTmpReg->openRootKey(rootKey);
while (iter != regFiles.end())
{
if ( (ret = pTmpReg->mergeKey(rootKey, aRoot, convertToFileUrl( *iter ))) )
{
if (ret != REG_MERGE_CONFLICT)
{
freeRegistries();
rootKey.closeKey();
pTmpReg->destroy( OUString() );
delete pTmpReg;
return sal_False;
}
}
iter++;
}
m_pImpl->m_pMergedRegistry = pTmpReg;
freeRegistries();
} else
{
delete pTmpReg;
freeRegistries();
return sal_False;
}
}
return sal_True;
}
TypeReader RegistryTypeManager::getTypeReader(const OString& name)
{
TypeReader reader;
RegistryKey key(searchTypeKey(name));
if (key.isValid())
{
RegValueType valueType;
sal_uInt32 valueSize;
if (!key.getValueInfo(OUString(), &valueType, &valueSize))
{
sal_uInt8* pBuffer = (sal_uInt8*)rtl_allocateMemory(valueSize);
if (!key.getValue(OUString(), pBuffer))
{
reader = TypeReader(pBuffer, valueSize, sal_True);
}
rtl_freeMemory(pBuffer);
}
}
return reader;
}
RTTypeClass RegistryTypeManager::getTypeClass(const OString& name)
{
if (m_pImpl->m_t2TypeClass.count(name) > 0)
{
return m_pImpl->m_t2TypeClass[name];
} else
{
RegistryKey key(searchTypeKey(name));
if (key.isValid())
{
RegValueType valueType;
sal_uInt32 valueSize;
if (!key.getValueInfo(OUString(), &valueType, &valueSize))
{
sal_uInt8* pBuffer = (sal_uInt8*)rtl_allocateMemory(valueSize);
if (!key.getValue(OUString(), pBuffer))
{
TypeReader reader(pBuffer, valueSize, sal_False);
RTTypeClass ret = reader.getTypeClass();
rtl_freeMemory(pBuffer);
m_pImpl->m_t2TypeClass[name] = ret;
return ret;
}
rtl_freeMemory(pBuffer);
}
}
}
return RT_TYPE_INVALID;
}
void RegistryTypeManager::setBase(const OString& base)
{
m_pImpl->m_base = base;
if (base.lastIndexOf('/') != (base.getLength() - 1))
{
m_pImpl->m_base += "/";
}
}
void RegistryTypeManager::freeRegistries()
{
RegistryList::const_iterator iter = m_pImpl->m_registries.begin();
while (iter != m_pImpl->m_registries.end())
{
delete *iter;
iter++;
}
}
RegistryKey RegistryTypeManager::searchTypeKey(const OString& name)
{
RegistryKey key, rootKey;
if (m_pImpl->m_isMerged)
{
if (!m_pImpl->m_pMergedRegistry->openRootKey(rootKey))
{
rootKey.openKey(OStringToOUString(m_pImpl->m_base + name, RTL_TEXTENCODING_UTF8), key);
}
} else
{
RegistryList::const_iterator iter = m_pImpl->m_registries.begin();
while (iter != m_pImpl->m_registries.end())
{
if (!(*iter)->openRootKey(rootKey))
{
if (!rootKey.openKey(OStringToOUString(m_pImpl->m_base + name, RTL_TEXTENCODING_UTF8), key))
break;
}
iter++;
}
}
return key;
}
<commit_msg>INTEGRATION: CWS changefileheader (1.8.8); FILE MERGED 2008/04/01 15:22:57 thb 1.8.8.3: #i85898# Stripping all external header guards 2008/04/01 12:32:33 thb 1.8.8.2: #i85898# Stripping all external header guards 2008/03/31 07:25:06 rt 1.8.8.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: typemanager.cxx,v $
* $Revision: 1.9 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org 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 version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include <rtl/alloc.h>
#include <osl/file.hxx>
#include <codemaker/typemanager.hxx>
using namespace rtl;
TypeManager::TypeManager()
{
m_pImpl = new TypeManagerImpl();
acquire();
}
TypeManager::~TypeManager()
{
release();
}
sal_Int32 TypeManager::acquire()
{
return osl_incrementInterlockedCount(&m_pImpl->m_refCount);
}
sal_Int32 TypeManager::release()
{
sal_Int32 refCount = 0;
if (0 == (refCount = osl_decrementInterlockedCount(&m_pImpl->m_refCount)) )
{
delete m_pImpl;
}
return refCount;;
}
RegistryTypeManager::RegistryTypeManager()
{
m_pImpl = new RegistryTypeManagerImpl();
acquire();
}
RegistryTypeManager::~RegistryTypeManager()
{
release();
}
void RegistryTypeManager::acquire()
{
TypeManager::acquire();
}
void RegistryTypeManager::release()
{
if (0 == TypeManager::release())
{
if (m_pImpl->m_pMergedRegistry)
{
if (m_pImpl->m_pMergedRegistry->isValid())
{
m_pImpl->m_pMergedRegistry->destroy(OUString());
}
delete m_pImpl->m_pMergedRegistry;
}
if (m_pImpl->m_registries.size() > 0)
{
freeRegistries();
}
delete m_pImpl;
}
}
sal_Bool RegistryTypeManager::init(sal_Bool bMerged, const StringVector& regFiles)
{
m_pImpl->m_isMerged = bMerged && (regFiles.size() > 1);
if (regFiles.empty())
return sal_False;
StringVector::const_iterator iter = regFiles.begin();
Registry tmpReg;
while (iter != regFiles.end())
{
if (!tmpReg.open( convertToFileUrl(*iter), REG_READONLY))
m_pImpl->m_registries.push_back(new Registry(tmpReg));
else
{
freeRegistries();
return sal_False;
}
iter++;
}
if (m_pImpl->m_isMerged)
{
Registry *pTmpReg = new Registry;
OUString tmpName;
osl::FileBase::createTempFile(0, 0, &tmpName);
if (!pTmpReg->create(tmpName))
{
RegistryKey rootKey;
RegError ret = REG_NO_ERROR;
OUString aRoot( RTL_CONSTASCII_USTRINGPARAM("/") );
iter = regFiles.begin();
pTmpReg->openRootKey(rootKey);
while (iter != regFiles.end())
{
if ( (ret = pTmpReg->mergeKey(rootKey, aRoot, convertToFileUrl( *iter ))) )
{
if (ret != REG_MERGE_CONFLICT)
{
freeRegistries();
rootKey.closeKey();
pTmpReg->destroy( OUString() );
delete pTmpReg;
return sal_False;
}
}
iter++;
}
m_pImpl->m_pMergedRegistry = pTmpReg;
freeRegistries();
} else
{
delete pTmpReg;
freeRegistries();
return sal_False;
}
}
return sal_True;
}
TypeReader RegistryTypeManager::getTypeReader(const OString& name)
{
TypeReader reader;
RegistryKey key(searchTypeKey(name));
if (key.isValid())
{
RegValueType valueType;
sal_uInt32 valueSize;
if (!key.getValueInfo(OUString(), &valueType, &valueSize))
{
sal_uInt8* pBuffer = (sal_uInt8*)rtl_allocateMemory(valueSize);
if (!key.getValue(OUString(), pBuffer))
{
reader = TypeReader(pBuffer, valueSize, sal_True);
}
rtl_freeMemory(pBuffer);
}
}
return reader;
}
RTTypeClass RegistryTypeManager::getTypeClass(const OString& name)
{
if (m_pImpl->m_t2TypeClass.count(name) > 0)
{
return m_pImpl->m_t2TypeClass[name];
} else
{
RegistryKey key(searchTypeKey(name));
if (key.isValid())
{
RegValueType valueType;
sal_uInt32 valueSize;
if (!key.getValueInfo(OUString(), &valueType, &valueSize))
{
sal_uInt8* pBuffer = (sal_uInt8*)rtl_allocateMemory(valueSize);
if (!key.getValue(OUString(), pBuffer))
{
TypeReader reader(pBuffer, valueSize, sal_False);
RTTypeClass ret = reader.getTypeClass();
rtl_freeMemory(pBuffer);
m_pImpl->m_t2TypeClass[name] = ret;
return ret;
}
rtl_freeMemory(pBuffer);
}
}
}
return RT_TYPE_INVALID;
}
void RegistryTypeManager::setBase(const OString& base)
{
m_pImpl->m_base = base;
if (base.lastIndexOf('/') != (base.getLength() - 1))
{
m_pImpl->m_base += "/";
}
}
void RegistryTypeManager::freeRegistries()
{
RegistryList::const_iterator iter = m_pImpl->m_registries.begin();
while (iter != m_pImpl->m_registries.end())
{
delete *iter;
iter++;
}
}
RegistryKey RegistryTypeManager::searchTypeKey(const OString& name)
{
RegistryKey key, rootKey;
if (m_pImpl->m_isMerged)
{
if (!m_pImpl->m_pMergedRegistry->openRootKey(rootKey))
{
rootKey.openKey(OStringToOUString(m_pImpl->m_base + name, RTL_TEXTENCODING_UTF8), key);
}
} else
{
RegistryList::const_iterator iter = m_pImpl->m_registries.begin();
while (iter != m_pImpl->m_registries.end())
{
if (!(*iter)->openRootKey(rootKey))
{
if (!rootKey.openKey(OStringToOUString(m_pImpl->m_base + name, RTL_TEXTENCODING_UTF8), key))
break;
}
iter++;
}
}
return key;
}
<|endoftext|> |
<commit_before>#ifndef UTILS_HPP
#define UTILS_HPP
#include <list>
#include <iostream>
#include "Object.hpp"
#include "ViewPort.hpp"
#define GUI_FILE "graphical_system.glade"
/* Global Variables */
static cairo_surface_t* surface = NULL;
GtkBuilder* builder;
GtkWidget* _window;
GtkWidget* _draw_area;
GtkTextView* _text_view;
GtkSpinButton* _new_obj_x;
GtkSpinButton* _new_obj_y;
ViewPort* _viewport;
std::list<Object*> _display_file;
std::vector<Coordinate> _coordinates_storage;
/**
* Prints a message on the GUI console.
*/
void print(const char* message)
{
GtkTextIter end;
auto buffer = gtk_text_view_get_buffer(_text_view);
gtk_text_buffer_get_end_iter(buffer, &end);
gtk_text_buffer_insert(buffer, &end, message, -1);
}
/* Callbacks */
extern "C" {
void close_window()
{
/* Close the interface window */
gtk_main_quit();
}
gboolean configure_event(GtkWidget* widget)
{
/* Creates a new surface */
if(surface)
cairo_surface_destroy(surface);
surface = gdk_window_create_similar_surface (
gtk_widget_get_window(widget),
CAIRO_CONTENT_COLOR,
gtk_widget_get_allocated_width(widget),
gtk_widget_get_allocated_height(widget)
);
/* Creates a cairo context over the surface */
cairo_t *cr = cairo_create(surface);
cairo_paint(cr);
cairo_destroy(cr);
/* Returning TRUE to avoide another call of the function */
return TRUE;
}
gboolean draw(GtkWidget* widget, cairo_t* cr)
{
/* Redraw a cairo context */
_viewport->draw_all_objects(cr, _display_file);
return FALSE;
}
void add_coordinate()
{
auto x = gtk_spin_button_get_value(_new_obj_x);
auto y = gtk_spin_button_get_value(_new_obj_y);
auto coord = Coordinate(x, y);
_coordinates_storage.push_back(coord);
print("Coordinate saved.\n");
}
void add_line(std::string name)
{
/* Inserts a line to the display file */
auto line = new Line(name, LINE);
line->add_coordinates(_coordinates_storage);
_display_file.push_back(line);
}
void add_polygon(std::string name)
{
/* Inserts a polygon to the display file */
auto polygon = new Polygon(name, POLYGON);
polygon->add_coordinates(_coordinates_storage);
_display_file.push_back(polygon);
}
void add_point(std::string name)
{
/* Inserts a point to the display file */
auto point = new Point(name, POINT);
point->add_coordinates(_coordinates_storage[0]);
_display_file.push_back(point);
}
void create_object_button(GtkButton* button, GtkEntry* obj_name)
{
auto name = gtk_entry_get_text(obj_name);
/* Detects the number of points and add it */
switch(_coordinates_storage.size())
{
case 0:
break;
case 1:
add_point(name);
break;
case 2:
add_line(name);
break;
default:
add_polygon(name);
break;
}
_coordinates_storage.clear();
print("Object with created and added to display file.\n");
}
}
#endif // UTILS_HPP
<commit_msg>Updating the draw when insert an object<commit_after>#ifndef UTILS_HPP
#define UTILS_HPP
#include <list>
#include <iostream>
#include "Object.hpp"
#include "ViewPort.hpp"
#define GUI_FILE "graphical_system.glade"
/* Global Variables */
static cairo_surface_t* surface = NULL;
GtkBuilder* builder;
GtkWidget* _window;
GtkWidget* _draw_area;
GtkTextView* _text_view;
GtkSpinButton* _new_obj_x;
GtkSpinButton* _new_obj_y;
ViewPort* _viewport;
std::list<Object*> _display_file;
std::vector<Coordinate> _coordinates_storage;
/**
* Prints a message on the GUI console.
*/
void print(const char* message)
{
GtkTextIter end;
auto buffer = gtk_text_view_get_buffer(_text_view);
gtk_text_buffer_get_end_iter(buffer, &end);
gtk_text_buffer_insert(buffer, &end, message, -1);
}
/* Callbacks */
extern "C" {
void close_window()
{
/* Close the interface window */
gtk_main_quit();
}
gboolean configure_event(GtkWidget* widget)
{
/* Creates a new surface */
if(surface)
cairo_surface_destroy(surface);
surface = gdk_window_create_similar_surface (
gtk_widget_get_window(widget),
CAIRO_CONTENT_COLOR,
gtk_widget_get_allocated_width(widget),
gtk_widget_get_allocated_height(widget)
);
/* Creates a cairo context over the surface */
cairo_t *cr = cairo_create(surface);
cairo_paint(cr);
cairo_destroy(cr);
/* Returning TRUE to avoide another call of the function */
return TRUE;
}
gboolean draw(GtkWidget* widget, cairo_t* cr)
{
/* Redraw a cairo context */
_viewport->draw_all_objects(cr, _display_file);
return FALSE;
}
void add_coordinate()
{
auto x = gtk_spin_button_get_value(_new_obj_x);
auto y = gtk_spin_button_get_value(_new_obj_y);
auto coord = Coordinate(x, y);
_coordinates_storage.push_back(coord);
print("Coordinate saved.\n");
}
void add_line(std::string name)
{
/* Inserts a line to the display file */
auto line = new Line(name, LINE);
line->add_coordinates(_coordinates_storage);
_display_file.push_back(line);
}
void add_polygon(std::string name)
{
/* Inserts a polygon to the display file */
auto polygon = new Polygon(name, POLYGON);
polygon->add_coordinates(_coordinates_storage);
_display_file.push_back(polygon);
}
void add_point(std::string name)
{
/* Inserts a point to the display file */
auto point = new Point(name, POINT);
point->add_coordinates(_coordinates_storage[0]);
_display_file.push_back(point);
}
void create_object_button(GtkButton* button, GtkEntry* obj_name)
{
auto name = gtk_entry_get_text(obj_name);
/* Detects the number of points and add it */
switch(_coordinates_storage.size())
{
case 0:
break;
case 1:
add_point(name);
break;
case 2:
add_line(name);
break;
default:
add_polygon(name);
break;
}
/* Invalidates the actual draw to update the draw area */
gtk_widget_queue_draw(_draw_area);
_coordinates_storage.clear();
print("Object with created and added to display file.\n");
}
}
#endif // UTILS_HPP
<|endoftext|> |
<commit_before>// Copyright (c) 2010 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/autofill/autofill_download.h"
#include <algorithm>
#include <vector>
#include "base/logging.h"
#include "base/rand_util.h"
#include "base/stl_util-inl.h"
#include "chrome/browser/autofill/autofill_metrics.h"
#include "chrome/browser/autofill/autofill_xml_parser.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/pref_names.h"
#include "net/http/http_response_headers.h"
#define DISABLED_REQUEST_URL "http://disabled"
#if defined(GOOGLE_CHROME_BUILD)
#include "chrome/browser/autofill/internal/autofill_download_internal.h"
#else
#define AUTO_FILL_QUERY_SERVER_REQUEST_URL DISABLED_REQUEST_URL
#define AUTO_FILL_UPLOAD_SERVER_REQUEST_URL DISABLED_REQUEST_URL
#define AUTO_FILL_QUERY_SERVER_NAME_START_IN_HEADER "SOMESERVER/"
#endif
namespace {
const size_t kMaxFormCacheSize = 16;
};
struct AutoFillDownloadManager::FormRequestData {
std::vector<std::string> form_signatures;
AutoFillRequestType request_type;
};
AutoFillDownloadManager::AutoFillDownloadManager(Profile* profile)
: profile_(profile),
observer_(NULL),
max_form_cache_size_(kMaxFormCacheSize),
next_query_request_(base::Time::Now()),
next_upload_request_(base::Time::Now()),
positive_upload_rate_(0),
negative_upload_rate_(0),
fetcher_id_for_unittest_(0),
is_testing_(false) {
// |profile_| could be NULL in some unit-tests.
if (profile_) {
PrefService* preferences = profile_->GetPrefs();
positive_upload_rate_ =
preferences->GetReal(prefs::kAutoFillPositiveUploadRate);
negative_upload_rate_ =
preferences->GetReal(prefs::kAutoFillNegativeUploadRate);
}
}
AutoFillDownloadManager::~AutoFillDownloadManager() {
STLDeleteContainerPairFirstPointers(url_fetchers_.begin(),
url_fetchers_.end());
}
void AutoFillDownloadManager::SetObserver(
AutoFillDownloadManager::Observer *observer) {
if (observer) {
DCHECK(!observer_);
observer_ = observer;
} else {
observer_ = NULL;
}
}
bool AutoFillDownloadManager::StartQueryRequest(
const ScopedVector<FormStructure>& forms,
const AutoFillMetrics& metric_logger) {
if (next_query_request_ > base::Time::Now()) {
// We are in back-off mode: do not do the request.
return false;
}
std::string form_xml;
FormRequestData request_data;
if (!FormStructure::EncodeQueryRequest(forms, &request_data.form_signatures,
&form_xml)) {
return false;
}
request_data.request_type = AutoFillDownloadManager::REQUEST_QUERY;
metric_logger.Log(AutoFillMetrics::QUERY_SENT);
std::string query_data;
if (CheckCacheForQueryRequest(request_data.form_signatures, &query_data)) {
VLOG(1) << "AutoFillDownloadManager: query request has been retrieved from"
<< "the cache";
if (observer_)
observer_->OnLoadedAutoFillHeuristics(query_data);
return true;
}
return StartRequest(form_xml, request_data);
}
bool AutoFillDownloadManager::StartUploadRequest(
const FormStructure& form, bool form_was_matched) {
if (next_upload_request_ > base::Time::Now()) {
// We are in back-off mode: do not do the request.
return false;
}
// Check if we need to upload form.
double upload_rate = form_was_matched ? GetPositiveUploadRate() :
GetNegativeUploadRate();
if (base::RandDouble() > upload_rate) {
VLOG(1) << "AutoFillDownloadManager: Upload request is ignored";
// If we ever need notification that upload was skipped, add it here.
return false;
}
std::string form_xml;
if (!form.EncodeUploadRequest(form_was_matched, &form_xml))
return false;
FormRequestData request_data;
request_data.form_signatures.push_back(form.FormSignature());
request_data.request_type = AutoFillDownloadManager::REQUEST_UPLOAD;
return StartRequest(form_xml, request_data);
}
bool AutoFillDownloadManager::CancelRequest(
const std::string& form_signature,
AutoFillDownloadManager::AutoFillRequestType request_type) {
for (std::map<URLFetcher *, FormRequestData>::iterator it =
url_fetchers_.begin();
it != url_fetchers_.end();
++it) {
if (std::find(it->second.form_signatures.begin(),
it->second.form_signatures.end(), form_signature) !=
it->second.form_signatures.end() &&
it->second.request_type == request_type) {
delete it->first;
url_fetchers_.erase(it);
return true;
}
}
return false;
}
double AutoFillDownloadManager::GetPositiveUploadRate() const {
return positive_upload_rate_;
}
double AutoFillDownloadManager::GetNegativeUploadRate() const {
return negative_upload_rate_;
}
void AutoFillDownloadManager::SetPositiveUploadRate(double rate) {
if (rate == positive_upload_rate_)
return;
positive_upload_rate_ = rate;
DCHECK_GE(rate, 0.0);
DCHECK_LE(rate, 1.0);
DCHECK(profile_);
PrefService* preferences = profile_->GetPrefs();
preferences->SetReal(prefs::kAutoFillPositiveUploadRate, rate);
}
void AutoFillDownloadManager::SetNegativeUploadRate(double rate) {
if (rate == negative_upload_rate_)
return;
negative_upload_rate_ = rate;
DCHECK_GE(rate, 0.0);
DCHECK_LE(rate, 1.0);
DCHECK(profile_);
PrefService* preferences = profile_->GetPrefs();
preferences->SetReal(prefs::kAutoFillNegativeUploadRate, rate);
}
bool AutoFillDownloadManager::StartRequest(
const std::string& form_xml,
const FormRequestData& request_data) {
std::string request_url;
if (request_data.request_type == AutoFillDownloadManager::REQUEST_QUERY)
request_url = AUTO_FILL_QUERY_SERVER_REQUEST_URL;
else
request_url = AUTO_FILL_UPLOAD_SERVER_REQUEST_URL;
if (!request_url.compare(DISABLED_REQUEST_URL) && !is_testing_) {
// We have it disabled - return true as if it succeeded, but do nothing.
return true;
}
// Id is ignored for regular chrome, in unit test id's for fake fetcher
// factory will be 0, 1, 2, ...
URLFetcher *fetcher = URLFetcher::Create(fetcher_id_for_unittest_++,
GURL(request_url),
URLFetcher::POST,
this);
url_fetchers_[fetcher] = request_data;
fetcher->set_automatically_retry_on_5xx(false);
fetcher->set_request_context(Profile::GetDefaultRequestContext());
fetcher->set_upload_data("text/plain", form_xml);
fetcher->Start();
return true;
}
void AutoFillDownloadManager::CacheQueryRequest(
const std::vector<std::string>& forms_in_query,
const std::string& query_data) {
std::string signature = GetCombinedSignature(forms_in_query);
for (QueryRequestCache::iterator it = cached_forms_.begin();
it != cached_forms_.end(); ++it) {
if (it->first == signature) {
// We hit the cache, move to the first position and return.
std::pair<std::string, std::string> data = *it;
cached_forms_.erase(it);
cached_forms_.push_front(data);
return;
}
}
std::pair<std::string, std::string> data;
data.first = signature;
data.second = query_data;
cached_forms_.push_front(data);
while (cached_forms_.size() > max_form_cache_size_)
cached_forms_.pop_back();
}
bool AutoFillDownloadManager::CheckCacheForQueryRequest(
const std::vector<std::string>& forms_in_query,
std::string* query_data) const {
std::string signature = GetCombinedSignature(forms_in_query);
for (QueryRequestCache::const_iterator it = cached_forms_.begin();
it != cached_forms_.end(); ++it) {
if (it->first == signature) {
// We hit the cache, fill the data and return.
*query_data = it->second;
return true;
}
}
return false;
}
std::string AutoFillDownloadManager::GetCombinedSignature(
const std::vector<std::string>& forms_in_query) const {
size_t total_size = forms_in_query.size();
for (size_t i = 0; i < forms_in_query.size(); ++i)
total_size += forms_in_query[i].length();
std::string signature;
signature.reserve(total_size);
for (size_t i = 0; i < forms_in_query.size(); ++i) {
if (i)
signature.append(",");
signature.append(forms_in_query[i]);
}
return signature;
}
void AutoFillDownloadManager::OnURLFetchComplete(
const URLFetcher* source,
const GURL& url,
const net::URLRequestStatus& status,
int response_code,
const ResponseCookies& cookies,
const std::string& data) {
std::map<URLFetcher *, FormRequestData>::iterator it =
url_fetchers_.find(const_cast<URLFetcher*>(source));
if (it == url_fetchers_.end()) {
// Looks like crash on Mac is possibly caused with callback entering here
// with unknown fetcher when network is refreshed.
return;
}
std::string type_of_request(
it->second.request_type == AutoFillDownloadManager::REQUEST_QUERY ?
"query" : "upload");
const int kHttpResponseOk = 200;
const int kHttpInternalServerError = 500;
const int kHttpBadGateway = 502;
const int kHttpServiceUnavailable = 503;
CHECK(it->second.form_signatures.size());
if (response_code != kHttpResponseOk) {
bool back_off = false;
std::string server_header;
switch (response_code) {
case kHttpBadGateway:
if (!source->response_headers()->EnumerateHeader(NULL, "server",
&server_header) ||
StartsWithASCII(server_header.c_str(),
AUTO_FILL_QUERY_SERVER_NAME_START_IN_HEADER,
false) != 0)
break;
// Bad getaway was received from AutoFill servers. Fall through to back
// off.
case kHttpInternalServerError:
case kHttpServiceUnavailable:
back_off = true;
break;
}
if (back_off) {
base::Time back_off_time(base::Time::Now() + source->backoff_delay());
if (it->second.request_type == AutoFillDownloadManager::REQUEST_QUERY) {
next_query_request_ = back_off_time;
} else {
next_upload_request_ = back_off_time;
}
}
LOG(WARNING) << "AutoFillDownloadManager: " << type_of_request
<< " request has failed with response " << response_code;
if (observer_) {
observer_->OnHeuristicsRequestError(it->second.form_signatures[0],
it->second.request_type,
response_code);
}
} else {
VLOG(1) << "AutoFillDownloadManager: " << type_of_request
<< " request has succeeded";
if (it->second.request_type == AutoFillDownloadManager::REQUEST_QUERY) {
CacheQueryRequest(it->second.form_signatures, data);
if (observer_)
observer_->OnLoadedAutoFillHeuristics(data);
} else {
double new_positive_upload_rate = 0;
double new_negative_upload_rate = 0;
AutoFillUploadXmlParser parse_handler(&new_positive_upload_rate,
&new_negative_upload_rate);
buzz::XmlParser parser(&parse_handler);
parser.Parse(data.data(), data.length(), true);
if (parse_handler.succeeded()) {
SetPositiveUploadRate(new_positive_upload_rate);
SetNegativeUploadRate(new_negative_upload_rate);
}
if (observer_)
observer_->OnUploadedAutoFillHeuristics(it->second.form_signatures[0]);
}
}
delete it->first;
url_fetchers_.erase(it);
}
<commit_msg>Inline internal autofill header.<commit_after>// Copyright (c) 2010 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/autofill/autofill_download.h"
#include <algorithm>
#include <vector>
#include "base/logging.h"
#include "base/rand_util.h"
#include "base/stl_util-inl.h"
#include "chrome/browser/autofill/autofill_metrics.h"
#include "chrome/browser/autofill/autofill_xml_parser.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/pref_names.h"
#include "net/http/http_response_headers.h"
#define DISABLED_REQUEST_URL "http://disabled"
#if defined(GOOGLE_CHROME_BUILD)
#define AUTO_FILL_QUERY_SERVER_REQUEST_URL \
"http://toolbarqueries.clients.google.com:80/tbproxy/af/query"
#define AUTO_FILL_UPLOAD_SERVER_REQUEST_URL \
"http://toolbarqueries.clients.google.com:80/tbproxy/af/upload"
#define AUTO_FILL_QUERY_SERVER_NAME_START_IN_HEADER "GFE/"
#else
#define AUTO_FILL_QUERY_SERVER_REQUEST_URL DISABLED_REQUEST_URL
#define AUTO_FILL_UPLOAD_SERVER_REQUEST_URL DISABLED_REQUEST_URL
#define AUTO_FILL_QUERY_SERVER_NAME_START_IN_HEADER "SOMESERVER/"
#endif
namespace {
const size_t kMaxFormCacheSize = 16;
};
struct AutoFillDownloadManager::FormRequestData {
std::vector<std::string> form_signatures;
AutoFillRequestType request_type;
};
AutoFillDownloadManager::AutoFillDownloadManager(Profile* profile)
: profile_(profile),
observer_(NULL),
max_form_cache_size_(kMaxFormCacheSize),
next_query_request_(base::Time::Now()),
next_upload_request_(base::Time::Now()),
positive_upload_rate_(0),
negative_upload_rate_(0),
fetcher_id_for_unittest_(0),
is_testing_(false) {
// |profile_| could be NULL in some unit-tests.
if (profile_) {
PrefService* preferences = profile_->GetPrefs();
positive_upload_rate_ =
preferences->GetReal(prefs::kAutoFillPositiveUploadRate);
negative_upload_rate_ =
preferences->GetReal(prefs::kAutoFillNegativeUploadRate);
}
}
AutoFillDownloadManager::~AutoFillDownloadManager() {
STLDeleteContainerPairFirstPointers(url_fetchers_.begin(),
url_fetchers_.end());
}
void AutoFillDownloadManager::SetObserver(
AutoFillDownloadManager::Observer *observer) {
if (observer) {
DCHECK(!observer_);
observer_ = observer;
} else {
observer_ = NULL;
}
}
bool AutoFillDownloadManager::StartQueryRequest(
const ScopedVector<FormStructure>& forms,
const AutoFillMetrics& metric_logger) {
if (next_query_request_ > base::Time::Now()) {
// We are in back-off mode: do not do the request.
return false;
}
std::string form_xml;
FormRequestData request_data;
if (!FormStructure::EncodeQueryRequest(forms, &request_data.form_signatures,
&form_xml)) {
return false;
}
request_data.request_type = AutoFillDownloadManager::REQUEST_QUERY;
metric_logger.Log(AutoFillMetrics::QUERY_SENT);
std::string query_data;
if (CheckCacheForQueryRequest(request_data.form_signatures, &query_data)) {
VLOG(1) << "AutoFillDownloadManager: query request has been retrieved from"
<< "the cache";
if (observer_)
observer_->OnLoadedAutoFillHeuristics(query_data);
return true;
}
return StartRequest(form_xml, request_data);
}
bool AutoFillDownloadManager::StartUploadRequest(
const FormStructure& form, bool form_was_matched) {
if (next_upload_request_ > base::Time::Now()) {
// We are in back-off mode: do not do the request.
return false;
}
// Check if we need to upload form.
double upload_rate = form_was_matched ? GetPositiveUploadRate() :
GetNegativeUploadRate();
if (base::RandDouble() > upload_rate) {
VLOG(1) << "AutoFillDownloadManager: Upload request is ignored";
// If we ever need notification that upload was skipped, add it here.
return false;
}
std::string form_xml;
if (!form.EncodeUploadRequest(form_was_matched, &form_xml))
return false;
FormRequestData request_data;
request_data.form_signatures.push_back(form.FormSignature());
request_data.request_type = AutoFillDownloadManager::REQUEST_UPLOAD;
return StartRequest(form_xml, request_data);
}
bool AutoFillDownloadManager::CancelRequest(
const std::string& form_signature,
AutoFillDownloadManager::AutoFillRequestType request_type) {
for (std::map<URLFetcher *, FormRequestData>::iterator it =
url_fetchers_.begin();
it != url_fetchers_.end();
++it) {
if (std::find(it->second.form_signatures.begin(),
it->second.form_signatures.end(), form_signature) !=
it->second.form_signatures.end() &&
it->second.request_type == request_type) {
delete it->first;
url_fetchers_.erase(it);
return true;
}
}
return false;
}
double AutoFillDownloadManager::GetPositiveUploadRate() const {
return positive_upload_rate_;
}
double AutoFillDownloadManager::GetNegativeUploadRate() const {
return negative_upload_rate_;
}
void AutoFillDownloadManager::SetPositiveUploadRate(double rate) {
if (rate == positive_upload_rate_)
return;
positive_upload_rate_ = rate;
DCHECK_GE(rate, 0.0);
DCHECK_LE(rate, 1.0);
DCHECK(profile_);
PrefService* preferences = profile_->GetPrefs();
preferences->SetReal(prefs::kAutoFillPositiveUploadRate, rate);
}
void AutoFillDownloadManager::SetNegativeUploadRate(double rate) {
if (rate == negative_upload_rate_)
return;
negative_upload_rate_ = rate;
DCHECK_GE(rate, 0.0);
DCHECK_LE(rate, 1.0);
DCHECK(profile_);
PrefService* preferences = profile_->GetPrefs();
preferences->SetReal(prefs::kAutoFillNegativeUploadRate, rate);
}
bool AutoFillDownloadManager::StartRequest(
const std::string& form_xml,
const FormRequestData& request_data) {
std::string request_url;
if (request_data.request_type == AutoFillDownloadManager::REQUEST_QUERY)
request_url = AUTO_FILL_QUERY_SERVER_REQUEST_URL;
else
request_url = AUTO_FILL_UPLOAD_SERVER_REQUEST_URL;
if (!request_url.compare(DISABLED_REQUEST_URL) && !is_testing_) {
// We have it disabled - return true as if it succeeded, but do nothing.
return true;
}
// Id is ignored for regular chrome, in unit test id's for fake fetcher
// factory will be 0, 1, 2, ...
URLFetcher *fetcher = URLFetcher::Create(fetcher_id_for_unittest_++,
GURL(request_url),
URLFetcher::POST,
this);
url_fetchers_[fetcher] = request_data;
fetcher->set_automatically_retry_on_5xx(false);
fetcher->set_request_context(Profile::GetDefaultRequestContext());
fetcher->set_upload_data("text/plain", form_xml);
fetcher->Start();
return true;
}
void AutoFillDownloadManager::CacheQueryRequest(
const std::vector<std::string>& forms_in_query,
const std::string& query_data) {
std::string signature = GetCombinedSignature(forms_in_query);
for (QueryRequestCache::iterator it = cached_forms_.begin();
it != cached_forms_.end(); ++it) {
if (it->first == signature) {
// We hit the cache, move to the first position and return.
std::pair<std::string, std::string> data = *it;
cached_forms_.erase(it);
cached_forms_.push_front(data);
return;
}
}
std::pair<std::string, std::string> data;
data.first = signature;
data.second = query_data;
cached_forms_.push_front(data);
while (cached_forms_.size() > max_form_cache_size_)
cached_forms_.pop_back();
}
bool AutoFillDownloadManager::CheckCacheForQueryRequest(
const std::vector<std::string>& forms_in_query,
std::string* query_data) const {
std::string signature = GetCombinedSignature(forms_in_query);
for (QueryRequestCache::const_iterator it = cached_forms_.begin();
it != cached_forms_.end(); ++it) {
if (it->first == signature) {
// We hit the cache, fill the data and return.
*query_data = it->second;
return true;
}
}
return false;
}
std::string AutoFillDownloadManager::GetCombinedSignature(
const std::vector<std::string>& forms_in_query) const {
size_t total_size = forms_in_query.size();
for (size_t i = 0; i < forms_in_query.size(); ++i)
total_size += forms_in_query[i].length();
std::string signature;
signature.reserve(total_size);
for (size_t i = 0; i < forms_in_query.size(); ++i) {
if (i)
signature.append(",");
signature.append(forms_in_query[i]);
}
return signature;
}
void AutoFillDownloadManager::OnURLFetchComplete(
const URLFetcher* source,
const GURL& url,
const net::URLRequestStatus& status,
int response_code,
const ResponseCookies& cookies,
const std::string& data) {
std::map<URLFetcher *, FormRequestData>::iterator it =
url_fetchers_.find(const_cast<URLFetcher*>(source));
if (it == url_fetchers_.end()) {
// Looks like crash on Mac is possibly caused with callback entering here
// with unknown fetcher when network is refreshed.
return;
}
std::string type_of_request(
it->second.request_type == AutoFillDownloadManager::REQUEST_QUERY ?
"query" : "upload");
const int kHttpResponseOk = 200;
const int kHttpInternalServerError = 500;
const int kHttpBadGateway = 502;
const int kHttpServiceUnavailable = 503;
CHECK(it->second.form_signatures.size());
if (response_code != kHttpResponseOk) {
bool back_off = false;
std::string server_header;
switch (response_code) {
case kHttpBadGateway:
if (!source->response_headers()->EnumerateHeader(NULL, "server",
&server_header) ||
StartsWithASCII(server_header.c_str(),
AUTO_FILL_QUERY_SERVER_NAME_START_IN_HEADER,
false) != 0)
break;
// Bad getaway was received from AutoFill servers. Fall through to back
// off.
case kHttpInternalServerError:
case kHttpServiceUnavailable:
back_off = true;
break;
}
if (back_off) {
base::Time back_off_time(base::Time::Now() + source->backoff_delay());
if (it->second.request_type == AutoFillDownloadManager::REQUEST_QUERY) {
next_query_request_ = back_off_time;
} else {
next_upload_request_ = back_off_time;
}
}
LOG(WARNING) << "AutoFillDownloadManager: " << type_of_request
<< " request has failed with response " << response_code;
if (observer_) {
observer_->OnHeuristicsRequestError(it->second.form_signatures[0],
it->second.request_type,
response_code);
}
} else {
VLOG(1) << "AutoFillDownloadManager: " << type_of_request
<< " request has succeeded";
if (it->second.request_type == AutoFillDownloadManager::REQUEST_QUERY) {
CacheQueryRequest(it->second.form_signatures, data);
if (observer_)
observer_->OnLoadedAutoFillHeuristics(data);
} else {
double new_positive_upload_rate = 0;
double new_negative_upload_rate = 0;
AutoFillUploadXmlParser parse_handler(&new_positive_upload_rate,
&new_negative_upload_rate);
buzz::XmlParser parser(&parse_handler);
parser.Parse(data.data(), data.length(), true);
if (parse_handler.succeeded()) {
SetPositiveUploadRate(new_positive_upload_rate);
SetNegativeUploadRate(new_negative_upload_rate);
}
if (observer_)
observer_->OnUploadedAutoFillHeuristics(it->second.form_signatures[0]);
}
}
delete it->first;
url_fetchers_.erase(it);
}
<|endoftext|> |
<commit_before>/**
* @file sa_impl.hpp
* @auther Zhihao Lou
*
* The implementation of the SA optimizer.
*/
#ifndef __MLPACK_CORE_OPTIMIZERS_SA_SA_IMPL_HPP
#define __MLPACK_CORE_OPTIMIZERS_SA_SA_IMPL_HPP
#include <mlpack/core/dists/laplace_distribution.hpp>
namespace mlpack {
namespace optimization {
template<
typename FunctionType,
typename CoolingScheduleType
>
SA<FunctionType, CoolingScheduleType>::SA(
FunctionType& function,
CoolingScheduleType& coolingSchedule,
const size_t maxIterations,
const double initT,
const size_t initMoves,
const size_t moveCtrlSweep,
const double tolerance,
const size_t maxToleranceSweep,
const double maxMoveCoef,
const double initMoveCoef,
const double gain) :
function(function),
coolingSchedule(coolingSchedule),
maxIterations(maxIterations),
temperature(initT),
initMoves(initMoves),
moveCtrlSweep(moveCtrlSweep),
tolerance(tolerance),
maxToleranceSweep(maxToleranceSweep),
gain(gain)
{
const size_t rows = function.GetInitialPoint().n_rows;
const size_t cols = function.GetInitialPoint().n_cols;
maxMove.set_size(rows, cols);
maxMove.fill(maxMoveCoef);
moveSize.set_size(rows, cols);
moveSize.fill(initMoveCoef);
}
//! Optimize the function (minimize).
template<
typename FunctionType,
typename CoolingScheduleType
>
double SA<FunctionType, CoolingScheduleType>::Optimize(arma::mat &iterate)
{
const size_t rows = function.GetInitialPoint().n_rows;
const size_t cols = function.GetInitialPoint().n_cols;
size_t frozenCount = 0;
double energy = function.Evaluate(iterate);
size_t oldEnergy = energy;
math::RandomSeed(std::time(NULL));
size_t idx = 0;
size_t sweepCounter = 0;
arma::mat accept(rows, cols);
accept.zeros();
// Initial moves to get rid of dependency of initial states.
for (size_t i = 0; i < initMoves; ++i)
GenerateMove(iterate, accept, energy, idx, sweepCounter);
// Iterating and cooling.
for (size_t i = 0; i != maxIterations; ++i)
{
oldEnergy = energy;
GenerateMove(iterate, accept, energy, idx, sweepCounter);
temperature = coolingSchedule.NextTemperature(temperature, energy);
// Determine if the optimization has entered (or continues to be in) a
// frozen state.
if (std::abs(energy - oldEnergy) < tolerance)
++frozenCount;
else
frozenCount = 0;
// Terminate, if possible.
if (frozenCount >= maxToleranceSweep * iterate.n_elem)
{
Log::Debug << "SA: minimized within tolerance " << tolerance << " for "
<< maxToleranceSweep << " sweeps after " << i << " iterations; "
<< "terminating optimization." << std::endl;
return energy;
}
}
Log::Debug << "SA: maximum iterations (" << maxIterations << ") reached; "
<< "terminating optimization." << std::endl;
return energy;
}
/**
* GenerateMove proposes a move on element iterate(idx), and determines
* it that move is acceptable or not according to the Metropolis criterion.
* After that it increments idx so next call will make a move on next
* parameters. When all elements of the state has been moved (a sweep), it
* resets idx and increments sweepCounter. When sweepCounter reaches
* moveCtrlSweep, it performs moveControl and resets sweepCounter.
*/
template<
typename FunctionType,
typename CoolingScheduleType
>
void SA<FunctionType, CoolingScheduleType>::GenerateMove(
arma::mat& iterate,
arma::mat& accept,
double& energy,
size_t& idx,
size_t& sweepCounter)
{
const double prevEnergy = energy;
const double prevValue = iterate(idx);
// It is possible to use a non-Laplace distribution here, but it is difficult
// because the acceptance ratio should be as close to 0.44 as possible, and
// MoveControl() is derived for the Laplace distribution.
// Sample from a Laplace distribution with scale parameter moveSize(idx).
const double unif = 2.0 * math::Random() - 1.0;
const double move = (unif < 0) ? (moveSize(idx) * std::log(1 + unif)) :
(-moveSize(idx) * std::log(1 - unif));
iterate(idx) += move;
energy = function.Evaluate(iterate);
// According to the Metropolis criterion, accept the move with probability
// min{1, exp(-(E_new - E_old) / T)}.
const double xi = math::Random();
const double delta = energy - prevEnergy;
const double criterion = std::exp(-delta / temperature);
if (delta <= 0. || criterion > xi)
{
accept(idx) += 1.;
}
else // Reject the move; restore previous state.
{
iterate(idx) = prevValue;
energy = prevEnergy;
}
++idx;
if (idx == iterate.n_elem) // Finished with a sweep.
{
idx = 0;
++sweepCounter;
}
if (sweepCounter == moveCtrlSweep) // Do MoveControl().
{
MoveControl(moveCtrlSweep, accept);
sweepCounter = 0;
}
}
/**
* MoveControl() uses a proportional feedback control to determine the size
* parameter to pass to the move generation distribution. The target of such
* move control is to make the acceptance ratio, accept/nMoves, be as close to
* 0.44 as possible. Generally speaking, the larger the move size is, the larger
* the function value change of the move will be, and less likely such move will
* be accepted by the Metropolis criterion. Thus, the move size is controlled by
*
* log(moveSize) = log(moveSize) + gain * (accept/nMoves - target)
*
* For more theory and the mysterious 0.44 value, see Jimmy K.-C. Lam and
* Jean-Marc Delosme. `An efficient simulated annealing schedule: derivation'.
* Technical Report 8816, Yale University, 1988.
*/
template<
typename FunctionType,
typename CoolingScheduleType
>
void SA<FunctionType, CoolingScheduleType>::MoveControl(const size_t nMoves,
arma::mat& accept)
{
arma::mat target;
target.copy_size(accept);
target.fill(0.44);
moveSize = arma::log(moveSize);
moveSize += gain * (accept / (double) nMoves - target);
moveSize = arma::exp(moveSize);
// To avoid the use of element-wise arma::min(), which is only available in
// Armadillo after v3.930, we use a for loop here instead.
for (size_t i = 0; i < accept.n_elem; ++i)
moveSize(i) = (moveSize(i) > maxMove(i)) ? maxMove(i) : moveSize(i);
accept.zeros();
}
template<
typename FunctionType,
typename CoolingScheduleType
>
std::string SA<FunctionType, CoolingScheduleType>::
ToString() const
{
std::ostringstream convert;
convert << "SA [" << this << "]" << std::endl;
convert << " Function:" << std::endl;
convert << util::Indent(function.ToString(), 2);
convert << " Cooling Schedule:" << std::endl;
convert << util::Indent(coolingSchedule.ToString(), 2);
convert << " Temperature: " << temperature << std::endl;
convert << " Initial moves: " << initMoves << std::endl;
convert << " Sweeps per move control: " << moveCtrlSweep << std::endl;
convert << " Tolerance: " << tolerance << std::endl;
convert << " Maximum sweeps below tolerance: " << maxToleranceSweep
<< std::endl;
convert << " Move control gain: " << gain << std::endl;
convert << " Maximum iterations: " << maxIterations << std::endl;
return convert.str();
}
}; // namespace optimization
}; // namespace mlpack
#endif
<commit_msg>Patch from Zhihao: sa_update.diff.<commit_after>/**
* @file sa_impl.hpp
* @auther Zhihao Lou
*
* The implementation of the SA optimizer.
*/
#ifndef __MLPACK_CORE_OPTIMIZERS_SA_SA_IMPL_HPP
#define __MLPACK_CORE_OPTIMIZERS_SA_SA_IMPL_HPP
#include <mlpack/core/dists/laplace_distribution.hpp>
namespace mlpack {
namespace optimization {
template<
typename FunctionType,
typename CoolingScheduleType
>
SA<FunctionType, CoolingScheduleType>::SA(
FunctionType& function,
CoolingScheduleType& coolingSchedule,
const size_t maxIterations,
const double initT,
const size_t initMoves,
const size_t moveCtrlSweep,
const double tolerance,
const size_t maxToleranceSweep,
const double maxMoveCoef,
const double initMoveCoef,
const double gain) :
function(function),
coolingSchedule(coolingSchedule),
maxIterations(maxIterations),
temperature(initT),
initMoves(initMoves),
moveCtrlSweep(moveCtrlSweep),
tolerance(tolerance),
maxToleranceSweep(maxToleranceSweep),
gain(gain)
{
const size_t rows = function.GetInitialPoint().n_rows;
const size_t cols = function.GetInitialPoint().n_cols;
maxMove.set_size(rows, cols);
maxMove.fill(maxMoveCoef);
moveSize.set_size(rows, cols);
moveSize.fill(initMoveCoef);
}
//! Optimize the function (minimize).
template<
typename FunctionType,
typename CoolingScheduleType
>
double SA<FunctionType, CoolingScheduleType>::Optimize(arma::mat &iterate)
{
const size_t rows = function.GetInitialPoint().n_rows;
const size_t cols = function.GetInitialPoint().n_cols;
size_t frozenCount = 0;
double energy = function.Evaluate(iterate);
double oldEnergy = energy;
math::RandomSeed(std::time(NULL));
size_t idx = 0;
size_t sweepCounter = 0;
arma::mat accept(rows, cols);
accept.zeros();
// Initial moves to get rid of dependency of initial states.
for (size_t i = 0; i < initMoves; ++i)
GenerateMove(iterate, accept, energy, idx, sweepCounter);
// Iterating and cooling.
for (size_t i = 0; i != maxIterations; ++i)
{
oldEnergy = energy;
GenerateMove(iterate, accept, energy, idx, sweepCounter);
temperature = coolingSchedule.NextTemperature(temperature, energy);
// Determine if the optimization has entered (or continues to be in) a
// frozen state.
if (std::abs(energy - oldEnergy) < tolerance)
++frozenCount;
else
frozenCount = 0;
// Terminate, if possible.
if (frozenCount >= maxToleranceSweep * moveCtrlSweep * iterate.n_elem)
{
Log::Debug << "SA: minimized within tolerance " << tolerance << " for "
<< maxToleranceSweep << " sweeps after " << i << " iterations; "
<< "terminating optimization." << std::endl;
return energy;
}
}
Log::Debug << "SA: maximum iterations (" << maxIterations << ") reached; "
<< "terminating optimization." << std::endl;
return energy;
}
/**
* GenerateMove proposes a move on element iterate(idx), and determines
* it that move is acceptable or not according to the Metropolis criterion.
* After that it increments idx so next call will make a move on next
* parameters. When all elements of the state has been moved (a sweep), it
* resets idx and increments sweepCounter. When sweepCounter reaches
* moveCtrlSweep, it performs moveControl and resets sweepCounter.
*/
template<
typename FunctionType,
typename CoolingScheduleType
>
void SA<FunctionType, CoolingScheduleType>::GenerateMove(
arma::mat& iterate,
arma::mat& accept,
double& energy,
size_t& idx,
size_t& sweepCounter)
{
const double prevEnergy = energy;
const double prevValue = iterate(idx);
// It is possible to use a non-Laplace distribution here, but it is difficult
// because the acceptance ratio should be as close to 0.44 as possible, and
// MoveControl() is derived for the Laplace distribution.
// Sample from a Laplace distribution with scale parameter moveSize(idx).
const double unif = 2.0 * math::Random() - 1.0;
const double move = (unif < 0) ? (moveSize(idx) * std::log(1 + unif)) :
(-moveSize(idx) * std::log(1 - unif));
iterate(idx) += move;
energy = function.Evaluate(iterate);
// According to the Metropolis criterion, accept the move with probability
// min{1, exp(-(E_new - E_old) / T)}.
const double xi = math::Random();
const double delta = energy - prevEnergy;
const double criterion = std::exp(-delta / temperature);
if (delta <= 0. || criterion > xi)
{
accept(idx) += 1.;
}
else // Reject the move; restore previous state.
{
iterate(idx) = prevValue;
energy = prevEnergy;
}
++idx;
if (idx == iterate.n_elem) // Finished with a sweep.
{
idx = 0;
++sweepCounter;
}
if (sweepCounter == moveCtrlSweep) // Do MoveControl().
{
MoveControl(moveCtrlSweep, accept);
sweepCounter = 0;
}
}
/**
* MoveControl() uses a proportional feedback control to determine the size
* parameter to pass to the move generation distribution. The target of such
* move control is to make the acceptance ratio, accept/nMoves, be as close to
* 0.44 as possible. Generally speaking, the larger the move size is, the larger
* the function value change of the move will be, and less likely such move will
* be accepted by the Metropolis criterion. Thus, the move size is controlled by
*
* log(moveSize) = log(moveSize) + gain * (accept/nMoves - target)
*
* For more theory and the mysterious 0.44 value, see Jimmy K.-C. Lam and
* Jean-Marc Delosme. `An efficient simulated annealing schedule: derivation'.
* Technical Report 8816, Yale University, 1988.
*/
template<
typename FunctionType,
typename CoolingScheduleType
>
void SA<FunctionType, CoolingScheduleType>::MoveControl(const size_t nMoves,
arma::mat& accept)
{
arma::mat target;
target.copy_size(accept);
target.fill(0.44);
moveSize = arma::log(moveSize);
moveSize += gain * (accept / (double) nMoves - target);
moveSize = arma::exp(moveSize);
// To avoid the use of element-wise arma::min(), which is only available in
// Armadillo after v3.930, we use a for loop here instead.
for (size_t i = 0; i < accept.n_elem; ++i)
moveSize(i) = (moveSize(i) > maxMove(i)) ? maxMove(i) : moveSize(i);
accept.zeros();
}
template<
typename FunctionType,
typename CoolingScheduleType
>
std::string SA<FunctionType, CoolingScheduleType>::
ToString() const
{
std::ostringstream convert;
convert << "SA [" << this << "]" << std::endl;
convert << " Function:" << std::endl;
convert << util::Indent(function.ToString(), 2);
convert << " Cooling Schedule:" << std::endl;
convert << util::Indent(coolingSchedule.ToString(), 2);
convert << " Temperature: " << temperature << std::endl;
convert << " Initial moves: " << initMoves << std::endl;
convert << " Sweeps per move control: " << moveCtrlSweep << std::endl;
convert << " Tolerance: " << tolerance << std::endl;
convert << " Maximum sweeps below tolerance: " << maxToleranceSweep
<< std::endl;
convert << " Move control gain: " << gain << std::endl;
convert << " Maximum iterations: " << maxIterations << std::endl;
return convert.str();
}
}; // namespace optimization
}; // namespace mlpack
#endif
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
/// @brief mruby client connection
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2004-2013 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Achim Brandt
/// @author Copyright 2012-2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
#include "MRubyClientConnection.h"
#include <sstream>
#include "Basics/StringUtils.h"
#include "BasicsC/json.h"
#include "BasicsC/tri-strings.h"
#include "Rest/HttpRequest.h"
#include "Rest/HttpResponse.h"
#include "SimpleHttpClient/GeneralClientConnection.h"
#include "SimpleHttpClient/SimpleHttpClient.h"
#include "SimpleHttpClient/SimpleHttpResult.h"
extern "C" {
#include "mruby/array.h"
#include "mruby/hash.h"
}
using namespace triagens::basics;
using namespace triagens::httpclient;
using namespace triagens::mrclient;
using namespace triagens::rest;
using namespace std;
// -----------------------------------------------------------------------------
// --SECTION-- constructors and destructors
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @addtogroup V8ClientConnection
/// @{
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/// @brief constructor
////////////////////////////////////////////////////////////////////////////////
MRubyClientConnection::MRubyClientConnection (mrb_state* mrb,
Endpoint* endpoint,
const string& username,
const string& password,
double requestTimeout,
double connectionTimeout,
size_t numRetries,
bool warn)
: _mrb(mrb),
_connection(0),
_lastHttpReturnCode(0),
_lastErrorMessage(""),
_client(0),
_httpResult(0) {
_connection = GeneralClientConnection::factory(endpoint, connectionTimeout, requestTimeout, numRetries);
if (_connection == 0) {
throw "out of memory";
}
_client = new SimpleHttpClient(_connection, requestTimeout, warn);
_client->setUserNamePassword("/", username, password);
// connect to server and get version number
map<string, string> headerFields;
SimpleHttpResult* result = _client->request(HttpRequest::HTTP_REQUEST_GET, "/_api/version", 0, 0, headerFields);
if (!result->isComplete()) {
// save error message
_lastErrorMessage = _client->getErrorMessage();
_lastHttpReturnCode = 500;
}
else {
_lastHttpReturnCode = result->getHttpReturnCode();
if (result->getHttpReturnCode() == HttpResponse::OK) {
// default value
_version = "arango";
// convert response body to json
TRI_json_t* json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, result->getBody().str().c_str());
if (json) {
// look up "server" value (this returns a pointer, not a copy)
TRI_json_t* server = TRI_LookupArrayJson(json, "server");
if (TRI_IsStringJson(server)) {
// "server" value is a string and content is "arango"
if (TRI_EqualString(server->_value._string.data, "arango")) {
// look up "version" value (this returns a pointer, not a copy)
TRI_json_t* vs = TRI_LookupArrayJson(json, "version");
if (TRI_IsStringJson(vs)) {
// "version" value is a string
_version = string(vs->_value._string.data, vs->_value._string.length);
}
}
// must not free server and vs, they are contained in the "json" variable and freed below
}
TRI_FreeJson(TRI_UNKNOWN_MEM_ZONE, json);
}
}
}
delete result;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief destructor
////////////////////////////////////////////////////////////////////////////////
MRubyClientConnection::~MRubyClientConnection () {
if (_httpResult) {
delete _httpResult;
}
if (_client) {
delete _client;
}
}
////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------------
// --SECTION-- public functions
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @addtogroup MRubyClientConnection
/// @{
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/// @brief returns true if it is connected
////////////////////////////////////////////////////////////////////////////////
bool MRubyClientConnection::isConnected () {
return _connection->isConnected();
}
////////////////////////////////////////////////////////////////////////////////
/// @brief returns the version and build number of the arango server
////////////////////////////////////////////////////////////////////////////////
const string& MRubyClientConnection::getVersion () {
return _version;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief get the last http return code
////////////////////////////////////////////////////////////////////////////////
int MRubyClientConnection::getLastHttpReturnCode () {
return _lastHttpReturnCode;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief get the last error message
////////////////////////////////////////////////////////////////////////////////
const std::string& MRubyClientConnection::getErrorMessage () {
return _lastErrorMessage;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief get the simple http client
////////////////////////////////////////////////////////////////////////////////
triagens::httpclient::SimpleHttpClient* MRubyClientConnection::getHttpClient() {
return _client;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief do a "GET" request
////////////////////////////////////////////////////////////////////////////////
mrb_value MRubyClientConnection::getData (std::string const& location,
map<string, string> const& headerFields) {
return requestData(HttpRequest::HTTP_REQUEST_GET, location, "", headerFields);
}
////////////////////////////////////////////////////////////////////////////////
/// @brief do a "DELETE" request
////////////////////////////////////////////////////////////////////////////////
mrb_value MRubyClientConnection::deleteData (std::string const& location,
map<string, string> const& headerFields) {
return requestData(HttpRequest::HTTP_REQUEST_DELETE, location, "", headerFields);
}
////////////////////////////////////////////////////////////////////////////////
/// @brief do a "HEAD" request
////////////////////////////////////////////////////////////////////////////////
mrb_value MRubyClientConnection::headData (std::string const& location,
map<string, string> const& headerFields) {
return requestData(HttpRequest::HTTP_REQUEST_HEAD, location, "", headerFields);
}
////////////////////////////////////////////////////////////////////////////////
/// @brief do a "POST" request
////////////////////////////////////////////////////////////////////////////////
mrb_value MRubyClientConnection::postData (std::string const& location,
std::string const& body,
map<string, string> const& headerFields) {
return requestData(HttpRequest::HTTP_REQUEST_POST, location, body, headerFields);
}
////////////////////////////////////////////////////////////////////////////////
/// @brief do a "PUT" request
////////////////////////////////////////////////////////////////////////////////
mrb_value MRubyClientConnection::putData (std::string const& location,
std::string const& body,
map<string, string> const& headerFields) {
return requestData(HttpRequest::HTTP_REQUEST_PUT, location, body, headerFields);
}
////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------------
// --SECTION-- public functions
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @addtogroup MRubyClientConnection
/// @{
////////////////////////////////////////////////////////////////////////////////
mrb_value MRubyClientConnection::requestData (HttpRequest::HttpRequestType method,
string const& location,
string const& body,
map<string, string> const& headerFields) {
MR_state_t* mrs;
mrs = (MR_state_t*) _mrb->ud;
_lastErrorMessage = "";
_lastHttpReturnCode = 0;
if (_httpResult) {
delete _httpResult;
}
if (body.empty()) {
_httpResult = _client->request(method, location, 0, 0, headerFields);
}
else {
_httpResult = _client->request(method, location, body.c_str(), body.length(), headerFields);
}
if (!_httpResult->isComplete()) {
// not complete
_lastErrorMessage = _client->getErrorMessage();
if (_lastErrorMessage.empty()) {
_lastErrorMessage = "Unknown error";
}
_lastHttpReturnCode = HttpResponse::SERVER_ERROR;
mrb_value result = mrb_hash_new_capa(_mrb, 2);
mrb_hash_set(_mrb, result, mrs->_errorSym, mrb_true_value());
mrb_hash_set(_mrb, result, mrs->_codeSym, mrb_fixnum_value(HttpResponse::SERVER_ERROR));
int errorNumber = 0;
switch (_httpResult->getResultType()) {
case (SimpleHttpResult::COULD_NOT_CONNECT) :
errorNumber = TRI_SIMPLE_CLIENT_COULD_NOT_CONNECT;
break;
case (SimpleHttpResult::READ_ERROR) :
errorNumber = TRI_SIMPLE_CLIENT_COULD_NOT_READ;
break;
case (SimpleHttpResult::WRITE_ERROR) :
errorNumber = TRI_SIMPLE_CLIENT_COULD_NOT_WRITE;
break;
default:
errorNumber = TRI_SIMPLE_CLIENT_UNKNOWN_ERROR;
break;
}
mrb_hash_set(_mrb, result, mrs->_errorNumSym, mrb_fixnum_value(errorNumber));
mrb_hash_set(_mrb,
result,
mrs->_errorMessageSym,
mrb_str_new(_mrb, _lastErrorMessage.c_str(), _lastErrorMessage.length()));
return result;
}
else {
// complete
_lastHttpReturnCode = _httpResult->getHttpReturnCode();
// got a body
if (_httpResult->getBody().str().length() > 0) {
string contentType = _httpResult->getContentType(true);
if (contentType == "application/json") {
TRI_json_t* js = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, _httpResult->getBody().str().c_str());
if (js != NULL) {
// return v8 object
mrb_value result = MR_ObjectJson(_mrb, js);
TRI_FreeJson(TRI_UNKNOWN_MEM_ZONE, js);
return result;
}
}
// return body as string
mrb_value result = mrb_str_new(_mrb,
_httpResult->getBody().str().c_str(),
_httpResult->getBody().str().length());
return result;
}
else {
// no body
// this should not happen
mrb_value result;
mrb_hash_set(_mrb, result, mrs->_errorSym, mrb_false_value());
mrb_hash_set(_mrb, result, mrs->_codeSym, mrb_fixnum_value(_httpResult->getHttpReturnCode()));
return result;
}
}
}
////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////
// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @addtogroup\\|/// @page\\|// --SECTION--\\|/// @\\}"
// End:
<commit_msg>fixed mrb client<commit_after>////////////////////////////////////////////////////////////////////////////////
/// @brief mruby client connection
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2004-2013 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Achim Brandt
/// @author Copyright 2012-2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
#include "MRubyClientConnection.h"
#include <sstream>
#include "Basics/StringUtils.h"
#include "BasicsC/json.h"
#include "BasicsC/tri-strings.h"
#include "Rest/HttpRequest.h"
#include "Rest/HttpResponse.h"
#include "SimpleHttpClient/GeneralClientConnection.h"
#include "SimpleHttpClient/SimpleHttpClient.h"
#include "SimpleHttpClient/SimpleHttpResult.h"
extern "C" {
#include "mruby/array.h"
#include "mruby/hash.h"
}
using namespace triagens::basics;
using namespace triagens::httpclient;
using namespace triagens::mrclient;
using namespace triagens::rest;
using namespace std;
// -----------------------------------------------------------------------------
// --SECTION-- constructors and destructors
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @addtogroup V8ClientConnection
/// @{
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/// @brief constructor
////////////////////////////////////////////////////////////////////////////////
MRubyClientConnection::MRubyClientConnection (mrb_state* mrb,
Endpoint* endpoint,
const string& username,
const string& password,
double requestTimeout,
double connectionTimeout,
size_t numRetries,
bool warn)
: _mrb(mrb),
_connection(0),
_lastHttpReturnCode(0),
_lastErrorMessage(""),
_client(0),
_httpResult(0) {
_connection = GeneralClientConnection::factory(endpoint, connectionTimeout, requestTimeout, numRetries, 0);
if (_connection == 0) {
throw "out of memory";
}
_client = new SimpleHttpClient(_connection, requestTimeout, warn);
_client->setUserNamePassword("/", username, password);
// connect to server and get version number
map<string, string> headerFields;
SimpleHttpResult* result = _client->request(HttpRequest::HTTP_REQUEST_GET, "/_api/version", 0, 0, headerFields);
if (!result->isComplete()) {
// save error message
_lastErrorMessage = _client->getErrorMessage();
_lastHttpReturnCode = 500;
}
else {
_lastHttpReturnCode = result->getHttpReturnCode();
if (result->getHttpReturnCode() == HttpResponse::OK) {
// default value
_version = "arango";
// convert response body to json
TRI_json_t* json = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, result->getBody().str().c_str());
if (json) {
// look up "server" value (this returns a pointer, not a copy)
TRI_json_t* server = TRI_LookupArrayJson(json, "server");
if (TRI_IsStringJson(server)) {
// "server" value is a string and content is "arango"
if (TRI_EqualString(server->_value._string.data, "arango")) {
// look up "version" value (this returns a pointer, not a copy)
TRI_json_t* vs = TRI_LookupArrayJson(json, "version");
if (TRI_IsStringJson(vs)) {
// "version" value is a string
_version = string(vs->_value._string.data, vs->_value._string.length);
}
}
// must not free server and vs, they are contained in the "json" variable and freed below
}
TRI_FreeJson(TRI_UNKNOWN_MEM_ZONE, json);
}
}
}
delete result;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief destructor
////////////////////////////////////////////////////////////////////////////////
MRubyClientConnection::~MRubyClientConnection () {
if (_httpResult) {
delete _httpResult;
}
if (_client) {
delete _client;
}
}
////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------------
// --SECTION-- public functions
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @addtogroup MRubyClientConnection
/// @{
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/// @brief returns true if it is connected
////////////////////////////////////////////////////////////////////////////////
bool MRubyClientConnection::isConnected () {
return _connection->isConnected();
}
////////////////////////////////////////////////////////////////////////////////
/// @brief returns the version and build number of the arango server
////////////////////////////////////////////////////////////////////////////////
const string& MRubyClientConnection::getVersion () {
return _version;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief get the last http return code
////////////////////////////////////////////////////////////////////////////////
int MRubyClientConnection::getLastHttpReturnCode () {
return _lastHttpReturnCode;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief get the last error message
////////////////////////////////////////////////////////////////////////////////
const std::string& MRubyClientConnection::getErrorMessage () {
return _lastErrorMessage;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief get the simple http client
////////////////////////////////////////////////////////////////////////////////
triagens::httpclient::SimpleHttpClient* MRubyClientConnection::getHttpClient() {
return _client;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief do a "GET" request
////////////////////////////////////////////////////////////////////////////////
mrb_value MRubyClientConnection::getData (std::string const& location,
map<string, string> const& headerFields) {
return requestData(HttpRequest::HTTP_REQUEST_GET, location, "", headerFields);
}
////////////////////////////////////////////////////////////////////////////////
/// @brief do a "DELETE" request
////////////////////////////////////////////////////////////////////////////////
mrb_value MRubyClientConnection::deleteData (std::string const& location,
map<string, string> const& headerFields) {
return requestData(HttpRequest::HTTP_REQUEST_DELETE, location, "", headerFields);
}
////////////////////////////////////////////////////////////////////////////////
/// @brief do a "HEAD" request
////////////////////////////////////////////////////////////////////////////////
mrb_value MRubyClientConnection::headData (std::string const& location,
map<string, string> const& headerFields) {
return requestData(HttpRequest::HTTP_REQUEST_HEAD, location, "", headerFields);
}
////////////////////////////////////////////////////////////////////////////////
/// @brief do a "POST" request
////////////////////////////////////////////////////////////////////////////////
mrb_value MRubyClientConnection::postData (std::string const& location,
std::string const& body,
map<string, string> const& headerFields) {
return requestData(HttpRequest::HTTP_REQUEST_POST, location, body, headerFields);
}
////////////////////////////////////////////////////////////////////////////////
/// @brief do a "PUT" request
////////////////////////////////////////////////////////////////////////////////
mrb_value MRubyClientConnection::putData (std::string const& location,
std::string const& body,
map<string, string> const& headerFields) {
return requestData(HttpRequest::HTTP_REQUEST_PUT, location, body, headerFields);
}
////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------------
// --SECTION-- public functions
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @addtogroup MRubyClientConnection
/// @{
////////////////////////////////////////////////////////////////////////////////
mrb_value MRubyClientConnection::requestData (HttpRequest::HttpRequestType method,
string const& location,
string const& body,
map<string, string> const& headerFields) {
MR_state_t* mrs;
mrs = (MR_state_t*) _mrb->ud;
_lastErrorMessage = "";
_lastHttpReturnCode = 0;
if (_httpResult) {
delete _httpResult;
}
if (body.empty()) {
_httpResult = _client->request(method, location, 0, 0, headerFields);
}
else {
_httpResult = _client->request(method, location, body.c_str(), body.length(), headerFields);
}
if (!_httpResult->isComplete()) {
// not complete
_lastErrorMessage = _client->getErrorMessage();
if (_lastErrorMessage.empty()) {
_lastErrorMessage = "Unknown error";
}
_lastHttpReturnCode = HttpResponse::SERVER_ERROR;
mrb_value result = mrb_hash_new_capa(_mrb, 2);
mrb_hash_set(_mrb, result, mrs->_errorSym, mrb_true_value());
mrb_hash_set(_mrb, result, mrs->_codeSym, mrb_fixnum_value(HttpResponse::SERVER_ERROR));
int errorNumber = 0;
switch (_httpResult->getResultType()) {
case (SimpleHttpResult::COULD_NOT_CONNECT) :
errorNumber = TRI_SIMPLE_CLIENT_COULD_NOT_CONNECT;
break;
case (SimpleHttpResult::READ_ERROR) :
errorNumber = TRI_SIMPLE_CLIENT_COULD_NOT_READ;
break;
case (SimpleHttpResult::WRITE_ERROR) :
errorNumber = TRI_SIMPLE_CLIENT_COULD_NOT_WRITE;
break;
default:
errorNumber = TRI_SIMPLE_CLIENT_UNKNOWN_ERROR;
break;
}
mrb_hash_set(_mrb, result, mrs->_errorNumSym, mrb_fixnum_value(errorNumber));
mrb_hash_set(_mrb,
result,
mrs->_errorMessageSym,
mrb_str_new(_mrb, _lastErrorMessage.c_str(), _lastErrorMessage.length()));
return result;
}
else {
// complete
_lastHttpReturnCode = _httpResult->getHttpReturnCode();
// got a body
if (_httpResult->getBody().str().length() > 0) {
string contentType = _httpResult->getContentType(true);
if (contentType == "application/json") {
TRI_json_t* js = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, _httpResult->getBody().str().c_str());
if (js != NULL) {
// return v8 object
mrb_value result = MR_ObjectJson(_mrb, js);
TRI_FreeJson(TRI_UNKNOWN_MEM_ZONE, js);
return result;
}
}
// return body as string
mrb_value result = mrb_str_new(_mrb,
_httpResult->getBody().str().c_str(),
_httpResult->getBody().str().length());
return result;
}
else {
// no body
// this should not happen
mrb_value result;
mrb_hash_set(_mrb, result, mrs->_errorSym, mrb_false_value());
mrb_hash_set(_mrb, result, mrs->_codeSym, mrb_fixnum_value(_httpResult->getHttpReturnCode()));
return result;
}
}
}
////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////
// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @addtogroup\\|/// @page\\|// --SECTION--\\|/// @\\}"
// End:
<|endoftext|> |
<commit_before>/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Author: jmarantz@google.com (Joshua Marantz)
// Unit-test AsyncCache, using LRUCache.
#include "net/instaweb/util/public/async_cache.h"
#include <cstddef>
#include <map>
#include <utility> // for pair
#include "base/logging.h"
#include "net/instaweb/util/public/basictypes.h"
#include "net/instaweb/util/public/function.h"
#include "net/instaweb/util/public/gtest.h"
#include "net/instaweb/util/public/lru_cache.h"
#include "net/instaweb/util/public/shared_string.h"
#include "net/instaweb/util/public/stl_util.h"
#include "net/instaweb/util/public/string.h"
#include "net/instaweb/util/public/thread_system.h"
#include "net/instaweb/util/public/threadsafe_cache.h"
#include "net/instaweb/util/public/timer.h"
#include "net/instaweb/util/cache_test_base.h"
#include "net/instaweb/util/worker_test_base.h"
namespace {
const size_t kMaxSize = 100;
}
namespace net_instaweb {
class AsyncCacheTest : public CacheTestBase {
protected:
typedef std::map<GoogleString, WorkerTestBase::SyncPoint*> DelayMap;
// Tweak of LRU cache to block in Get on a sync-point. Note that we don't
// use DelayCache because that doeesn't block; it only defers the Done
// callback. In this case we want to mimic the behavior of a slow blocking
// cache using a fast blocking cache, so we use a sync-point.
class SyncedLRUCache : public ThreadsafeCache {
public:
SyncedLRUCache(DelayMap* delay_map, LRUCache* lru_cache,
AbstractMutex* mutex)
: ThreadsafeCache(lru_cache, mutex),
delay_map_(delay_map) {
}
virtual ~SyncedLRUCache() {}
void Get(const GoogleString& key, Callback* callback) {
DelayMap::iterator p = delay_map_->find(key);
if (p != delay_map_->end()) {
WorkerTestBase::SyncPoint* sync_point = p->second;
sync_point->Wait();
delay_map_->erase(p);
delete sync_point;
}
ThreadsafeCache::Get(key, callback);
}
private:
DelayMap* delay_map_;
DISALLOW_COPY_AND_ASSIGN(SyncedLRUCache);
};
class AsyncCallback : public CacheTestBase::Callback {
public:
explicit AsyncCallback(AsyncCacheTest* test)
: Callback(test),
sync_point_(test->thread_system_.get()) {
}
virtual void Done(CacheInterface::KeyState state) {
Callback::Done(state);
sync_point_.Notify();
}
virtual void Wait() { sync_point_.Wait(); }
private:
WorkerTestBase::SyncPoint sync_point_;
};
AsyncCacheTest()
: lru_cache_(new LRUCache(kMaxSize)),
thread_system_(ThreadSystem::CreateThreadSystem()),
timer_(thread_system_->NewTimer()),
suppress_post_get_cleanup_(false) {
set_mutex(thread_system_->NewMutex());
}
void InitCache(int num_workers, int num_threads) {
pool_.reset(new QueuedWorkerPool(num_workers, thread_system_.get()));
SyncedLRUCache* synced_lru_cache = new SyncedLRUCache(
&delay_map_, lru_cache_, thread_system_->NewMutex());
async_cache_.reset(new AsyncCache(
synced_lru_cache, thread_system_->NewMutex(), pool_.get()));
async_cache_->set_num_threads(num_threads);
}
virtual ~AsyncCacheTest() { STLDeleteValues(&delay_map_); }
virtual CacheInterface* Cache() { return async_cache_.get(); }
virtual Callback* NewCallback() { return new AsyncCallback(this); }
virtual void PostOpCleanup() {
// Wait until the AsyncCache available thread-count is restored to
// non-zero. Note that in AsyncCache we call blocking cache
// Get/MultiGet first, then decrement the in-use thread-count, so
// the cache is not immediately available for another Get until
// the thread-count has been decremented.
//
// If mainline issues another Get too quickly after the callback is
// called, it will immediately fail due to the count not being
// updated yet.
if (!suppress_post_get_cleanup_) {
while (!async_cache_->CanIssueGet()) {
timer_->SleepMs(1);
}
}
}
void DelayKey(const GoogleString& key) {
delay_map_[key] = new WorkerTestBase::SyncPoint(thread_system_.get());
}
void ReleaseKey(const GoogleString& key) {
DelayMap::iterator p = delay_map_.find(key);
CHECK(p != delay_map_.end());
WorkerTestBase::SyncPoint* sync_point = p->second;
sync_point->Notify();
}
DelayMap delay_map_;
LRUCache* lru_cache_;
scoped_ptr<ThreadSystem> thread_system_;
scoped_ptr<Timer> timer_;
scoped_ptr<QueuedWorkerPool> pool_;
scoped_ptr<AsyncCache> async_cache_;
bool suppress_post_get_cleanup_;
};
// In this version, no keys are delayed, so AsyncCache will not
// introduce parallelism. This test is copied from lru_cache_test.cc.
// Note that we are going through the AsyncCache/ThreadsafeCache but
// the LRUCache should be quiescent every time we look directly at it.
//
// TODO(jmarantz): refactor this with LRUCacheTest::PutGetDelete.
TEST_F(AsyncCacheTest, PutGetDelete) {
InitCache(1, 1);
EXPECT_EQ(static_cast<size_t>(0), lru_cache_->size_bytes());
EXPECT_EQ(static_cast<size_t>(0), lru_cache_->num_elements());
CheckPut("Name", "Value");
CheckGet("Name", "Value");
EXPECT_EQ(static_cast<size_t>(9), lru_cache_->size_bytes());
EXPECT_EQ(static_cast<size_t>(1), lru_cache_->num_elements());
CheckNotFound("Another Name");
CheckPut("Name", "NewValue");
CheckGet("Name", "NewValue");
EXPECT_EQ(static_cast<size_t>(12), lru_cache_->size_bytes());
EXPECT_EQ(static_cast<size_t>(1), lru_cache_->num_elements());
async_cache_->Delete("Name");
lru_cache_->SanityCheck();
SharedString value_buffer;
CheckNotFound("Name");
EXPECT_EQ(static_cast<size_t>(0), lru_cache_->size_bytes());
EXPECT_EQ(static_cast<size_t>(0), lru_cache_->num_elements());
lru_cache_->SanityCheck();
}
TEST_F(AsyncCacheTest, DelayN0NoParallelism) {
InitCache(1, 1);
PopulateCache(4); // Inserts "n0"->"v0", "n1"->"v1", "n2"->"v2", "n3"->"v3".
// Delaying "n0" causes the fetches for "n1" to be dropped
// immediately because we've initialized the cache to only one
// request at a time.
DelayKey("n0");
Callback* n0 = InitiateGet("n0");
EXPECT_EQ(1, outstanding_fetches());
suppress_post_get_cleanup_ = true; // avoid blocking waiting for delayed n0.
CheckNotFound("n1");
suppress_post_get_cleanup_ = false;
EXPECT_EQ(1, outstanding_fetches());
ReleaseKey("n0");
WaitAndCheck(n0, "v0");
CheckNotFound("not found");
EXPECT_EQ(0, outstanding_fetches());
// Further fetches will execute immediately again.
CheckGet("n3", "v3");
}
TEST_F(AsyncCacheTest, DelayN0TwoWayParallelism) {
InitCache(2, 2);
PopulateCache(8);
DelayKey("n0");
Callback* n0 = InitiateGet("n0");
EXPECT_EQ(1, outstanding_fetches());
// We still have some parallelism available to us, so "n2" and "n3" will
// complete even while n1 is outstanding.
CheckGet("n1", "v1");
CheckGet("n2", "v2");
// Now block "n3" and look it up. n4 and n5 will now be dropped.
DelayKey("n3");
Callback* n3 = InitiateGet("n3");
Callback* n4 = InitiateGet("n4");
Callback* n5 = InitiateGet("n5");
EXPECT_EQ(2, outstanding_fetches());
suppress_post_get_cleanup_ = true; // avoid blocking waiting for delayed n0.
WaitAndCheckNotFound(n4);
WaitAndCheckNotFound(n5);
suppress_post_get_cleanup_ = false;
ReleaseKey("n0");
WaitAndCheck(n0, "v0");
CheckGet("n6", "v6");
EXPECT_EQ(1, outstanding_fetches());
// Finally, release n3 and we are all clean.
ReleaseKey("n3");
WaitAndCheck(n3, "v3");
EXPECT_EQ(0, outstanding_fetches());
CheckGet("n7", "v7");
EXPECT_EQ(0, outstanding_fetches());
}
TEST_F(AsyncCacheTest, MultiGet) {
InitCache(1, 1);
TestMultiGet();
}
TEST_F(AsyncCacheTest, MultiGetDrop) {
InitCache(1, 1);
PopulateCache(3);
DelayKey("n2");
Callback* n2 = InitiateGet("n2");
Callback* n0 = AddCallback();
Callback* not_found = AddCallback();
Callback* n1 = AddCallback();
IssueMultiGet(n0, "n0", not_found, "not_found", n1, "n1");
suppress_post_get_cleanup_ = true; // avoid blocking waiting for delayed n0.
WaitAndCheckNotFound(n0);
WaitAndCheckNotFound(not_found);
WaitAndCheckNotFound(n1);
suppress_post_get_cleanup_ = false;
ReleaseKey("n2");
WaitAndCheck(n2, "v2");
}
TEST_F(AsyncCacheTest, StopGets) {
InitCache(1, 1);
PopulateCache(1);
CheckGet("n0", "v0");
async_cache_->StopCacheGets();
suppress_post_get_cleanup_ = true; // avoid blocking waiting for delayed n0.
CheckNotFound("n0");
suppress_post_get_cleanup_ = false;
}
TEST_F(AsyncCacheTest, ShutdownQueue) {
InitCache(1, 1);
PopulateCache(1);
pool_->ShutDown();
CheckNotFound("n0");
}
TEST_F(AsyncCacheTest, ShutdownQueueWhileBusy) {
InitCache(1, 1);
PopulateCache(1);
WorkerTestBase::SyncPoint sync_point(thread_system_.get());
QueuedWorkerPool::Sequence* sequence = pool_->NewSequence();
sequence->Add(new WorkerTestBase::WaitRunFunction(&sync_point));
Callback* n0 = InitiateGet("n0"); // blocks waiting for timer.
QueuedWorkerPool pool2(2, thread_system_.get());
QueuedWorkerPool::Sequence* sequence2 = pool2.NewSequence();
sequence2->Add(MakeFunction(pool_.get(), &QueuedWorkerPool::ShutDown));
// We must now wait for the ShutDown sequence be *initiated* on
// pool_. However, there is no callback for this at all, and
// ShutDown itself will block due to the fact that the function
// currently running in pool_ is blocked. To resolve this we can
// add a short sleep, so we are likely to get into the ShutDown
// flow before releasing the sync_point.
//
// Calling pool->ShutDown() directly blocks on the completion
// of the function blocked on sync_point.
timer_->SleepMs(10);
sync_point.Notify();
pool2.ShutDown();
WaitAndCheckNotFound(n0);
}
TEST_F(AsyncCacheTest, ShutdownQueueWhileBusyWithMultiGet) {
InitCache(1, 1);
PopulateCache(1);
WorkerTestBase::SyncPoint sync_point(thread_system_.get());
QueuedWorkerPool::Sequence* sequence = pool_->NewSequence();
sequence->Add(new WorkerTestBase::WaitRunFunction(&sync_point));
Callback* n0 = AddCallback();
Callback* not_found = AddCallback();
Callback* n1 = AddCallback();
IssueMultiGet(n0, "n0", not_found, "not_found", n1, "n1");
QueuedWorkerPool pool2(2, thread_system_.get());
QueuedWorkerPool::Sequence* sequence2 = pool2.NewSequence();
sequence2->Add(MakeFunction(pool_.get(), &QueuedWorkerPool::ShutDown));
// We must now wait for the ShutDown sequence be *initiated* on
// pool_. However, there is no callback for this at all, and
// ShutDown itself will block due to the fact that the function
// currently running in pool_ is blocked. To resolve this we can
// add a short sleep, so we are certain we'll get into the ShutDown
// flow before releaing the sync_point.
timer_->SleepMs(10);
sync_point.Notify();
pool2.ShutDown();
WaitAndCheckNotFound(n0);
WaitAndCheckNotFound(not_found);
WaitAndCheckNotFound(n1);
}
} // namespace net_instaweb
<commit_msg>Fix a couple of races found in the async cache test, including a shutdown race.<commit_after>/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Author: jmarantz@google.com (Joshua Marantz)
// Unit-test AsyncCache, using LRUCache.
#include "net/instaweb/util/public/async_cache.h"
#include <cstddef>
#include <map>
#include <utility> // for pair
#include "base/logging.h"
#include "net/instaweb/util/public/abstract_mutex.h"
#include "net/instaweb/util/public/basictypes.h"
#include "net/instaweb/util/public/function.h"
#include "net/instaweb/util/public/gtest.h"
#include "net/instaweb/util/public/lru_cache.h"
#include "net/instaweb/util/public/shared_string.h"
#include "net/instaweb/util/public/stl_util.h"
#include "net/instaweb/util/public/string.h"
#include "net/instaweb/util/public/thread_system.h"
#include "net/instaweb/util/public/threadsafe_cache.h"
#include "net/instaweb/util/public/timer.h"
#include "net/instaweb/util/cache_test_base.h"
#include "net/instaweb/util/worker_test_base.h"
namespace {
const size_t kMaxSize = 100;
}
namespace net_instaweb {
class AsyncCacheTest : public CacheTestBase {
protected:
class DelayMap {
public:
explicit DelayMap(ThreadSystem* thread_system)
: mutex_(thread_system->NewMutex()),
thread_system_(thread_system) {
}
~DelayMap() { STLDeleteValues(&map_); }
// Note that Delay is called only in test mainlines, prior to
// any cache lookups being queued for that key.
void Delay(const GoogleString& key) {
WorkerTestBase::SyncPoint* sync_point =
new WorkerTestBase::SyncPoint(thread_system_);
{
ScopedMutex lock(mutex_.get());
map_[key] = sync_point;
}
}
// Note that Wait is only called once per key, so there is no wait/wait
// race.
void Wait(const GoogleString& key) {
// We can't use ScopedMutex easily here because we want to avoid
// holding our mutex while blocking or freeing memory.
mutex_->Lock();
Map::iterator p = map_.find(key);
if (p != map_.end()) {
WorkerTestBase::SyncPoint* sync_point = p->second;
// In order to avoid deadlock with Wait/Delay on other keys,
// and most importantly Notify() on this key, we must release
// the lock before waiting on the sync-point.
mutex_->Unlock();
sync_point->Wait();
mutex_->Lock();
map_.erase(p);
mutex_->Unlock();
delete sync_point;
} else {
mutex_->Unlock();
}
}
void Notify(const GoogleString& key) {
WorkerTestBase::SyncPoint* sync_point = NULL;
{
ScopedMutex lock(mutex_.get());
Map::iterator p = map_.find(key);
if (p != map_.end()) {
sync_point = p->second;
}
}
CHECK(sync_point != NULL);
sync_point->Notify();
}
typedef std::map<GoogleString, WorkerTestBase::SyncPoint*> Map;
scoped_ptr<AbstractMutex> mutex_;
ThreadSystem* thread_system_;
Map map_;
};
// Tweak of LRU cache to block in Get on a sync-point. Note that we don't
// use DelayCache because that doeesn't block; it only defers the Done
// callback. In this case we want to mimic the behavior of a slow blocking
// cache using a fast blocking cache, so we use a sync-point.
class SyncedLRUCache : public ThreadsafeCache {
public:
SyncedLRUCache(DelayMap* delay_map, LRUCache* lru_cache,
AbstractMutex* mutex)
: ThreadsafeCache(lru_cache, mutex),
delay_map_(delay_map) {
}
virtual ~SyncedLRUCache() {}
void Get(const GoogleString& key, Callback* callback) {
delay_map_->Wait(key);
ThreadsafeCache::Get(key, callback);
}
private:
DelayMap* delay_map_;
DISALLOW_COPY_AND_ASSIGN(SyncedLRUCache);
};
class AsyncCallback : public CacheTestBase::Callback {
public:
explicit AsyncCallback(AsyncCacheTest* test)
: Callback(test),
sync_point_(test->thread_system_.get()) {
}
virtual void Done(CacheInterface::KeyState state) {
Callback::Done(state);
sync_point_.Notify();
}
virtual void Wait() { sync_point_.Wait(); }
private:
WorkerTestBase::SyncPoint sync_point_;
};
AsyncCacheTest()
: lru_cache_(new LRUCache(kMaxSize)),
thread_system_(ThreadSystem::CreateThreadSystem()),
delay_map_(thread_system_.get()),
timer_(thread_system_->NewTimer()),
suppress_post_get_cleanup_(false) {
set_mutex(thread_system_->NewMutex());
}
~AsyncCacheTest() {
pool_->ShutDown(); // quiesce before destructing cache.
}
void InitCache(int num_workers, int num_threads) {
pool_.reset(new QueuedWorkerPool(num_workers, thread_system_.get()));
SyncedLRUCache* synced_lru_cache = new SyncedLRUCache(
&delay_map_, lru_cache_, thread_system_->NewMutex());
async_cache_.reset(new AsyncCache(
synced_lru_cache, thread_system_->NewMutex(), pool_.get()));
async_cache_->set_num_threads(num_threads);
}
virtual CacheInterface* Cache() { return async_cache_.get(); }
virtual Callback* NewCallback() { return new AsyncCallback(this); }
virtual void PostOpCleanup() {
// Wait until the AsyncCache available thread-count is restored to
// non-zero. Note that in AsyncCache we call blocking cache
// Get/MultiGet first, then decrement the in-use thread-count, so
// the cache is not immediately available for another Get until
// the thread-count has been decremented.
//
// If mainline issues another Get too quickly after the callback is
// called, it will immediately fail due to the count not being
// updated yet.
if (!suppress_post_get_cleanup_) {
while (!async_cache_->CanIssueGet()) {
timer_->SleepMs(1);
}
}
}
void DelayKey(const GoogleString& key) {
delay_map_.Delay(key);
}
void ReleaseKey(const GoogleString& key) {
delay_map_.Notify(key);
}
LRUCache* lru_cache_;
scoped_ptr<ThreadSystem> thread_system_;
DelayMap delay_map_;
scoped_ptr<Timer> timer_;
scoped_ptr<QueuedWorkerPool> pool_;
scoped_ptr<AsyncCache> async_cache_;
bool suppress_post_get_cleanup_;
};
// In this version, no keys are delayed, so AsyncCache will not
// introduce parallelism. This test is copied from lru_cache_test.cc.
// Note that we are going through the AsyncCache/ThreadsafeCache but
// the LRUCache should be quiescent every time we look directly at it.
//
// TODO(jmarantz): refactor this with LRUCacheTest::PutGetDelete.
TEST_F(AsyncCacheTest, PutGetDelete) {
InitCache(1, 1);
EXPECT_EQ(static_cast<size_t>(0), lru_cache_->size_bytes());
EXPECT_EQ(static_cast<size_t>(0), lru_cache_->num_elements());
CheckPut("Name", "Value");
CheckGet("Name", "Value");
EXPECT_EQ(static_cast<size_t>(9), lru_cache_->size_bytes());
EXPECT_EQ(static_cast<size_t>(1), lru_cache_->num_elements());
CheckNotFound("Another Name");
CheckPut("Name", "NewValue");
CheckGet("Name", "NewValue");
EXPECT_EQ(static_cast<size_t>(12), lru_cache_->size_bytes());
EXPECT_EQ(static_cast<size_t>(1), lru_cache_->num_elements());
async_cache_->Delete("Name");
lru_cache_->SanityCheck();
SharedString value_buffer;
CheckNotFound("Name");
EXPECT_EQ(static_cast<size_t>(0), lru_cache_->size_bytes());
EXPECT_EQ(static_cast<size_t>(0), lru_cache_->num_elements());
lru_cache_->SanityCheck();
}
TEST_F(AsyncCacheTest, DelayN0NoParallelism) {
InitCache(1, 1);
PopulateCache(4); // Inserts "n0"->"v0", "n1"->"v1", "n2"->"v2", "n3"->"v3".
// Delaying "n0" causes the fetches for "n1" to be dropped
// immediately because we've initialized the cache to only one
// request at a time.
DelayKey("n0");
Callback* n0 = InitiateGet("n0");
EXPECT_EQ(1, outstanding_fetches());
suppress_post_get_cleanup_ = true; // avoid blocking waiting for delayed n0.
CheckNotFound("n1");
suppress_post_get_cleanup_ = false;
EXPECT_EQ(1, outstanding_fetches());
ReleaseKey("n0");
WaitAndCheck(n0, "v0");
CheckNotFound("not found");
EXPECT_EQ(0, outstanding_fetches());
// Further fetches will execute immediately again.
CheckGet("n3", "v3");
}
TEST_F(AsyncCacheTest, DelayN0TwoWayParallelism) {
InitCache(2, 2);
PopulateCache(8);
DelayKey("n0");
Callback* n0 = InitiateGet("n0");
EXPECT_EQ(1, outstanding_fetches());
// We still have some parallelism available to us, so "n2" and "n3" will
// complete even while n1 is outstanding.
CheckGet("n1", "v1");
CheckGet("n2", "v2");
// Now block "n3" and look it up. n4 and n5 will now be dropped.
DelayKey("n3");
Callback* n3 = InitiateGet("n3");
Callback* n4 = InitiateGet("n4");
Callback* n5 = InitiateGet("n5");
EXPECT_EQ(2, outstanding_fetches());
suppress_post_get_cleanup_ = true; // avoid blocking waiting for delayed n0.
WaitAndCheckNotFound(n4);
WaitAndCheckNotFound(n5);
suppress_post_get_cleanup_ = false;
ReleaseKey("n0");
WaitAndCheck(n0, "v0");
CheckGet("n6", "v6");
EXPECT_EQ(1, outstanding_fetches());
// Finally, release n3 and we are all clean.
ReleaseKey("n3");
WaitAndCheck(n3, "v3");
EXPECT_EQ(0, outstanding_fetches());
CheckGet("n7", "v7");
EXPECT_EQ(0, outstanding_fetches());
}
TEST_F(AsyncCacheTest, MultiGet) {
InitCache(1, 1);
TestMultiGet();
}
TEST_F(AsyncCacheTest, MultiGetDrop) {
InitCache(1, 1);
PopulateCache(3);
DelayKey("n2");
Callback* n2 = InitiateGet("n2");
Callback* n0 = AddCallback();
Callback* not_found = AddCallback();
Callback* n1 = AddCallback();
IssueMultiGet(n0, "n0", not_found, "not_found", n1, "n1");
suppress_post_get_cleanup_ = true; // avoid blocking waiting for delayed n0.
WaitAndCheckNotFound(n0);
WaitAndCheckNotFound(not_found);
WaitAndCheckNotFound(n1);
suppress_post_get_cleanup_ = false;
ReleaseKey("n2");
WaitAndCheck(n2, "v2");
}
TEST_F(AsyncCacheTest, StopGets) {
InitCache(1, 1);
PopulateCache(1);
CheckGet("n0", "v0");
async_cache_->StopCacheGets();
suppress_post_get_cleanup_ = true; // avoid blocking waiting for delayed n0.
CheckNotFound("n0");
suppress_post_get_cleanup_ = false;
}
TEST_F(AsyncCacheTest, ShutdownQueue) {
InitCache(1, 1);
PopulateCache(1);
pool_->ShutDown();
CheckNotFound("n0");
}
TEST_F(AsyncCacheTest, ShutdownQueueWhileBusy) {
InitCache(1, 1);
PopulateCache(1);
WorkerTestBase::SyncPoint sync_point(thread_system_.get());
QueuedWorkerPool::Sequence* sequence = pool_->NewSequence();
sequence->Add(new WorkerTestBase::WaitRunFunction(&sync_point));
Callback* n0 = InitiateGet("n0"); // blocks waiting for timer.
QueuedWorkerPool pool2(2, thread_system_.get());
QueuedWorkerPool::Sequence* sequence2 = pool2.NewSequence();
sequence2->Add(MakeFunction(pool_.get(), &QueuedWorkerPool::ShutDown));
// We must now wait for the ShutDown sequence be *initiated* on
// pool_. However, there is no callback for this at all, and
// ShutDown itself will block due to the fact that the function
// currently running in pool_ is blocked. To resolve this we can
// add a short sleep, so we are likely to get into the ShutDown
// flow before releasing the sync_point.
//
// Calling pool->ShutDown() directly blocks on the completion
// of the function blocked on sync_point.
timer_->SleepMs(10);
sync_point.Notify();
pool2.ShutDown();
WaitAndCheckNotFound(n0);
}
TEST_F(AsyncCacheTest, ShutdownQueueWhileBusyWithMultiGet) {
InitCache(1, 1);
PopulateCache(1);
WorkerTestBase::SyncPoint sync_point(thread_system_.get());
QueuedWorkerPool::Sequence* sequence = pool_->NewSequence();
sequence->Add(new WorkerTestBase::WaitRunFunction(&sync_point));
Callback* n0 = AddCallback();
Callback* not_found = AddCallback();
Callback* n1 = AddCallback();
IssueMultiGet(n0, "n0", not_found, "not_found", n1, "n1");
QueuedWorkerPool pool2(2, thread_system_.get());
QueuedWorkerPool::Sequence* sequence2 = pool2.NewSequence();
sequence2->Add(MakeFunction(pool_.get(), &QueuedWorkerPool::ShutDown));
// We must now wait for the ShutDown sequence be *initiated* on
// pool_. However, there is no callback for this at all, and
// ShutDown itself will block due to the fact that the function
// currently running in pool_ is blocked. To resolve this we can
// add a short sleep, so we are certain we'll get into the ShutDown
// flow before releaing the sync_point.
timer_->SleepMs(10);
sync_point.Notify();
pool2.ShutDown();
WaitAndCheckNotFound(n0);
WaitAndCheckNotFound(not_found);
WaitAndCheckNotFound(n1);
}
} // namespace net_instaweb
<|endoftext|> |
<commit_before>/** @file
@brief Implementation
@date 2015
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2015 Sensics, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Internal Includes
#include <osvr/PluginKit/SkeletonInterfaceC.h>
#include <osvr/Connection/DeviceToken.h>
#include <osvr/Connection/DeviceInitObject.h>
#include <osvr/PluginHost/PluginSpecificRegistrationContext.h>
#include "HandleNullContext.h"
#include <osvr/Util/PointerWrapper.h>
#include <osvr/Common/SkeletonComponent.h>
#include <osvr/Util/Verbosity.h>
#include <osvr/Connection/DeviceInterfaceBase.h>
// Library/third-party includes
// - none
// Standard includes
// - none
struct OSVR_SkeletonDeviceInterfaceObject
: public osvr::connection::DeviceInterfaceBase {
osvr::common::SkeletonComponent *skeleton;
};
OSVR_ReturnCode
osvrDeviceSkeletonConfigure(OSVR_INOUT_PTR OSVR_DeviceInitOptions opts,
OSVR_OUT_PTR OSVR_SkeletonDeviceInterface *iface,
OSVR_IN OSVR_ChannelCount numSensors) {
OSVR_PLUGIN_HANDLE_NULL_CONTEXT("osvrDeviceSkeletonConfigure", opts);
OSVR_PLUGIN_HANDLE_NULL_CONTEXT("osvrDeviceSkeletonConfigure", iface);
OSVR_SkeletonDeviceInterface ifaceObj =
opts->makeInterfaceObject<OSVR_SkeletonDeviceInterfaceObject>();
*iface = ifaceObj;
auto skeleton = osvr::common::SkeletonComponent::create();
ifaceObj->skeleton = skeleton.get();
opts->addComponent(skeleton);
return OSVR_RETURN_SUCCESS;
}
OSVR_ReturnCode
osvrDeviceSkeletonComplete(OSVR_IN_PTR OSVR_SkeletonDeviceInterface iface,
OSVR_IN OSVR_ChannelCount sensor,
OSVR_IN_PTR OSVR_TimeValue const *timestamp) {
auto guard = iface->getSendGuard();
if (guard->lock()) {
iface->skeleton->sendNotification(sensor, *timestamp);
return OSVR_RETURN_SUCCESS;
}
return OSVR_RETURN_FAILURE;
}
<commit_msg>pass number of sensors to skeleton component<commit_after>/** @file
@brief Implementation
@date 2015
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2015 Sensics, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Internal Includes
#include <osvr/PluginKit/SkeletonInterfaceC.h>
#include <osvr/Connection/DeviceToken.h>
#include <osvr/Connection/DeviceInitObject.h>
#include <osvr/PluginHost/PluginSpecificRegistrationContext.h>
#include "HandleNullContext.h"
#include <osvr/Util/PointerWrapper.h>
#include <osvr/Common/SkeletonComponent.h>
#include <osvr/Util/Verbosity.h>
#include <osvr/Connection/DeviceInterfaceBase.h>
// Library/third-party includes
// - none
// Standard includes
// - none
struct OSVR_SkeletonDeviceInterfaceObject
: public osvr::connection::DeviceInterfaceBase {
osvr::common::SkeletonComponent *skeleton;
};
OSVR_ReturnCode
osvrDeviceSkeletonConfigure(OSVR_INOUT_PTR OSVR_DeviceInitOptions opts,
OSVR_OUT_PTR OSVR_SkeletonDeviceInterface *iface,
OSVR_IN OSVR_ChannelCount numSensors) {
OSVR_PLUGIN_HANDLE_NULL_CONTEXT("osvrDeviceSkeletonConfigure", opts);
OSVR_PLUGIN_HANDLE_NULL_CONTEXT("osvrDeviceSkeletonConfigure", iface);
OSVR_SkeletonDeviceInterface ifaceObj =
opts->makeInterfaceObject<OSVR_SkeletonDeviceInterfaceObject>();
*iface = ifaceObj;
auto skeleton = osvr::common::SkeletonComponent::create(numSensors);
ifaceObj->skeleton = skeleton.get();
opts->addComponent(skeleton);
return OSVR_RETURN_SUCCESS;
}
OSVR_ReturnCode
osvrDeviceSkeletonComplete(OSVR_IN_PTR OSVR_SkeletonDeviceInterface iface,
OSVR_IN OSVR_ChannelCount sensor,
OSVR_IN_PTR OSVR_TimeValue const *timestamp) {
auto guard = iface->getSendGuard();
if (guard->lock()) {
iface->skeleton->sendNotification(sensor, *timestamp);
return OSVR_RETURN_SUCCESS;
}
return OSVR_RETURN_FAILURE;
}
<|endoftext|> |
<commit_before>// $Id$
/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Authors: Matthias Richter <Matthias.Richter@ift.uib.no> *
* Timm Steinbeck <timm@kip.uni-heidelberg.de> *
* for The ALICE Off-line Project. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
///////////////////////////////////////////////////////////////////////////////
// //
// a TPC cluster finder processing component for the HLT //
// //
///////////////////////////////////////////////////////////////////////////////
#if __GNUC__== 3
using namespace std;
#endif
#include "AliHLTTPCRawDataUnpackerComponent.h"
#include "AliTPCRawStream.h"
#include "AliRawDataHeader.h"
#include "AliRawReaderMemory.h"
#include "AliHLTTPCRawDataFormat.h"
#include "AliL3DigitData.h"
#include "AliL3Transform.h"
#include <stdlib.h>
#include <errno.h>
// this is a global object used for automatic component registration, do not use this
AliHLTTPCRawDataUnpackerComponent gAliHLTTPCRawDataUnpackerComponent;
ClassImp(AliHLTTPCRawDataUnpackerComponent)
AliHLTTPCRawDataUnpackerComponent::AliHLTTPCRawDataUnpackerComponent()
{
fRawMemoryReader = NULL;
fTPCRawStream = NULL;
}
AliHLTTPCRawDataUnpackerComponent::~AliHLTTPCRawDataUnpackerComponent()
{
}
// Public functions to implement AliHLTComponent's interface.
// These functions are required for the registration process
const char* AliHLTTPCRawDataUnpackerComponent::GetComponentID()
{
return "TPCRawDataUnpacker";
}
void AliHLTTPCRawDataUnpackerComponent::GetInputDataTypes( vector<AliHLTComponent_DataType>& list)
{
list.clear();
list.push_back( AliHLTTPCDefinitions::gkPackedRawDataType );
}
AliHLTComponent_DataType AliHLTTPCRawDataUnpackerComponent::GetOutputDataType()
{
return AliHLTTPCDefinitions::gkUnpackedRawDataType;
}
void AliHLTTPCRawDataUnpackerComponent::GetOutputDataSize( unsigned long& constBase, double& inputMultiplier )
{
// XXX TODO: Find more realistic values.
constBase = 0;
inputMultiplier = 3.0;
}
AliHLTComponent* AliHLTTPCRawDataUnpackerComponent::Spawn()
{
return new AliHLTTPCRawDataUnpackerComponent;
}
int AliHLTTPCRawDataUnpackerComponent::DoInit( int argc, const char** argv )
{
if ( fRawMemoryReader || fTPCRawStream )
return EINPROGRESS;
int i = 0;
const char* tableFileBaseDir = NULL;
while ( i < argc )
{
if ( !strcmp( argv[i], "-table-dir" ) )
{
if ( i+1>=argc )
{
Logging(kHLTLogError, "HLT::TPCRawDataUnpacker::DoInit", "Missing Argument", "Missing -table-dir parameter");
return ENOTSUP;
}
tableFileBaseDir = argv[i+1];
i += 2;
continue;
}
Logging(kHLTLogError, "HLT::TPCRawDataUnpacker::DoInit", "Unknown Option", "Unknown option '%s'", argv[i] );
return EINVAL;
}
if ( !tableFileBaseDir )
{
Logging(kHLTLogError, "HLT::TPCRawDataUnpacker::DoInit", "Table file directory missing ",
"Table file base directory has to be set using the -table-dir component parameter." );
return EINVAL;
}
fRawMemoryReader = new AliRawReaderMemory;
//fTPCRawStream = new AliTPCRawStream( fRawMemoryReader, tableFileBaseDir );
fTPCRawStream = new AliTPCRawStream( fRawMemoryReader );
return 0;
}
int AliHLTTPCRawDataUnpackerComponent::DoDeinit()
{
if ( fRawMemoryReader )
delete fRawMemoryReader;
fRawMemoryReader = NULL;
if ( fTPCRawStream )
delete fTPCRawStream;
fTPCRawStream = NULL;
return 0;
}
int AliHLTTPCRawDataUnpackerComponent::DoEvent( const AliHLTComponent_EventData& evtData, const AliHLTComponent_BlockData* blocks,
AliHLTComponent_TriggerData& trigData, AliHLTUInt8_t* outputPtr,
AliHLTUInt32_t& size, vector<AliHLTComponent_BlockData>& outputBlocks )
{
const AliHLTComponent_BlockData* iter = NULL;
unsigned long ndx;
AliHLTUInt8_t* outBPtr;
AliHLTTPCUnpackedRawData* outPtr;
AliL3DigitRowData* currentRow;
AliL3DigitData* currentDigit;
unsigned long long outputSize = 0;
unsigned long blockOutputSize = 0;
unsigned long rowSize = 0;
Int_t slice, patch, row[2];
outBPtr = outputPtr;
outPtr = (AliHLTTPCUnpackedRawData*)outputPtr;
currentRow = outPtr->fDigits;
currentDigit = currentRow->fDigitData;
for ( ndx = 0; ndx < evtData.fBlockCnt; ndx++ )
{
iter = blocks+ndx;
if ( iter->fDataType != AliHLTTPCDefinitions::gkDDLPackedRawDataType )
{
continue;
}
slice = AliHLTTPCDefinitions::GetMinSliceNr( *iter );
patch = AliHLTTPCDefinitions::GetMinPatchNr( *iter );
row[0] = AliL3Transform::GetFirstRow( patch );
row[1] = AliL3Transform::GetLastRow( patch );
blockOutputSize = 0;
fRawMemoryReader->SetMemory( reinterpret_cast<UChar_t*>( iter->fPtr ), iter->fSize );
bool readValue = true;
readValue = fTPCRawStream->Next();
int row = -1, oldRow = -1;
Int_t rowOffset = 0;
if ( patch >= 2 ) // Outer sector, patches 2, 3, 4, 5
rowOffset = AliL3Transform::GetFirstRow( 2 );
while ( readValue )
{
row = fTPCRawStream->GetRow();
if ( row != oldRow )
{
if ( oldRow!=-1 && rowSize != sizeof(AliL3DigitRowData)+currentRow->fNDigit*sizeof(AliL3DigitData) )
{
Logging( kHLTLogFatal, "TPCRawDataUnpackerSubscriber::ProcessEvent", "Size inconsistency",
"Size inconsistency for row %d data: %lu != %lu (%lu digits).", oldRow, rowSize,
sizeof(AliL3DigitRowData)+currentRow->fNDigit*sizeof(AliL3DigitData), currentRow->fNDigit );
}
rowSize = 0;
if ( size < outputSize+sizeof(AliL3DigitRowData) )
{
Logging( kHLTLogFatal, "TPCRawDataUnpackerSubscriber::ProcessEvent", "Too much data",
"Output data too big, output memory full. Aborting event 0x%08lX (%lu)" ,
evtData.fEventID, evtData.fEventID );
return 0;
}
currentRow = (AliL3DigitRowData*)(outBPtr+outputSize);
currentDigit = currentRow->fDigitData;
currentRow->fRow = row+rowOffset;
currentRow->fNDigit = 0;
oldRow = row;
outputSize += sizeof(AliL3DigitRowData);
blockOutputSize += sizeof(AliL3DigitRowData);
rowSize += sizeof(AliL3DigitRowData);
}
if ( size < outputSize+sizeof(AliL3DigitData) )
{
Logging( kHLTLogFatal, "TPCRawDataUnpackerSubscriber::ProcessEvent", "Too much data",
"Output data too big, output memory full. Aborting event 0x%08lX (%lu)" ,
evtData.fEventID, evtData.fEventID );
return 0;
}
currentDigit->fCharge = fTPCRawStream->GetSignal();
currentDigit->fPad = fTPCRawStream->GetPad();
currentDigit->fTime = fTPCRawStream->GetTime();
currentRow->fNDigit++;
currentDigit++;
outputSize += sizeof(AliL3DigitData);
blockOutputSize += sizeof(AliL3DigitData);
rowSize += sizeof(AliL3DigitData);
readValue = fTPCRawStream->Next();
}
if ( oldRow!=-1 && rowSize != sizeof(AliL3DigitRowData)+currentRow->fNDigit*sizeof(AliL3DigitData) )
{
Logging( kHLTLogFatal, "TPCRawDataUnpackerSubscriber::ProcessEvent", "Size inconsistency",
"Size inconsistency for row %d data: %lu != %lu (%lu digits).", oldRow, rowSize,
sizeof(AliL3DigitRowData)+currentRow->fNDigit*sizeof(AliL3DigitData), currentRow->fNDigit );
}
AliHLTComponent_BlockData bd;
FillBlockData( bd );
bd.fOffset = outputSize-blockOutputSize;
bd.fSize = blockOutputSize;
bd.fSpecification = iter->fSpecification;
//AliHLTSubEventDescriptor::FillBlockAttributes( bd.fAttributes );
outputBlocks.push_back( bd );
}
size = outputSize;
return 0;
}
<commit_msg>Removed the table directory component parameter for the TPC raw data unpacker component. (Uses $ALCIE_ROOT as a base dir in current versions of the AliRoot RAW package)<commit_after>// $Id$
/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Authors: Matthias Richter <Matthias.Richter@ift.uib.no> *
* Timm Steinbeck <timm@kip.uni-heidelberg.de> *
* for The ALICE Off-line Project. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
///////////////////////////////////////////////////////////////////////////////
// //
// a TPC cluster finder processing component for the HLT //
// //
///////////////////////////////////////////////////////////////////////////////
#if __GNUC__== 3
using namespace std;
#endif
#include "AliHLTTPCRawDataUnpackerComponent.h"
#include "AliTPCRawStream.h"
#include "AliRawDataHeader.h"
#include "AliRawReaderMemory.h"
#include "AliHLTTPCRawDataFormat.h"
#include "AliL3DigitData.h"
#include "AliL3Transform.h"
#include <stdlib.h>
#include <errno.h>
// this is a global object used for automatic component registration, do not use this
AliHLTTPCRawDataUnpackerComponent gAliHLTTPCRawDataUnpackerComponent;
ClassImp(AliHLTTPCRawDataUnpackerComponent)
AliHLTTPCRawDataUnpackerComponent::AliHLTTPCRawDataUnpackerComponent()
{
fRawMemoryReader = NULL;
fTPCRawStream = NULL;
}
AliHLTTPCRawDataUnpackerComponent::~AliHLTTPCRawDataUnpackerComponent()
{
}
// Public functions to implement AliHLTComponent's interface.
// These functions are required for the registration process
const char* AliHLTTPCRawDataUnpackerComponent::GetComponentID()
{
return "TPCRawDataUnpacker";
}
void AliHLTTPCRawDataUnpackerComponent::GetInputDataTypes( vector<AliHLTComponent_DataType>& list)
{
list.clear();
list.push_back( AliHLTTPCDefinitions::gkPackedRawDataType );
}
AliHLTComponent_DataType AliHLTTPCRawDataUnpackerComponent::GetOutputDataType()
{
return AliHLTTPCDefinitions::gkUnpackedRawDataType;
}
void AliHLTTPCRawDataUnpackerComponent::GetOutputDataSize( unsigned long& constBase, double& inputMultiplier )
{
// XXX TODO: Find more realistic values.
constBase = 0;
inputMultiplier = 3.0;
}
AliHLTComponent* AliHLTTPCRawDataUnpackerComponent::Spawn()
{
return new AliHLTTPCRawDataUnpackerComponent;
}
int AliHLTTPCRawDataUnpackerComponent::DoInit( int argc, const char** argv )
{
if ( fRawMemoryReader || fTPCRawStream )
return EINPROGRESS;
int i = 0;
const char* tableFileBaseDir = NULL;
while ( i < argc )
{
// if ( !strcmp( argv[i], "-table-dir" ) )
// {
// if ( i+1>=argc )
// {
// Logging(kHLTLogError, "HLT::TPCRawDataUnpacker::DoInit", "Missing Argument", "Missing -table-dir parameter");
// return ENOTSUP;
// }
// tableFileBaseDir = argv[i+1];
// i += 2;
// continue;
// }
Logging(kHLTLogError, "HLT::TPCRawDataUnpacker::DoInit", "Unknown Option", "Unknown option '%s'", argv[i] );
return EINVAL;
}
// if ( !tableFileBaseDir )
// {
// Logging(kHLTLogError, "HLT::TPCRawDataUnpacker::DoInit", "Table file directory missing ",
// "Table file base directory has to be set using the -table-dir component parameter." );
// return EINVAL;
// }
fRawMemoryReader = new AliRawReaderMemory;
//fTPCRawStream = new AliTPCRawStream( fRawMemoryReader, tableFileBaseDir );
fTPCRawStream = new AliTPCRawStream( fRawMemoryReader );
return 0;
}
int AliHLTTPCRawDataUnpackerComponent::DoDeinit()
{
if ( fRawMemoryReader )
delete fRawMemoryReader;
fRawMemoryReader = NULL;
if ( fTPCRawStream )
delete fTPCRawStream;
fTPCRawStream = NULL;
return 0;
}
int AliHLTTPCRawDataUnpackerComponent::DoEvent( const AliHLTComponent_EventData& evtData, const AliHLTComponent_BlockData* blocks,
AliHLTComponent_TriggerData& trigData, AliHLTUInt8_t* outputPtr,
AliHLTUInt32_t& size, vector<AliHLTComponent_BlockData>& outputBlocks )
{
const AliHLTComponent_BlockData* iter = NULL;
unsigned long ndx;
AliHLTUInt8_t* outBPtr;
AliHLTTPCUnpackedRawData* outPtr;
AliL3DigitRowData* currentRow;
AliL3DigitData* currentDigit;
unsigned long long outputSize = 0;
unsigned long blockOutputSize = 0;
unsigned long rowSize = 0;
Int_t slice, patch, row[2];
outBPtr = outputPtr;
outPtr = (AliHLTTPCUnpackedRawData*)outputPtr;
currentRow = outPtr->fDigits;
currentDigit = currentRow->fDigitData;
for ( ndx = 0; ndx < evtData.fBlockCnt; ndx++ )
{
iter = blocks+ndx;
if ( iter->fDataType != AliHLTTPCDefinitions::gkDDLPackedRawDataType )
{
continue;
}
slice = AliHLTTPCDefinitions::GetMinSliceNr( *iter );
patch = AliHLTTPCDefinitions::GetMinPatchNr( *iter );
row[0] = AliL3Transform::GetFirstRow( patch );
row[1] = AliL3Transform::GetLastRow( patch );
blockOutputSize = 0;
fRawMemoryReader->SetMemory( reinterpret_cast<UChar_t*>( iter->fPtr ), iter->fSize );
bool readValue = true;
readValue = fTPCRawStream->Next();
int row = -1, oldRow = -1;
Int_t rowOffset = 0;
if ( patch >= 2 ) // Outer sector, patches 2, 3, 4, 5
rowOffset = AliL3Transform::GetFirstRow( 2 );
while ( readValue )
{
row = fTPCRawStream->GetRow();
if ( row != oldRow )
{
if ( oldRow!=-1 && rowSize != sizeof(AliL3DigitRowData)+currentRow->fNDigit*sizeof(AliL3DigitData) )
{
Logging( kHLTLogFatal, "TPCRawDataUnpackerSubscriber::ProcessEvent", "Size inconsistency",
"Size inconsistency for row %d data: %lu != %lu (%lu digits).", oldRow, rowSize,
sizeof(AliL3DigitRowData)+currentRow->fNDigit*sizeof(AliL3DigitData), currentRow->fNDigit );
}
rowSize = 0;
if ( size < outputSize+sizeof(AliL3DigitRowData) )
{
Logging( kHLTLogFatal, "TPCRawDataUnpackerSubscriber::ProcessEvent", "Too much data",
"Output data too big, output memory full. Aborting event 0x%08lX (%lu)" ,
evtData.fEventID, evtData.fEventID );
return 0;
}
currentRow = (AliL3DigitRowData*)(outBPtr+outputSize);
currentDigit = currentRow->fDigitData;
currentRow->fRow = row+rowOffset;
currentRow->fNDigit = 0;
oldRow = row;
outputSize += sizeof(AliL3DigitRowData);
blockOutputSize += sizeof(AliL3DigitRowData);
rowSize += sizeof(AliL3DigitRowData);
}
if ( size < outputSize+sizeof(AliL3DigitData) )
{
Logging( kHLTLogFatal, "TPCRawDataUnpackerSubscriber::ProcessEvent", "Too much data",
"Output data too big, output memory full. Aborting event 0x%08lX (%lu)" ,
evtData.fEventID, evtData.fEventID );
return 0;
}
currentDigit->fCharge = fTPCRawStream->GetSignal();
currentDigit->fPad = fTPCRawStream->GetPad();
currentDigit->fTime = fTPCRawStream->GetTime();
currentRow->fNDigit++;
currentDigit++;
outputSize += sizeof(AliL3DigitData);
blockOutputSize += sizeof(AliL3DigitData);
rowSize += sizeof(AliL3DigitData);
readValue = fTPCRawStream->Next();
}
if ( oldRow!=-1 && rowSize != sizeof(AliL3DigitRowData)+currentRow->fNDigit*sizeof(AliL3DigitData) )
{
Logging( kHLTLogFatal, "TPCRawDataUnpackerSubscriber::ProcessEvent", "Size inconsistency",
"Size inconsistency for row %d data: %lu != %lu (%lu digits).", oldRow, rowSize,
sizeof(AliL3DigitRowData)+currentRow->fNDigit*sizeof(AliL3DigitData), currentRow->fNDigit );
}
AliHLTComponent_BlockData bd;
FillBlockData( bd );
bd.fOffset = outputSize-blockOutputSize;
bd.fSize = blockOutputSize;
bd.fSpecification = iter->fSpecification;
//AliHLTSubEventDescriptor::FillBlockAttributes( bd.fAttributes );
outputBlocks.push_back( bd );
}
size = outputSize;
return 0;
}
<|endoftext|> |
<commit_before>// -*- C++ -*-
//
// ----------------------------------------------------------------------
//
// Brad T. Aagaard
// U.S. Geological Survey
//
// <LicenseText>
//
// ----------------------------------------------------------------------
//
#include <portinfo>
#include "SpatialDB.hh" // ISA SpatialDB object
#include "SimpleDB.hh" // Implementation of class methods
#include "SimpleIO.hh" // USES SimpleIO
#include "SimpleDBQuery.hh" // USES SimpleDBQuery
#include "SimpleDBTypes.hh" // USES SimpleDBTypes
#include "spatialdata/geocoords/CoordSys.hh" // USES CoordSys
#include <stdexcept> // USES std::runtime_error
#include "Exception.hh" // USES OutOfBounds
#include <sstream> // USES std::ostringsgream
#include <assert.h> // USES assert()
// ----------------------------------------------------------------------
/// Default constructor
spatialdata::spatialdb::SimpleDB::SimpleDB(void) :
_iohandler(0),
_query(0),
_data(0),
_cs(0)
{ // constructor
} // constructor
// ----------------------------------------------------------------------
/// Constructor with label
spatialdata::spatialdb::SimpleDB::SimpleDB(const char* label) :
SpatialDB(label),
_iohandler(0),
_query(0),
_data(0),
_cs(0)
{ // constructor
} // constructor
// ----------------------------------------------------------------------
/// Default destructor
spatialdata::spatialdb::SimpleDB::~SimpleDB(void)
{ // destructor
delete _query; _query = 0;
if (0 != _data) {
delete[] _data->data; _data->data = 0;
delete[] _data->valNames; _data->valNames = 0;
delete[] _data->valUnits; _data->valUnits = 0;
} // if
delete _data; _data = 0;
delete _iohandler; _iohandler = 0;
delete _cs; _cs = 0;
} // destructor
// ----------------------------------------------------------------------
/// Open the database and prepare for querying.
void
spatialdata::spatialdb::SimpleDB::open(void)
{ // open
assert(0 != _iohandler);
// Read data
if (0 == _data) {
_data = new DataStruct;
_data->data = 0;
_data->valNames = 0;
_data->valUnits = 0;
_iohandler->read(_data, &_cs);
} // if
// Create query object
if (0 == _query)
_query = new SimpleDBQuery(*this);
} // open
// ----------------------------------------------------------------------
/// Close the database.
void
spatialdata::spatialdb::SimpleDB::close(void)
{ // close
delete _query; _query = 0;
if (0 != _data) {
delete[] _data->data; _data->data = 0;
delete[] _data->valNames; _data->valNames = 0;
delete[] _data->valUnits; _data->valUnits = 0;
} // if
delete _data; _data = 0;
} // close
// ----------------------------------------------------------------------
// Set query type.
void
spatialdata::spatialdb::SimpleDB::queryType(const SimpleDB::QueryEnum queryType)
{ // queryType
if (0 == _query)
_query = new SimpleDBQuery(*this);
_query->queryType(queryType);
} // QueryType
// ----------------------------------------------------------------------
// Set values to be returned by queries.
void
spatialdata::spatialdb::SimpleDB::queryVals(const char** names,
const int numVals)
{ // queryVals
if (0 == _query) {
std::ostringstream msg;
msg
<< "Spatial database " << label() << " has not been opened.\n"
<< "Please call Open() before calling QueryVals().";
throw std::runtime_error(msg.str());
} // if
_query->queryVals(names, numVals);
} // queryVals
// ----------------------------------------------------------------------
// Set the I/O handler.
void
spatialdata::spatialdb::SimpleDB::ioHandler(const SimpleIO* iohandler)
{ // ioHandler
_iohandler = iohandler->clone();
} // ioHandler
// ----------------------------------------------------------------------
// Query the database.
int
spatialdata::spatialdb::SimpleDB::query(double* vals,
const int numVals,
const double* coords,
const int numDims,
const spatialdata::geocoords::CoordSys* pCSQuery)
{ // query
try {
if (0 == _query) {
std::ostringstream msg;
msg
<< "Spatial database " << label() << " has not been opened.\n"
<< "Please call open() before calling query().";
throw std::runtime_error(msg.str());
} // if
else if (0 == _data) {
std::ostringstream msg;
msg
<< "Spatial database " << label() << " does not contain any data.\n"
<< "Database query aborted.";
throw std::runtime_error(msg.str());
} // if
_query->query(vals, numVals, coords, numDims, pCSQuery);
} catch(const OutOfBounds& err) {
std::fill(vals, vals+numVals, 0);
return 1;
} catch(std::exception& err) {
throw std::runtime_error(err.what());
} catch(...) {
throw std::runtime_error("Unknown error in SpatialDB query");
} // catch
return 0;
} // query
// End of file
<commit_msg>Fixed memory leak.<commit_after>// -*- C++ -*-
//
// ----------------------------------------------------------------------
//
// Brad T. Aagaard
// U.S. Geological Survey
//
// <LicenseText>
//
// ----------------------------------------------------------------------
//
#include <portinfo>
#include "SpatialDB.hh" // ISA SpatialDB object
#include "SimpleDB.hh" // Implementation of class methods
#include "SimpleIO.hh" // USES SimpleIO
#include "SimpleDBQuery.hh" // USES SimpleDBQuery
#include "SimpleDBTypes.hh" // USES SimpleDBTypes
#include "spatialdata/geocoords/CoordSys.hh" // USES CoordSys
#include <stdexcept> // USES std::runtime_error
#include "Exception.hh" // USES OutOfBounds
#include <sstream> // USES std::ostringsgream
#include <assert.h> // USES assert()
// ----------------------------------------------------------------------
/// Default constructor
spatialdata::spatialdb::SimpleDB::SimpleDB(void) :
_iohandler(0),
_query(0),
_data(0),
_cs(0)
{ // constructor
} // constructor
// ----------------------------------------------------------------------
/// Constructor with label
spatialdata::spatialdb::SimpleDB::SimpleDB(const char* label) :
SpatialDB(label),
_iohandler(0),
_query(0),
_data(0),
_cs(0)
{ // constructor
} // constructor
// ----------------------------------------------------------------------
/// Default destructor
spatialdata::spatialdb::SimpleDB::~SimpleDB(void)
{ // destructor
delete _query; _query = 0;
if (0 != _data) {
delete[] _data->data; _data->data = 0;
delete[] _data->valNames; _data->valNames = 0;
delete[] _data->valUnits; _data->valUnits = 0;
} // if
delete _data; _data = 0;
delete _iohandler; _iohandler = 0;
delete _cs; _cs = 0;
} // destructor
// ----------------------------------------------------------------------
/// Open the database and prepare for querying.
void
spatialdata::spatialdb::SimpleDB::open(void)
{ // open
assert(0 != _iohandler);
// Read data
if (0 == _data) {
_data = new DataStruct;
_data->data = 0;
_data->valNames = 0;
_data->valUnits = 0;
_iohandler->read(_data, &_cs);
} // if
// Create query object
if (0 == _query)
_query = new SimpleDBQuery(*this);
} // open
// ----------------------------------------------------------------------
/// Close the database.
void
spatialdata::spatialdb::SimpleDB::close(void)
{ // close
delete _query; _query = 0;
if (0 != _data) {
delete[] _data->data; _data->data = 0;
delete[] _data->valNames; _data->valNames = 0;
delete[] _data->valUnits; _data->valUnits = 0;
} // if
delete _data; _data = 0;
} // close
// ----------------------------------------------------------------------
// Set query type.
void
spatialdata::spatialdb::SimpleDB::queryType(const SimpleDB::QueryEnum queryType)
{ // queryType
if (0 == _query)
_query = new SimpleDBQuery(*this);
_query->queryType(queryType);
} // QueryType
// ----------------------------------------------------------------------
// Set values to be returned by queries.
void
spatialdata::spatialdb::SimpleDB::queryVals(const char** names,
const int numVals)
{ // queryVals
if (0 == _query) {
std::ostringstream msg;
msg
<< "Spatial database " << label() << " has not been opened.\n"
<< "Please call Open() before calling QueryVals().";
throw std::runtime_error(msg.str());
} // if
_query->queryVals(names, numVals);
} // queryVals
// ----------------------------------------------------------------------
// Set the I/O handler.
void
spatialdata::spatialdb::SimpleDB::ioHandler(const SimpleIO* iohandler)
{ // ioHandler
delete _iohandler; _iohandler = (0 != iohandler) ? iohandler->clone() : 0;
} // ioHandler
// ----------------------------------------------------------------------
// Query the database.
int
spatialdata::spatialdb::SimpleDB::query(double* vals,
const int numVals,
const double* coords,
const int numDims,
const spatialdata::geocoords::CoordSys* pCSQuery)
{ // query
try {
if (0 == _query) {
std::ostringstream msg;
msg
<< "Spatial database " << label() << " has not been opened.\n"
<< "Please call open() before calling query().";
throw std::runtime_error(msg.str());
} // if
else if (0 == _data) {
std::ostringstream msg;
msg
<< "Spatial database " << label() << " does not contain any data.\n"
<< "Database query aborted.";
throw std::runtime_error(msg.str());
} // if
_query->query(vals, numVals, coords, numDims, pCSQuery);
} catch(const OutOfBounds& err) {
std::fill(vals, vals+numVals, 0);
return 1;
} catch(std::exception& err) {
throw std::runtime_error(err.what());
} catch(...) {
throw std::runtime_error("Unknown error in SpatialDB query");
} // catch
return 0;
} // query
// End of file
<|endoftext|> |
<commit_before>#include "GarageDoor/GPIO/Manager.h"
GarageDoor::GPIO::Manager::Manager()
{
LoadPins();
}
void GarageDoor::GPIO::Manager::LoadPins()
{
std::string path = "/sys/class/gpio_hw";
std::vector<std::string> dirList = GarageDoor::Filesystem::ListDirectory(path);
std::cout << "Dirs found: " << dirList.size() << std::endl;
}
<commit_msg>God damn misspelling<commit_after>#include "GarageDoor/GPIO/Manager.h"
GarageDoor::GPIO::Manager::Manager()
{
LoadPins();
}
void GarageDoor::GPIO::Manager::LoadPins()
{
std::string path = "/sys/class/gpio_sw";
std::vector<std::string> dirList = GarageDoor::Filesystem::ListDirectory(path);
std::cout << "Dirs found: " << dirList.size() << std::endl;
}
<|endoftext|> |
<commit_before>/******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
#define SUITE table_index
#include "test.hpp"
#include "fixtures/events.hpp"
#include "fixtures/filesystem.hpp"
#include "vast/bitmap.hpp"
#include "vast/concept/parseable/to.hpp"
#include "vast/concept/parseable/vast/expression.hpp"
#include "vast/concept/printable/stream.hpp"
#include "vast/concept/printable/vast/error.hpp"
#include "vast/concept/printable/vast/event.hpp"
#include "vast/concept/printable/vast/expression.hpp"
#include "vast/default_table_slice.hpp"
#include "vast/table_index.hpp"
using namespace vast;
namespace {
struct fixture : fixtures::events, fixtures::filesystem {
template <class T>
T unbox(expected<T> x) {
if (!x)
FAIL("error: " << x.error());
return std::move(*x);
}
ids query(std::string_view what) {
return unbox(tbl->lookup(unbox(to<expression>(what))));
}
void reset(table_index&& new_tbl) {
tbl = std::make_unique<table_index>(std::move(new_tbl));
}
void reset(expected<table_index>&& new_tbl) {
if (!new_tbl)
FAIL("error: " << new_tbl.error());
reset(std::move(*new_tbl));
}
void add(const_table_slice_ptr x) {
auto err = tbl->add(x);
if (err)
FAIL("error: " << err);
}
std::unique_ptr<table_index> tbl;
};
} // namespace <anonymous>
FIXTURE_SCOPE(table_index_tests, fixture)
TEST(integer values) {
MESSAGE("generate table layout for flat integer type");
integer_type column_type;
record_type layout{{"value", column_type}};
reset(make_table_index(directory, layout));
MESSAGE("ingest test data (integers)");
auto rows = make_rows(1, 2, 3, 1, 2, 3, 1, 2, 3);
auto slice = default_table_slice::make(layout, rows);
REQUIRE_NOT_EQUAL(slice.get(), nullptr);
REQUIRE_EQUAL(slice->columns(), 1u);
REQUIRE_EQUAL(slice->rows(), rows.size());
add(slice);
auto res = [&](auto... args) {
return make_ids({args...}, rows.size());
};
MESSAGE("verify table index");
auto verify = [&] {
CHECK_EQUAL(query("value == +1"), res(0, 3, 6));
CHECK_EQUAL(query(":int == +1"), res(0, 3, 6));
CHECK_EQUAL(query(":int == +2"), res(1, 4, 7));
CHECK_EQUAL(query(":int == +3"), res(2, 5, 8));
CHECK_EQUAL(query(":int == +4"), res());
CHECK_EQUAL(query(":int != +1"), res(1, 2, 4, 5, 7, 8));
CHECK_EQUAL(query("!(:int == +1)"), res(1, 2, 4, 5, 7, 8));
CHECK_EQUAL(query(":int > +1 && :int < +3"), res(1, 4, 7));
};
verify();
MESSAGE("(automatically) persist table index and restore from disk");
reset(make_table_index(directory, layout));
MESSAGE("verify table index again");
verify();
}
TEST(record type) {
MESSAGE("generate table layout for record type");
record_type layout {
{"x.a", integer_type{}},
{"x.b", boolean_type{}},
{"y.a", string_type{}},
};
reset(make_table_index(directory, layout));
MESSAGE("ingest test data (records)");
auto mk_row = [&](int x, bool y, std::string z) {
return vector{x, y, std::move(z)};
};
// Some test data.
std::vector<vector> rows{mk_row(1, true, "abc"), mk_row(10, false, "def"),
mk_row(5, true, "hello"), mk_row(1, true, "d e f"),
mk_row(15, true, "world"), mk_row(5, true, "bar"),
mk_row(10, false, "a b c"), mk_row(10, false, "baz"),
mk_row(5, false, "foo"), mk_row(1, true, "test")};
auto slice = default_table_slice::make(layout, rows);
REQUIRE_EQUAL(slice->rows(), rows.size());
REQUIRE_EQUAL(slice->columns(), 3u);
add(slice);
auto res = [&](auto... args) {
return make_ids({args...}, rows.size());
};
MESSAGE("verify table index");
auto verify = [&] {
CHECK_EQUAL(query("x.a == +1"), res(0, 3, 9));
CHECK_EQUAL(query("x.a > +1"), res(1, 2, 4, 5, 6, 7, 8));
CHECK_EQUAL(query("x.a > +1 && x.b == T"), res(2, 4, 5));
};
verify();
MESSAGE("(automatically) persist table index and restore from disk");
reset(make_table_index(directory, layout));
MESSAGE("verify table index again");
verify();
}
TEST(bro conn logs) {
MESSAGE("generate table layout for bro conn logs");
auto layout = bro_conn_log_layout();
reset(make_table_index(directory, layout));
MESSAGE("ingest test data (bro conn log)");
for (auto slice : const_bro_conn_log_slices)
add(slice);
MESSAGE("verify table index");
auto verify = [&] {
CHECK_EQUAL(rank(query("id.resp_p == 995/?")), 53u);
CHECK_EQUAL(rank(query("id.resp_p == 5355/?")), 49u);
CHECK_EQUAL(rank(query("id.resp_p == 995/? || id.resp_p == 5355/?")), 102u);
CHECK_EQUAL(rank(query("&time > 1970-01-01")), bro_conn_log.size());
CHECK_EQUAL(rank(query("proto == \"udp\"")), 5306u);
CHECK_EQUAL(rank(query("proto == \"tcp\"")), 3135u);
CHECK_EQUAL(rank(query("uid == \"nkCxlvNN8pi\"")), 1u);
CHECK_EQUAL(rank(query("orig_bytes < 400")), 5332u);
CHECK_EQUAL(rank(query("orig_bytes < 400 && proto == \"udp\"")), 4357u);
CHECK_EQUAL(rank(query(":addr == 169.254.225.22")), 4u);
CHECK_EQUAL(rank(query("service == \"http\"")), 2386u);
CHECK_EQUAL(rank(query("service == \"http\" && :addr == 212.227.96.110")),
28u);
};
verify();
MESSAGE("(automatically) persist table index and restore from disk");
reset(make_table_index(directory, layout));
MESSAGE("verify table index again");
verify();
}
FIXTURE_SCOPE_END()
<commit_msg>Reproduce faulty HTTP lookups in table_index<commit_after>/******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
#define SUITE table_index
#include "test.hpp"
#include "fixtures/events.hpp"
#include "fixtures/filesystem.hpp"
#include "vast/bitmap.hpp"
#include "vast/concept/parseable/to.hpp"
#include "vast/concept/parseable/vast/expression.hpp"
#include "vast/concept/printable/stream.hpp"
#include "vast/concept/printable/vast/error.hpp"
#include "vast/concept/printable/vast/event.hpp"
#include "vast/concept/printable/vast/expression.hpp"
#include "vast/default_table_slice.hpp"
#include "vast/table_index.hpp"
using namespace vast;
namespace {
struct fixture : fixtures::events, fixtures::filesystem {
template <class T>
T unbox(expected<T> x) {
if (!x)
FAIL("error: " << x.error());
return std::move(*x);
}
ids query(std::string_view what) {
return unbox(tbl->lookup(unbox(to<expression>(what))));
}
void reset(table_index&& new_tbl) {
tbl = std::make_unique<table_index>(std::move(new_tbl));
}
void reset(expected<table_index>&& new_tbl) {
if (!new_tbl)
FAIL("error: " << new_tbl.error());
reset(std::move(*new_tbl));
}
void add(const_table_slice_ptr x) {
auto err = tbl->add(x);
if (err)
FAIL("error: " << err);
}
std::unique_ptr<table_index> tbl;
};
} // namespace <anonymous>
FIXTURE_SCOPE(table_index_tests, fixture)
TEST(integer values) {
MESSAGE("generate table layout for flat integer type");
integer_type column_type;
record_type layout{{"value", column_type}};
reset(make_table_index(directory, layout));
MESSAGE("ingest test data (integers)");
auto rows = make_rows(1, 2, 3, 1, 2, 3, 1, 2, 3);
auto slice = default_table_slice::make(layout, rows);
REQUIRE_NOT_EQUAL(slice.get(), nullptr);
REQUIRE_EQUAL(slice->columns(), 1u);
REQUIRE_EQUAL(slice->rows(), rows.size());
add(slice);
auto res = [&](auto... args) {
return make_ids({args...}, rows.size());
};
MESSAGE("verify table index");
auto verify = [&] {
CHECK_EQUAL(query("value == +1"), res(0, 3, 6));
CHECK_EQUAL(query(":int == +1"), res(0, 3, 6));
CHECK_EQUAL(query(":int == +2"), res(1, 4, 7));
CHECK_EQUAL(query(":int == +3"), res(2, 5, 8));
CHECK_EQUAL(query(":int == +4"), res());
CHECK_EQUAL(query(":int != +1"), res(1, 2, 4, 5, 7, 8));
CHECK_EQUAL(query("!(:int == +1)"), res(1, 2, 4, 5, 7, 8));
CHECK_EQUAL(query(":int > +1 && :int < +3"), res(1, 4, 7));
};
verify();
MESSAGE("(automatically) persist table index and restore from disk");
reset(make_table_index(directory, layout));
MESSAGE("verify table index again");
verify();
}
TEST(record type) {
MESSAGE("generate table layout for record type");
record_type layout {
{"x.a", integer_type{}},
{"x.b", boolean_type{}},
{"y.a", string_type{}},
};
reset(make_table_index(directory, layout));
MESSAGE("ingest test data (records)");
auto mk_row = [&](int x, bool y, std::string z) {
return vector{x, y, std::move(z)};
};
// Some test data.
std::vector<vector> rows{mk_row(1, true, "abc"), mk_row(10, false, "def"),
mk_row(5, true, "hello"), mk_row(1, true, "d e f"),
mk_row(15, true, "world"), mk_row(5, true, "bar"),
mk_row(10, false, "a b c"), mk_row(10, false, "baz"),
mk_row(5, false, "foo"), mk_row(1, true, "test")};
auto slice = default_table_slice::make(layout, rows);
REQUIRE_EQUAL(slice->rows(), rows.size());
REQUIRE_EQUAL(slice->columns(), 3u);
add(slice);
auto res = [&](auto... args) {
return make_ids({args...}, rows.size());
};
MESSAGE("verify table index");
auto verify = [&] {
CHECK_EQUAL(query("x.a == +1"), res(0, 3, 9));
CHECK_EQUAL(query("x.a > +1"), res(1, 2, 4, 5, 6, 7, 8));
CHECK_EQUAL(query("x.a > +1 && x.b == T"), res(2, 4, 5));
};
verify();
MESSAGE("(automatically) persist table index and restore from disk");
reset(make_table_index(directory, layout));
MESSAGE("verify table index again");
verify();
}
TEST(bro conn logs) {
MESSAGE("generate table layout for bro conn logs");
auto layout = bro_conn_log_layout();
reset(make_table_index(directory, layout));
MESSAGE("ingest test data (bro conn log)");
for (auto slice : const_bro_conn_log_slices)
add(slice);
MESSAGE("verify table index");
auto verify = [&] {
CHECK_EQUAL(rank(query("id.resp_p == 995/?")), 53u);
CHECK_EQUAL(rank(query("id.resp_p == 5355/?")), 49u);
CHECK_EQUAL(rank(query("id.resp_p == 995/? || id.resp_p == 5355/?")), 102u);
CHECK_EQUAL(rank(query("&time > 1970-01-01")), bro_conn_log.size());
CHECK_EQUAL(rank(query("proto == \"udp\"")), 5306u);
CHECK_EQUAL(rank(query("proto == \"tcp\"")), 3135u);
CHECK_EQUAL(rank(query("uid == \"nkCxlvNN8pi\"")), 1u);
CHECK_EQUAL(rank(query("orig_bytes < 400")), 5332u);
CHECK_EQUAL(rank(query("orig_bytes < 400 && proto == \"udp\"")), 4357u);
CHECK_EQUAL(rank(query(":addr == 169.254.225.22")), 4u);
CHECK_EQUAL(rank(query("service == \"http\"")), 2386u);
CHECK_EQUAL(rank(query("service == \"http\" && :addr == 212.227.96.110")),
28u);
};
verify();
MESSAGE("(automatically) persist table index and restore from disk");
reset(make_table_index(directory, layout));
MESSAGE("verify table index again");
verify();
}
TEST(bro conn log http slices) {
MESSAGE("scrutinize each bro conn log slice individually");
// Pre-computed via:
// grep http libvast/test/logs/bro/conn.log -n
// | awk -F ':' '{tbl[int($1 / 100)] += 1}
// END { for (key in tbl) { print key " " tbl[key] } }'
// | sort -n
// | awk '{print $2","}'
std::vector<size_t> hits{
9, 20, 14, 28, 31, 7, 15, 28, 16, 41, 40, 51, 61, 50, 65, 58, 54,
24, 26, 30, 20, 30, 8, 57, 48, 57, 30, 55, 22, 25, 34, 35, 40, 59,
40, 23, 31, 26, 27, 53, 26, 5, 56, 35, 1, 5, 7, 10, 4, 44, 48,
2, 9, 7, 1, 13, 4, 2, 13, 2, 33, 36, 16, 43, 50, 30, 38, 13,
92, 70, 73, 67, 5, 53, 21, 8, 2, 2, 22, 7, 2, 14, 7,
};
auto layout = bro_conn_log_layout();
REQUIRE_EQUAL(std::accumulate(hits.begin(), hits.end(), size_t(0)), 2386u);
for (size_t slice_id = 0; slice_id < hits.size(); ++slice_id) {
tbl.reset();
rm(directory);
reset(make_table_index(directory, layout));
add(const_bro_conn_log_slices[slice_id]);
CHECK_EQUAL(rank(query("service == \"http\"")), hits[slice_id]);
}
}
FIXTURE_SCOPE_END()
<|endoftext|> |
<commit_before>/**
* @file callbacks.hpp
* @brief Callbacks for histograms computation.
* @author Paolo D'Apice
*/
#ifndef VIS_CALLBACKS_HPP
#define VIS_CALLBACKS_HPP
#include "callbacks_hog.hpp"
#include "descriptors_type.hpp"
#include "hsv.hpp"
namespace vis {
class Vocabulary;
/// @brief Base class for callbacks.
template <typename Derived, DescriptorsType t>
struct Callback {
/// DescriptorsType of the callback.
static const DescriptorsType type = t;
arma::fvec operator()(const cv::Mat& image) const {
return static_cast<Derived*>(this)->operator()(image);
}
size_t length() const {
return static_cast<Derived*>(this)->length();
}
};
/// Compute HOG bag-of-words.
struct HogBagOfWordsCallback : Callback<BagOfWords, vis::HOG> {
HogBagOfWordsCallback(const Vocabulary* v);
arma::fvec operator()(const cv::Mat& image) const;
size_t length() const { return bow.numWords(); }
private:
BagOfWords bow;
HogExtractor hog;
};
/// Compute HSV color histogram.
struct HsvHistogramsCallback : Callback<HsvHistogramsCallback, vis::HSV> {
HsvHistogramsCallback();
arma::fvec operator()(const cv::Mat& image) const;
size_t length() const { return hsv.getNumBins(); }
private:
HsvExtractor hsv;
};
/// Compute both HOG bag-of-words and HSV color histogram.
struct CompositeCallback : Callback<CompositeCallback, vis::HOG_HSV> {
CompositeCallback(const Vocabulary* v);
arma::fvec operator()(const cv::Mat& image) const;
size_t length() const { return hsv.length() + hog.length(); }
private:
HogBagOfWordsCallback hog;
HsvHistogramsCallback hsv;
};
} /* namespace vis */
#endif /* VIS_CALLBACKS_HPP */
<commit_msg>Fix wrong template in HogBagOfWordsCallback<commit_after>/**
* @file callbacks.hpp
* @brief Callbacks for histograms computation.
* @author Paolo D'Apice
*/
#ifndef VIS_CALLBACKS_HPP
#define VIS_CALLBACKS_HPP
#include "callbacks_hog.hpp"
#include "descriptors_type.hpp"
#include "hsv.hpp"
namespace vis {
class Vocabulary;
/// @brief Base class for callbacks.
template <typename Derived, DescriptorsType t>
struct Callback {
/// DescriptorsType of the callback.
static const DescriptorsType type = t;
arma::fvec operator()(const cv::Mat& image) const {
return static_cast<Derived*>(this)->operator()(image);
}
size_t length() const {
return static_cast<Derived*>(this)->length();
}
};
/// Compute HOG bag-of-words.
struct HogBagOfWordsCallback : Callback<HogBagOfWordsCallback, vis::HOG> {
HogBagOfWordsCallback(const Vocabulary* v);
arma::fvec operator()(const cv::Mat& image) const;
size_t length() const { return bow.numWords(); }
private:
BagOfWords bow;
HogExtractor hog;
};
/// Compute HSV color histogram.
struct HsvHistogramsCallback : Callback<HsvHistogramsCallback, vis::HSV> {
HsvHistogramsCallback();
arma::fvec operator()(const cv::Mat& image) const;
size_t length() const { return hsv.getNumBins(); }
private:
HsvExtractor hsv;
};
/// Compute both HOG bag-of-words and HSV color histogram.
struct CompositeCallback : Callback<CompositeCallback, vis::HOG_HSV> {
CompositeCallback(const Vocabulary* v);
arma::fvec operator()(const cv::Mat& image) const;
size_t length() const { return hsv.length() + hog.length(); }
private:
HogBagOfWordsCallback hog;
HsvHistogramsCallback hsv;
};
} /* namespace vis */
#endif /* VIS_CALLBACKS_HPP */
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: lngreg.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: obo $ $Date: 2006-09-17 03:54:25 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* 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
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_linguistic.hxx"
#include <cppuhelper/factory.hxx> // helper for factories
#ifndef _RTL_STRING_HXX_
#include <rtl/string.hxx>
#endif
#include <com/sun/star/registry/XRegistryKey.hpp>
using namespace com::sun::star::lang;
using namespace com::sun::star::registry;
////////////////////////////////////////
// declaration of external RegEntry-functions defined by the service objects
//
extern sal_Bool SAL_CALL LngSvcMgr_writeInfo
(
void * /*pServiceManager*/,
XRegistryKey * pRegistryKey
);
extern sal_Bool SAL_CALL DicList_writeInfo
(
void * /*pServiceManager*/, XRegistryKey * pRegistryKey
);
extern sal_Bool SAL_CALL LinguProps_writeInfo
(
void * /*pServiceManager*/,
XRegistryKey * pRegistryKey
);
extern sal_Bool SAL_CALL ConvDicList_writeInfo
(
void * /*pServiceManager*/, XRegistryKey * pRegistryKey
);
extern void * SAL_CALL LngSvcMgr_getFactory
(
const sal_Char * pImplName,
XMultiServiceFactory * pServiceManager,
void * /*pRegistryKey*/
);
extern void * SAL_CALL DicList_getFactory
(
const sal_Char * pImplName,
XMultiServiceFactory * pServiceManager,
void *
);
void * SAL_CALL LinguProps_getFactory
(
const sal_Char * pImplName,
XMultiServiceFactory * pServiceManager,
void *
);
extern void * SAL_CALL ConvDicList_getFactory
(
const sal_Char * pImplName,
XMultiServiceFactory * pServiceManager,
void *
);
////////////////////////////////////////
// definition of the two functions that are used to provide the services
//
extern "C"
{
sal_Bool SAL_CALL component_writeInfo
(
void * pServiceManager,
XRegistryKey * pRegistryKey
)
{
sal_Bool bRet = LngSvcMgr_writeInfo( pServiceManager, pRegistryKey );
if(bRet)
bRet = LinguProps_writeInfo( pServiceManager, pRegistryKey );
if(bRet)
bRet = DicList_writeInfo( pServiceManager, pRegistryKey );
if(bRet)
bRet = ConvDicList_writeInfo( pServiceManager, pRegistryKey );
return bRet;
}
void SAL_CALL component_getImplementationEnvironment(
const sal_Char ** ppEnvTypeName, uno_Environment ** ppEnv )
{
*ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
}
void * SAL_CALL component_getFactory(
const sal_Char * pImplName, void * pServiceManager, void * pRegistryKey )
{
void * pRet =
LngSvcMgr_getFactory(
pImplName,
reinterpret_cast< XMultiServiceFactory * >( pServiceManager ),
pRegistryKey );
if(!pRet)
pRet = LinguProps_getFactory(
pImplName,
reinterpret_cast< XMultiServiceFactory * >( pServiceManager ),
pRegistryKey );
if(!pRet)
pRet = DicList_getFactory(
pImplName,
reinterpret_cast< XMultiServiceFactory * >( pServiceManager ),
pRegistryKey );
if(!pRet)
pRet = ConvDicList_getFactory(
pImplName,
reinterpret_cast< XMultiServiceFactory * >( pServiceManager ),
pRegistryKey );
return pRet;
}
}
///////////////////////////////////////////////////////////////////////////
<commit_msg>INTEGRATION: CWS tl32 (1.4.8); FILE MERGED 2006/10/26 11:26:02 tl 1.4.8.1: #140479# make linguistic warning-free<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: lngreg.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: vg $ $Date: 2007-05-25 12:23:59 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* 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
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_linguistic.hxx"
#include <cppuhelper/factory.hxx> // helper for factories
#ifndef _RTL_STRING_HXX_
#include <rtl/string.hxx>
#endif
#include <com/sun/star/registry/XRegistryKey.hpp>
using namespace com::sun::star::lang;
using namespace com::sun::star::registry;
////////////////////////////////////////
// declaration of external RegEntry-functions defined by the service objects
//
extern sal_Bool SAL_CALL LngSvcMgr_writeInfo
(
void * /*pServiceManager*/,
XRegistryKey * pRegistryKey
);
extern sal_Bool SAL_CALL DicList_writeInfo
(
void * /*pServiceManager*/, XRegistryKey * pRegistryKey
);
extern sal_Bool SAL_CALL LinguProps_writeInfo
(
void * /*pServiceManager*/,
XRegistryKey * pRegistryKey
);
extern sal_Bool SAL_CALL ConvDicList_writeInfo
(
void * /*pServiceManager*/, XRegistryKey * pRegistryKey
);
extern void * SAL_CALL LngSvcMgr_getFactory
(
const sal_Char * pImplName,
XMultiServiceFactory * pServiceManager,
void * /*pRegistryKey*/
);
extern void * SAL_CALL DicList_getFactory
(
const sal_Char * pImplName,
XMultiServiceFactory * pServiceManager,
void *
);
void * SAL_CALL LinguProps_getFactory
(
const sal_Char * pImplName,
XMultiServiceFactory * pServiceManager,
void *
);
extern void * SAL_CALL ConvDicList_getFactory
(
const sal_Char * pImplName,
XMultiServiceFactory * pServiceManager,
void *
);
////////////////////////////////////////
// definition of the two functions that are used to provide the services
//
extern "C"
{
sal_Bool SAL_CALL component_writeInfo
(
void * pServiceManager,
XRegistryKey * pRegistryKey
)
{
sal_Bool bRet = LngSvcMgr_writeInfo( pServiceManager, pRegistryKey );
if(bRet)
bRet = LinguProps_writeInfo( pServiceManager, pRegistryKey );
if(bRet)
bRet = DicList_writeInfo( pServiceManager, pRegistryKey );
if(bRet)
bRet = ConvDicList_writeInfo( pServiceManager, pRegistryKey );
return bRet;
}
void SAL_CALL component_getImplementationEnvironment(
const sal_Char ** ppEnvTypeName, uno_Environment ** /*ppEnv*/ )
{
*ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
}
void * SAL_CALL component_getFactory(
const sal_Char * pImplName, void * pServiceManager, void * pRegistryKey )
{
void * pRet =
LngSvcMgr_getFactory(
pImplName,
reinterpret_cast< XMultiServiceFactory * >( pServiceManager ),
pRegistryKey );
if(!pRet)
pRet = LinguProps_getFactory(
pImplName,
reinterpret_cast< XMultiServiceFactory * >( pServiceManager ),
pRegistryKey );
if(!pRet)
pRet = DicList_getFactory(
pImplName,
reinterpret_cast< XMultiServiceFactory * >( pServiceManager ),
pRegistryKey );
if(!pRet)
pRet = ConvDicList_getFactory(
pImplName,
reinterpret_cast< XMultiServiceFactory * >( pServiceManager ),
pRegistryKey );
return pRet;
}
}
///////////////////////////////////////////////////////////////////////////
<|endoftext|> |
<commit_before>#include <ctre.hpp>
#include <ctre-unicode.hpp>
#include <string_view>
void empty_symbol() { }
template <typename T> struct identify;
template <size_t N> struct number_id;
#if !(__cpp_nontype_template_parameter_class || (__cpp_nontype_template_args >= 201911L))
#define CTRE_CREATE(pattern) (pattern ## _ctre)
#define CTRE_SYNTAX(pattern) (pattern ## _ctre_syntax)
#define CTRE_GEN(pattern) decltype(pattern ## _ctre_gen)
#else
template <ctll::fixed_string input> constexpr auto create() {
constexpr auto _input = input;
using tmp = typename ctll::parser<ctre::pcre, _input, ctre::pcre_actions>::template output<ctre::pcre_context<>>;
static_assert(tmp(), "Regular Expression contains syntax error.");
using re = decltype(front(typename tmp::output_type::stack_type()));
return ctre::regular_expression(re());
}
template <ctll::fixed_string input> constexpr bool syntax() {
constexpr auto _input = input;
return ctll::parser<ctre::pcre, _input, ctre::pcre_actions>::template correct_with<ctre::pcre_context<>>;
}
template <ctll::fixed_string input> constexpr auto gen() {
constexpr auto _input = input;
using tmp = typename ctll::parser<ctre::pcre, _input, ctre::pcre_actions>::template output<ctre::pcre_context<>>;
static_assert(tmp(), "Regular Expression contains syntax error.");
return typename tmp::output_type::stack_type();
}
#define CTRE_GEN(pattern) decltype(gen<pattern>())
#define CTRE_CREATE(pattern) create<pattern>()
#define CTRE_SYNTAX(pattern) syntax<pattern>()
#endif
using namespace ctre::literals;
using namespace ctre::test_literals;
using namespace std::string_view_literals;
// UTS #18 Level 1: RL1.1: Hex Notation
static_assert(CTRE_CREATE(U"\\u{1F92A}").match(U"🤪"));
static_assert(CTRE_CREATE(U"\\u20AC").match(U"€"));
// TODO multiple character inside \u{AA BB CC}
// TODO deal with normalization 1.1.1
// UTS #18 Level 1: RL1.2: Properties
// TODO only \p and \P is not supported
static_assert(CTRE_SYNTAX(U"\\p{L}"));
static_assert(CTRE_SYNTAX(U"\\p{Letter}"));
static_assert(CTRE_CREATE(U"\\p{Letter}+").match(u8"abcDEF"));
static_assert(CTRE_CREATE(U"\\p{Letter}+").match(U"abcDEF"));
static_assert(CTRE_CREATE(U"\\p{Ll}+").match(U"abcdef"));
static_assert(CTRE_CREATE(U"\\p{Lu}+").match(U"ABCD"));
static_assert(!CTRE_CREATE(U"\\p{Lu}+").match(U"ABcD"));
static_assert(CTRE_CREATE(U"\\p{Nd}+").match(U"1234567890"));
static_assert(!CTRE_CREATE(U"\\p{Nd}+").match(U"1234567890h"));
static_assert(CTRE_CREATE(U"\\p{script=Latin}+").match(U"abcd"));
static_assert(CTRE_CREATE(U"\\p{script=Greek}+").match(U"βΩ"));
static_assert(!CTRE_CREATE(U"\\p{script=Latin}+").match(U"βΩ"));
static_assert(!CTRE_CREATE(U"\\p{script=Greek}+").match(U"abcd"));
static_assert(CTRE_CREATE(U"\\p{emoji}+").match(u8"🤪😍"));
static_assert(CTRE_CREATE("\\p{emoji}+").match(u8"🤪😍"));
static_assert(CTRE_CREATE(U"\\p{emoji}+").match(U"🤪😍✨\U0001F3F3"));
static_assert(CTRE_SYNTAX(U"\\p{sc=greek}+?\\p{Emoji}\\p{sc=greek}+?"));
static_assert(CTRE_CREATE(U"\\p{sc=greek}+?\\p{Emoji}").match(U"αΩ😍"));
static_assert(CTRE_CREATE(U"\\p{sc=greek}+?\\p{Emoji}\\p{sc=greek}+?").match(U"α😍Ω"));
static_assert(CTRE_SYNTAX(U"\\p{age=10.0}"));
static_assert(CTRE_CREATE(U"\\p{age=10.0}").match(U"🤩"));
static_assert(CTRE_CREATE(U"\\p{block=misc_pictographs}").match(U"🎉"));
static_assert(CTRE_CREATE(U"\\p{scx=Hira}+").match(U"ゖ"));
//identify<decltype(ctll::fixed_string{u8"ěščř"})> a;
//identify<decltype(CTRE_CREATE(u8"ěščř"))> i;
//identify<CTRE_GEN(u8"a+")> a;
//identify<CTRE_GEN(u8"😍")> b;
#if __cpp_char8_t
static_assert(CTRE_SYNTAX(u8"a+"));
static_assert(CTRE_SYNTAX(u8"😍+"));
static_assert(CTRE_CREATE(u8"😍").match(U"😍"));
static_assert(CTRE_CREATE(u8"😍+").match(U"😍"));
static_assert(CTRE_CREATE(u8"😍+").match(U"😍😍😍😍"));
static_assert(CTRE_CREATE(u8"[😍a\\x{1F92A}]+").match(U"😍a😍aa😍😍a🤪"));
static_assert(!CTRE_CREATE(u8"[😍a\\x{1F92A}]+").match(U"😍a😍aa😍😍a🤪x"));
constexpr auto m1 = CTRE_CREATE(u8"[😍a-z\\x{1F92A}]+").match(U"abc😍😍xyz");
static_assert(m1.to_view().length() == 8);
#endif
static_assert(CTRE_SYNTAX(U"a+"));
static_assert(CTRE_SYNTAX(U"😍+"));
static_assert(CTRE_CREATE(U"😍").match(U"😍"));
static_assert(CTRE_CREATE(U"😍+").match(U"😍"));
static_assert(CTRE_CREATE(U"😍+").match(U"😍😍😍😍"));
static_assert(CTRE_CREATE(U"[😍a\\x{1F92A}]+").match(U"😍a😍aa😍😍a🤪"));
static_assert(!CTRE_CREATE(U"[😍a\\x{1F92A}]+").match(U"😍a😍aa😍😍a🤪x"));
constexpr auto m2 = CTRE_CREATE(U"[😍a-z\\x{1F92A}]+").match(U"abc😍😍xyz");
static_assert(m2.to_view().length() == 8);
//identify<decltype(CTRE_CREATE(u8"😍+"))> i;
//static_assert(CTRE_CREATE(u8"😍+").match(U"😍"));
//ctre::match<u8"😍">(u8"😍😍😍");
//static_assert(CTRE_CREATE(u8"😍+").match(u8"😍😍😍"));
static_assert(CTRE_CREATE(U"[ěščřabc]+").match(U"ěěcěěař"));
//static_assert(CTRE_CREATE(u"ěščř").match(u8"ěščř"));
//static_assert(CTRE_CREATE(L"ěščř").match(u8"ěščř"));
//static_assert(CTRE_CREATE(u8"ěščř").match(u8"ěščř"));
//
//static_assert(CTRE_SYNTAX("\\p{Latin}"));
//static_assert(!CTRE_SYNTAX("\\p{Latin42}"));
//
//static_assert(CTRE_CREATE("\\p{Latin}").match("a"sv));
//static_assert(CTRE_CREATE("\\p{Emoji}").match("a"sv));
//
<commit_msg>u8string doesn't make sense to test before char8_t<commit_after>#include <ctre.hpp>
#include <ctre-unicode.hpp>
#include <string_view>
void empty_symbol() { }
template <typename T> struct identify;
template <size_t N> struct number_id;
#if !(__cpp_nontype_template_parameter_class || (__cpp_nontype_template_args >= 201911L))
#define CTRE_CREATE(pattern) (pattern ## _ctre)
#define CTRE_SYNTAX(pattern) (pattern ## _ctre_syntax)
#define CTRE_GEN(pattern) decltype(pattern ## _ctre_gen)
#else
template <ctll::fixed_string input> constexpr auto create() {
constexpr auto _input = input;
using tmp = typename ctll::parser<ctre::pcre, _input, ctre::pcre_actions>::template output<ctre::pcre_context<>>;
static_assert(tmp(), "Regular Expression contains syntax error.");
using re = decltype(front(typename tmp::output_type::stack_type()));
return ctre::regular_expression(re());
}
template <ctll::fixed_string input> constexpr bool syntax() {
constexpr auto _input = input;
return ctll::parser<ctre::pcre, _input, ctre::pcre_actions>::template correct_with<ctre::pcre_context<>>;
}
template <ctll::fixed_string input> constexpr auto gen() {
constexpr auto _input = input;
using tmp = typename ctll::parser<ctre::pcre, _input, ctre::pcre_actions>::template output<ctre::pcre_context<>>;
static_assert(tmp(), "Regular Expression contains syntax error.");
return typename tmp::output_type::stack_type();
}
#define CTRE_GEN(pattern) decltype(gen<pattern>())
#define CTRE_CREATE(pattern) create<pattern>()
#define CTRE_SYNTAX(pattern) syntax<pattern>()
#endif
using namespace ctre::literals;
using namespace ctre::test_literals;
using namespace std::string_view_literals;
// UTS #18 Level 1: RL1.1: Hex Notation
static_assert(CTRE_CREATE(U"\\u{1F92A}").match(U"🤪"));
static_assert(CTRE_CREATE(U"\\u20AC").match(U"€"));
// TODO multiple character inside \u{AA BB CC}
// TODO deal with normalization 1.1.1
// UTS #18 Level 1: RL1.2: Properties
// TODO only \p and \P is not supported
static_assert(CTRE_SYNTAX(U"\\p{L}"));
static_assert(CTRE_SYNTAX(U"\\p{Letter}"));
static_assert(CTRE_CREATE(U"\\p{Letter}+").match(u8"abcDEF"));
static_assert(CTRE_CREATE(U"\\p{Letter}+").match(U"abcDEF"));
static_assert(CTRE_CREATE(U"\\p{Ll}+").match(U"abcdef"));
static_assert(CTRE_CREATE(U"\\p{Lu}+").match(U"ABCD"));
static_assert(!CTRE_CREATE(U"\\p{Lu}+").match(U"ABcD"));
static_assert(CTRE_CREATE(U"\\p{Nd}+").match(U"1234567890"));
static_assert(!CTRE_CREATE(U"\\p{Nd}+").match(U"1234567890h"));
static_assert(CTRE_CREATE(U"\\p{script=Latin}+").match(U"abcd"));
static_assert(CTRE_CREATE(U"\\p{script=Greek}+").match(U"βΩ"));
static_assert(!CTRE_CREATE(U"\\p{script=Latin}+").match(U"βΩ"));
static_assert(!CTRE_CREATE(U"\\p{script=Greek}+").match(U"abcd"));
#if __cpp_char8_t >= 201811
static_assert(CTRE_CREATE(U"\\p{emoji}+").match(u8"🤪😍"));
static_assert(CTRE_CREATE("\\p{emoji}+").match(u8"🤪😍"));
#endif
static_assert(CTRE_CREATE(U"\\p{emoji}+").match(U"🤪😍✨\U0001F3F3"));
static_assert(CTRE_SYNTAX(U"\\p{sc=greek}+?\\p{Emoji}\\p{sc=greek}+?"));
static_assert(CTRE_CREATE(U"\\p{sc=greek}+?\\p{Emoji}").match(U"αΩ😍"));
static_assert(CTRE_CREATE(U"\\p{sc=greek}+?\\p{Emoji}\\p{sc=greek}+?").match(U"α😍Ω"));
static_assert(CTRE_SYNTAX(U"\\p{age=10.0}"));
static_assert(CTRE_CREATE(U"\\p{age=10.0}").match(U"🤩"));
static_assert(CTRE_CREATE(U"\\p{block=misc_pictographs}").match(U"🎉"));
static_assert(CTRE_CREATE(U"\\p{scx=Hira}+").match(U"ゖ"));
//identify<decltype(ctll::fixed_string{u8"ěščř"})> a;
//identify<decltype(CTRE_CREATE(u8"ěščř"))> i;
//identify<CTRE_GEN(u8"a+")> a;
//identify<CTRE_GEN(u8"😍")> b;
#if __cpp_char8_t
static_assert(CTRE_SYNTAX(u8"a+"));
static_assert(CTRE_SYNTAX(u8"😍+"));
static_assert(CTRE_CREATE(u8"😍").match(U"😍"));
static_assert(CTRE_CREATE(u8"😍+").match(U"😍"));
static_assert(CTRE_CREATE(u8"😍+").match(U"😍😍😍😍"));
static_assert(CTRE_CREATE(u8"[😍a\\x{1F92A}]+").match(U"😍a😍aa😍😍a🤪"));
static_assert(!CTRE_CREATE(u8"[😍a\\x{1F92A}]+").match(U"😍a😍aa😍😍a🤪x"));
constexpr auto m1 = CTRE_CREATE(u8"[😍a-z\\x{1F92A}]+").match(U"abc😍😍xyz");
static_assert(m1.to_view().length() == 8);
#endif
static_assert(CTRE_SYNTAX(U"a+"));
static_assert(CTRE_SYNTAX(U"😍+"));
static_assert(CTRE_CREATE(U"😍").match(U"😍"));
static_assert(CTRE_CREATE(U"😍+").match(U"😍"));
static_assert(CTRE_CREATE(U"😍+").match(U"😍😍😍😍"));
static_assert(CTRE_CREATE(U"[😍a\\x{1F92A}]+").match(U"😍a😍aa😍😍a🤪"));
static_assert(!CTRE_CREATE(U"[😍a\\x{1F92A}]+").match(U"😍a😍aa😍😍a🤪x"));
constexpr auto m2 = CTRE_CREATE(U"[😍a-z\\x{1F92A}]+").match(U"abc😍😍xyz");
static_assert(m2.to_view().length() == 8);
//identify<decltype(CTRE_CREATE(u8"😍+"))> i;
//static_assert(CTRE_CREATE(u8"😍+").match(U"😍"));
//ctre::match<u8"😍">(u8"😍😍😍");
//static_assert(CTRE_CREATE(u8"😍+").match(u8"😍😍😍"));
static_assert(CTRE_CREATE(U"[ěščřabc]+").match(U"ěěcěěař"));
//static_assert(CTRE_CREATE(u"ěščř").match(u8"ěščř"));
//static_assert(CTRE_CREATE(L"ěščř").match(u8"ěščř"));
//static_assert(CTRE_CREATE(u8"ěščř").match(u8"ěščř"));
//
//static_assert(CTRE_SYNTAX("\\p{Latin}"));
//static_assert(!CTRE_SYNTAX("\\p{Latin42}"));
//
//static_assert(CTRE_CREATE("\\p{Latin}").match("a"sv));
//static_assert(CTRE_CREATE("\\p{Emoji}").match("a"sv));
//
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** 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, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/
#include "fancyactionbar.h"
#include "coreconstants.h"
#include <utils/stylehelper.h>
#include <utils/stringutils.h>
#include <coreplugin/icore.h>
#include <coreplugin/imode.h>
#include <QtGui/QHBoxLayout>
#include <QtGui/QPainter>
#include <QtGui/QPicture>
#include <QtGui/QVBoxLayout>
#include <QtGui/QAction>
#include <QtGui/QStatusBar>
#include <QtGui/QStyle>
#include <QtGui/QStyleOption>
#include <QtGui/QMouseEvent>
#include <QtGui/QApplication>
#include <QtCore/QEvent>
#include <QtCore/QAnimationGroup>
#include <QtCore/QPropertyAnimation>
#include <QtCore/QDebug>
using namespace Core;
using namespace Internal;
FancyToolButton::FancyToolButton(QWidget *parent)
: QToolButton(parent), m_fader(0)
{
m_hasForceVisible = false;
setAttribute(Qt::WA_Hover, true);
setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
}
void FancyToolButton::forceVisible(bool visible)
{
m_hasForceVisible = true;
setVisible(visible);
}
bool FancyToolButton::event(QEvent *e)
{
switch(e->type()) {
case QEvent::Enter:
{
QPropertyAnimation *animation = new QPropertyAnimation(this, "fader");
animation->setDuration(125);
animation->setEndValue(1.0);
animation->start(QAbstractAnimation::DeleteWhenStopped);
}
break;
case QEvent::Leave:
{
QPropertyAnimation *animation = new QPropertyAnimation(this, "fader");
animation->setDuration(125);
animation->setEndValue(0.0);
animation->start(QAbstractAnimation::DeleteWhenStopped);
}
break;
default:
return QToolButton::event(e);
}
return false;
}
static QVector<QString> splitInTwoLines(const QString &text, const QFontMetrics &fontMetrics,
qreal availableWidth)
{
// split in two lines.
// this looks if full words can be split off at the end of the string,
// to put them in the second line. First line is drawn with ellipsis,
// second line gets ellipsis if it couldn't split off full words.
QVector<QString> splitLines(2);
QRegExp rx(QLatin1String("\\s+"));
int splitPos = -1;
int nextSplitPos = text.length();
do {
nextSplitPos = rx.lastIndexIn(text,
nextSplitPos - text.length() - 1);
if (nextSplitPos != -1) {
int splitCandidate = nextSplitPos + rx.matchedLength();
if (fontMetrics.width(text.mid(splitCandidate)) <= availableWidth) {
splitPos = splitCandidate;
} else {
break;
}
}
} while (nextSplitPos > 0 && fontMetrics.width(text.left(nextSplitPos)) > availableWidth);
// check if we could split at white space at all
if (splitPos < 0) {
splitLines[0] = fontMetrics.elidedText(text, Qt::ElideRight,
availableWidth);
QString common = Utils::commonPrefix(QStringList()
<< splitLines[0] << text);
splitLines[1] = text.mid(common.length());
// elide the second line even if it fits, since it is cut off in mid-word
while (fontMetrics.width(QChar(0x2026) /*'...'*/ + splitLines[1]) > availableWidth
&& splitLines[1].length() > 3
/*keep at least three original characters (should not happen)*/) {
splitLines[1].remove(0, 1);
}
splitLines[1] = QChar(0x2026) /*'...'*/ + splitLines[1];
} else {
splitLines[0] = fontMetrics.elidedText(text.left(splitPos).trimmed(), Qt::ElideRight, availableWidth);
splitLines[1] = text.mid(splitPos);
}
return splitLines;
}
void FancyToolButton::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event)
QPainter painter(this);
// draw borders
bool isTitledAction = defaultAction()->property("titledAction").toBool();
#ifndef Q_OS_MAC // Mac UIs usually don't hover
if (m_fader > 0 && isEnabled() && !isDown() && !isChecked()) {
painter.save();
int fader = int(40 * m_fader);
QLinearGradient grad(rect().topLeft(), rect().topRight());
grad.setColorAt(0, Qt::transparent);
grad.setColorAt(0.5, QColor(255, 255, 255, fader));
grad.setColorAt(1, Qt::transparent);
painter.fillRect(rect(), grad);
painter.setPen(QPen(grad, 1.0));
painter.drawLine(rect().topLeft(), rect().topRight());
painter.drawLine(rect().bottomLeft(), rect().bottomRight());
painter.restore();
} else
#endif
if (isDown() || isChecked()) {
painter.save();
QLinearGradient grad(rect().topLeft(), rect().topRight());
grad.setColorAt(0, Qt::transparent);
grad.setColorAt(0.5, QColor(0, 0, 0, 50));
grad.setColorAt(1, Qt::transparent);
painter.fillRect(rect(), grad);
painter.setPen(QPen(grad, 1.0));
painter.drawLine(rect().topLeft(), rect().topRight());
painter.drawLine(rect().topLeft(), rect().topRight());
painter.drawLine(rect().topLeft() + QPoint(0,1), rect().topRight() + QPoint(0,1));
painter.drawLine(rect().bottomLeft(), rect().bottomRight());
painter.drawLine(rect().bottomLeft(), rect().bottomRight());
painter.drawLine(rect().topLeft() - QPoint(0,1), rect().topRight() - QPoint(0,1));
painter.restore();
}
QPixmap borderPixmap;
QMargins margins;
QRect iconRect(0, 0, Core::Constants::TARGET_ICON_SIZE, Core::Constants::TARGET_ICON_SIZE);
// draw popup texts
if (isTitledAction) {
QFont normalFont(painter.font());
QRect centerRect = rect();
normalFont.setPointSizeF(Utils::StyleHelper::sidebarFontSize());
QFont boldFont(normalFont);
boldFont.setBold(true);
QFontMetrics fm(normalFont);
QFontMetrics boldFm(boldFont);
int lineHeight = boldFm.height();
int textFlags = Qt::AlignVCenter|Qt::AlignHCenter;
const QString projectName = defaultAction()->property("heading").toString();
if (!projectName.isNull())
centerRect.adjust(0, lineHeight + 4, 0, 0);
const QString buildConfiguration = defaultAction()->property("subtitle").toString();
if (!buildConfiguration.isNull())
centerRect.adjust(0, 0, 0, -lineHeight*2 - 4);
iconRect.moveCenter(centerRect.center());
Utils::StyleHelper::drawIconWithShadow(icon(), iconRect, &painter, isEnabled() ? QIcon::Normal : QIcon::Disabled);
painter.setFont(normalFont);
QPoint textOffset = centerRect.center() - QPoint(iconRect.width()/2, iconRect.height()/2);
textOffset = textOffset - QPoint(0, lineHeight + 4);
QRectF r(0, textOffset.y(), rect().width(), lineHeight);
QColor penColor;
if (isEnabled())
penColor = Qt::white;
else
penColor = Qt::gray;
painter.setPen(penColor);
// draw project name
const int margin = 6;
const qreal availableWidth = r.width() - margin;
QString ellidedProjectName = fm.elidedText(projectName, Qt::ElideMiddle, availableWidth);
if (isEnabled()) {
const QRectF shadowR = r.translated(0, 1);
painter.setPen(QColor(30, 30, 30, 80));
painter.drawText(shadowR, textFlags, ellidedProjectName);
painter.setPen(penColor);
}
painter.drawText(r, textFlags, ellidedProjectName);
// draw build configuration name
textOffset = iconRect.center() + QPoint(iconRect.width()/2, iconRect.height()/2);
QRectF buildConfigRect[2];
buildConfigRect[0] = QRectF(0, textOffset.y() + 5, rect().width(), lineHeight);
buildConfigRect[1] = QRectF(0, textOffset.y() + 5 + lineHeight, rect().width(), lineHeight);
painter.setFont(boldFont);
QVector<QString> splitBuildConfiguration(2);
if (boldFm.width(buildConfiguration) <= availableWidth) {
// text fits in one line
splitBuildConfiguration[0] = buildConfiguration;
} else {
splitBuildConfiguration = splitInTwoLines(buildConfiguration, boldFm, availableWidth);
}
// draw the two lines for the build configuration
for (int i = 0; i < 2; ++i) {
if (splitBuildConfiguration[i].isEmpty())
continue;
if (isEnabled()) {
const QRectF shadowR = buildConfigRect[i].translated(0, 1);
painter.setPen(QColor(30, 30, 30, 80));
painter.drawText(shadowR, textFlags, splitBuildConfiguration[i]);
painter.setPen(penColor);
}
painter.drawText(buildConfigRect[i], textFlags, splitBuildConfiguration[i]);
}
// pop up arrow next to icon
if (!icon().isNull()) {
QStyleOption opt;
opt.initFrom(this);
opt.rect = rect().adjusted(rect().width() - 16, 0, -8, 0);
Utils::StyleHelper::drawArrow(QStyle::PE_IndicatorArrowRight, &painter, &opt);
}
} else {
iconRect.moveCenter(rect().center());
Utils::StyleHelper::drawIconWithShadow(icon(), iconRect, &painter, isEnabled() ? QIcon::Normal : QIcon::Disabled);
}
}
void FancyActionBar::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
Q_UNUSED(event)
QColor light = Utils::StyleHelper::sidebarHighlight();
QColor dark = Utils::StyleHelper::sidebarShadow();
painter.setPen(dark);
painter.drawLine(rect().topLeft(), rect().topRight());
painter.setPen(light);
painter.drawLine(rect().topLeft() + QPoint(1,1), rect().topRight() + QPoint(0,1));
}
QSize FancyToolButton::sizeHint() const
{
QSizeF buttonSize = iconSize().expandedTo(QSize(64, 38));
if (defaultAction()->property("titledAction").toBool()) {
QFont boldFont(font());
boldFont.setPointSizeF(Utils::StyleHelper::sidebarFontSize());
boldFont.setBold(true);
QFontMetrics fm(boldFont);
qreal lineHeight = fm.height();
const QString projectName = defaultAction()->property("heading").toString();
buttonSize += QSizeF(0, 10);
if (!projectName.isEmpty())
buttonSize += QSizeF(0, lineHeight + 2);
const QString buildConfiguration = defaultAction()->property("subtitle").toString();
if (!buildConfiguration.isEmpty())
buttonSize += QSizeF(0, lineHeight*2 + 2);
}
return buttonSize.toSize();
}
QSize FancyToolButton::minimumSizeHint() const
{
return QSize(8, 8);
}
void FancyToolButton::actionChanged()
{
// the default action changed in some way, e.g. it might got hidden
// since we inherit a tool button we won't get invisible, so do this here
if (!m_hasForceVisible) {
if (QAction* action = defaultAction())
setVisible(action->isVisible());
}
}
FancyActionBar::FancyActionBar(QWidget *parent)
: QWidget(parent)
{
setObjectName(QLatin1String("actionbar"));
m_actionsLayout = new QVBoxLayout;
QVBoxLayout *spacerLayout = new QVBoxLayout;
spacerLayout->addLayout(m_actionsLayout);
int sbh = 8;
spacerLayout->addSpacing(sbh);
spacerLayout->setMargin(0);
spacerLayout->setSpacing(0);
setLayout(spacerLayout);
setContentsMargins(0,2,0,0);
}
void FancyActionBar::addProjectSelector(QAction *action)
{
FancyToolButton* toolButton = new FancyToolButton(this);
toolButton->setDefaultAction(action);
connect(action, SIGNAL(changed()), toolButton, SLOT(actionChanged()));
m_actionsLayout->insertWidget(0, toolButton);
}
void FancyActionBar::insertAction(int index, QAction *action)
{
FancyToolButton *toolButton = new FancyToolButton(this);
toolButton->setDefaultAction(action);
connect(action, SIGNAL(changed()), toolButton, SLOT(actionChanged()));
m_actionsLayout->insertWidget(index, toolButton);
}
QLayout *FancyActionBar::actionsLayout() const
{
return m_actionsLayout;
}
QSize FancyActionBar::minimumSizeHint() const
{
return sizeHint();
}
<commit_msg>Ensure consistent size of facnyactionbar button<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** 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, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/
#include "fancyactionbar.h"
#include "coreconstants.h"
#include <utils/stylehelper.h>
#include <utils/stringutils.h>
#include <coreplugin/icore.h>
#include <coreplugin/imode.h>
#include <QtGui/QHBoxLayout>
#include <QtGui/QPainter>
#include <QtGui/QPicture>
#include <QtGui/QVBoxLayout>
#include <QtGui/QAction>
#include <QtGui/QStatusBar>
#include <QtGui/QStyle>
#include <QtGui/QStyleOption>
#include <QtGui/QMouseEvent>
#include <QtGui/QApplication>
#include <QtCore/QEvent>
#include <QtCore/QAnimationGroup>
#include <QtCore/QPropertyAnimation>
#include <QtCore/QDebug>
using namespace Core;
using namespace Internal;
FancyToolButton::FancyToolButton(QWidget *parent)
: QToolButton(parent), m_fader(0)
{
m_hasForceVisible = false;
setAttribute(Qt::WA_Hover, true);
setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
}
void FancyToolButton::forceVisible(bool visible)
{
m_hasForceVisible = true;
setVisible(visible);
}
bool FancyToolButton::event(QEvent *e)
{
switch(e->type()) {
case QEvent::Enter:
{
QPropertyAnimation *animation = new QPropertyAnimation(this, "fader");
animation->setDuration(125);
animation->setEndValue(1.0);
animation->start(QAbstractAnimation::DeleteWhenStopped);
}
break;
case QEvent::Leave:
{
QPropertyAnimation *animation = new QPropertyAnimation(this, "fader");
animation->setDuration(125);
animation->setEndValue(0.0);
animation->start(QAbstractAnimation::DeleteWhenStopped);
}
break;
default:
return QToolButton::event(e);
}
return false;
}
static QVector<QString> splitInTwoLines(const QString &text, const QFontMetrics &fontMetrics,
qreal availableWidth)
{
// split in two lines.
// this looks if full words can be split off at the end of the string,
// to put them in the second line. First line is drawn with ellipsis,
// second line gets ellipsis if it couldn't split off full words.
QVector<QString> splitLines(2);
QRegExp rx(QLatin1String("\\s+"));
int splitPos = -1;
int nextSplitPos = text.length();
do {
nextSplitPos = rx.lastIndexIn(text,
nextSplitPos - text.length() - 1);
if (nextSplitPos != -1) {
int splitCandidate = nextSplitPos + rx.matchedLength();
if (fontMetrics.width(text.mid(splitCandidate)) <= availableWidth) {
splitPos = splitCandidate;
} else {
break;
}
}
} while (nextSplitPos > 0 && fontMetrics.width(text.left(nextSplitPos)) > availableWidth);
// check if we could split at white space at all
if (splitPos < 0) {
splitLines[0] = fontMetrics.elidedText(text, Qt::ElideRight,
availableWidth);
QString common = Utils::commonPrefix(QStringList()
<< splitLines[0] << text);
splitLines[1] = text.mid(common.length());
// elide the second line even if it fits, since it is cut off in mid-word
while (fontMetrics.width(QChar(0x2026) /*'...'*/ + splitLines[1]) > availableWidth
&& splitLines[1].length() > 3
/*keep at least three original characters (should not happen)*/) {
splitLines[1].remove(0, 1);
}
splitLines[1] = QChar(0x2026) /*'...'*/ + splitLines[1];
} else {
splitLines[0] = fontMetrics.elidedText(text.left(splitPos).trimmed(), Qt::ElideRight, availableWidth);
splitLines[1] = text.mid(splitPos);
}
return splitLines;
}
void FancyToolButton::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event)
QPainter painter(this);
// draw borders
bool isTitledAction = defaultAction()->property("titledAction").toBool();
#ifndef Q_OS_MAC // Mac UIs usually don't hover
if (m_fader > 0 && isEnabled() && !isDown() && !isChecked()) {
painter.save();
int fader = int(40 * m_fader);
QLinearGradient grad(rect().topLeft(), rect().topRight());
grad.setColorAt(0, Qt::transparent);
grad.setColorAt(0.5, QColor(255, 255, 255, fader));
grad.setColorAt(1, Qt::transparent);
painter.fillRect(rect(), grad);
painter.setPen(QPen(grad, 1.0));
painter.drawLine(rect().topLeft(), rect().topRight());
painter.drawLine(rect().bottomLeft(), rect().bottomRight());
painter.restore();
} else
#endif
if (isDown() || isChecked()) {
painter.save();
QLinearGradient grad(rect().topLeft(), rect().topRight());
grad.setColorAt(0, Qt::transparent);
grad.setColorAt(0.5, QColor(0, 0, 0, 50));
grad.setColorAt(1, Qt::transparent);
painter.fillRect(rect(), grad);
painter.setPen(QPen(grad, 1.0));
painter.drawLine(rect().topLeft(), rect().topRight());
painter.drawLine(rect().topLeft(), rect().topRight());
painter.drawLine(rect().topLeft() + QPoint(0,1), rect().topRight() + QPoint(0,1));
painter.drawLine(rect().bottomLeft(), rect().bottomRight());
painter.drawLine(rect().bottomLeft(), rect().bottomRight());
painter.drawLine(rect().topLeft() - QPoint(0,1), rect().topRight() - QPoint(0,1));
painter.restore();
}
QPixmap borderPixmap;
QMargins margins;
QRect iconRect(0, 0, Core::Constants::TARGET_ICON_SIZE, Core::Constants::TARGET_ICON_SIZE);
// draw popup texts
if (isTitledAction) {
QFont normalFont(painter.font());
QRect centerRect = rect();
normalFont.setPointSizeF(Utils::StyleHelper::sidebarFontSize());
QFont boldFont(normalFont);
boldFont.setBold(true);
QFontMetrics fm(normalFont);
QFontMetrics boldFm(boldFont);
int lineHeight = boldFm.height();
int textFlags = Qt::AlignVCenter|Qt::AlignHCenter;
const QString projectName = defaultAction()->property("heading").toString();
if (!projectName.isNull())
centerRect.adjust(0, lineHeight + 4, 0, 0);
centerRect.adjust(0, 0, 0, -lineHeight*2 - 4);
iconRect.moveCenter(centerRect.center());
Utils::StyleHelper::drawIconWithShadow(icon(), iconRect, &painter, isEnabled() ? QIcon::Normal : QIcon::Disabled);
painter.setFont(normalFont);
QPoint textOffset = centerRect.center() - QPoint(iconRect.width()/2, iconRect.height()/2);
textOffset = textOffset - QPoint(0, lineHeight + 4);
QRectF r(0, textOffset.y(), rect().width(), lineHeight);
QColor penColor;
if (isEnabled())
penColor = Qt::white;
else
penColor = Qt::gray;
painter.setPen(penColor);
// draw project name
const int margin = 6;
const qreal availableWidth = r.width() - margin;
QString ellidedProjectName = fm.elidedText(projectName, Qt::ElideMiddle, availableWidth);
if (isEnabled()) {
const QRectF shadowR = r.translated(0, 1);
painter.setPen(QColor(30, 30, 30, 80));
painter.drawText(shadowR, textFlags, ellidedProjectName);
painter.setPen(penColor);
}
painter.drawText(r, textFlags, ellidedProjectName);
// draw build configuration name
textOffset = iconRect.center() + QPoint(iconRect.width()/2, iconRect.height()/2);
QRectF buildConfigRect[2];
buildConfigRect[0] = QRectF(0, textOffset.y() + 5, rect().width(), lineHeight);
buildConfigRect[1] = QRectF(0, textOffset.y() + 5 + lineHeight, rect().width(), lineHeight);
painter.setFont(boldFont);
QVector<QString> splitBuildConfiguration(2);
const QString buildConfiguration = defaultAction()->property("subtitle").toString();
if (boldFm.width(buildConfiguration) <= availableWidth) {
// text fits in one line
splitBuildConfiguration[0] = buildConfiguration;
} else {
splitBuildConfiguration = splitInTwoLines(buildConfiguration, boldFm, availableWidth);
}
// draw the two lines for the build configuration
for (int i = 0; i < 2; ++i) {
if (splitBuildConfiguration[i].isEmpty())
continue;
if (isEnabled()) {
const QRectF shadowR = buildConfigRect[i].translated(0, 1);
painter.setPen(QColor(30, 30, 30, 80));
painter.drawText(shadowR, textFlags, splitBuildConfiguration[i]);
painter.setPen(penColor);
}
painter.drawText(buildConfigRect[i], textFlags, splitBuildConfiguration[i]);
}
// pop up arrow next to icon
if (!icon().isNull()) {
QStyleOption opt;
opt.initFrom(this);
opt.rect = rect().adjusted(rect().width() - 16, 0, -8, 0);
Utils::StyleHelper::drawArrow(QStyle::PE_IndicatorArrowRight, &painter, &opt);
}
} else {
iconRect.moveCenter(rect().center());
Utils::StyleHelper::drawIconWithShadow(icon(), iconRect, &painter, isEnabled() ? QIcon::Normal : QIcon::Disabled);
}
}
void FancyActionBar::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
Q_UNUSED(event)
QColor light = Utils::StyleHelper::sidebarHighlight();
QColor dark = Utils::StyleHelper::sidebarShadow();
painter.setPen(dark);
painter.drawLine(rect().topLeft(), rect().topRight());
painter.setPen(light);
painter.drawLine(rect().topLeft() + QPoint(1,1), rect().topRight() + QPoint(0,1));
}
QSize FancyToolButton::sizeHint() const
{
QSizeF buttonSize = iconSize().expandedTo(QSize(64, 38));
if (defaultAction()->property("titledAction").toBool()) {
QFont boldFont(font());
boldFont.setPointSizeF(Utils::StyleHelper::sidebarFontSize());
boldFont.setBold(true);
QFontMetrics fm(boldFont);
qreal lineHeight = fm.height();
const QString projectName = defaultAction()->property("heading").toString();
buttonSize += QSizeF(0, 10);
if (!projectName.isEmpty())
buttonSize += QSizeF(0, lineHeight + 2);
buttonSize += QSizeF(0, lineHeight*2 + 2);
}
return buttonSize.toSize();
}
QSize FancyToolButton::minimumSizeHint() const
{
return QSize(8, 8);
}
void FancyToolButton::actionChanged()
{
// the default action changed in some way, e.g. it might got hidden
// since we inherit a tool button we won't get invisible, so do this here
if (!m_hasForceVisible) {
if (QAction* action = defaultAction())
setVisible(action->isVisible());
}
}
FancyActionBar::FancyActionBar(QWidget *parent)
: QWidget(parent)
{
setObjectName(QLatin1String("actionbar"));
m_actionsLayout = new QVBoxLayout;
QVBoxLayout *spacerLayout = new QVBoxLayout;
spacerLayout->addLayout(m_actionsLayout);
int sbh = 8;
spacerLayout->addSpacing(sbh);
spacerLayout->setMargin(0);
spacerLayout->setSpacing(0);
setLayout(spacerLayout);
setContentsMargins(0,2,0,0);
}
void FancyActionBar::addProjectSelector(QAction *action)
{
FancyToolButton* toolButton = new FancyToolButton(this);
toolButton->setDefaultAction(action);
connect(action, SIGNAL(changed()), toolButton, SLOT(actionChanged()));
m_actionsLayout->insertWidget(0, toolButton);
}
void FancyActionBar::insertAction(int index, QAction *action)
{
FancyToolButton *toolButton = new FancyToolButton(this);
toolButton->setDefaultAction(action);
connect(action, SIGNAL(changed()), toolButton, SLOT(actionChanged()));
m_actionsLayout->insertWidget(index, toolButton);
}
QLayout *FancyActionBar::actionsLayout() const
{
return m_actionsLayout;
}
QSize FancyActionBar::minimumSizeHint() const
{
return sizeHint();
}
<|endoftext|> |
<commit_before>/** \brief Generates a continous decompressed stream of data from a BASE tarball containing gzipped ListRecord files.
* \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)
*
* \copyright 2016 Universitätsbiblothek Tübingen. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <cstdlib>
#include "Archive.h"
#include "Compiler.h"
#include "FileUtil.h"
#include "GzStream.h"
#include "util.h"
__attribute__((noreturn)) void Usage() {
std::cerr << "Usage: " << ::progname << " [--verbose] base_tarball_input output\n";
std::exit(EXIT_FAILURE);
}
void ProcessTarball(const bool verbose, const std::string &input_filename, File * const output) {
ArchiveReader reader(input_filename);
unsigned member_count(0);
ArchiveReader::EntryInfo entry_info;
while (reader.getNext(&entry_info)) {
++member_count;
GzStream gunzip_streamer(GzStream::GUNZIP);
char compressed_data[8192];
ssize_t n_read;
unsigned bytes_consumed, bytes_produced;
bool more(false);
char decompressed_data[8192];
while ((n_read = reader.read(compressed_data, sizeof compressed_data)) > 0) {
unsigned total_processed(0);
do {
more = gunzip_streamer.decompress(compressed_data + total_processed,
static_cast<unsigned>(n_read) - total_processed, decompressed_data,
sizeof decompressed_data, &bytes_consumed, &bytes_produced);
if (unlikely(output->write(decompressed_data, bytes_produced) != bytes_produced))
Error("unexpected error while writing to \"" + output->getPath() + "\"!");
total_processed += bytes_consumed;
} while (total_processed < n_read);
}
if (unlikely(n_read == -1))
Error("unexpected error while reading tar member data! (" + reader.getLastErrorMessage() + ")");
while (more) {
more = gunzip_streamer.decompress(nullptr, n_read, decompressed_data, sizeof(decompressed_data),
&bytes_consumed, &bytes_produced);
if (unlikely(output->write(decompressed_data, bytes_produced) != bytes_produced))
Error("unexpected error while writing to \"" + output->getPath() + "\"!");
}
}
if (verbose)
std::cerr << "The tarball contained " << member_count << " entries.\n";
}
int main(int argc, char *argv[]) {
::progname = argv[0];
if (argc != 3 and argc != 4)
Usage();
bool verbose(false);
if (argc == 4) {
if (std::strcmp(argv[1], "--verbose") != 0)
Usage();
verbose = true;
--argc, ++argv;
}
const std::unique_ptr<File> output(FileUtil::OpenOutputFileOrDie(argv[2]));
try {
ProcessTarball(verbose, argv[1], output.get());
} catch (const std::exception &x) {
Error("caught exception: " + std::string(x.what()));
}
}
<commit_msg>Fixed a typo.<commit_after>/** \brief Generates a continous decompressed stream of data from a BASE tarball containing gzipped ListRecord files.
* \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)
*
* \copyright 2016 Universitätsbibliothek Tübingen. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <cstdlib>
#include "Archive.h"
#include "Compiler.h"
#include "FileUtil.h"
#include "GzStream.h"
#include "util.h"
__attribute__((noreturn)) void Usage() {
std::cerr << "Usage: " << ::progname << " [--verbose] base_tarball_input output\n";
std::exit(EXIT_FAILURE);
}
void ProcessTarball(const bool verbose, const std::string &input_filename, File * const output) {
ArchiveReader reader(input_filename);
unsigned member_count(0);
ArchiveReader::EntryInfo entry_info;
while (reader.getNext(&entry_info)) {
++member_count;
GzStream gunzip_streamer(GzStream::GUNZIP);
char compressed_data[8192];
ssize_t n_read;
unsigned bytes_consumed, bytes_produced;
bool more(false);
char decompressed_data[8192];
while ((n_read = reader.read(compressed_data, sizeof compressed_data)) > 0) {
unsigned total_processed(0);
do {
more = gunzip_streamer.decompress(compressed_data + total_processed,
static_cast<unsigned>(n_read) - total_processed, decompressed_data,
sizeof decompressed_data, &bytes_consumed, &bytes_produced);
if (unlikely(output->write(decompressed_data, bytes_produced) != bytes_produced))
Error("unexpected error while writing to \"" + output->getPath() + "\"!");
total_processed += bytes_consumed;
} while (total_processed < n_read);
}
if (unlikely(n_read == -1))
Error("unexpected error while reading tar member data! (" + reader.getLastErrorMessage() + ")");
while (more) {
more = gunzip_streamer.decompress(nullptr, n_read, decompressed_data, sizeof(decompressed_data),
&bytes_consumed, &bytes_produced);
if (unlikely(output->write(decompressed_data, bytes_produced) != bytes_produced))
Error("unexpected error while writing to \"" + output->getPath() + "\"!");
}
}
if (verbose)
std::cerr << "The tarball contained " << member_count << " entries.\n";
}
int main(int argc, char *argv[]) {
::progname = argv[0];
if (argc != 3 and argc != 4)
Usage();
bool verbose(false);
if (argc == 4) {
if (std::strcmp(argv[1], "--verbose") != 0)
Usage();
verbose = true;
--argc, ++argv;
}
const std::unique_ptr<File> output(FileUtil::OpenOutputFileOrDie(argv[2]));
try {
ProcessTarball(verbose, argv[1], output.get());
} catch (const std::exception &x) {
Error("caught exception: " + std::string(x.what()));
}
}
<|endoftext|> |
<commit_before>/* 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.
==============================================================================*/
#include "tensorflow/compiler/jit/xla_kernel_creator.h"
#include "absl/memory/memory.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "tensorflow/compiler/jit/compilability_check_util.h"
#include "tensorflow/compiler/jit/defs.h"
#include "tensorflow/compiler/jit/flags.h"
#include "tensorflow/compiler/jit/kernels/xla_ops.h"
#include "tensorflow/compiler/tf2xla/const_analysis.h"
#include "tensorflow/compiler/tf2xla/mlir_bridge_pass.h"
#include "tensorflow/compiler/tf2xla/xla_op_registry.h"
#include "tensorflow/core/common_runtime/function.h"
#include "tensorflow/core/framework/node_def_builder.h"
#include "tensorflow/core/framework/node_def_util.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/util/ptr_util.h"
namespace tensorflow {
// Returns true iff 'ndef' is a call to a function that is compilable. A
// function is compilable iff every operator in the function body is
// compilable. If 'ndef' is not compilable and 'uncompilable_node_info' is not
// null, we will populate 'uncompilable_node_info' with uncompilable node info.
static bool IsCompilable(FunctionLibraryRuntime* flr, const NodeDef& ndef,
RecursiveCompilabilityChecker::UncompilableNodesMap*
uncompilable_node_info) {
Device* device = flr->device();
const XlaOpRegistry::DeviceRegistration* registration;
CHECK(XlaOpRegistry::GetCompilationDevice(device->device_type(),
®istration));
// We can always *compile* resource operations, stateful RNGs and dummy ops,
// even if we are sometimes unable to auto-cluster them.
RecursiveCompilabilityChecker::OperationFilter op_filter;
op_filter.allow_resource_ops_in_called_functions = true;
op_filter.allow_stack_ops = true;
op_filter.allow_tensor_array_ops = true;
op_filter.allow_stateful_rng_ops = true;
op_filter.allow_control_trigger = true;
op_filter.allow_eliding_assert_and_checknumerics_ops = true;
op_filter.allow_ops_producing_or_consuming_variant = true;
op_filter.allow_slow_ops = true;
op_filter.allow_inaccurate_ops = true;
RecursiveCompilabilityChecker checker{
op_filter, DeviceType{registration->compilation_device_name}};
if (!uncompilable_node_info) {
// We do not need uncompilable node info. Just return the result.
return checker.IsCompilableCall(ndef, flr);
}
RecursiveCompilabilityChecker::UncompilableNodesMap uncompilable_node_result =
checker.FindUncompilableNodes(ndef, flr);
uncompilable_node_info->swap(uncompilable_node_result);
return uncompilable_node_info->empty();
}
bool XlaKernelCreator::CanCreateKernel(
const FunctionLibraryRuntime& flr,
const std::shared_ptr<const NodeProperties>& props) const {
return CanCreateXlaKernel(props->node_def) &&
!XlaOpRegistry::IsCompilationDevice(flr.device()->device_type());
}
static Status CreateXlaKernel(FunctionLibraryRuntime* flr,
const NodeDef& node_def,
std::unique_ptr<OpKernel>* kernel) {
if (!CanCreateXlaKernel(node_def)) {
return errors::Internal("Invalid node: ", node_def.ShortDebugString());
}
VLOG(3) << "Attempting to create XlaLaunchOp for " << node_def.DebugString();
// Make sure that kernels have been registered on the JIT device.
XlaOpRegistry::RegisterCompilationKernels();
// Get function body, constant args, and resource args.
NameAttrList function;
TF_RETURN_IF_ERROR(NameAndAttrsFromFunctionCall(node_def, &function));
const FunctionBody* fbody = nullptr;
std::vector<int> constant_arg_indices;
std::vector<int> resource_arg_indices;
TF_RETURN_IF_ERROR(GetBodyAndConstantsAndResources(
flr, function, &fbody, &constant_arg_indices, &resource_arg_indices));
// Only check for compilability if the MLIR bridge is not enabled.
absl::optional<ConfigProto> config_proto;
if (flr->config_proto()) {
config_proto = *flr->config_proto();
}
if (!IsMlirBridgePassEnabled(*fbody->graph, config_proto)) {
RecursiveCompilabilityChecker::UncompilableNodesMap uncompilable_nodes_map;
if (!IsCompilable(flr, node_def, &uncompilable_nodes_map)) {
std::vector<RecursiveCompilabilityChecker::UncompilableNodeInfo>
uncompilable_node_info;
for (const auto& it : uncompilable_nodes_map) {
for (const auto& info : it.second.second) {
uncompilable_node_info.emplace_back(info);
}
}
string message = absl::StrCat(
"Function invoked by the following node is not compilable: ",
SummarizeNodeDef(node_def, /*max_inputs_in_summary=*/10), ".\n");
absl::StrAppend(&message, "Uncompilable nodes:");
for (const auto& node_info : uncompilable_node_info) {
string node_message = absl::StrCat("\n", node_info.name, ": ",
node_info.uncompilable_reason, "\n",
"\tStacktrace:\n");
for (const auto& stack_frame : node_info.stack_trace) {
absl::StrAppendFormat(&node_message, "\t\tNode: %s, function: %s\n",
stack_frame.name, stack_frame.function_name);
}
absl::StrAppend(&message, node_message);
}
VLOG(1) << message;
return errors::InvalidArgument(message);
}
}
MemoryTypeVector input_memory_types =
GetInputMemoryTypes(fbody, constant_arg_indices, resource_arg_indices);
MemoryTypeVector output_memory_types = GetOutputMemoryTypes(fbody);
// Create the kernel.
Device* dev = flr->device();
Status s;
auto props = std::make_shared<NodeProperties>(
&fbody->fdef.signature(), node_def, fbody->arg_types, fbody->ret_types);
OpKernelConstruction construction(DeviceType(dev->device_type()), dev,
dev->GetAllocator(AllocatorAttributes()),
flr, dev->resource_manager(), props,
input_memory_types, output_memory_types,
flr->graph_def_version(), &s);
*kernel = absl::make_unique<XlaLocalLaunchBase>(
&construction, constant_arg_indices, resource_arg_indices, function,
/*has_ref_vars=*/false);
return s;
}
Status XlaKernelCreator::CreateKernel(
FunctionLibraryRuntime* flr,
const std::shared_ptr<const NodeProperties>& props,
std::unique_ptr<OpKernel>* kernel) const {
return CreateXlaKernel(flr, props->node_def, kernel);
}
static bool RegisterLaunchOpCreator() {
XlaKernelCreator* xla_kernel_creator = new XlaKernelCreator();
RegisterDefaultCustomKernelCreator(xla_kernel_creator);
return true;
}
static bool register_me = RegisterLaunchOpCreator();
} // namespace tensorflow
<commit_msg>Enable XLA verification only if MLIR bridge is not enabled explicitly by user.<commit_after>/* 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.
==============================================================================*/
#include "tensorflow/compiler/jit/xla_kernel_creator.h"
#include "absl/memory/memory.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "tensorflow/compiler/jit/compilability_check_util.h"
#include "tensorflow/compiler/jit/defs.h"
#include "tensorflow/compiler/jit/flags.h"
#include "tensorflow/compiler/jit/kernels/xla_ops.h"
#include "tensorflow/compiler/tf2xla/const_analysis.h"
#include "tensorflow/compiler/tf2xla/mlir_bridge_pass.h"
#include "tensorflow/compiler/tf2xla/xla_op_registry.h"
#include "tensorflow/core/common_runtime/function.h"
#include "tensorflow/core/framework/node_def_builder.h"
#include "tensorflow/core/framework/node_def_util.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/util/ptr_util.h"
namespace tensorflow {
// Returns true iff 'ndef' is a call to a function that is compilable. A
// function is compilable iff every operator in the function body is
// compilable. If 'ndef' is not compilable and 'uncompilable_node_info' is not
// null, we will populate 'uncompilable_node_info' with uncompilable node info.
static bool IsCompilable(FunctionLibraryRuntime* flr, const NodeDef& ndef,
RecursiveCompilabilityChecker::UncompilableNodesMap*
uncompilable_node_info) {
Device* device = flr->device();
const XlaOpRegistry::DeviceRegistration* registration;
CHECK(XlaOpRegistry::GetCompilationDevice(device->device_type(),
®istration));
// We can always *compile* resource operations, stateful RNGs and dummy ops,
// even if we are sometimes unable to auto-cluster them.
RecursiveCompilabilityChecker::OperationFilter op_filter;
op_filter.allow_resource_ops_in_called_functions = true;
op_filter.allow_stack_ops = true;
op_filter.allow_tensor_array_ops = true;
op_filter.allow_stateful_rng_ops = true;
op_filter.allow_control_trigger = true;
op_filter.allow_eliding_assert_and_checknumerics_ops = true;
op_filter.allow_ops_producing_or_consuming_variant = true;
op_filter.allow_slow_ops = true;
op_filter.allow_inaccurate_ops = true;
RecursiveCompilabilityChecker checker{
op_filter, DeviceType{registration->compilation_device_name}};
if (!uncompilable_node_info) {
// We do not need uncompilable node info. Just return the result.
return checker.IsCompilableCall(ndef, flr);
}
RecursiveCompilabilityChecker::UncompilableNodesMap uncompilable_node_result =
checker.FindUncompilableNodes(ndef, flr);
uncompilable_node_info->swap(uncompilable_node_result);
return uncompilable_node_info->empty();
}
bool XlaKernelCreator::CanCreateKernel(
const FunctionLibraryRuntime& flr,
const std::shared_ptr<const NodeProperties>& props) const {
return CanCreateXlaKernel(props->node_def) &&
!XlaOpRegistry::IsCompilationDevice(flr.device()->device_type());
}
static Status CreateXlaKernel(FunctionLibraryRuntime* flr,
const NodeDef& node_def,
std::unique_ptr<OpKernel>* kernel) {
if (!CanCreateXlaKernel(node_def)) {
return errors::Internal("Invalid node: ", node_def.ShortDebugString());
}
VLOG(3) << "Attempting to create XlaLaunchOp for " << node_def.DebugString();
// Make sure that kernels have been registered on the JIT device.
XlaOpRegistry::RegisterCompilationKernels();
// Get function body, constant args, and resource args.
NameAttrList function;
TF_RETURN_IF_ERROR(NameAndAttrsFromFunctionCall(node_def, &function));
const FunctionBody* fbody = nullptr;
std::vector<int> constant_arg_indices;
std::vector<int> resource_arg_indices;
TF_RETURN_IF_ERROR(GetBodyAndConstantsAndResources(
flr, function, &fbody, &constant_arg_indices, &resource_arg_indices));
// Only check for compilability if the MLIR bridge is not enabled.
absl::optional<ConfigProto> config_proto;
if (flr->config_proto()) {
config_proto = *flr->config_proto();
}
MlirBridgeRolloutPolicy policy =
GetMlirBridgeRolloutPolicy(*fbody->graph, config_proto);
if (policy != MlirBridgeRolloutPolicy::kEnabledByUser) {
RecursiveCompilabilityChecker::UncompilableNodesMap uncompilable_nodes_map;
if (!IsCompilable(flr, node_def, &uncompilable_nodes_map)) {
std::vector<RecursiveCompilabilityChecker::UncompilableNodeInfo>
uncompilable_node_info;
for (const auto& it : uncompilable_nodes_map) {
for (const auto& info : it.second.second) {
uncompilable_node_info.emplace_back(info);
}
}
string message = absl::StrCat(
"Function invoked by the following node is not compilable: ",
SummarizeNodeDef(node_def, /*max_inputs_in_summary=*/10), ".\n");
absl::StrAppend(&message, "Uncompilable nodes:");
for (const auto& node_info : uncompilable_node_info) {
string node_message = absl::StrCat("\n", node_info.name, ": ",
node_info.uncompilable_reason, "\n",
"\tStacktrace:\n");
for (const auto& stack_frame : node_info.stack_trace) {
absl::StrAppendFormat(&node_message, "\t\tNode: %s, function: %s\n",
stack_frame.name, stack_frame.function_name);
}
absl::StrAppend(&message, node_message);
}
VLOG(1) << message;
return errors::InvalidArgument(message);
}
}
MemoryTypeVector input_memory_types =
GetInputMemoryTypes(fbody, constant_arg_indices, resource_arg_indices);
MemoryTypeVector output_memory_types = GetOutputMemoryTypes(fbody);
// Create the kernel.
Device* dev = flr->device();
Status s;
auto props = std::make_shared<NodeProperties>(
&fbody->fdef.signature(), node_def, fbody->arg_types, fbody->ret_types);
OpKernelConstruction construction(DeviceType(dev->device_type()), dev,
dev->GetAllocator(AllocatorAttributes()),
flr, dev->resource_manager(), props,
input_memory_types, output_memory_types,
flr->graph_def_version(), &s);
*kernel = absl::make_unique<XlaLocalLaunchBase>(
&construction, constant_arg_indices, resource_arg_indices, function,
/*has_ref_vars=*/false);
return s;
}
Status XlaKernelCreator::CreateKernel(
FunctionLibraryRuntime* flr,
const std::shared_ptr<const NodeProperties>& props,
std::unique_ptr<OpKernel>* kernel) const {
return CreateXlaKernel(flr, props->node_def, kernel);
}
static bool RegisterLaunchOpCreator() {
XlaKernelCreator* xla_kernel_creator = new XlaKernelCreator();
RegisterDefaultCustomKernelCreator(xla_kernel_creator);
return true;
}
static bool register_me = RegisterLaunchOpCreator();
} // namespace tensorflow
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "cpphoverhandler.h"
#include "cppeditor.h"
#include <coreplugin/icore.h>
#include <coreplugin/helpmanager.h>
#include <coreplugin/uniqueidmanager.h>
#include <coreplugin/editormanager/editormanager.h>
#include <cpptools/cppmodelmanagerinterface.h>
#include <extensionsystem/pluginmanager.h>
#include <texteditor/itexteditor.h>
#include <texteditor/basetexteditor.h>
#include <debugger/debuggerconstants.h>
#include <utils/htmldocextractor.h>
#include <FullySpecifiedType.h>
#include <Scope.h>
#include <Symbol.h>
#include <Symbols.h>
#include <cplusplus/ExpressionUnderCursor.h>
#include <cplusplus/Overview.h>
#include <cplusplus/TypeOfExpression.h>
#include <cplusplus/LookupContext.h>
#include <cplusplus/LookupItem.h>
#include <QtCore/QDir>
#include <QtCore/QFileInfo>
#include <QtGui/QToolTip>
#include <QtGui/QTextCursor>
using namespace CppEditor::Internal;
using namespace CPlusPlus;
using namespace Core;
namespace {
QString removeQualificationIfAny(const QString &name) {
int index = name.lastIndexOf(QLatin1Char(':'));
if (index == -1)
return name;
else
return name.right(name.length() - index - 1);
}
void moveCursorToEndOfQualifiedName(QTextCursor *tc) {
QTextDocument *doc = tc->document();
if (!doc)
return;
while (true) {
const QChar &ch = doc->characterAt(tc->position());
if (ch.isLetterOrNumber() || ch == QLatin1Char('_'))
tc->movePosition(QTextCursor::NextCharacter);
else if (ch == QLatin1Char(':') &&
doc->characterAt(tc->position() + 1) == QLatin1Char(':'))
tc->movePosition(QTextCursor::NextCharacter, QTextCursor::MoveAnchor, 2);
else
break;
}
}
}
CppHoverHandler::CppHoverHandler(QObject *parent)
: QObject(parent), m_modelManager(0), m_matchingHelpCandidate(-1)
{
m_modelManager =
ExtensionSystem::PluginManager::instance()->getObject<CppTools::CppModelManagerInterface>();
m_htmlDocExtractor.setLengthReference(1000, true);
// Listen for editor opened events in order to connect to tooltip/helpid requests
connect(ICore::instance()->editorManager(), SIGNAL(editorOpened(Core::IEditor *)),
this, SLOT(editorOpened(Core::IEditor *)));
}
void CppHoverHandler::editorOpened(IEditor *editor)
{
CPPEditorEditable *cppEditor = qobject_cast<CPPEditorEditable *>(editor);
if (!cppEditor)
return;
connect(cppEditor, SIGNAL(tooltipRequested(TextEditor::ITextEditor*, QPoint, int)),
this, SLOT(showToolTip(TextEditor::ITextEditor*, QPoint, int)));
connect(cppEditor, SIGNAL(contextHelpIdRequested(TextEditor::ITextEditor*, int)),
this, SLOT(updateContextHelpId(TextEditor::ITextEditor*, int)));
}
void CppHoverHandler::updateContextHelpId(TextEditor::ITextEditor *editor, int pos)
{
if (!editor)
return;
// If the tooltip is visible and there is a help match, this match is used to update the help
// id. Otherwise, the identification process happens.
if (!QToolTip::isVisible() || m_matchingHelpCandidate == -1)
identifyMatch(editor, pos);
if (m_matchingHelpCandidate != -1)
editor->setContextHelpId(m_helpCandidates.at(m_matchingHelpCandidate).m_helpId);
else
editor->setContextHelpId(QString());
}
void CppHoverHandler::showToolTip(TextEditor::ITextEditor *editor, const QPoint &point, int pos)
{
if (!editor)
return;
editor->setContextHelpId(QString());
ICore *core = ICore::instance();
const int dbgContext =
core->uniqueIDManager()->uniqueIdentifier(Debugger::Constants::C_DEBUGMODE);
if (core->hasContext(dbgContext))
return;
identifyMatch(editor, pos);
if (m_toolTip.isEmpty()) {
QToolTip::hideText();
} else {
if (m_matchingHelpCandidate != -1) {
const QString &contents = getDocContents();
if (!contents.isEmpty()) {
m_toolTip = contents;
} else {
m_toolTip = Qt::escape(m_toolTip);
m_toolTip.prepend(QLatin1String("<nobr>"));
m_toolTip.append(QLatin1String("</nobr>"));
}
m_toolTip = QString(QLatin1String("<table><tr>"
"<td valign=middle>%1</td>"
"<td><img src=\":/cppeditor/images/f1.png\"></td>"
"</tr></table>")).arg(m_toolTip);
}
const QPoint pnt = point - QPoint(0,
#ifdef Q_WS_WIN
24
#else
16
#endif
);
QToolTip::showText(pnt, m_toolTip);
}
}
void CppHoverHandler::identifyMatch(TextEditor::ITextEditor *editor, int pos)
{
resetMatchings();
if (!m_modelManager)
return;
const Snapshot &snapshot = m_modelManager->snapshot();
Document::Ptr doc = snapshot.document(editor->file()->fileName());
if (!doc)
return;
int line = 0;
int column = 0;
editor->convertPosition(pos, &line, &column);
if (!matchDiagnosticMessage(doc, line) &&
!matchIncludeFile(doc, line) &&
!matchMacroInUse(doc, pos)) {
TextEditor::BaseTextEditor *baseEditor = baseTextEditor(editor);
if (!baseEditor)
return;
bool extraSelectionTooltip = false;
if (!baseEditor->extraSelectionTooltip(pos).isEmpty()) {
m_toolTip = baseEditor->extraSelectionTooltip(pos);
extraSelectionTooltip = true;
}
QTextCursor tc(baseEditor->document());
tc.setPosition(pos);
moveCursorToEndOfQualifiedName(&tc);
// Fetch the expression's code
ExpressionUnderCursor expressionUnderCursor;
const QString &expression = expressionUnderCursor(tc);
Scope *scope = doc->scopeAt(line, column);
TypeOfExpression typeOfExpression;
typeOfExpression.init(doc, snapshot);
const QList<LookupItem> &lookupItems = typeOfExpression(expression, scope);
if (lookupItems.isEmpty())
return;
const LookupItem &lookupItem = lookupItems.first(); // ### TODO: select the best candidate.
handleLookupItemMatch(lookupItem, !extraSelectionTooltip);
}
evaluateHelpCandidates();
}
bool CppHoverHandler::matchDiagnosticMessage(const CPlusPlus::Document::Ptr &document,
const int line)
{
foreach (const Document::DiagnosticMessage &m, document->diagnosticMessages()) {
if (m.line() == line) {
m_toolTip = m.text();
return true;
}
}
return false;
}
bool CppHoverHandler::matchIncludeFile(const CPlusPlus::Document::Ptr &document, const int line)
{
foreach (const Document::Include &includeFile, document->includes()) {
if (includeFile.line() == line) {
m_toolTip = QDir::toNativeSeparators(includeFile.fileName());
const QString &fileName = QFileInfo(includeFile.fileName()).fileName();
m_helpCandidates.append(HelpCandidate(fileName, fileName, HelpCandidate::Include));
return true;
}
}
return false;
}
bool CppHoverHandler::matchMacroInUse(const CPlusPlus::Document::Ptr &document, const int pos)
{
foreach (const Document::MacroUse &use, document->macroUses()) {
if (use.contains(pos)) {
const Macro& macro = use.macro();
m_toolTip = macro.toString();
m_helpCandidates.append(HelpCandidate(macro.name(),
macro.name(),
HelpCandidate::Macro));
return true;
}
}
return false;
}
void CppHoverHandler::handleLookupItemMatch(const LookupItem &lookupItem, const bool assignTooltip)
{
Symbol *matchingDeclaration = lookupItem.declaration();
FullySpecifiedType matchingType = lookupItem.type();
Overview overview;
overview.setShowArgumentNames(true);
overview.setShowReturnTypes(true);
overview.setShowFullyQualifiedNamed(true);
if (!matchingDeclaration && assignTooltip) {
m_toolTip = overview.prettyType(matchingType, QLatin1String(""));
} else {
QString qualifiedName;
HelpCandidate::Category helpCategory;
if (matchingDeclaration->enclosingSymbol()->isClass() ||
matchingDeclaration->enclosingSymbol()->isNamespace() ||
matchingDeclaration->enclosingSymbol()->isEnum()) {
// Fully qualify the name if enclosed by a class, namespace or enum.
QList<const Name *> names = LookupContext::fullyQualifiedName(matchingDeclaration);
if (matchingDeclaration->isNamespace() ||
matchingDeclaration->isClass() ||
matchingDeclaration->isForwardClassDeclaration()) {
// In this case the declaration name appears in the fully qualified name. Remove
// it since it is already considered below.
names.removeLast();
helpCategory = HelpCandidate::ClassOrNamespace;
} else if (matchingDeclaration->isEnum()) {
helpCategory = HelpCandidate::Enum;
} else if (matchingDeclaration->isTypedef()) {
helpCategory = HelpCandidate::Typedef;
} else if (matchingDeclaration->isStatic() && !matchingDeclaration->isFunction()) {
helpCategory = HelpCandidate::Var;
} else {
helpCategory = HelpCandidate::Function;
}
foreach (const Name *name, names) {
qualifiedName.append(overview.prettyName(name));
qualifiedName.append(QLatin1String("::"));
}
}
qualifiedName.append(overview.prettyName(matchingDeclaration->name()));
if (assignTooltip) {
if (matchingDeclaration->isClass() ||
matchingDeclaration->isNamespace() ||
matchingDeclaration->isForwardClassDeclaration() ||
matchingDeclaration->isEnum()) {
m_toolTip = qualifiedName;
} else {
m_toolTip = overview.prettyType(matchingType, qualifiedName);
}
}
// Help identifiers are simply the name with no signature, arguments or return type.
// They might or might not include a qualification. This is why two candidates are
// created.
overview.setShowArgumentNames(false);
overview.setShowReturnTypes(false);
overview.setShowFunctionSignatures(false);
overview.setShowFullyQualifiedNamed(false);
const QString &simpleName = overview.prettyName(matchingDeclaration->name());
overview.setShowFunctionSignatures(true);
const QString &specifierId = overview.prettyType(matchingType, simpleName);
m_helpCandidates.append(HelpCandidate(simpleName, specifierId, helpCategory));
m_helpCandidates.append(HelpCandidate(qualifiedName, specifierId, helpCategory));
}
}
void CppHoverHandler::evaluateHelpCandidates()
{
for (int i = 0; i < m_helpCandidates.size(); ++i) {
if (helpIdExists(m_helpCandidates.at(i).m_helpId)) {
m_matchingHelpCandidate = i;
return;
}
}
}
bool CppHoverHandler::helpIdExists(const QString &helpId) const
{
QMap<QString, QUrl> helpLinks = Core::HelpManager::instance()->linksForIdentifier(helpId);
if (!helpLinks.isEmpty())
return true;
return false;
}
QString CppHoverHandler::getDocContents()
{
Q_ASSERT(m_matchingHelpCandidate >= 0);
QString contents;
const HelpCandidate &help = m_helpCandidates.at(m_matchingHelpCandidate);
QMap<QString, QUrl> helpLinks =
Core::HelpManager::instance()->linksForIdentifier(help.m_helpId);
foreach (const QUrl &url, helpLinks) {
// The help id might or might not be qualified. But anchors and marks are not qualified.
const QString &name = removeQualificationIfAny(help.m_helpId);
const QByteArray &html = Core::HelpManager::instance()->fileData(url);
switch (help.m_category) {
case HelpCandidate::Include:
contents = m_htmlDocExtractor.getClassOrNamespaceBrief(html, name);
break;
case HelpCandidate::ClassOrNamespace:
contents = m_htmlDocExtractor.getClassOrNamespaceDescription(html, name);
break;
case HelpCandidate::Function:
contents =
m_htmlDocExtractor.getFunctionDescription(html, help.m_markId, name);
break;
case HelpCandidate::Enum:
contents = m_htmlDocExtractor.getEnumDescription(html, name);
break;
case HelpCandidate::Typedef:
contents = m_htmlDocExtractor.getTypedefDescription(html, name);
break;
case HelpCandidate::Var:
contents = m_htmlDocExtractor.getVarDescription(html, name);
break;
case HelpCandidate::Macro:
contents = m_htmlDocExtractor.getMacroDescription(html, help.m_markId, name);
break;
default:
break;
}
if (!contents.isEmpty())
break;
}
return contents;
}
void CppHoverHandler::resetMatchings()
{
m_matchingHelpCandidate = -1;
m_helpCandidates.clear();
m_toolTip.clear();
}
TextEditor::BaseTextEditor *CppHoverHandler::baseTextEditor(TextEditor::ITextEditor *editor)
{
return qobject_cast<TextEditor::BaseTextEditor *>(editor->widget());
}
<commit_msg>C++ tooltip: Display macro tooltip only if hover is actually over the macro name.<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "cpphoverhandler.h"
#include "cppeditor.h"
#include <coreplugin/icore.h>
#include <coreplugin/helpmanager.h>
#include <coreplugin/uniqueidmanager.h>
#include <coreplugin/editormanager/editormanager.h>
#include <cpptools/cppmodelmanagerinterface.h>
#include <extensionsystem/pluginmanager.h>
#include <texteditor/itexteditor.h>
#include <texteditor/basetexteditor.h>
#include <debugger/debuggerconstants.h>
#include <utils/htmldocextractor.h>
#include <FullySpecifiedType.h>
#include <Scope.h>
#include <Symbol.h>
#include <Symbols.h>
#include <cplusplus/ExpressionUnderCursor.h>
#include <cplusplus/Overview.h>
#include <cplusplus/TypeOfExpression.h>
#include <cplusplus/LookupContext.h>
#include <cplusplus/LookupItem.h>
#include <QtCore/QDir>
#include <QtCore/QFileInfo>
#include <QtGui/QToolTip>
#include <QtGui/QTextCursor>
using namespace CppEditor::Internal;
using namespace CPlusPlus;
using namespace Core;
namespace {
QString removeQualificationIfAny(const QString &name) {
int index = name.lastIndexOf(QLatin1Char(':'));
if (index == -1)
return name;
else
return name.right(name.length() - index - 1);
}
void moveCursorToEndOfQualifiedName(QTextCursor *tc) {
QTextDocument *doc = tc->document();
if (!doc)
return;
while (true) {
const QChar &ch = doc->characterAt(tc->position());
if (ch.isLetterOrNumber() || ch == QLatin1Char('_'))
tc->movePosition(QTextCursor::NextCharacter);
else if (ch == QLatin1Char(':') &&
doc->characterAt(tc->position() + 1) == QLatin1Char(':'))
tc->movePosition(QTextCursor::NextCharacter, QTextCursor::MoveAnchor, 2);
else
break;
}
}
}
CppHoverHandler::CppHoverHandler(QObject *parent)
: QObject(parent), m_modelManager(0), m_matchingHelpCandidate(-1)
{
m_modelManager =
ExtensionSystem::PluginManager::instance()->getObject<CppTools::CppModelManagerInterface>();
m_htmlDocExtractor.setLengthReference(1000, true);
// Listen for editor opened events in order to connect to tooltip/helpid requests
connect(ICore::instance()->editorManager(), SIGNAL(editorOpened(Core::IEditor *)),
this, SLOT(editorOpened(Core::IEditor *)));
}
void CppHoverHandler::editorOpened(IEditor *editor)
{
CPPEditorEditable *cppEditor = qobject_cast<CPPEditorEditable *>(editor);
if (!cppEditor)
return;
connect(cppEditor, SIGNAL(tooltipRequested(TextEditor::ITextEditor*, QPoint, int)),
this, SLOT(showToolTip(TextEditor::ITextEditor*, QPoint, int)));
connect(cppEditor, SIGNAL(contextHelpIdRequested(TextEditor::ITextEditor*, int)),
this, SLOT(updateContextHelpId(TextEditor::ITextEditor*, int)));
}
void CppHoverHandler::updateContextHelpId(TextEditor::ITextEditor *editor, int pos)
{
if (!editor)
return;
// If the tooltip is visible and there is a help match, this match is used to update the help
// id. Otherwise, the identification process happens.
if (!QToolTip::isVisible() || m_matchingHelpCandidate == -1)
identifyMatch(editor, pos);
if (m_matchingHelpCandidate != -1)
editor->setContextHelpId(m_helpCandidates.at(m_matchingHelpCandidate).m_helpId);
else
editor->setContextHelpId(QString());
}
void CppHoverHandler::showToolTip(TextEditor::ITextEditor *editor, const QPoint &point, int pos)
{
if (!editor)
return;
editor->setContextHelpId(QString());
ICore *core = ICore::instance();
const int dbgContext =
core->uniqueIDManager()->uniqueIdentifier(Debugger::Constants::C_DEBUGMODE);
if (core->hasContext(dbgContext))
return;
identifyMatch(editor, pos);
if (m_toolTip.isEmpty()) {
QToolTip::hideText();
} else {
if (m_matchingHelpCandidate != -1) {
const QString &contents = getDocContents();
if (!contents.isEmpty()) {
m_toolTip = contents;
} else {
m_toolTip = Qt::escape(m_toolTip);
m_toolTip.prepend(QLatin1String("<nobr>"));
m_toolTip.append(QLatin1String("</nobr>"));
}
m_toolTip = QString(QLatin1String("<table><tr>"
"<td valign=middle>%1</td>"
"<td><img src=\":/cppeditor/images/f1.png\"></td>"
"</tr></table>")).arg(m_toolTip);
}
const QPoint pnt = point - QPoint(0,
#ifdef Q_WS_WIN
24
#else
16
#endif
);
QToolTip::showText(pnt, m_toolTip);
}
}
void CppHoverHandler::identifyMatch(TextEditor::ITextEditor *editor, int pos)
{
resetMatchings();
if (!m_modelManager)
return;
const Snapshot &snapshot = m_modelManager->snapshot();
Document::Ptr doc = snapshot.document(editor->file()->fileName());
if (!doc)
return;
int line = 0;
int column = 0;
editor->convertPosition(pos, &line, &column);
if (!matchDiagnosticMessage(doc, line) &&
!matchIncludeFile(doc, line) &&
!matchMacroInUse(doc, pos)) {
TextEditor::BaseTextEditor *baseEditor = baseTextEditor(editor);
if (!baseEditor)
return;
bool extraSelectionTooltip = false;
if (!baseEditor->extraSelectionTooltip(pos).isEmpty()) {
m_toolTip = baseEditor->extraSelectionTooltip(pos);
extraSelectionTooltip = true;
}
QTextCursor tc(baseEditor->document());
tc.setPosition(pos);
moveCursorToEndOfQualifiedName(&tc);
// Fetch the expression's code
ExpressionUnderCursor expressionUnderCursor;
const QString &expression = expressionUnderCursor(tc);
Scope *scope = doc->scopeAt(line, column);
TypeOfExpression typeOfExpression;
typeOfExpression.init(doc, snapshot);
const QList<LookupItem> &lookupItems = typeOfExpression(expression, scope);
if (lookupItems.isEmpty())
return;
const LookupItem &lookupItem = lookupItems.first(); // ### TODO: select the best candidate.
handleLookupItemMatch(lookupItem, !extraSelectionTooltip);
}
evaluateHelpCandidates();
}
bool CppHoverHandler::matchDiagnosticMessage(const CPlusPlus::Document::Ptr &document,
const int line)
{
foreach (const Document::DiagnosticMessage &m, document->diagnosticMessages()) {
if (m.line() == line) {
m_toolTip = m.text();
return true;
}
}
return false;
}
bool CppHoverHandler::matchIncludeFile(const CPlusPlus::Document::Ptr &document, const int line)
{
foreach (const Document::Include &includeFile, document->includes()) {
if (includeFile.line() == line) {
m_toolTip = QDir::toNativeSeparators(includeFile.fileName());
const QString &fileName = QFileInfo(includeFile.fileName()).fileName();
m_helpCandidates.append(HelpCandidate(fileName, fileName, HelpCandidate::Include));
return true;
}
}
return false;
}
bool CppHoverHandler::matchMacroInUse(const CPlusPlus::Document::Ptr &document, const int pos)
{
foreach (const Document::MacroUse &use, document->macroUses()) {
if (use.contains(pos)) {
const int begin = use.begin();
const QString &name = use.macro().name();
if (pos < begin + name.length()) {
m_toolTip = use.macro().toString();
m_helpCandidates.append(HelpCandidate(name, name, HelpCandidate::Macro));
return true;
}
}
}
return false;
}
void CppHoverHandler::handleLookupItemMatch(const LookupItem &lookupItem, const bool assignTooltip)
{
Symbol *matchingDeclaration = lookupItem.declaration();
FullySpecifiedType matchingType = lookupItem.type();
Overview overview;
overview.setShowArgumentNames(true);
overview.setShowReturnTypes(true);
overview.setShowFullyQualifiedNamed(true);
if (!matchingDeclaration && assignTooltip) {
m_toolTip = overview.prettyType(matchingType, QLatin1String(""));
} else {
QString qualifiedName;
HelpCandidate::Category helpCategory;
if (matchingDeclaration->enclosingSymbol()->isClass() ||
matchingDeclaration->enclosingSymbol()->isNamespace() ||
matchingDeclaration->enclosingSymbol()->isEnum()) {
// Fully qualify the name if enclosed by a class, namespace or enum.
QList<const Name *> names = LookupContext::fullyQualifiedName(matchingDeclaration);
if (matchingDeclaration->isNamespace() ||
matchingDeclaration->isClass() ||
matchingDeclaration->isForwardClassDeclaration()) {
// In this case the declaration name appears in the fully qualified name. Remove
// it since it is already considered below.
names.removeLast();
helpCategory = HelpCandidate::ClassOrNamespace;
} else if (matchingDeclaration->isEnum()) {
helpCategory = HelpCandidate::Enum;
} else if (matchingDeclaration->isTypedef()) {
helpCategory = HelpCandidate::Typedef;
} else if (matchingDeclaration->isStatic() && !matchingDeclaration->isFunction()) {
helpCategory = HelpCandidate::Var;
} else {
helpCategory = HelpCandidate::Function;
}
foreach (const Name *name, names) {
qualifiedName.append(overview.prettyName(name));
qualifiedName.append(QLatin1String("::"));
}
}
qualifiedName.append(overview.prettyName(matchingDeclaration->name()));
if (assignTooltip) {
if (matchingDeclaration->isClass() ||
matchingDeclaration->isNamespace() ||
matchingDeclaration->isForwardClassDeclaration() ||
matchingDeclaration->isEnum()) {
m_toolTip = qualifiedName;
} else {
m_toolTip = overview.prettyType(matchingType, qualifiedName);
}
}
// Help identifiers are simply the name with no signature, arguments or return type.
// They might or might not include a qualification. This is why two candidates are
// created.
overview.setShowArgumentNames(false);
overview.setShowReturnTypes(false);
overview.setShowFunctionSignatures(false);
overview.setShowFullyQualifiedNamed(false);
const QString &simpleName = overview.prettyName(matchingDeclaration->name());
overview.setShowFunctionSignatures(true);
const QString &specifierId = overview.prettyType(matchingType, simpleName);
m_helpCandidates.append(HelpCandidate(simpleName, specifierId, helpCategory));
m_helpCandidates.append(HelpCandidate(qualifiedName, specifierId, helpCategory));
}
}
void CppHoverHandler::evaluateHelpCandidates()
{
for (int i = 0; i < m_helpCandidates.size(); ++i) {
if (helpIdExists(m_helpCandidates.at(i).m_helpId)) {
m_matchingHelpCandidate = i;
return;
}
}
}
bool CppHoverHandler::helpIdExists(const QString &helpId) const
{
QMap<QString, QUrl> helpLinks = Core::HelpManager::instance()->linksForIdentifier(helpId);
if (!helpLinks.isEmpty())
return true;
return false;
}
QString CppHoverHandler::getDocContents()
{
Q_ASSERT(m_matchingHelpCandidate >= 0);
QString contents;
const HelpCandidate &help = m_helpCandidates.at(m_matchingHelpCandidate);
QMap<QString, QUrl> helpLinks =
Core::HelpManager::instance()->linksForIdentifier(help.m_helpId);
foreach (const QUrl &url, helpLinks) {
// The help id might or might not be qualified. But anchors and marks are not qualified.
const QString &name = removeQualificationIfAny(help.m_helpId);
const QByteArray &html = Core::HelpManager::instance()->fileData(url);
switch (help.m_category) {
case HelpCandidate::Include:
contents = m_htmlDocExtractor.getClassOrNamespaceBrief(html, name);
break;
case HelpCandidate::ClassOrNamespace:
contents = m_htmlDocExtractor.getClassOrNamespaceDescription(html, name);
break;
case HelpCandidate::Function:
contents =
m_htmlDocExtractor.getFunctionDescription(html, help.m_markId, name);
break;
case HelpCandidate::Enum:
contents = m_htmlDocExtractor.getEnumDescription(html, name);
break;
case HelpCandidate::Typedef:
contents = m_htmlDocExtractor.getTypedefDescription(html, name);
break;
case HelpCandidate::Var:
contents = m_htmlDocExtractor.getVarDescription(html, name);
break;
case HelpCandidate::Macro:
contents = m_htmlDocExtractor.getMacroDescription(html, help.m_markId, name);
break;
default:
break;
}
if (!contents.isEmpty())
break;
}
return contents;
}
void CppHoverHandler::resetMatchings()
{
m_matchingHelpCandidate = -1;
m_helpCandidates.clear();
m_toolTip.clear();
}
TextEditor::BaseTextEditor *CppHoverHandler::baseTextEditor(TextEditor::ITextEditor *editor)
{
return qobject_cast<TextEditor::BaseTextEditor *>(editor->widget());
}
<|endoftext|> |
<commit_before>/**
* @author Andre Anjos <andre.anjos@idiap.ch>
* @date Thu 7 Nov 13:50:16 2013
*
* @brief Binds configuration information available from bob
*/
#include <Python.h>
#include <string>
#include <cstdlib>
#include <blitz/blitz.h>
#include <boost/preprocessor/stringize.hpp>
#include <boost/version.hpp>
#include <boost/format.hpp>
#ifdef NO_IMPORT_ARRAY
#undef NO_IMPORT_ARRAY
#endif
#include <xbob.blitz/capi.h>
#include <xbob.blitz/cleanup.h>
static int dict_set(PyObject* d, const char* key, const char* value) {
PyObject* v = Py_BuildValue("s", value);
if (!v) return 0;
int retval = PyDict_SetItemString(d, key, v);
Py_DECREF(v);
if (retval == 0) return 1; //all good
return 0; //a problem occurred
}
static int dict_steal(PyObject* d, const char* key, PyObject* value) {
if (!value) return 0;
int retval = PyDict_SetItemString(d, key, value);
Py_DECREF(value);
if (retval == 0) return 1; //all good
return 0; //a problem occurred
}
/**
* Describes the version of Boost libraries installed
*/
static PyObject* boost_version() {
boost::format f("%d.%d.%d");
f % (BOOST_VERSION / 100000);
f % (BOOST_VERSION / 100 % 1000);
f % (BOOST_VERSION % 100);
return Py_BuildValue("s", f.str().c_str());
}
/**
* Describes the compiler version
*/
static PyObject* compiler_version() {
# if defined(__GNUC__) && !defined(__llvm__)
boost::format f("%s.%s.%s");
f % BOOST_PP_STRINGIZE(__GNUC__);
f % BOOST_PP_STRINGIZE(__GNUC_MINOR__);
f % BOOST_PP_STRINGIZE(__GNUC_PATCHLEVEL__);
return Py_BuildValue("{ssss}", "name", "gcc", "version", f.str().c_str());
# elif defined(__llvm__) && !defined(__clang__)
return Py_BuildValue("{ssss}", "name", "llvm-gcc", "version", __VERSION__);
# elif defined(__clang__)
return Py_BuildValue("{ssss}", "name", "clang", "version", __clang_version__);
# else
return Py_BuildValue("{ssss}", "name", "unsupported", "version", "unknown");
# endif
}
/**
* Python version with which we compiled the extensions
*/
static PyObject* python_version() {
boost::format f("%s.%s.%s");
f % BOOST_PP_STRINGIZE(PY_MAJOR_VERSION);
f % BOOST_PP_STRINGIZE(PY_MINOR_VERSION);
f % BOOST_PP_STRINGIZE(PY_MICRO_VERSION);
return Py_BuildValue("s", f.str().c_str());
}
/**
* Numpy version
*/
static PyObject* numpy_version() {
return Py_BuildValue("{ssss}", "abi", BOOST_PP_STRINGIZE(NPY_VERSION),
"api", BOOST_PP_STRINGIZE(NPY_API_VERSION));
}
static PyObject* build_version_dictionary() {
PyObject* retval = PyDict_New();
if (!retval) return 0;
if (!dict_set(retval, "Blitz++", BZ_VERSION)) {
Py_DECREF(retval);
return 0;
}
if (!dict_steal(retval, "Boost", boost_version())) {
Py_DECREF(retval);
return 0;
}
if (!dict_steal(retval, "Compiler", compiler_version())) {
Py_DECREF(retval);
return 0;
}
if (!dict_steal(retval, "Python", python_version())) {
Py_DECREF(retval);
return 0;
}
if (!dict_steal(retval, "NumPy", numpy_version())) {
Py_DECREF(retval);
return 0;
}
return retval;
}
static PyMethodDef module_methods[] = {
{0} /* Sentinel */
};
PyDoc_STRVAR(module_docstr,
"Information about software used to compile these Python bindings"
);
#if PY_VERSION_HEX >= 0x03000000
static PyModuleDef module_definition = {
PyModuleDef_HEAD_INIT,
XBOB_EXT_MODULE_NAME,
module_docstr,
-1,
module_methods,
0, 0, 0, 0
};
#endif
static PyObject* create_module (void) {
# if PY_VERSION_HEX >= 0x03000000
PyObject* m = PyModule_Create(&module_definition);
# else
PyObject* m = Py_InitModule3(XBOB_EXT_MODULE_NAME, module_methods, module_docstr);
# endif
if (!m) return 0;
auto m_ = make_safe(m); ///< protects against early returns
/* register version numbers and constants */
if (PyModule_AddIntConstant(m, "api", XBOB_BLITZ_API_VERSION) < 0)
return 0;
if (PyModule_AddStringConstant(m, "module", XBOB_EXT_MODULE_VERSION) < 0)
return 0;
PyObject* externals = build_version_dictionary();
if (!externals) return 0;
if (PyModule_AddObject(m, "externals", externals) < 0) return 0;
if (import_xbob_blitz() < 0) return 0;
Py_INCREF(m);
return m;
}
PyMODINIT_FUNC XBOB_EXT_ENTRY_NAME (void) {
# if PY_VERSION_HEX >= 0x03000000
return
# endif
create_module();
}
<commit_msg>Use make_safe()<commit_after>/**
* @author Andre Anjos <andre.anjos@idiap.ch>
* @date Thu 7 Nov 13:50:16 2013
*
* @brief Binds configuration information available from bob
*/
#include <Python.h>
#include <string>
#include <cstdlib>
#include <blitz/blitz.h>
#include <boost/preprocessor/stringize.hpp>
#include <boost/version.hpp>
#include <boost/format.hpp>
#ifdef NO_IMPORT_ARRAY
#undef NO_IMPORT_ARRAY
#endif
#include <xbob.blitz/capi.h>
#include <xbob.blitz/cleanup.h>
static int dict_set(PyObject* d, const char* key, const char* value) {
PyObject* v = Py_BuildValue("s", value);
if (!v) return 0;
int retval = PyDict_SetItemString(d, key, v);
Py_DECREF(v);
if (retval == 0) return 1; //all good
return 0; //a problem occurred
}
static int dict_steal(PyObject* d, const char* key, PyObject* value) {
if (!value) return 0;
int retval = PyDict_SetItemString(d, key, value);
Py_DECREF(value);
if (retval == 0) return 1; //all good
return 0; //a problem occurred
}
/**
* Describes the version of Boost libraries installed
*/
static PyObject* boost_version() {
boost::format f("%d.%d.%d");
f % (BOOST_VERSION / 100000);
f % (BOOST_VERSION / 100 % 1000);
f % (BOOST_VERSION % 100);
return Py_BuildValue("s", f.str().c_str());
}
/**
* Describes the compiler version
*/
static PyObject* compiler_version() {
# if defined(__GNUC__) && !defined(__llvm__)
boost::format f("%s.%s.%s");
f % BOOST_PP_STRINGIZE(__GNUC__);
f % BOOST_PP_STRINGIZE(__GNUC_MINOR__);
f % BOOST_PP_STRINGIZE(__GNUC_PATCHLEVEL__);
return Py_BuildValue("{ssss}", "name", "gcc", "version", f.str().c_str());
# elif defined(__llvm__) && !defined(__clang__)
return Py_BuildValue("{ssss}", "name", "llvm-gcc", "version", __VERSION__);
# elif defined(__clang__)
return Py_BuildValue("{ssss}", "name", "clang", "version", __clang_version__);
# else
return Py_BuildValue("{ssss}", "name", "unsupported", "version", "unknown");
# endif
}
/**
* Python version with which we compiled the extensions
*/
static PyObject* python_version() {
boost::format f("%s.%s.%s");
f % BOOST_PP_STRINGIZE(PY_MAJOR_VERSION);
f % BOOST_PP_STRINGIZE(PY_MINOR_VERSION);
f % BOOST_PP_STRINGIZE(PY_MICRO_VERSION);
return Py_BuildValue("s", f.str().c_str());
}
/**
* Numpy version
*/
static PyObject* numpy_version() {
return Py_BuildValue("{ssss}", "abi", BOOST_PP_STRINGIZE(NPY_VERSION),
"api", BOOST_PP_STRINGIZE(NPY_API_VERSION));
}
static PyObject* build_version_dictionary() {
PyObject* retval = PyDict_New();
if (!retval) return 0;
auto retval_ = make_safe(retval);
if (!dict_set(retval, "Blitz++", BZ_VERSION)) return 0;
if (!dict_steal(retval, "Boost", boost_version())) return 0;
if (!dict_steal(retval, "Compiler", compiler_version())) return 0;
if (!dict_steal(retval, "Python", python_version())) return 0;
if (!dict_steal(retval, "NumPy", numpy_version())) return 0;
return retval;
}
static PyMethodDef module_methods[] = {
{0} /* Sentinel */
};
PyDoc_STRVAR(module_docstr,
"Information about software used to compile these Python bindings"
);
#if PY_VERSION_HEX >= 0x03000000
static PyModuleDef module_definition = {
PyModuleDef_HEAD_INIT,
XBOB_EXT_MODULE_NAME,
module_docstr,
-1,
module_methods,
0, 0, 0, 0
};
#endif
static PyObject* create_module (void) {
# if PY_VERSION_HEX >= 0x03000000
PyObject* m = PyModule_Create(&module_definition);
# else
PyObject* m = Py_InitModule3(XBOB_EXT_MODULE_NAME, module_methods, module_docstr);
# endif
if (!m) return 0;
auto m_ = make_safe(m); ///< protects against early returns
/* register version numbers and constants */
if (PyModule_AddIntConstant(m, "api", XBOB_BLITZ_API_VERSION) < 0)
return 0;
if (PyModule_AddStringConstant(m, "module", XBOB_EXT_MODULE_VERSION) < 0)
return 0;
PyObject* externals = build_version_dictionary();
if (!externals) return 0;
if (PyModule_AddObject(m, "externals", externals) < 0) return 0;
if (import_xbob_blitz() < 0) return 0;
Py_INCREF(m);
return m;
}
PyMODINIT_FUNC XBOB_EXT_ENTRY_NAME (void) {
# if PY_VERSION_HEX >= 0x03000000
return
# endif
create_module();
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** 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 "changeselectiondialog.h"
#include "logchangedialog.h"
#include "gitplugin.h"
#include "gitclient.h"
#include "ui_changeselectiondialog.h"
#include <QProcess>
#include <QFormLayout>
#include <QHBoxLayout>
#include <QPushButton>
#include <QLabel>
#include <QLineEdit>
#include <QPlainTextEdit>
#include <QDir>
#include <QFileDialog>
namespace Git {
namespace Internal {
ChangeSelectionDialog::ChangeSelectionDialog(const QString &workingDirectory, Core::Id id, QWidget *parent)
: QDialog(parent)
, m_ui(new Ui::ChangeSelectionDialog)
, m_process(0)
, m_command(NoCommand)
{
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
m_gitBinaryPath = GitPlugin::instance()->gitClient()->gitBinaryPath();
m_ui->setupUi(this);
m_ui->workingDirectoryEdit->setText(workingDirectory);
m_gitEnvironment = GitPlugin::instance()->gitClient()->processEnvironment();
m_ui->changeNumberEdit->setFocus();
m_ui->changeNumberEdit->selectAll();
connect(m_ui->changeNumberEdit, SIGNAL(textChanged(QString)), this, SLOT(recalculateDetails()));
connect(m_ui->workingDirectoryEdit, SIGNAL(textChanged(QString)), this, SLOT(recalculateDetails()));
connect(m_ui->selectDirectoryButton, SIGNAL(clicked()), this, SLOT(chooseWorkingDirectory()));
connect(m_ui->selectFromHistoryButton, SIGNAL(clicked()), this, SLOT(selectCommitFromRecentHistory()));
connect(m_ui->showButton, SIGNAL(clicked()), this, SLOT(acceptShow()));
connect(m_ui->cherryPickButton, SIGNAL(clicked()), this, SLOT(acceptCherryPick()));
connect(m_ui->revertButton, SIGNAL(clicked()), this, SLOT(acceptRevert()));
connect(m_ui->checkoutButton, SIGNAL(clicked()), this, SLOT(acceptCheckout()));
if (id == "Git.Revert")
m_ui->revertButton->setDefault(true);
else if (id == "Git.CherryPick")
m_ui->cherryPickButton->setDefault(true);
else if (id == "Git.Checkout")
m_ui->checkoutButton->setDefault(true);
else
m_ui->showButton->setDefault(true);
recalculateDetails();
}
ChangeSelectionDialog::~ChangeSelectionDialog()
{
delete m_ui;
delete m_process;
}
QString ChangeSelectionDialog::change() const
{
return m_ui->changeNumberEdit->text();
}
void ChangeSelectionDialog::selectCommitFromRecentHistory()
{
QString workingDir = workingDirectory();
if (workingDir.isEmpty())
return;
QString commit = change();
int tilde = commit.indexOf(QLatin1Char('~'));
if (tilde != -1)
commit.truncate(tilde);
LogChangeDialog dialog(false, this);
dialog.setWindowTitle(tr("Select Commit"));
dialog.runDialog(workingDir, commit);
if (dialog.result() == QDialog::Rejected || dialog.commitIndex() == -1)
return;
if (dialog.commitIndex() > 0)
commit += QLatin1Char('~') + QString::number(dialog.commitIndex());
m_ui->changeNumberEdit->setText(commit);
}
void ChangeSelectionDialog::chooseWorkingDirectory()
{
QString folder = QFileDialog::getExistingDirectory(this, tr("Select Git Directory"),
m_ui->workingDirectoryEdit->text());
if (folder.isEmpty())
return;
m_ui->workingDirectoryEdit->setText(folder);
}
QString ChangeSelectionDialog::workingDirectory() const
{
const QString workingDir = m_ui->workingDirectoryEdit->text();
if (workingDir.isEmpty() || !QDir(workingDir).exists())
return QString();
return GitPlugin::instance()->gitClient()->findRepositoryForDirectory(workingDir);
}
ChangeCommand ChangeSelectionDialog::command() const
{
return m_command;
}
void ChangeSelectionDialog::acceptCheckout()
{
m_command = Checkout;
accept();
}
void ChangeSelectionDialog::acceptCherryPick()
{
m_command = CherryPick;
accept();
}
void ChangeSelectionDialog::acceptRevert()
{
m_command = Revert;
accept();
}
void ChangeSelectionDialog::acceptShow()
{
m_command = Show;
accept();
}
//! Set commit message in details
void ChangeSelectionDialog::setDetails(int exitCode)
{
QPalette palette = m_ui->changeNumberEdit->palette();
if (exitCode == 0) {
m_ui->detailsText->setPlainText(QString::fromUtf8(m_process->readAllStandardOutput()));
palette.setColor(QPalette::Text, Qt::black);
m_ui->changeNumberEdit->setPalette(palette);
enableButtons(true);
} else {
m_ui->detailsText->setPlainText(tr("Error: Unknown reference"));
palette.setColor(QPalette::Text, Qt::red);
m_ui->changeNumberEdit->setPalette(palette);
}
}
void ChangeSelectionDialog::enableButtons(bool b)
{
m_ui->showButton->setEnabled(b);
m_ui->cherryPickButton->setEnabled(b);
m_ui->revertButton->setEnabled(b);
m_ui->checkoutButton->setEnabled(b);
}
void ChangeSelectionDialog::recalculateDetails()
{
if (m_process) {
m_process->kill();
m_process->waitForFinished();
delete m_process;
m_process = 0;
}
enableButtons(false);
const QString workingDir = workingDirectory();
QPalette palette = m_ui->workingDirectoryEdit->palette();
if (workingDir.isEmpty()) {
m_ui->detailsText->setPlainText(tr("Error: Bad working directory."));
palette.setColor(QPalette::Text, Qt::red);
m_ui->workingDirectoryEdit->setPalette(palette);
return;
} else {
palette.setColor(QPalette::Text, Qt::black);
m_ui->workingDirectoryEdit->setPalette(palette);
}
const QString change = m_ui->changeNumberEdit->text();
if (change.isEmpty()) {
m_ui->detailsText->setPlainText(QString());
return;
}
QStringList args;
args << QLatin1String("log") << QLatin1String("-n1") << change;
m_process = new QProcess(this);
m_process->setWorkingDirectory(workingDir);
m_process->setProcessEnvironment(m_gitEnvironment);
connect(m_process, SIGNAL(finished(int)), this, SLOT(setDetails(int)));
m_process->start(m_gitBinaryPath, args);
m_process->closeWriteChannel();
if (!m_process->waitForStarted())
m_ui->detailsText->setPlainText(tr("Error: Could not start Git."));
else
m_ui->detailsText->setPlainText(tr("Fetching commit data..."));
}
} // Internal
} // Git
<commit_msg>Git: Trim change on ChangeSelectionDialog<commit_after>/****************************************************************************
**
** 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 "changeselectiondialog.h"
#include "logchangedialog.h"
#include "gitplugin.h"
#include "gitclient.h"
#include "ui_changeselectiondialog.h"
#include <QProcess>
#include <QFormLayout>
#include <QHBoxLayout>
#include <QPushButton>
#include <QLabel>
#include <QLineEdit>
#include <QPlainTextEdit>
#include <QDir>
#include <QFileDialog>
namespace Git {
namespace Internal {
ChangeSelectionDialog::ChangeSelectionDialog(const QString &workingDirectory, Core::Id id, QWidget *parent)
: QDialog(parent)
, m_ui(new Ui::ChangeSelectionDialog)
, m_process(0)
, m_command(NoCommand)
{
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
m_gitBinaryPath = GitPlugin::instance()->gitClient()->gitBinaryPath();
m_ui->setupUi(this);
m_ui->workingDirectoryEdit->setText(workingDirectory);
m_gitEnvironment = GitPlugin::instance()->gitClient()->processEnvironment();
m_ui->changeNumberEdit->setFocus();
m_ui->changeNumberEdit->selectAll();
connect(m_ui->changeNumberEdit, SIGNAL(textChanged(QString)), this, SLOT(recalculateDetails()));
connect(m_ui->workingDirectoryEdit, SIGNAL(textChanged(QString)), this, SLOT(recalculateDetails()));
connect(m_ui->selectDirectoryButton, SIGNAL(clicked()), this, SLOT(chooseWorkingDirectory()));
connect(m_ui->selectFromHistoryButton, SIGNAL(clicked()), this, SLOT(selectCommitFromRecentHistory()));
connect(m_ui->showButton, SIGNAL(clicked()), this, SLOT(acceptShow()));
connect(m_ui->cherryPickButton, SIGNAL(clicked()), this, SLOT(acceptCherryPick()));
connect(m_ui->revertButton, SIGNAL(clicked()), this, SLOT(acceptRevert()));
connect(m_ui->checkoutButton, SIGNAL(clicked()), this, SLOT(acceptCheckout()));
if (id == "Git.Revert")
m_ui->revertButton->setDefault(true);
else if (id == "Git.CherryPick")
m_ui->cherryPickButton->setDefault(true);
else if (id == "Git.Checkout")
m_ui->checkoutButton->setDefault(true);
else
m_ui->showButton->setDefault(true);
recalculateDetails();
}
ChangeSelectionDialog::~ChangeSelectionDialog()
{
delete m_ui;
delete m_process;
}
QString ChangeSelectionDialog::change() const
{
return m_ui->changeNumberEdit->text().trimmed();
}
void ChangeSelectionDialog::selectCommitFromRecentHistory()
{
QString workingDir = workingDirectory();
if (workingDir.isEmpty())
return;
QString commit = change();
int tilde = commit.indexOf(QLatin1Char('~'));
if (tilde != -1)
commit.truncate(tilde);
LogChangeDialog dialog(false, this);
dialog.setWindowTitle(tr("Select Commit"));
dialog.runDialog(workingDir, commit);
if (dialog.result() == QDialog::Rejected || dialog.commitIndex() == -1)
return;
if (dialog.commitIndex() > 0)
commit += QLatin1Char('~') + QString::number(dialog.commitIndex());
m_ui->changeNumberEdit->setText(commit);
}
void ChangeSelectionDialog::chooseWorkingDirectory()
{
QString folder = QFileDialog::getExistingDirectory(this, tr("Select Git Directory"),
m_ui->workingDirectoryEdit->text());
if (folder.isEmpty())
return;
m_ui->workingDirectoryEdit->setText(folder);
}
QString ChangeSelectionDialog::workingDirectory() const
{
const QString workingDir = m_ui->workingDirectoryEdit->text();
if (workingDir.isEmpty() || !QDir(workingDir).exists())
return QString();
return GitPlugin::instance()->gitClient()->findRepositoryForDirectory(workingDir);
}
ChangeCommand ChangeSelectionDialog::command() const
{
return m_command;
}
void ChangeSelectionDialog::acceptCheckout()
{
m_command = Checkout;
accept();
}
void ChangeSelectionDialog::acceptCherryPick()
{
m_command = CherryPick;
accept();
}
void ChangeSelectionDialog::acceptRevert()
{
m_command = Revert;
accept();
}
void ChangeSelectionDialog::acceptShow()
{
m_command = Show;
accept();
}
//! Set commit message in details
void ChangeSelectionDialog::setDetails(int exitCode)
{
QPalette palette = m_ui->changeNumberEdit->palette();
if (exitCode == 0) {
m_ui->detailsText->setPlainText(QString::fromUtf8(m_process->readAllStandardOutput()));
palette.setColor(QPalette::Text, Qt::black);
m_ui->changeNumberEdit->setPalette(palette);
enableButtons(true);
} else {
m_ui->detailsText->setPlainText(tr("Error: Unknown reference"));
palette.setColor(QPalette::Text, Qt::red);
m_ui->changeNumberEdit->setPalette(palette);
}
}
void ChangeSelectionDialog::enableButtons(bool b)
{
m_ui->showButton->setEnabled(b);
m_ui->cherryPickButton->setEnabled(b);
m_ui->revertButton->setEnabled(b);
m_ui->checkoutButton->setEnabled(b);
}
void ChangeSelectionDialog::recalculateDetails()
{
if (m_process) {
m_process->kill();
m_process->waitForFinished();
delete m_process;
m_process = 0;
}
enableButtons(false);
const QString workingDir = workingDirectory();
QPalette palette = m_ui->workingDirectoryEdit->palette();
if (workingDir.isEmpty()) {
m_ui->detailsText->setPlainText(tr("Error: Bad working directory."));
palette.setColor(QPalette::Text, Qt::red);
m_ui->workingDirectoryEdit->setPalette(palette);
return;
} else {
palette.setColor(QPalette::Text, Qt::black);
m_ui->workingDirectoryEdit->setPalette(palette);
}
const QString ref = change();
if (ref.isEmpty()) {
m_ui->detailsText->setPlainText(QString());
return;
}
QStringList args;
args << QLatin1String("log") << QLatin1String("-n1") << ref;
m_process = new QProcess(this);
m_process->setWorkingDirectory(workingDir);
m_process->setProcessEnvironment(m_gitEnvironment);
connect(m_process, SIGNAL(finished(int)), this, SLOT(setDetails(int)));
m_process->start(m_gitBinaryPath, args);
m_process->closeWriteChannel();
if (!m_process->waitForStarted())
m_ui->detailsText->setPlainText(tr("Error: Could not start Git."));
else
m_ui->detailsText->setPlainText(tr("Fetching commit data..."));
}
} // Internal
} // Git
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_system.h"
#include "nvs_flash.h"
#include "driver/uart.h"
#include "freertos/queue.h"
#include "esp_log.h"
#include "soc/uart_struct.h"
static const char *TAG = "MFRC522";
#define BUF_SIZE (1024)
#define NFC_UART_TXD (16)
#define NFC_UART_RXD (17)
#define NFC_UART_RTS (18)
#define NFC_UART_CTS (19)
QueueHandle_t uart2_queue;
#include "MFRC522.h"
//------------------MFRC522 register ---------------
#define COMMAND_WAIT 0x02
#define COMMAND_READBLOCK 0x03
#define COMMAND_WRITEBLOCK 0x04
#define MFRC522_HEADER 0xAB
#define STATUS_ERROR 0
#define STATUS_OK 1
#define MIFARE_KEYA 0x00
#define MIFARE_KEYB 0x01
/**
* Constructor.
*/
MFRC522::MFRC522() {
}
/**
* Description: Obtiene control del Serial para controlar MFRC522.
* Ademas, pone MFRC522 en modo de espera.
*/
void MFRC522::begin(void) {
uart_port_t uart_num = UART_NUM_2;
uart_config_t uart_config = {
.baud_rate = 9600,
.data_bits = UART_DATA_8_BITS,
.parity = UART_PARITY_DISABLE,
.stop_bits = UART_STOP_BITS_1,
.flow_ctrl = UART_HW_FLOWCTRL_DISABLE,
.rx_flow_ctrl_thresh = 122,
};
//Set UART parameters
uart_param_config(uart_num, &uart_config);
//Set UART log level
esp_log_level_set(TAG, ESP_LOG_INFO);
//Set UART pins,(-1: default pin, no change.)
//For UART2, we can just use the default pins.
uart_set_pin(uart_num, NFC_UART_TXD, NFC_UART_RXD, NFC_UART_RTS, NFC_UART_CTS);
//Install UART driver, and get the queue.
esp_err_t installed = uart_driver_install(uart_num, BUF_SIZE * 2, BUF_SIZE * 2, 10, &uart2_queue, 0);
printf("installed : %d\n", installed);
wait();
}
/**
* Description:Pone MFRC522 en modo espera.
*/
void MFRC522::wait() {
write(COMMAND_WAIT);
}
/**
* Description:Returns true if detect card in MFRC522.
*/
bool MFRC522::available() {
return true;
}
/**
* Description:Read the serial number of the card.
*/
void MFRC522::readCardSerial() {
for (int i = 0; i < sizeof(cardSerial); ){
if (available()){
cardSerial[i] = read();
i++;
}
}
}
/**
* Description:Returns a pointer to array with card serial.
*/
byte *MFRC522::getCardSerial() {
return cardSerial;
}
/**
* Description:Read a block data of the card.
* Return:Return STATUS_OK if success.
*/
bool MFRC522::getBlock(byte block, byte keyType, byte *key, byte *returnBlock) {
byte sendData[8] = {
block, // block
keyType, // key type
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF // key
};
byte returnBlockLength;
for (int i = 0; i < 6; ++i) {
sendData[2 + i] = key[i];
}
return communicate(
COMMAND_READBLOCK, // command
sendData, // sendData
0x0A, // length
returnBlock, // returnData
&returnBlockLength // returnDataLength
);
}
/**
* Description:Write a block data in the card.
* Return:Return STATUS_OK if success.
*/
bool MFRC522::writeBlock(byte block, byte keyType, byte *key, byte *data) {
byte sendData[24] = {
block, // block
keyType, // key type
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // key
0x00, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // Data
};
byte returnBlock[3];
byte returnBlockLength;
for (int i = 0; i < 6; ++i) {
sendData[2 + i] = key[i];
}
for (int i = 0; i < 16; ++i) {
sendData[8 + i] = data[i];
}
byte result = communicate(
COMMAND_WRITEBLOCK, // command
sendData, // sendData
0x1A, // length
returnBlock, // returnData
&returnBlockLength // returnDataLength
);
return result;
}
/**
* Description:Comunication between MFRC522 and ISO14443.
* Return:Return STATUS_OK if success.
*/
bool MFRC522::communicate(byte command, byte *sendData, byte sendDataLength, byte *returnData, byte *returnDataLength) {
// Send instruction to MFRC522
write(MFRC522_HEADER); // Header
write(sendDataLength); // Length (Length + Command + Data)
write(command); // Command
for (int i = 0; i < sendDataLength - 2; i++) {
write(sendData[i]); // Data
}
// Read response to MFRC522
while (!available());
byte header = read(); // Header
while (!available());
*returnDataLength = read(); // Length (Length + Command + Data)
while (!available());
byte commandResult = read(); // Command result
for (int i = 0; i < *returnDataLength - 2; i=i) {
if (available()) {
returnData[i] = read(); // Data
i++;
}
}
// Return
if (command != commandResult) {
return STATUS_ERROR;
}
return STATUS_OK;
}
/*
* Description:Write a byte data into MFRC522.
*/
void MFRC522::write(byte value) {
uart_port_t uart_num = UART_NUM_2;
char data[1];
data[0] = value;
uart_write_bytes(uart_num, (const char*)data, 1);
}
/*
* Description:Read a byte data of MFRC522
* Return:Return the read value.
*/
byte MFRC522::read() {
uart_port_t uart_num = UART_NUM_2;
uint8_t *data = (uint8_t *)malloc(1);
TickType_t ticks_to_wait = portTICK_RATE_MS;
uart_read_bytes(uart_num,data,1,ticks_to_wait);
return *data;
}
const portTickType xDelay = 500 / portTICK_RATE_MS;
extern "C" void MFRC522_main() {
MFRC522 Conector;
Conector.begin();
printf("begin :\n");
while(true)
{
byte *cardSerial = Conector.readCardSerial();
printf("readCardSerial cardSerial=<%s>\n",(char*)cardSerial);
Conector.wait();
vTaskDelay( xDelay );
}
}
<commit_msg>Update MFRC522.cpp<commit_after>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_system.h"
#include "nvs_flash.h"
#include "driver/uart.h"
#include "freertos/queue.h"
#include "esp_log.h"
#include "soc/uart_struct.h"
static const char *TAG = "MFRC522";
#define BUF_SIZE (1024)
#define NFC_UART_TXD (16)
#define NFC_UART_RXD (17)
#define NFC_UART_RTS (18)
#define NFC_UART_CTS (19)
QueueHandle_t uart2_queue;
#include "MFRC522.h"
//------------------MFRC522 register ---------------
#define COMMAND_WAIT 0x02
#define COMMAND_READBLOCK 0x03
#define COMMAND_WRITEBLOCK 0x04
#define MFRC522_HEADER 0xAB
#define STATUS_ERROR 0
#define STATUS_OK 1
#define MIFARE_KEYA 0x00
#define MIFARE_KEYB 0x01
/**
* Constructor.
*/
MFRC522::MFRC522() {
}
/**
* Description: Obtiene control del Serial para controlar MFRC522.
* Ademas, pone MFRC522 en modo de espera.
*/
void MFRC522::begin(void) {
uart_port_t uart_num = UART_NUM_2;
uart_config_t uart_config = {
.baud_rate = 9600,
.data_bits = UART_DATA_8_BITS,
.parity = UART_PARITY_DISABLE,
.stop_bits = UART_STOP_BITS_1,
.flow_ctrl = UART_HW_FLOWCTRL_DISABLE,
.rx_flow_ctrl_thresh = 122,
};
//Set UART parameters
uart_param_config(uart_num, &uart_config);
//Set UART log level
esp_log_level_set(TAG, ESP_LOG_INFO);
//Set UART pins,(-1: default pin, no change.)
//For UART2, we can just use the default pins.
uart_set_pin(uart_num, NFC_UART_TXD, NFC_UART_RXD, NFC_UART_RTS, NFC_UART_CTS);
//Install UART driver, and get the queue.
esp_err_t installed = uart_driver_install(uart_num, BUF_SIZE * 2, BUF_SIZE * 2, 10, &uart2_queue, 0);
printf("installed : %d\n", installed);
wait();
}
/**
* Description:Pone MFRC522 en modo espera.
*/
void MFRC522::wait() {
write(COMMAND_WAIT);
}
/**
* Description:Returns true if detect card in MFRC522.
*/
bool MFRC522::available() {
return true;
}
/**
* Description:Read the serial number of the card.
*/
void MFRC522::readCardSerial() {
for (int i = 0; i < sizeof(cardSerial); ){
if (available()){
cardSerial[i] = read();
i++;
}
}
}
/**
* Description:Returns a pointer to array with card serial.
*/
byte *MFRC522::getCardSerial() {
return cardSerial;
}
/**
* Description:Read a block data of the card.
* Return:Return STATUS_OK if success.
*/
bool MFRC522::getBlock(byte block, byte keyType, byte *key, byte *returnBlock) {
byte sendData[8] = {
block, // block
keyType, // key type
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF // key
};
byte returnBlockLength;
for (int i = 0; i < 6; ++i) {
sendData[2 + i] = key[i];
}
return communicate(
COMMAND_READBLOCK, // command
sendData, // sendData
0x0A, // length
returnBlock, // returnData
&returnBlockLength // returnDataLength
);
}
/**
* Description:Write a block data in the card.
* Return:Return STATUS_OK if success.
*/
bool MFRC522::writeBlock(byte block, byte keyType, byte *key, byte *data) {
byte sendData[24] = {
block, // block
keyType, // key type
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // key
0x00, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // Data
};
byte returnBlock[3];
byte returnBlockLength;
for (int i = 0; i < 6; ++i) {
sendData[2 + i] = key[i];
}
for (int i = 0; i < 16; ++i) {
sendData[8 + i] = data[i];
}
byte result = communicate(
COMMAND_WRITEBLOCK, // command
sendData, // sendData
0x1A, // length
returnBlock, // returnData
&returnBlockLength // returnDataLength
);
return result;
}
/**
* Description:Comunication between MFRC522 and ISO14443.
* Return:Return STATUS_OK if success.
*/
bool MFRC522::communicate(byte command, byte *sendData, byte sendDataLength, byte *returnData, byte *returnDataLength) {
// Send instruction to MFRC522
write(MFRC522_HEADER); // Header
write(sendDataLength); // Length (Length + Command + Data)
write(command); // Command
for (int i = 0; i < sendDataLength - 2; i++) {
write(sendData[i]); // Data
}
// Read response to MFRC522
while (!available());
byte header = read(); // Header
while (!available());
*returnDataLength = read(); // Length (Length + Command + Data)
while (!available());
byte commandResult = read(); // Command result
for (int i = 0; i < *returnDataLength - 2; i=i) {
if (available()) {
returnData[i] = read(); // Data
i++;
}
}
// Return
if (command != commandResult) {
return STATUS_ERROR;
}
return STATUS_OK;
}
/*
* Description:Write a byte data into MFRC522.
*/
void MFRC522::write(byte value) {
uart_port_t uart_num = UART_NUM_2;
char data[1];
data[0] = value;
uart_write_bytes(uart_num, (const char*)data, 1);
}
/*
* Description:Read a byte data of MFRC522
* Return:Return the read value.
*/
byte MFRC522::read() {
uart_port_t uart_num = UART_NUM_2;
uint8_t *data = (uint8_t *)malloc(1);
TickType_t ticks_to_wait = portTICK_RATE_MS;
uart_read_bytes(uart_num,data,1,ticks_to_wait);
return *data;
}
const portTickType xDelay = 500 / portTICK_RATE_MS;
extern "C" void MFRC522_main() {
MFRC522 Conector;
Conector.begin();
printf("begin :\n");
while(true)
{
Conector.readCardSerial();
byte *cardSerial = Conector.getCardSerial();
printf("readCardSerial cardSerial=<%s>\n",(char*)cardSerial);
Conector.wait();
vTaskDelay( xDelay );
}
}
<|endoftext|> |
<commit_before>/* Copyright 2015 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.
==============================================================================*/
// See core/ops/sparse_ops.cc for documentation.
//
// NOTE: the operations in this file only are suitable for execution
// on CPUs.
#define EIGEN_USE_THREADS
#include <numeric>
#include <sstream>
#include <string>
#include <unordered_map>
#include <utility>
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/gtl/inlined_vector.h"
#include "tensorflow/core/lib/strings/stringprintf.h"
#include "tensorflow/core/util/ptr_util.h"
#include "tensorflow/core/util/sparse/sparse_tensor.h"
#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
#include "tensorflow/core/kernels/gpu_utils.h"
#include "tensorflow/core/kernels/sparse_to_dense_op_gpu.h"
#include "tensorflow/core/platform/stream_executor.h"
#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM
namespace tensorflow {
namespace {
Status CheckSparseToDenseShapes(const Tensor& indices,
const Tensor& output_shape,
const Tensor& sparse_values,
const Tensor& default_value) {
// sparse_indices
if (indices.dims() > 2) {
return errors::InvalidArgument(
"sparse_indices should be a scalar, vector, or matrix, "
"got shape ",
indices.shape().DebugString());
}
const int64_t num_elems = indices.dims() > 0 ? indices.dim_size(0) : 1;
const int64_t num_dims = indices.dims() > 1 ? indices.dim_size(1) : 1;
// output_shape
if (!TensorShapeUtils::IsVector(output_shape.shape())) {
return errors::InvalidArgument("output_shape must be rank 1, got shape ",
output_shape.shape().DebugString());
}
if (output_shape.NumElements() != num_dims) {
return errors::InvalidArgument(
"output_shape has incorrect number of elements: ",
output_shape.NumElements(), " should be: ", num_dims);
}
// sparse_values
const int64_t num_values = sparse_values.NumElements();
if (sparse_values.dims() != 0 &&
(sparse_values.dims() != 1 || num_values != num_elems)) {
return errors::InvalidArgument("sparse_values has incorrect shape ",
sparse_values.shape().DebugString(),
", should be [] or [", num_elems, "]");
}
// default_value
if (!TensorShapeUtils::IsScalar(default_value.shape())) {
return errors::InvalidArgument("default_value should be a scalar.");
}
return OkStatus();
}
} // end namespace
// Operator to convert sparse representations to dense.
template <typename T, typename Index>
class SparseToDense : public OpKernel {
public:
explicit SparseToDense(OpKernelConstruction* context) : OpKernel(context) {
OP_REQUIRES_OK(context,
context->GetAttr("validate_indices", &validate_indices_));
}
void Compute(OpKernelContext* c) override {
const Tensor& indices = c->input(0);
const Tensor& output_shape = c->input(1);
const Tensor& sparse_values = c->input(2);
const Tensor& default_value = c->input(3);
OP_REQUIRES_OK(c, CheckSparseToDenseShapes(indices, output_shape,
sparse_values, default_value));
const int64_t num_elems = indices.dims() > 0 ? indices.dim_size(0) : 1;
const int64_t num_dims = indices.dims() > 1 ? indices.dim_size(1) : 1;
auto output_shape_vec = output_shape.flat<Index>();
TensorShape output_tensor_shape;
OP_REQUIRES_OK(c, TensorShapeUtils::MakeShape(output_shape_vec.data(),
output_shape_vec.size(),
&output_tensor_shape));
Tensor* output = nullptr;
OP_REQUIRES_OK(c, c->allocate_output(0, output_tensor_shape, &output));
const Tensor* indices_shaped;
std::unique_ptr<Tensor> indices_shaped_holder;
if (indices.dtype() == DT_INT64 && indices.dims() == 2) {
indices_shaped = &indices;
} else {
TensorShape ix_shape({num_elems, num_dims});
indices_shaped_holder = MakeUnique<Tensor>(DT_INT64, ix_shape);
indices_shaped = indices_shaped_holder.get();
if (indices.dtype() == DT_INT64) {
CHECK(indices_shaped_holder->CopyFrom(indices, ix_shape));
} else {
indices_shaped_holder->matrix<int64_t>() =
indices.shaped<Index, 2>(ix_shape.dim_sizes())
.template cast<int64_t>();
}
}
// If we received a scalar, we'll need to create a new
// tensor with copies of the values as a vec.
const Tensor* sparse_values_b;
std::unique_ptr<Tensor> sparse_values_b_holder;
if (TensorShapeUtils::IsScalar(sparse_values.shape())) {
sparse_values_b_holder = MakeUnique<Tensor>(DataTypeToEnum<T>::value,
TensorShape({num_elems}));
sparse_values_b = sparse_values_b_holder.get();
sparse_values_b_holder->vec<T>().setConstant(sparse_values.scalar<T>()());
} else {
sparse_values_b = &sparse_values;
}
// Assume SparseTensor is lexicographically sorted.
gtl::InlinedVector<int64_t, 8> order(output->shape().dims());
std::iota(order.begin(), order.end(), 0);
sparse::SparseTensor st;
OP_REQUIRES_OK(
c, sparse::SparseTensor::Create(*indices_shaped, *sparse_values_b,
output->shape(), order, &st));
if (validate_indices_) {
OP_REQUIRES_OK(c, st.IndicesValid());
}
output->flat<T>().setConstant(default_value.scalar<T>()());
OP_REQUIRES(c, st.template ToDense<T>(output, false /* initialize */),
errors::InvalidArgument(
"Indices are not valid (out of bounds). Shape: ",
output->shape().DebugString()));
}
private:
bool validate_indices_;
};
#define REGISTER_KERNELS(type, index_type) \
REGISTER_KERNEL_BUILDER(Name("SparseToDense") \
.Device(DEVICE_CPU) \
.TypeConstraint<type>("T") \
.TypeConstraint<index_type>("Tindices"), \
SparseToDense<type, index_type>);
#define REGISTER_KERNELS_ALL(type) \
REGISTER_KERNELS(type, int32); \
REGISTER_KERNELS(type, int64_t);
TF_CALL_REAL_NUMBER_TYPES(REGISTER_KERNELS_ALL);
REGISTER_KERNELS_ALL(bool);
REGISTER_KERNELS_ALL(tstring);
REGISTER_KERNELS_ALL(complex64);
REGISTER_KERNELS_ALL(complex128);
REGISTER_KERNELS_ALL(qint8);
REGISTER_KERNELS_ALL(qint16);
#undef REGISTER_KERNELS_ALL
#undef REGISTER_KERNELS
#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
template <typename T, typename Index>
class SparseToDenseGPU : public AsyncOpKernel {
public:
explicit SparseToDenseGPU(OpKernelConstruction* context)
: AsyncOpKernel(context) {
OP_REQUIRES_OK(context,
context->GetAttr("validate_indices", &validate_indices_));
}
void ComputeAsync(OpKernelContext* c, DoneCallback done) final {
auto* stream = c->op_device_context()->stream();
OP_REQUIRES_ASYNC(c, stream, errors::Internal("No GPU stream available."),
done);
const Tensor& indices = c->input(0);
const Tensor& output_shape = c->input(1);
const Tensor& sparse_values = c->input(2);
const Tensor& default_value = c->input(3);
OP_REQUIRES_OK_ASYNC(c,
CheckSparseToDenseShapes(indices, output_shape,
sparse_values, default_value),
done);
auto output_shape_vec = output_shape.flat<Index>();
TensorShape output_tensor_shape;
OP_REQUIRES_OK_ASYNC(c,
TensorShapeUtils::MakeShape(output_shape_vec.data(),
output_shape_vec.size(),
&output_tensor_shape),
done);
Tensor* output = nullptr;
OP_REQUIRES_OK_ASYNC(c, c->allocate_output(0, output_tensor_shape, &output),
done);
Tensor output_shape_tensor;
OP_REQUIRES_OK_ASYNC(
c,
c->allocate_temp(DataTypeToEnum<Index>::value,
{output_shape_vec.size()}, &output_shape_tensor),
done);
auto output_shape_data =
AsDeviceMemory(output_shape_tensor.template flat<Index>().data(),
output_shape_tensor.template flat<Index>().size());
OP_REQUIRES_ASYNC(
c,
stream
->ThenMemcpy(&output_shape_data, output_shape_vec.data(),
output_shape_tensor.NumElements() * sizeof(Index))
.ok(),
errors::InvalidArgument(
"failed to copy output_shape vector from host to "
"device in SparseToDenseOp"),
done);
functor::LaunchSparseToDense<T, Index>()(
c, done, this, validate_indices_, indices, sparse_values,
output_shape_tensor, default_value.scalar<T>()(), output);
}
private:
bool validate_indices_;
};
// TODO(b/184077412): SparseToDense causes an illegal access error.
#define REGISTER_GPU_KERNELS(type, index_type) \
REGISTER_KERNEL_BUILDER(Name("SparseToDense") \
.Device(DEVICE_GPU) \
.HostMemory("default_value") \
.HostMemory("output_shape") \
.TypeConstraint<type>("T") \
.TypeConstraint<index_type>("Tindices"), \
SparseToDenseGPU<type, index_type>);
#define REGISTER_GPU_KERNELS_ALL(type) \
REGISTER_GPU_KERNELS(type, int32); \
REGISTER_GPU_KERNELS(type, int64_t);
TF_CALL_GPU_NUMBER_TYPES(REGISTER_GPU_KERNELS_ALL);
TF_CALL_INTEGRAL_TYPES(REGISTER_GPU_KERNELS_ALL)
REGISTER_GPU_KERNELS_ALL(bool)
#undef REGISTER_GPU_KERNELS_ALL
#undef REGISTER_GPU_KERNELS
#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM
} // namespace tensorflow
<commit_msg>Add tf.quint8/quint16 support for tf.sparse.to_dense<commit_after>/* Copyright 2015 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.
==============================================================================*/
// See core/ops/sparse_ops.cc for documentation.
//
// NOTE: the operations in this file only are suitable for execution
// on CPUs.
#define EIGEN_USE_THREADS
#include <numeric>
#include <sstream>
#include <string>
#include <unordered_map>
#include <utility>
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/gtl/inlined_vector.h"
#include "tensorflow/core/lib/strings/stringprintf.h"
#include "tensorflow/core/util/ptr_util.h"
#include "tensorflow/core/util/sparse/sparse_tensor.h"
#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
#include "tensorflow/core/kernels/gpu_utils.h"
#include "tensorflow/core/kernels/sparse_to_dense_op_gpu.h"
#include "tensorflow/core/platform/stream_executor.h"
#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM
namespace tensorflow {
namespace {
Status CheckSparseToDenseShapes(const Tensor& indices,
const Tensor& output_shape,
const Tensor& sparse_values,
const Tensor& default_value) {
// sparse_indices
if (indices.dims() > 2) {
return errors::InvalidArgument(
"sparse_indices should be a scalar, vector, or matrix, "
"got shape ",
indices.shape().DebugString());
}
const int64_t num_elems = indices.dims() > 0 ? indices.dim_size(0) : 1;
const int64_t num_dims = indices.dims() > 1 ? indices.dim_size(1) : 1;
// output_shape
if (!TensorShapeUtils::IsVector(output_shape.shape())) {
return errors::InvalidArgument("output_shape must be rank 1, got shape ",
output_shape.shape().DebugString());
}
if (output_shape.NumElements() != num_dims) {
return errors::InvalidArgument(
"output_shape has incorrect number of elements: ",
output_shape.NumElements(), " should be: ", num_dims);
}
// sparse_values
const int64_t num_values = sparse_values.NumElements();
if (sparse_values.dims() != 0 &&
(sparse_values.dims() != 1 || num_values != num_elems)) {
return errors::InvalidArgument("sparse_values has incorrect shape ",
sparse_values.shape().DebugString(),
", should be [] or [", num_elems, "]");
}
// default_value
if (!TensorShapeUtils::IsScalar(default_value.shape())) {
return errors::InvalidArgument("default_value should be a scalar.");
}
return OkStatus();
}
} // end namespace
// Operator to convert sparse representations to dense.
template <typename T, typename Index>
class SparseToDense : public OpKernel {
public:
explicit SparseToDense(OpKernelConstruction* context) : OpKernel(context) {
OP_REQUIRES_OK(context,
context->GetAttr("validate_indices", &validate_indices_));
}
void Compute(OpKernelContext* c) override {
const Tensor& indices = c->input(0);
const Tensor& output_shape = c->input(1);
const Tensor& sparse_values = c->input(2);
const Tensor& default_value = c->input(3);
OP_REQUIRES_OK(c, CheckSparseToDenseShapes(indices, output_shape,
sparse_values, default_value));
const int64_t num_elems = indices.dims() > 0 ? indices.dim_size(0) : 1;
const int64_t num_dims = indices.dims() > 1 ? indices.dim_size(1) : 1;
auto output_shape_vec = output_shape.flat<Index>();
TensorShape output_tensor_shape;
OP_REQUIRES_OK(c, TensorShapeUtils::MakeShape(output_shape_vec.data(),
output_shape_vec.size(),
&output_tensor_shape));
Tensor* output = nullptr;
OP_REQUIRES_OK(c, c->allocate_output(0, output_tensor_shape, &output));
const Tensor* indices_shaped;
std::unique_ptr<Tensor> indices_shaped_holder;
if (indices.dtype() == DT_INT64 && indices.dims() == 2) {
indices_shaped = &indices;
} else {
TensorShape ix_shape({num_elems, num_dims});
indices_shaped_holder = MakeUnique<Tensor>(DT_INT64, ix_shape);
indices_shaped = indices_shaped_holder.get();
if (indices.dtype() == DT_INT64) {
CHECK(indices_shaped_holder->CopyFrom(indices, ix_shape));
} else {
indices_shaped_holder->matrix<int64_t>() =
indices.shaped<Index, 2>(ix_shape.dim_sizes())
.template cast<int64_t>();
}
}
// If we received a scalar, we'll need to create a new
// tensor with copies of the values as a vec.
const Tensor* sparse_values_b;
std::unique_ptr<Tensor> sparse_values_b_holder;
if (TensorShapeUtils::IsScalar(sparse_values.shape())) {
sparse_values_b_holder = MakeUnique<Tensor>(DataTypeToEnum<T>::value,
TensorShape({num_elems}));
sparse_values_b = sparse_values_b_holder.get();
sparse_values_b_holder->vec<T>().setConstant(sparse_values.scalar<T>()());
} else {
sparse_values_b = &sparse_values;
}
// Assume SparseTensor is lexicographically sorted.
gtl::InlinedVector<int64_t, 8> order(output->shape().dims());
std::iota(order.begin(), order.end(), 0);
sparse::SparseTensor st;
OP_REQUIRES_OK(
c, sparse::SparseTensor::Create(*indices_shaped, *sparse_values_b,
output->shape(), order, &st));
if (validate_indices_) {
OP_REQUIRES_OK(c, st.IndicesValid());
}
output->flat<T>().setConstant(default_value.scalar<T>()());
OP_REQUIRES(c, st.template ToDense<T>(output, false /* initialize */),
errors::InvalidArgument(
"Indices are not valid (out of bounds). Shape: ",
output->shape().DebugString()));
}
private:
bool validate_indices_;
};
#define REGISTER_KERNELS(type, index_type) \
REGISTER_KERNEL_BUILDER(Name("SparseToDense") \
.Device(DEVICE_CPU) \
.TypeConstraint<type>("T") \
.TypeConstraint<index_type>("Tindices"), \
SparseToDense<type, index_type>);
#define REGISTER_KERNELS_ALL(type) \
REGISTER_KERNELS(type, int32); \
REGISTER_KERNELS(type, int64_t);
TF_CALL_REAL_NUMBER_TYPES(REGISTER_KERNELS_ALL);
REGISTER_KERNELS_ALL(bool);
REGISTER_KERNELS_ALL(tstring);
REGISTER_KERNELS_ALL(complex64);
REGISTER_KERNELS_ALL(complex128);
REGISTER_KERNELS_ALL(qint8);
REGISTER_KERNELS_ALL(qint16);
REGISTER_KERNELS_ALL(quint8);
REGISTER_KERNELS_ALL(quint16);
#undef REGISTER_KERNELS_ALL
#undef REGISTER_KERNELS
#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
template <typename T, typename Index>
class SparseToDenseGPU : public AsyncOpKernel {
public:
explicit SparseToDenseGPU(OpKernelConstruction* context)
: AsyncOpKernel(context) {
OP_REQUIRES_OK(context,
context->GetAttr("validate_indices", &validate_indices_));
}
void ComputeAsync(OpKernelContext* c, DoneCallback done) final {
auto* stream = c->op_device_context()->stream();
OP_REQUIRES_ASYNC(c, stream, errors::Internal("No GPU stream available."),
done);
const Tensor& indices = c->input(0);
const Tensor& output_shape = c->input(1);
const Tensor& sparse_values = c->input(2);
const Tensor& default_value = c->input(3);
OP_REQUIRES_OK_ASYNC(c,
CheckSparseToDenseShapes(indices, output_shape,
sparse_values, default_value),
done);
auto output_shape_vec = output_shape.flat<Index>();
TensorShape output_tensor_shape;
OP_REQUIRES_OK_ASYNC(c,
TensorShapeUtils::MakeShape(output_shape_vec.data(),
output_shape_vec.size(),
&output_tensor_shape),
done);
Tensor* output = nullptr;
OP_REQUIRES_OK_ASYNC(c, c->allocate_output(0, output_tensor_shape, &output),
done);
Tensor output_shape_tensor;
OP_REQUIRES_OK_ASYNC(
c,
c->allocate_temp(DataTypeToEnum<Index>::value,
{output_shape_vec.size()}, &output_shape_tensor),
done);
auto output_shape_data =
AsDeviceMemory(output_shape_tensor.template flat<Index>().data(),
output_shape_tensor.template flat<Index>().size());
OP_REQUIRES_ASYNC(
c,
stream
->ThenMemcpy(&output_shape_data, output_shape_vec.data(),
output_shape_tensor.NumElements() * sizeof(Index))
.ok(),
errors::InvalidArgument(
"failed to copy output_shape vector from host to "
"device in SparseToDenseOp"),
done);
functor::LaunchSparseToDense<T, Index>()(
c, done, this, validate_indices_, indices, sparse_values,
output_shape_tensor, default_value.scalar<T>()(), output);
}
private:
bool validate_indices_;
};
// TODO(b/184077412): SparseToDense causes an illegal access error.
#define REGISTER_GPU_KERNELS(type, index_type) \
REGISTER_KERNEL_BUILDER(Name("SparseToDense") \
.Device(DEVICE_GPU) \
.HostMemory("default_value") \
.HostMemory("output_shape") \
.TypeConstraint<type>("T") \
.TypeConstraint<index_type>("Tindices"), \
SparseToDenseGPU<type, index_type>);
#define REGISTER_GPU_KERNELS_ALL(type) \
REGISTER_GPU_KERNELS(type, int32); \
REGISTER_GPU_KERNELS(type, int64_t);
TF_CALL_GPU_NUMBER_TYPES(REGISTER_GPU_KERNELS_ALL);
TF_CALL_INTEGRAL_TYPES(REGISTER_GPU_KERNELS_ALL)
REGISTER_GPU_KERNELS_ALL(bool)
#undef REGISTER_GPU_KERNELS_ALL
#undef REGISTER_GPU_KERNELS
#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM
} // namespace tensorflow
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "qmljsdelta.h"
#include "qmljsclientproxy.h"
#include <qmljs/parser/qmljsast_p.h>
#include <qmljs/parser/qmljsastvisitor_p.h>
#include <QtCore/QDebug>
using namespace QmlJS;
using namespace QmlJS::AST;
using namespace QmlJSInspector::Internal;
namespace {
class ScriptBindingParser : protected Visitor
{
QList<UiObjectMember *> objectStack;
QHash<UiScriptBinding *, UiObjectMember *> _parent;
QHash<UiObjectMember *, UiScriptBinding *> _id;
QHash<UiScriptBinding *, QDeclarativeDebugObjectReference> _idBindings;
public:
QmlJS::Document::Ptr doc;
QList<UiScriptBinding *> scripts;
ScriptBindingParser(Document::Ptr doc, const QList<QDeclarativeDebugObjectReference> &objectReferences = QList<QDeclarativeDebugObjectReference>());
void process();
UiObjectMember *parent(UiScriptBinding *script) const
{ return _parent.value(script); }
UiScriptBinding *id(UiObjectMember *parent) const
{ return _id.value(parent); }
QList<UiScriptBinding *> ids() const
{ return _id.values(); }
QDeclarativeDebugObjectReference objectReferenceForPosition(const QUrl &url, int line, int col) const;
QDeclarativeDebugObjectReference objectReferenceForScriptBinding(UiScriptBinding *binding) const;
QDeclarativeDebugObjectReference objectReferenceForOffset(unsigned int offset);
QString header(UiObjectMember *member) const
{
if (member) {
if (UiObjectDefinition *def = cast<UiObjectDefinition *>(member)) {
const int begin = def->firstSourceLocation().begin();
const int end = def->initializer->lbraceToken.begin();
return doc->source().mid(begin, end - begin);
} else if (UiObjectBinding *binding = cast<UiObjectBinding *>(member)) {
const int begin = binding->firstSourceLocation().begin();
const int end = binding->initializer->lbraceToken.begin();
return doc->source().mid(begin, end - begin);
}
}
return QString();
}
QString scriptCode(UiScriptBinding *script) const
{
if (script) {
const int begin = script->statement->firstSourceLocation().begin();
const int end = script->statement->lastSourceLocation().end();
return doc->source().mid(begin, end - begin);
}
return QString();
}
protected:
QDeclarativeDebugObjectReference objectReference(const QString &id) const;
virtual bool visit(UiObjectDefinition *ast);
virtual void endVisit(UiObjectDefinition *);
virtual bool visit(UiObjectBinding *ast);
virtual void endVisit(UiObjectBinding *);
virtual bool visit(UiScriptBinding *ast);
private:
QList<QDeclarativeDebugObjectReference> objectReferences;
QDeclarativeDebugObjectReference m_foundObjectReference;
unsigned int m_searchElementOffset;
};
} // end of anonymous namespace
static bool isLiteralValue(ExpressionNode *expr)
{
if (cast<NumericLiteral*>(expr))
return true;
else if (cast<StringLiteral*>(expr))
return true;
else if (UnaryPlusExpression *plusExpr = cast<UnaryPlusExpression*>(expr))
return isLiteralValue(plusExpr->expression);
else if (UnaryMinusExpression *minusExpr = cast<UnaryMinusExpression*>(expr))
return isLiteralValue(minusExpr->expression);
else if (cast<TrueLiteral*>(expr))
return true;
else if (cast<FalseLiteral*>(expr))
return true;
else
return false;
}
static inline bool isLiteralValue(UiScriptBinding *script)
{
if (!script || !script->statement)
return false;
ExpressionStatement *exprStmt = cast<ExpressionStatement *>(script->statement);
if (exprStmt)
return isLiteralValue(exprStmt->expression);
else
return false;
}
static inline QString stripQuotes(const QString &str)
{
if ((str.startsWith(QLatin1Char('"')) && str.endsWith(QLatin1Char('"')))
|| (str.startsWith(QLatin1Char('\'')) && str.endsWith(QLatin1Char('\''))))
return str.mid(1, str.length() - 2);
return str;
}
static inline QString deEscape(const QString &value)
{
QString result = value;
result.replace(QLatin1String("\\\\"), QLatin1String("\\"));
result.replace(QLatin1String("\\\""), QLatin1String("\""));
result.replace(QLatin1String("\\\t"), QLatin1String("\t"));
result.replace(QLatin1String("\\\r"), QLatin1String("\\\r"));
result.replace(QLatin1String("\\\n"), QLatin1String("\n"));
return result;
}
static QString cleanExpression(const QString &expression, UiScriptBinding *scriptBinding)
{
QString trimmedExpression = expression.trimmed();
if (ExpressionStatement *expStatement = cast<ExpressionStatement*>(scriptBinding->statement)) {
if (expStatement->semicolonToken.isValid())
trimmedExpression.chop(1);
}
return deEscape(stripQuotes(trimmedExpression));
}
static QVariant castToLiteral(const QString &expression, UiScriptBinding *scriptBinding)
{
const QString cleanedValue = cleanExpression(expression, scriptBinding);
QVariant castedExpression;
ExpressionStatement *expStatement = cast<ExpressionStatement*>(scriptBinding->statement);
switch(expStatement->expression->kind) {
case Node::Kind_NumericLiteral:
case Node::Kind_UnaryPlusExpression:
case Node::Kind_UnaryMinusExpression:
castedExpression = QVariant(cleanedValue).toReal();
break;
case Node::Kind_StringLiteral:
castedExpression = QVariant(cleanedValue).toString();
break;
case Node::Kind_TrueLiteral:
case Node::Kind_FalseLiteral:
castedExpression = QVariant(cleanedValue).toBool();
break;
default:
castedExpression = cleanedValue;
break;
}
return castedExpression;
}
ScriptBindingParser::ScriptBindingParser(QmlJS::Document::Ptr doc,
const QList<QDeclarativeDebugObjectReference> &objectReferences)
: doc(doc), objectReferences(objectReferences), m_searchElementOffset(-1)
{
}
void ScriptBindingParser::process()
{
if (!doc.isNull() && doc->qmlProgram())
doc->qmlProgram()->accept(this);
}
QDeclarativeDebugObjectReference ScriptBindingParser::objectReferenceForOffset(unsigned int offset)
{
m_searchElementOffset = offset;
if (!doc.isNull() && doc->qmlProgram())
doc->qmlProgram()->accept(this);
return m_foundObjectReference;
}
QDeclarativeDebugObjectReference ScriptBindingParser::objectReference(const QString &id) const
{
foreach (const QDeclarativeDebugObjectReference &ref, objectReferences) {
if (ref.idString() == id)
return ref;
}
return QDeclarativeDebugObjectReference();
}
QDeclarativeDebugObjectReference ScriptBindingParser::objectReferenceForPosition(const QUrl &url, int line, int col) const
{
foreach (const QDeclarativeDebugObjectReference &ref, objectReferences) {
if (ref.source().lineNumber() == line
&& ref.source().columnNumber() == col
&& ref.source().url() == url)
{
return ref;
}
}
return QDeclarativeDebugObjectReference();
}
bool ScriptBindingParser::visit(UiObjectDefinition *ast)
{
objectStack.append(ast);
return true;
}
void ScriptBindingParser::endVisit(UiObjectDefinition *)
{
objectStack.removeLast();
}
bool ScriptBindingParser::visit(UiObjectBinding *ast)
{
objectStack.append(ast);
return true;
}
void ScriptBindingParser::endVisit(UiObjectBinding *)
{
objectStack.removeLast();
}
bool ScriptBindingParser::visit(UiScriptBinding *ast)
{
scripts.append(ast);
_parent[ast] = objectStack.back();
if (ast->qualifiedId && ast->qualifiedId->name && ! ast->qualifiedId->next) {
const QString bindingName = ast->qualifiedId->name->asString();
if (bindingName == QLatin1String("id")) {
_id[objectStack.back()] = ast;
if (ExpressionStatement *s = cast<ExpressionStatement *>(ast->statement)) {
if (IdentifierExpression *id = cast<IdentifierExpression *>(s->expression)) {
if (id->name) {
_idBindings.insert(ast, objectReference(id->name->asString()));
if (parent(ast)->firstSourceLocation().offset == m_searchElementOffset)
m_foundObjectReference = objectReference(id->name->asString());
}
}
}
}
}
return true;
}
QDeclarativeDebugObjectReference ScriptBindingParser::objectReferenceForScriptBinding(UiScriptBinding *binding) const
{
return _idBindings.value(binding);
}
// Delta
static QString propertyName(UiQualifiedId *id)
{
QString s;
for (; id; id = id->next) {
if (! id->name)
return QString();
s += id->name->asString();
if (id->next)
s += QLatin1Char('.');
}
return s;
}
void Delta::operator()(Document::Ptr doc, Document::Ptr previousDoc)
{
_doc = doc;
_previousDoc = previousDoc;
_changes.clear();
const QUrl url = QUrl::fromLocalFile(doc->fileName());
ScriptBindingParser bindingParser(doc, ClientProxy::instance()->objectReferences(url));
bindingParser.process();
ScriptBindingParser previousBindingParser(previousDoc, ClientProxy::instance()->objectReferences(url));
previousBindingParser.process();
QHash<UiObjectMember *, UiObjectMember *> preservedObjects;
foreach (UiScriptBinding *id, bindingParser.ids()) {
UiObjectMember *parent = bindingParser.parent(id);
const QString idCode = bindingParser.scriptCode(id);
foreach (UiScriptBinding *otherId, previousBindingParser.ids()) {
const QString otherIdCode = previousBindingParser.scriptCode(otherId);
if (idCode == otherIdCode) {
preservedObjects.insert(parent, previousBindingParser.parent(otherId));
}
}
}
QHashIterator<UiObjectMember *, UiObjectMember *> it(preservedObjects);
while (it.hasNext()) {
it.next();
UiObjectMember *object = it.key();
UiObjectMember *previousObject = it.value();
for (UiObjectMemberList *objectMemberIt = objectMembers(object); objectMemberIt; objectMemberIt = objectMemberIt->next) {
if (UiScriptBinding *script = cast<UiScriptBinding *>(objectMemberIt->member)) {
for (UiObjectMemberList *previousObjectMemberIt = objectMembers(previousObject); previousObjectMemberIt; previousObjectMemberIt = previousObjectMemberIt->next) {
if (UiScriptBinding *previousScript = cast<UiScriptBinding *>(previousObjectMemberIt->member)) {
if (compare(script->qualifiedId, previousScript->qualifiedId)) {
const QString scriptCode = bindingParser.scriptCode(script);
const QString previousScriptCode = previousBindingParser.scriptCode(previousScript);
if (scriptCode != previousScriptCode) {
const QString property = propertyName(script->qualifiedId);
qDebug() << "property:" << qPrintable(property) << scriptCode;
if (UiScriptBinding *idBinding = bindingParser.id(object)) {
if (ExpressionStatement *s = cast<ExpressionStatement *>(idBinding->statement)) {
if (IdentifierExpression *idExpr = cast<IdentifierExpression *>(s->expression)) {
const QString idString = idExpr->name->asString();
qDebug() << "the enclosing object id is:" << idString;
const QList<QDeclarativeDebugObjectReference> refs = ClientProxy::instance()->objectReferences(url);
foreach (const QDeclarativeDebugObjectReference &ref, refs) {
if (ref.idString() == idString) {
updateScriptBinding(ref, script, property, scriptCode);
break;
}
}
}
}
}
}
}
}
}
}
}
}
}
void Delta::updateScriptBinding(const QDeclarativeDebugObjectReference &objectReference,
UiScriptBinding *scriptBinding,
const QString &propertyName,
const QString &scriptCode)
{
qDebug() << "update script:" << propertyName << scriptCode << scriptBinding;
QVariant expr = scriptCode;
//qDebug() << " " << scriptBinding->statement->kind << typeid(*scriptBinding->statement).name();
const bool isLiteral = isLiteralValue(scriptBinding);
if (isLiteral)
expr = castToLiteral(scriptCode, scriptBinding);
Change change;
change.script = scriptBinding;
change.ref = objectReference;
change.isLiteral = isLiteral;
_changes.append(change);
ClientProxy::instance()->setBindingForObject(objectReference.debugId(), propertyName, expr, isLiteral); // ### remove
}
bool Delta::compare(UiQualifiedId *id, UiQualifiedId *other)
{
if (id == other)
return true;
else if (id && other) {
if (id->name && other->name) {
if (id->name->asString() == other->name->asString())
return compare(id->next, other->next);
}
}
return false;
}
UiObjectMemberList *Delta::objectMembers(UiObjectMember *object)
{
if (UiObjectDefinition *def = cast<UiObjectDefinition *>(object))
return def->initializer->members;
else if (UiObjectBinding *binding = cast<UiObjectBinding *>(object))
return binding->initializer->members;
return 0;
}
Document::Ptr Delta::document() const
{
return _doc;
}
Document::Ptr Delta::previousDocument() const
{
return _previousDoc;
}
QList<Delta::Change> Delta::changes() const
{
return _changes;
}
<commit_msg>Share the debug object references.<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "qmljsdelta.h"
#include "qmljsclientproxy.h"
#include <qmljs/parser/qmljsast_p.h>
#include <qmljs/parser/qmljsastvisitor_p.h>
#include <QtCore/QDebug>
using namespace QmlJS;
using namespace QmlJS::AST;
using namespace QmlJSInspector::Internal;
namespace {
class ScriptBindingParser : protected Visitor
{
QList<UiObjectMember *> objectStack;
QHash<UiScriptBinding *, UiObjectMember *> _parent;
QHash<UiObjectMember *, UiScriptBinding *> _id;
QHash<UiScriptBinding *, QDeclarativeDebugObjectReference> _idBindings;
public:
QmlJS::Document::Ptr doc;
QList<UiScriptBinding *> scripts;
ScriptBindingParser(Document::Ptr doc, const QList<QDeclarativeDebugObjectReference> &objectReferences = QList<QDeclarativeDebugObjectReference>());
void process();
UiObjectMember *parent(UiScriptBinding *script) const
{ return _parent.value(script); }
UiScriptBinding *id(UiObjectMember *parent) const
{ return _id.value(parent); }
QList<UiScriptBinding *> ids() const
{ return _id.values(); }
QDeclarativeDebugObjectReference objectReferenceForPosition(const QUrl &url, int line, int col) const;
QDeclarativeDebugObjectReference objectReferenceForScriptBinding(UiScriptBinding *binding) const;
QDeclarativeDebugObjectReference objectReferenceForOffset(unsigned int offset);
QString header(UiObjectMember *member) const
{
if (member) {
if (UiObjectDefinition *def = cast<UiObjectDefinition *>(member)) {
const int begin = def->firstSourceLocation().begin();
const int end = def->initializer->lbraceToken.begin();
return doc->source().mid(begin, end - begin);
} else if (UiObjectBinding *binding = cast<UiObjectBinding *>(member)) {
const int begin = binding->firstSourceLocation().begin();
const int end = binding->initializer->lbraceToken.begin();
return doc->source().mid(begin, end - begin);
}
}
return QString();
}
QString scriptCode(UiScriptBinding *script) const
{
if (script) {
const int begin = script->statement->firstSourceLocation().begin();
const int end = script->statement->lastSourceLocation().end();
return doc->source().mid(begin, end - begin);
}
return QString();
}
protected:
QDeclarativeDebugObjectReference objectReference(const QString &id) const;
virtual bool visit(UiObjectDefinition *ast);
virtual void endVisit(UiObjectDefinition *);
virtual bool visit(UiObjectBinding *ast);
virtual void endVisit(UiObjectBinding *);
virtual bool visit(UiScriptBinding *ast);
private:
QList<QDeclarativeDebugObjectReference> objectReferences;
QDeclarativeDebugObjectReference m_foundObjectReference;
unsigned int m_searchElementOffset;
};
} // end of anonymous namespace
static bool isLiteralValue(ExpressionNode *expr)
{
if (cast<NumericLiteral*>(expr))
return true;
else if (cast<StringLiteral*>(expr))
return true;
else if (UnaryPlusExpression *plusExpr = cast<UnaryPlusExpression*>(expr))
return isLiteralValue(plusExpr->expression);
else if (UnaryMinusExpression *minusExpr = cast<UnaryMinusExpression*>(expr))
return isLiteralValue(minusExpr->expression);
else if (cast<TrueLiteral*>(expr))
return true;
else if (cast<FalseLiteral*>(expr))
return true;
else
return false;
}
static inline bool isLiteralValue(UiScriptBinding *script)
{
if (!script || !script->statement)
return false;
ExpressionStatement *exprStmt = cast<ExpressionStatement *>(script->statement);
if (exprStmt)
return isLiteralValue(exprStmt->expression);
else
return false;
}
static inline QString stripQuotes(const QString &str)
{
if ((str.startsWith(QLatin1Char('"')) && str.endsWith(QLatin1Char('"')))
|| (str.startsWith(QLatin1Char('\'')) && str.endsWith(QLatin1Char('\''))))
return str.mid(1, str.length() - 2);
return str;
}
static inline QString deEscape(const QString &value)
{
QString result = value;
result.replace(QLatin1String("\\\\"), QLatin1String("\\"));
result.replace(QLatin1String("\\\""), QLatin1String("\""));
result.replace(QLatin1String("\\\t"), QLatin1String("\t"));
result.replace(QLatin1String("\\\r"), QLatin1String("\\\r"));
result.replace(QLatin1String("\\\n"), QLatin1String("\n"));
return result;
}
static QString cleanExpression(const QString &expression, UiScriptBinding *scriptBinding)
{
QString trimmedExpression = expression.trimmed();
if (ExpressionStatement *expStatement = cast<ExpressionStatement*>(scriptBinding->statement)) {
if (expStatement->semicolonToken.isValid())
trimmedExpression.chop(1);
}
return deEscape(stripQuotes(trimmedExpression));
}
static QVariant castToLiteral(const QString &expression, UiScriptBinding *scriptBinding)
{
const QString cleanedValue = cleanExpression(expression, scriptBinding);
QVariant castedExpression;
ExpressionStatement *expStatement = cast<ExpressionStatement*>(scriptBinding->statement);
switch(expStatement->expression->kind) {
case Node::Kind_NumericLiteral:
case Node::Kind_UnaryPlusExpression:
case Node::Kind_UnaryMinusExpression:
castedExpression = QVariant(cleanedValue).toReal();
break;
case Node::Kind_StringLiteral:
castedExpression = QVariant(cleanedValue).toString();
break;
case Node::Kind_TrueLiteral:
case Node::Kind_FalseLiteral:
castedExpression = QVariant(cleanedValue).toBool();
break;
default:
castedExpression = cleanedValue;
break;
}
return castedExpression;
}
ScriptBindingParser::ScriptBindingParser(QmlJS::Document::Ptr doc,
const QList<QDeclarativeDebugObjectReference> &objectReferences)
: doc(doc), objectReferences(objectReferences), m_searchElementOffset(-1)
{
}
void ScriptBindingParser::process()
{
if (!doc.isNull() && doc->qmlProgram())
doc->qmlProgram()->accept(this);
}
QDeclarativeDebugObjectReference ScriptBindingParser::objectReferenceForOffset(unsigned int offset)
{
m_searchElementOffset = offset;
if (!doc.isNull() && doc->qmlProgram())
doc->qmlProgram()->accept(this);
return m_foundObjectReference;
}
QDeclarativeDebugObjectReference ScriptBindingParser::objectReference(const QString &id) const
{
foreach (const QDeclarativeDebugObjectReference &ref, objectReferences) {
if (ref.idString() == id)
return ref;
}
return QDeclarativeDebugObjectReference();
}
QDeclarativeDebugObjectReference ScriptBindingParser::objectReferenceForPosition(const QUrl &url, int line, int col) const
{
foreach (const QDeclarativeDebugObjectReference &ref, objectReferences) {
if (ref.source().lineNumber() == line
&& ref.source().columnNumber() == col
&& ref.source().url() == url)
{
return ref;
}
}
return QDeclarativeDebugObjectReference();
}
bool ScriptBindingParser::visit(UiObjectDefinition *ast)
{
objectStack.append(ast);
return true;
}
void ScriptBindingParser::endVisit(UiObjectDefinition *)
{
objectStack.removeLast();
}
bool ScriptBindingParser::visit(UiObjectBinding *ast)
{
objectStack.append(ast);
return true;
}
void ScriptBindingParser::endVisit(UiObjectBinding *)
{
objectStack.removeLast();
}
bool ScriptBindingParser::visit(UiScriptBinding *ast)
{
scripts.append(ast);
_parent[ast] = objectStack.back();
if (ast->qualifiedId && ast->qualifiedId->name && ! ast->qualifiedId->next) {
const QString bindingName = ast->qualifiedId->name->asString();
if (bindingName == QLatin1String("id")) {
_id[objectStack.back()] = ast;
if (ExpressionStatement *s = cast<ExpressionStatement *>(ast->statement)) {
if (IdentifierExpression *id = cast<IdentifierExpression *>(s->expression)) {
if (id->name) {
_idBindings.insert(ast, objectReference(id->name->asString()));
if (parent(ast)->firstSourceLocation().offset == m_searchElementOffset)
m_foundObjectReference = objectReference(id->name->asString());
}
}
}
}
}
return true;
}
QDeclarativeDebugObjectReference ScriptBindingParser::objectReferenceForScriptBinding(UiScriptBinding *binding) const
{
return _idBindings.value(binding);
}
// Delta
static QString propertyName(UiQualifiedId *id)
{
QString s;
for (; id; id = id->next) {
if (! id->name)
return QString();
s += id->name->asString();
if (id->next)
s += QLatin1Char('.');
}
return s;
}
void Delta::operator()(Document::Ptr doc, Document::Ptr previousDoc)
{
_doc = doc;
_previousDoc = previousDoc;
_changes.clear();
const QUrl url = QUrl::fromLocalFile(doc->fileName());
const QList<QDeclarativeDebugObjectReference> references = ClientProxy::instance()->objectReferences(url);
ScriptBindingParser bindingParser(doc, references);
bindingParser.process();
ScriptBindingParser previousBindingParser(previousDoc, references);
previousBindingParser.process();
QHash<UiObjectMember *, UiObjectMember *> preservedObjects;
foreach (UiScriptBinding *id, bindingParser.ids()) {
UiObjectMember *parent = bindingParser.parent(id);
const QString idCode = bindingParser.scriptCode(id);
foreach (UiScriptBinding *otherId, previousBindingParser.ids()) {
const QString otherIdCode = previousBindingParser.scriptCode(otherId);
if (idCode == otherIdCode) {
preservedObjects.insert(parent, previousBindingParser.parent(otherId));
}
}
}
QHashIterator<UiObjectMember *, UiObjectMember *> it(preservedObjects);
while (it.hasNext()) {
it.next();
UiObjectMember *object = it.key();
UiObjectMember *previousObject = it.value();
for (UiObjectMemberList *objectMemberIt = objectMembers(object); objectMemberIt; objectMemberIt = objectMemberIt->next) {
if (UiScriptBinding *script = cast<UiScriptBinding *>(objectMemberIt->member)) {
for (UiObjectMemberList *previousObjectMemberIt = objectMembers(previousObject); previousObjectMemberIt; previousObjectMemberIt = previousObjectMemberIt->next) {
if (UiScriptBinding *previousScript = cast<UiScriptBinding *>(previousObjectMemberIt->member)) {
if (compare(script->qualifiedId, previousScript->qualifiedId)) {
const QString scriptCode = bindingParser.scriptCode(script);
const QString previousScriptCode = previousBindingParser.scriptCode(previousScript);
if (scriptCode != previousScriptCode) {
const QString property = propertyName(script->qualifiedId);
qDebug() << "property:" << qPrintable(property) << scriptCode;
if (UiScriptBinding *idBinding = bindingParser.id(object)) {
if (ExpressionStatement *s = cast<ExpressionStatement *>(idBinding->statement)) {
if (IdentifierExpression *idExpr = cast<IdentifierExpression *>(s->expression)) {
const QString idString = idExpr->name->asString();
qDebug() << "the enclosing object id is:" << idString;
const QList<QDeclarativeDebugObjectReference> refs = ClientProxy::instance()->objectReferences(url);
foreach (const QDeclarativeDebugObjectReference &ref, refs) {
if (ref.idString() == idString) {
updateScriptBinding(ref, script, property, scriptCode);
break;
}
}
}
}
}
}
}
}
}
}
}
}
}
void Delta::updateScriptBinding(const QDeclarativeDebugObjectReference &objectReference,
UiScriptBinding *scriptBinding,
const QString &propertyName,
const QString &scriptCode)
{
qDebug() << "update script:" << propertyName << scriptCode << scriptBinding;
QVariant expr = scriptCode;
//qDebug() << " " << scriptBinding->statement->kind << typeid(*scriptBinding->statement).name();
const bool isLiteral = isLiteralValue(scriptBinding);
if (isLiteral)
expr = castToLiteral(scriptCode, scriptBinding);
Change change;
change.script = scriptBinding;
change.ref = objectReference;
change.isLiteral = isLiteral;
_changes.append(change);
ClientProxy::instance()->setBindingForObject(objectReference.debugId(), propertyName, expr, isLiteral); // ### remove
}
bool Delta::compare(UiQualifiedId *id, UiQualifiedId *other)
{
if (id == other)
return true;
else if (id && other) {
if (id->name && other->name) {
if (id->name->asString() == other->name->asString())
return compare(id->next, other->next);
}
}
return false;
}
UiObjectMemberList *Delta::objectMembers(UiObjectMember *object)
{
if (UiObjectDefinition *def = cast<UiObjectDefinition *>(object))
return def->initializer->members;
else if (UiObjectBinding *binding = cast<UiObjectBinding *>(object))
return binding->initializer->members;
return 0;
}
Document::Ptr Delta::document() const
{
return _doc;
}
Document::Ptr Delta::previousDocument() const
{
return _previousDoc;
}
QList<Delta::Change> Delta::changes() const
{
return _changes;
}
<|endoftext|> |
<commit_before>//RUN: make -C %testexecdir/../../clang/ test TESTSUITE=Sema CLANG=%p/clangTestUnloader.sh
//XFAIL: *
// Current SemaCXX failures:
// Expected Passes : 392
// Expected Failures : 1
// Unexpected Failures: 184
// Current Sema failures:
// Expected Passes : 331
// Unexpected Failures: 90
<commit_msg>This test is a no-op in CMake - we need to fix that.<commit_after>//RUN: make -C %testexecdir/../../clang/ test TESTSUITE=Sema CLANG=%p/clangTestUnloader.sh
// FIXME: this test is a no-op in CMake :-(
// Current SemaCXX failures:
// Expected Passes : 392
// Expected Failures : 1
// Unexpected Failures: 184
// Current Sema failures:
// Expected Passes : 331
// Unexpected Failures: 90
<|endoftext|> |
<commit_before>#define PUT(x) std::cout << #x "=" << (x) << std::endl
#include <cybozu/benchmark.hpp>
#include <cybozu/option.hpp>
#include <cybozu/xorshift.hpp>
#include <mcl/fp.hpp>
#include <mcl/fp_tower.hpp>
typedef mcl::FpT<mcl::FpTag> Fp;
typedef mcl::Fp2T<Fp> Fp2;
typedef mcl::FpDblT<Fp> FpDbl;
typedef mcl::Fp6T<Fp> Fp6;
typedef mcl::Fp12T<Fp> Fp12;
typedef mcl::fp::Unit Unit;
void mul9(const mcl::fp::Op& op, Unit *y, const Unit *x, const Unit *p)
{
const size_t maxN = sizeof(Fp) / sizeof(Unit);
Unit tmp[maxN];
op.fp_add(tmp, x, x, p); // 2x
op.fp_add(tmp, tmp, tmp, p); // 4x
op.fp_add(tmp, tmp, tmp, p); // 8x
op.fp_add(y, tmp, x, p); // 9x
}
void benchRaw(const char *p, mcl::fp::Mode mode)
{
Fp::init(p, mode);
Fp2::init();
const size_t maxN = sizeof(Fp) / sizeof(Unit);
const mcl::fp::Op& op = Fp::getOp();
cybozu::XorShift rg;
Fp fx, fy;
fx.setRand(rg);
fy.setRand(rg);
Unit ux[maxN * 2] = {};
Unit uy[maxN * 2] = {};
Unit uz[maxN * 2] = {};
memcpy(ux, fx.getUnit(), sizeof(Unit) * op.N);
memcpy(ux + op.N, fx.getUnit(), sizeof(Unit) * op.N);
memcpy(uy, fy.getUnit(), sizeof(Unit) * op.N);
memcpy(ux + op.N, fx.getUnit(), sizeof(Unit) * op.N);
double fp_addT, fp_subT;
double fp_addPreT, fp_subPreT;
double fp_sqrT, fp_mulT;
double fp_mulUnitT;
double mul9T;
double fp_mulUnitPreT;
double fpN1_modT;
double fpDbl_addT, fpDbl_subT;
double fpDbl_sqrPreT, fpDbl_mulPreT, fpDbl_modT;
double fp2_sqrT, fp2_mulT;
CYBOZU_BENCH_T(fp_addT, op.fp_add, uz, ux, uy, op.p);
CYBOZU_BENCH_T(fp_subT, op.fp_sub, uz, uy, ux, op.p);
CYBOZU_BENCH_T(fp_addPreT, op.fp_addPre, uz, ux, uy);
CYBOZU_BENCH_T(fp_subPreT, op.fp_subPre, uz, uy, ux);
CYBOZU_BENCH_T(fp_sqrT, op.fp_sqr, uz, ux, op.p);
CYBOZU_BENCH_T(fp_mulT, op.fp_mul, uz, ux, uy, op.p);
CYBOZU_BENCH_T(fp_mulUnitT, op.fp_mulUnit, uz, ux, 9, op.p);
CYBOZU_BENCH_T(mul9T, mul9, op, uz, ux, op.p);
CYBOZU_BENCH_T(fp_mulUnitPreT, op.fp_mulUnitPre, ux, ux, 9);
CYBOZU_BENCH_T(fpN1_modT, op.fpN1_mod, ux, uy, op.p);
CYBOZU_BENCH_T(fpDbl_addT, op.fpDbl_add, uz, ux, uy, op.p);
CYBOZU_BENCH_T(fpDbl_subT, op.fpDbl_sub, uz, uy, ux, op.p);
CYBOZU_BENCH_T(fpDbl_sqrPreT, op.fpDbl_sqrPre, uz, ux);
CYBOZU_BENCH_T(fpDbl_mulPreT, op.fpDbl_mulPre, uz, ux, uy);
CYBOZU_BENCH_T(fpDbl_modT, op.fpDbl_mod, uz, ux, op.p);
Fp2 f2x, f2y;
f2x.a = fx;
f2x.b = fy;
f2y = f2x;
CYBOZU_BENCH_T(fp2_sqrT, Fp2::sqr, f2x, f2x);
CYBOZU_BENCH_T(fp2_mulT, Fp2::mul, f2x, f2x, f2y);
printf("%s\n", mcl::fp::ModeToStr(mode));
const char *tStrTbl[] = {
"fp_add", "fp_sub",
"addPre", "subPre",
"fp_sqr", "fp_mul",
"mulUnit",
"mul9",
"mulUnitP",
"fpN1_mod",
"D_add", "D_sub",
"D_sqrPre", "D_mulPre", "D_mod",
"fp2_sqr", "fp2_mul",
};
for (size_t i = 0; i < CYBOZU_NUM_OF_ARRAY(tStrTbl); i++) {
printf(" %8s", tStrTbl[i]);
}
printf("\n");
const double tTbl[] = {
fp_addT, fp_subT,
fp_addPreT, fp_subPreT,
fp_sqrT, fp_mulT,
fp_mulUnitT,
mul9T,
fp_mulUnitPreT,
fpN1_modT,
fpDbl_addT, fpDbl_subT,
fpDbl_sqrPreT, fpDbl_mulPreT, fpDbl_modT,
fp2_sqrT, fp2_mulT,
};
for (size_t i = 0; i < CYBOZU_NUM_OF_ARRAY(tTbl); i++) {
printf(" %8.2f", tTbl[i]);
}
printf("\n");
}
int main(int argc, char *argv[])
try
{
cybozu::Option opt;
size_t bitSize;
opt.appendOpt(&bitSize, 0, "s", ": bitSize");
opt.appendHelp("h", ": show this message");
if (!opt.parse(argc, argv)) {
opt.usage();
return 1;
}
const char *tbl[] = {
// N = 2
"0x0000000000000001000000000000000d",
"0x7fffffffffffffffffffffffffffffff",
"0x8000000000000000000000000000001d",
"0xffffffffffffffffffffffffffffff61",
// N = 3
"0x000000000000000100000000000000000000000000000033", // min prime
"0x70000000000000000000000000000000000000000000001f",
"0x800000000000000000000000000000000000000000000005",
"0xfffffffffffffffffffffffe26f2fc170f69466a74defd8d",
"0xfffffffffffffffffffffffffffffffeffffffffffffffff",
"0xffffffffffffffffffffffffffffffffffffffffffffff13", // max prime
// N = 4
"0x0000000000000001000000000000000000000000000000000000000000000085", // min prime
"0x2523648240000001ba344d80000000086121000000000013a700000000000013", // BN254
"0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47", // Snark
"0x7523648240000001ba344d80000000086121000000000013a700000000000017",
"0x800000000000000000000000000000000000000000000000000000000000005f",
"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff43", // max prime
// N = 5
"0x80000000000000000000000000000000000000000000000000000000000000000000000000000009",
"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff3b",
// N = 6
"0x800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000171",
"0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec3",
// N = 7
"0x8000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000063",
"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff35",
// N = 8
"0x8000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000006f",
"0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffdc7",
#if MCL_MAX_BIT_SIZE == 1024
"0xc70b1ddda9b96e3965e5855942aa5852d8f8e052c760ac32cdfec16a2ed3d56981e1a475e20a70144ed2f5061ba64900f69451492803f815d446ee133d0668f7a7f3276d6301c95ce231f0e4b0d0f3882f10014fca04454cff55d2e2d4cfc1aad33b8d38397e2fc8b623177e63d0b783269c40a85b8f105654783b8ed2e737df",
"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff97",
#endif
};
for (size_t i = 0; i < CYBOZU_NUM_OF_ARRAY(tbl); i++) {
const char *p = tbl[i];
if (bitSize > 0 && (strlen(p) - 2) * 4 != bitSize) {
continue;
}
printf("prime=%s\n", p);
benchRaw(tbl[i], mcl::fp::FP_GMP);
benchRaw(tbl[i], mcl::fp::FP_GMP_MONT);
#ifdef MCL_USE_LLVM
benchRaw(tbl[i], mcl::fp::FP_LLVM);
benchRaw(tbl[i], mcl::fp::FP_LLVM_MONT);
#endif
#ifdef MCL_USE_XBYAK
if (bitSize <= 384) {
benchRaw(tbl[i], mcl::fp::FP_XBYAK);
}
#endif
}
} catch (std::exception& e) {
printf("ERR %s\n", e.what());
return 1;
}
<commit_msg>set xi_a for Fp::init<commit_after>#define PUT(x) std::cout << #x "=" << (x) << std::endl
#include <cybozu/benchmark.hpp>
#include <cybozu/option.hpp>
#include <cybozu/xorshift.hpp>
#include <mcl/fp.hpp>
#include <mcl/fp_tower.hpp>
typedef mcl::FpT<mcl::FpTag> Fp;
typedef mcl::Fp2T<Fp> Fp2;
typedef mcl::FpDblT<Fp> FpDbl;
typedef mcl::Fp6T<Fp> Fp6;
typedef mcl::Fp12T<Fp> Fp12;
typedef mcl::fp::Unit Unit;
void mul9(const mcl::fp::Op& op, Unit *y, const Unit *x, const Unit *p)
{
const size_t maxN = sizeof(Fp) / sizeof(Unit);
Unit tmp[maxN];
op.fp_add(tmp, x, x, p); // 2x
op.fp_add(tmp, tmp, tmp, p); // 4x
op.fp_add(tmp, tmp, tmp, p); // 8x
op.fp_add(y, tmp, x, p); // 9x
}
void benchRaw(const char *p, mcl::fp::Mode mode)
{
Fp::init(1, p, mode);
Fp2::init();
const size_t maxN = sizeof(Fp) / sizeof(Unit);
const mcl::fp::Op& op = Fp::getOp();
cybozu::XorShift rg;
Fp fx, fy;
fx.setRand(rg);
fy.setRand(rg);
Unit ux[maxN * 2] = {};
Unit uy[maxN * 2] = {};
Unit uz[maxN * 2] = {};
memcpy(ux, fx.getUnit(), sizeof(Unit) * op.N);
memcpy(ux + op.N, fx.getUnit(), sizeof(Unit) * op.N);
memcpy(uy, fy.getUnit(), sizeof(Unit) * op.N);
memcpy(ux + op.N, fx.getUnit(), sizeof(Unit) * op.N);
double fp_addT, fp_subT;
double fp_addPreT, fp_subPreT;
double fp_sqrT, fp_mulT;
double fp_mulUnitT;
double mul9T;
double fp_mulUnitPreT;
double fpN1_modT;
double fpDbl_addT, fpDbl_subT;
double fpDbl_sqrPreT, fpDbl_mulPreT, fpDbl_modT;
double fp2_sqrT, fp2_mulT;
CYBOZU_BENCH_T(fp_addT, op.fp_add, uz, ux, uy, op.p);
CYBOZU_BENCH_T(fp_subT, op.fp_sub, uz, uy, ux, op.p);
CYBOZU_BENCH_T(fp_addPreT, op.fp_addPre, uz, ux, uy);
CYBOZU_BENCH_T(fp_subPreT, op.fp_subPre, uz, uy, ux);
CYBOZU_BENCH_T(fp_sqrT, op.fp_sqr, uz, ux, op.p);
CYBOZU_BENCH_T(fp_mulT, op.fp_mul, uz, ux, uy, op.p);
CYBOZU_BENCH_T(fp_mulUnitT, op.fp_mulUnit, uz, ux, 9, op.p);
CYBOZU_BENCH_T(mul9T, mul9, op, uz, ux, op.p);
CYBOZU_BENCH_T(fp_mulUnitPreT, op.fp_mulUnitPre, ux, ux, 9);
CYBOZU_BENCH_T(fpN1_modT, op.fpN1_mod, ux, uy, op.p);
CYBOZU_BENCH_T(fpDbl_addT, op.fpDbl_add, uz, ux, uy, op.p);
CYBOZU_BENCH_T(fpDbl_subT, op.fpDbl_sub, uz, uy, ux, op.p);
CYBOZU_BENCH_T(fpDbl_sqrPreT, op.fpDbl_sqrPre, uz, ux);
CYBOZU_BENCH_T(fpDbl_mulPreT, op.fpDbl_mulPre, uz, ux, uy);
CYBOZU_BENCH_T(fpDbl_modT, op.fpDbl_mod, uz, ux, op.p);
Fp2 f2x, f2y;
f2x.a = fx;
f2x.b = fy;
f2y = f2x;
CYBOZU_BENCH_T(fp2_sqrT, Fp2::sqr, f2x, f2x);
CYBOZU_BENCH_T(fp2_mulT, Fp2::mul, f2x, f2x, f2y);
printf("%s\n", mcl::fp::ModeToStr(mode));
const char *tStrTbl[] = {
"fp_add", "fp_sub",
"addPre", "subPre",
"fp_sqr", "fp_mul",
"mulUnit",
"mul9",
"mulUnitP",
"fpN1_mod",
"D_add", "D_sub",
"D_sqrPre", "D_mulPre", "D_mod",
"fp2_sqr", "fp2_mul",
};
for (size_t i = 0; i < CYBOZU_NUM_OF_ARRAY(tStrTbl); i++) {
printf(" %8s", tStrTbl[i]);
}
printf("\n");
const double tTbl[] = {
fp_addT, fp_subT,
fp_addPreT, fp_subPreT,
fp_sqrT, fp_mulT,
fp_mulUnitT,
mul9T,
fp_mulUnitPreT,
fpN1_modT,
fpDbl_addT, fpDbl_subT,
fpDbl_sqrPreT, fpDbl_mulPreT, fpDbl_modT,
fp2_sqrT, fp2_mulT,
};
for (size_t i = 0; i < CYBOZU_NUM_OF_ARRAY(tTbl); i++) {
printf(" %8.2f", tTbl[i]);
}
printf("\n");
}
int main(int argc, char *argv[])
try
{
cybozu::Option opt;
size_t bitSize;
opt.appendOpt(&bitSize, 0, "s", ": bitSize");
opt.appendHelp("h", ": show this message");
if (!opt.parse(argc, argv)) {
opt.usage();
return 1;
}
const char *tbl[] = {
// N = 2
"0x0000000000000001000000000000000d",
"0x7fffffffffffffffffffffffffffffff",
"0x8000000000000000000000000000001d",
"0xffffffffffffffffffffffffffffff61",
// N = 3
"0x000000000000000100000000000000000000000000000033", // min prime
"0x70000000000000000000000000000000000000000000001f",
"0x800000000000000000000000000000000000000000000005",
"0xfffffffffffffffffffffffe26f2fc170f69466a74defd8d",
"0xfffffffffffffffffffffffffffffffeffffffffffffffff",
"0xffffffffffffffffffffffffffffffffffffffffffffff13", // max prime
// N = 4
"0x0000000000000001000000000000000000000000000000000000000000000085", // min prime
"0x2523648240000001ba344d80000000086121000000000013a700000000000013", // BN254
"0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47", // Snark
"0x7523648240000001ba344d80000000086121000000000013a700000000000017",
"0x800000000000000000000000000000000000000000000000000000000000005f",
"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff43", // max prime
// N = 5
"0x80000000000000000000000000000000000000000000000000000000000000000000000000000009",
"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff3b",
// N = 6
"0x800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000171",
"0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec3",
// N = 7
"0x8000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000063",
"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff35",
// N = 8
"0x8000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000006f",
"0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffdc7",
#if MCL_MAX_BIT_SIZE == 1024
"0xc70b1ddda9b96e3965e5855942aa5852d8f8e052c760ac32cdfec16a2ed3d56981e1a475e20a70144ed2f5061ba64900f69451492803f815d446ee133d0668f7a7f3276d6301c95ce231f0e4b0d0f3882f10014fca04454cff55d2e2d4cfc1aad33b8d38397e2fc8b623177e63d0b783269c40a85b8f105654783b8ed2e737df",
"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff97",
#endif
};
for (size_t i = 0; i < CYBOZU_NUM_OF_ARRAY(tbl); i++) {
const char *p = tbl[i];
if (bitSize > 0 && (strlen(p) - 2) * 4 != bitSize) {
continue;
}
printf("prime=%s\n", p);
benchRaw(tbl[i], mcl::fp::FP_GMP);
benchRaw(tbl[i], mcl::fp::FP_GMP_MONT);
#ifdef MCL_USE_LLVM
benchRaw(tbl[i], mcl::fp::FP_LLVM);
benchRaw(tbl[i], mcl::fp::FP_LLVM_MONT);
#endif
#ifdef MCL_USE_XBYAK
if (bitSize <= 384) {
benchRaw(tbl[i], mcl::fp::FP_XBYAK);
}
#endif
}
} catch (std::exception& e) {
printf("ERR %s\n", e.what());
return 1;
}
<|endoftext|> |
<commit_before>#ifndef MIMOSA_SYNC_CONDITION_HH
# define MIMOSA_SYNC_CONDITION_HH
# include <stdexcept>
# include <melon/melon.h>
# include "../non-copyable.hh"
# include "../runtime/time.hh"
namespace mimosa
{
namespace sync
{
class Condition : private NonCopyable
{
public:
inline Condition()
: cond_(::melon_cond_new())
{
if (!cond_)
throw std::bad_alloc();
}
inline ~Condition() { ::melon_cond_destroy(cond_); }
template <typename Mutex>
inline void wait(Mutex & mutex, runtime::Time time = 0)
{ ::melon_cond_timedwait(cond_, mutex.mutex_, time); }
inline void wakeOne() { ::melon_cond_signal(cond_); }
inline void wakeAll() { ::melon_cond_broadcast(cond_); }
private:
::melon_cond * cond_;
};
}
}
#endif /* !MIMOSA_SYNC_CONDITION_HH */
<commit_msg>condition: distinguishing wait and timedWait<commit_after>#ifndef MIMOSA_SYNC_CONDITION_HH
# define MIMOSA_SYNC_CONDITION_HH
# include <stdexcept>
# include <melon/melon.h>
# include "../non-copyable.hh"
# include "../runtime/time.hh"
namespace mimosa
{
namespace sync
{
class Condition : private NonCopyable
{
public:
inline Condition()
: cond_(::melon_cond_new())
{
if (!cond_)
throw std::bad_alloc();
}
inline ~Condition() { ::melon_cond_destroy(cond_); }
template <typename Mutex>
inline void wait(Mutex & mutex)
{ ::melon_cond_wait(cond_, mutex.mutex_); }
inline void timedWait(Mutex & mutex, runtime::Time time)
{ ::melon_cond_timedwait(cond_, mutex.mutex_, time); }
inline void wakeOne() { ::melon_cond_signal(cond_); }
inline void wakeAll() { ::melon_cond_broadcast(cond_); }
private:
::melon_cond * cond_;
};
}
}
#endif /* !MIMOSA_SYNC_CONDITION_HH */
<|endoftext|> |
<commit_before>// ======================================================================== //
// Copyright 2009-2015 Intel Corporation //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// ======================================================================== //
#include "tessellation_cache.h"
namespace embree
{
SharedLazyTessellationCache SharedLazyTessellationCache::sharedLazyTessellationCache;
__thread ThreadWorkState* SharedLazyTessellationCache::init_t_state = nullptr;
ThreadWorkState* SharedLazyTessellationCache::current_t_state = nullptr;
void resizeTessellationCache(const size_t new_size)
{
if (SharedLazyTessellationCache::MAX_TESSELLATION_CACHE_SIZE >= new_size &&
SharedLazyTessellationCache::sharedLazyTessellationCache.getSize() != new_size)
SharedLazyTessellationCache::sharedLazyTessellationCache.realloc(new_size);
}
void resetTessellationCache()
{
//SharedLazyTessellationCache::sharedLazyTessellationCache.addCurrentIndex(SharedLazyTessellationCache::NUM_CACHE_SEGMENTS);
SharedLazyTessellationCache::sharedLazyTessellationCache.reset();
}
/* alloc cache memory */
float *alloc_tessellation_cache_mem(const size_t blocks)
{
return (float*)_mm_malloc(64 * blocks,64);
}
/* free cache memory */
void free_tessellation_cache_mem(void *mem, const size_t blocks)
{
assert(mem);
_mm_free(mem);
}
SharedLazyTessellationCache::SharedLazyTessellationCache()
{
size = DEFAULT_TESSELLATION_CACHE_SIZE;
#if defined(_MSC_VER)
data = (float*)os_malloc(size); // FIXME: should only reserve memory under windows
#else
data = (float*)os_reserve(size);
#endif
maxBlocks = size/64;
localTime = NUM_CACHE_SEGMENTS;
next_block = 0;
numRenderThreads = 0;
#if FORCE_SIMPLE_FLUSH == 1
switch_block_threshold = maxBlocks;
#else
switch_block_threshold = maxBlocks/NUM_CACHE_SEGMENTS;
#endif
threadWorkState = (ThreadWorkState*)_mm_malloc(sizeof(ThreadWorkState)*NUM_PREALLOC_THREAD_WORK_STATES,64);
for (size_t i=0;i<NUM_PREALLOC_THREAD_WORK_STATES;i++)
threadWorkState[i].reset();
reset_state.reset();
linkedlist_mtx.reset();
}
void SharedLazyTessellationCache::getNextRenderThreadWorkState()
{
const size_t id = numRenderThreads.add(1);
if (id >= NUM_PREALLOC_THREAD_WORK_STATES)
{
init_t_state = (ThreadWorkState*)_mm_malloc(sizeof(ThreadWorkState),64);
init_t_state->reset();
}
else
{
init_t_state = &threadWorkState[id];
}
/* critical section for updating link list with new thread state */
linkedlist_mtx.lock();
init_t_state->prev = current_t_state;
current_t_state = init_t_state;
linkedlist_mtx.unlock();
}
void SharedLazyTessellationCache::waitForUsersLessEqual(ThreadWorkState *const t_state,
const unsigned int users)
{
while( !(t_state->counter <= users) )
{
#if defined(__MIC__)
_mm_delay_32(128);
#else
_mm_pause();
_mm_pause();
_mm_pause();
_mm_pause();
#endif
}
}
void SharedLazyTessellationCache::allocNextSegment()
{
if (reset_state.try_lock())
{
if (next_block >= switch_block_threshold)
{
/* lock the linked list of thread states */
linkedlist_mtx.lock();
/* block all threads */
for (ThreadWorkState *t=current_t_state;t!=nullptr;t=t->prev)
if (lockThread(t) == 1)
waitForUsersLessEqual(t,1);
/* switch to the next segment */
addCurrentIndex();
CACHE_STATS(PRINT("RESET TESS CACHE"));
#if FORCE_SIMPLE_FLUSH == 1
next_block = 0;
switch_block_threshold = maxBlocks;
#else
const size_t region = localTime % NUM_CACHE_SEGMENTS;
next_block = region * (maxBlocks/NUM_CACHE_SEGMENTS);
switch_block_threshold = next_block + (maxBlocks/NUM_CACHE_SEGMENTS);
#if 0
PRINT( region );
PRINT( maxBlocks );
PRINT( NUM_CACHE_SEGMENTS );
PRINT( maxBlocks/NUM_CACHE_SEGMENTS );
PRINT( next_block );
PRINT( switch_block_threshold );
#endif
assert( switch_block_threshold <= maxBlocks );
#endif
CACHE_STATS(SharedTessellationCacheStats::cache_flushes++);
/* release all blocked threads */
for (ThreadWorkState *t=current_t_state;t!=nullptr;t=t->prev)
unlockThread(t);
/* unlock the linked list of thread states */
linkedlist_mtx.unlock();
}
reset_state.unlock();
}
else
reset_state.wait_until_unlocked();
}
void SharedLazyTessellationCache::reset()
{
#if 1
/* lock the reset_state */
reset_state.lock();
/* lock the linked list of thread states */
linkedlist_mtx.lock();
/* block all threads */
for (ThreadWorkState *t=current_t_state;t!=nullptr;t=t->prev)
if (lockThread(t) == 1)
waitForUsersLessEqual(t,1);
#endif
/* reset to the first segment */
next_block = 0;
#if FORCE_SIMPLE_FLUSH == 1
switch_block_threshold = maxBlocks;
#else
switch_block_threshold = maxBlocks/NUM_CACHE_SEGMENTS;
#endif
#if 1
/* release all blocked threads */
for (ThreadWorkState *t=current_t_state;t!=nullptr;t=t->prev)
unlockThread(t);
/* unlock the linked list of thread states */
linkedlist_mtx.unlock();
/* unlock the reset_state */
reset_state.unlock();
#endif
}
void SharedLazyTessellationCache::realloc(const size_t new_size)
{
if (data)
{
os_free(data,size);
}
size = new_size;
data = (float*)os_malloc(size);
maxBlocks = size/64;
#if FORCE_SIMPLE_FLUSH == 1
switch_block_threshold = maxBlocks;
#else
switch_block_threshold = maxBlocks/NUM_CACHE_SEGMENTS;
#endif
if (State::instance()->verbose >= 1)
std::cout << "Reallocating tessellation cache to " << size << " bytes, " << maxBlocks << " 64-byte blocks" << std::endl;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////
AtomicCounter SharedTessellationCacheStats::cache_accesses = 0;
AtomicCounter SharedTessellationCacheStats::cache_hits = 0;
AtomicCounter SharedTessellationCacheStats::cache_misses = 0;
AtomicCounter SharedTessellationCacheStats::cache_flushes = 0;
AtomicMutex SharedTessellationCacheStats::mtx;
AtomicCounter *SharedTessellationCacheStats::cache_patch_builds = NULL;
size_t SharedTessellationCacheStats::cache_num_patches = 0;
float **SharedTessellationCacheStats::cache_new_delete_ptr = NULL;
void SharedTessellationCacheStats::printStats()
{
PRINT(cache_accesses);
PRINT(cache_misses);
PRINT(cache_hits);
PRINT(cache_flushes);
PRINT(100.0f * cache_hits / cache_accesses);
assert(cache_hits + cache_misses == cache_accesses);
PRINT(cache_num_patches);
size_t patches = 0;
size_t builds = 0;
for (size_t i=0;i<cache_num_patches;i++)
if (cache_patch_builds[i])
{
patches++;
builds += cache_patch_builds[i];
}
PRINT(patches);
PRINT(builds);
PRINT((double)builds/patches);
}
void SharedTessellationCacheStats::clearStats()
{
SharedTessellationCacheStats::cache_accesses = 0;
SharedTessellationCacheStats::cache_hits = 0;
SharedTessellationCacheStats::cache_misses = 0;
SharedTessellationCacheStats::cache_flushes = 0;
for (size_t i=0;i<cache_num_patches;i++)
cache_patch_builds[i] = 0;
}
void SharedTessellationCacheStats::incPatchBuild(const size_t ID, const size_t numPatches)
{
if (!cache_patch_builds)
{
mtx.lock();
if (!cache_patch_builds)
{
PRINT(numPatches);
cache_num_patches = numPatches;
cache_patch_builds = (AtomicCounter*)os_malloc(numPatches*sizeof(AtomicCounter));
memset(cache_patch_builds,0,numPatches*sizeof(AtomicCounter));
}
mtx.unlock();
}
assert(ID < cache_num_patches);
cache_patch_builds[ID].add(1);
}
void SharedTessellationCacheStats::newDeletePatchPtr(const size_t ID, const size_t numPatches, const size_t size)
{
assert(ID < numPatches);
if(!cache_new_delete_ptr)
{
mtx.lock();
if(!cache_new_delete_ptr)
{
PRINT(numPatches);
cache_num_patches = numPatches;
cache_new_delete_ptr = new float*[numPatches];
memset(cache_new_delete_ptr,0,sizeof(float*)*numPatches);
}
mtx.unlock();
}
if (cache_new_delete_ptr[ID])
free(cache_new_delete_ptr[ID]);
cache_new_delete_ptr[ID] = (float*)malloc(size);
memset(cache_new_delete_ptr[ID],0,size);
}
};
extern "C" void printTessCacheStats()
{
PRINT("SHARED TESSELLATION CACHE");
embree::SharedTessellationCacheStats::printStats();
embree::SharedTessellationCacheStats::clearStats();
}
<commit_msg>added fixme<commit_after>// ======================================================================== //
// Copyright 2009-2015 Intel Corporation //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// ======================================================================== //
#include "tessellation_cache.h"
namespace embree
{
SharedLazyTessellationCache SharedLazyTessellationCache::sharedLazyTessellationCache;
__thread ThreadWorkState* SharedLazyTessellationCache::init_t_state = nullptr;
ThreadWorkState* SharedLazyTessellationCache::current_t_state = nullptr;
void resizeTessellationCache(const size_t new_size)
{
if (SharedLazyTessellationCache::MAX_TESSELLATION_CACHE_SIZE >= new_size &&
SharedLazyTessellationCache::sharedLazyTessellationCache.getSize() != new_size)
SharedLazyTessellationCache::sharedLazyTessellationCache.realloc(new_size);
}
void resetTessellationCache()
{
//SharedLazyTessellationCache::sharedLazyTessellationCache.addCurrentIndex(SharedLazyTessellationCache::NUM_CACHE_SEGMENTS);
SharedLazyTessellationCache::sharedLazyTessellationCache.reset();
}
/* alloc cache memory */
float *alloc_tessellation_cache_mem(const size_t blocks)
{
return (float*)_mm_malloc(64 * blocks,64);
}
/* free cache memory */
void free_tessellation_cache_mem(void *mem, const size_t blocks)
{
assert(mem);
_mm_free(mem);
}
SharedLazyTessellationCache::SharedLazyTessellationCache()
{
size = DEFAULT_TESSELLATION_CACHE_SIZE;
#if defined(_MSC_VER)
data = (float*)os_malloc(size); // FIXME: should only reserve memory under windows
#else
data = (float*)os_reserve(size);
#endif
maxBlocks = size/64;
localTime = NUM_CACHE_SEGMENTS;
next_block = 0;
numRenderThreads = 0;
#if FORCE_SIMPLE_FLUSH == 1
switch_block_threshold = maxBlocks;
#else
switch_block_threshold = maxBlocks/NUM_CACHE_SEGMENTS;
#endif
threadWorkState = (ThreadWorkState*)_mm_malloc(sizeof(ThreadWorkState)*NUM_PREALLOC_THREAD_WORK_STATES,64);
for (size_t i=0;i<NUM_PREALLOC_THREAD_WORK_STATES;i++)
threadWorkState[i].reset();
reset_state.reset();
linkedlist_mtx.reset();
}
void SharedLazyTessellationCache::getNextRenderThreadWorkState()
{
const size_t id = numRenderThreads.add(1);
if (id >= NUM_PREALLOC_THREAD_WORK_STATES)
{
init_t_state = (ThreadWorkState*)_mm_malloc(sizeof(ThreadWorkState),64);
init_t_state->reset();
}
else
{
init_t_state = &threadWorkState[id];
}
/* critical section for updating link list with new thread state */
linkedlist_mtx.lock();
init_t_state->prev = current_t_state;
current_t_state = init_t_state;
linkedlist_mtx.unlock();
}
void SharedLazyTessellationCache::waitForUsersLessEqual(ThreadWorkState *const t_state,
const unsigned int users)
{
while( !(t_state->counter <= users) )
{
#if defined(__MIC__)
_mm_delay_32(128);
#else
_mm_pause();
_mm_pause();
_mm_pause();
_mm_pause();
#endif
}
}
void SharedLazyTessellationCache::allocNextSegment()
{
if (reset_state.try_lock())
{
if (next_block >= switch_block_threshold)
{
/* lock the linked list of thread states */
linkedlist_mtx.lock();
/* block all threads */
for (ThreadWorkState *t=current_t_state;t!=nullptr;t=t->prev)
if (lockThread(t) == 1)
waitForUsersLessEqual(t,1);
/* switch to the next segment */
addCurrentIndex();
CACHE_STATS(PRINT("RESET TESS CACHE"));
#if FORCE_SIMPLE_FLUSH == 1
next_block = 0;
switch_block_threshold = maxBlocks;
#else
const size_t region = localTime % NUM_CACHE_SEGMENTS;
next_block = region * (maxBlocks/NUM_CACHE_SEGMENTS);
switch_block_threshold = next_block + (maxBlocks/NUM_CACHE_SEGMENTS);
#if 0
PRINT( region );
PRINT( maxBlocks );
PRINT( NUM_CACHE_SEGMENTS );
PRINT( maxBlocks/NUM_CACHE_SEGMENTS );
PRINT( next_block );
PRINT( switch_block_threshold );
#endif
assert( switch_block_threshold <= maxBlocks );
#endif
CACHE_STATS(SharedTessellationCacheStats::cache_flushes++);
/* release all blocked threads */
for (ThreadWorkState *t=current_t_state;t!=nullptr;t=t->prev)
unlockThread(t);
/* unlock the linked list of thread states */
linkedlist_mtx.unlock();
}
reset_state.unlock();
}
else
reset_state.wait_until_unlocked();
}
void SharedLazyTessellationCache::reset()
{
#if 1
/* lock the reset_state */
reset_state.lock();
/* lock the linked list of thread states */
linkedlist_mtx.lock();
/* block all threads */
for (ThreadWorkState *t=current_t_state;t!=nullptr;t=t->prev)
if (lockThread(t) == 1)
waitForUsersLessEqual(t,1);
#endif
/* reset to the first segment */
next_block = 0;
#if FORCE_SIMPLE_FLUSH == 1
switch_block_threshold = maxBlocks;
#else
switch_block_threshold = maxBlocks/NUM_CACHE_SEGMENTS;
#endif
#if 1
/* release all blocked threads */
for (ThreadWorkState *t=current_t_state;t!=nullptr;t=t->prev)
unlockThread(t);
/* unlock the linked list of thread states */
linkedlist_mtx.unlock();
/* unlock the reset_state */
reset_state.unlock();
#endif
}
void SharedLazyTessellationCache::realloc(const size_t new_size)
{
if (data)
{
os_free(data,size);
}
size = new_size;
data = (float*)os_malloc(size); // FIXME: do os_reserve under linux
maxBlocks = size/64;
#if FORCE_SIMPLE_FLUSH == 1
switch_block_threshold = maxBlocks;
#else
switch_block_threshold = maxBlocks/NUM_CACHE_SEGMENTS;
#endif
if (State::instance()->verbose >= 1)
std::cout << "Reallocating tessellation cache to " << size << " bytes, " << maxBlocks << " 64-byte blocks" << std::endl;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////
AtomicCounter SharedTessellationCacheStats::cache_accesses = 0;
AtomicCounter SharedTessellationCacheStats::cache_hits = 0;
AtomicCounter SharedTessellationCacheStats::cache_misses = 0;
AtomicCounter SharedTessellationCacheStats::cache_flushes = 0;
AtomicMutex SharedTessellationCacheStats::mtx;
AtomicCounter *SharedTessellationCacheStats::cache_patch_builds = NULL;
size_t SharedTessellationCacheStats::cache_num_patches = 0;
float **SharedTessellationCacheStats::cache_new_delete_ptr = NULL;
void SharedTessellationCacheStats::printStats()
{
PRINT(cache_accesses);
PRINT(cache_misses);
PRINT(cache_hits);
PRINT(cache_flushes);
PRINT(100.0f * cache_hits / cache_accesses);
assert(cache_hits + cache_misses == cache_accesses);
PRINT(cache_num_patches);
size_t patches = 0;
size_t builds = 0;
for (size_t i=0;i<cache_num_patches;i++)
if (cache_patch_builds[i])
{
patches++;
builds += cache_patch_builds[i];
}
PRINT(patches);
PRINT(builds);
PRINT((double)builds/patches);
}
void SharedTessellationCacheStats::clearStats()
{
SharedTessellationCacheStats::cache_accesses = 0;
SharedTessellationCacheStats::cache_hits = 0;
SharedTessellationCacheStats::cache_misses = 0;
SharedTessellationCacheStats::cache_flushes = 0;
for (size_t i=0;i<cache_num_patches;i++)
cache_patch_builds[i] = 0;
}
void SharedTessellationCacheStats::incPatchBuild(const size_t ID, const size_t numPatches)
{
if (!cache_patch_builds)
{
mtx.lock();
if (!cache_patch_builds)
{
PRINT(numPatches);
cache_num_patches = numPatches;
cache_patch_builds = (AtomicCounter*)os_malloc(numPatches*sizeof(AtomicCounter));
memset(cache_patch_builds,0,numPatches*sizeof(AtomicCounter));
}
mtx.unlock();
}
assert(ID < cache_num_patches);
cache_patch_builds[ID].add(1);
}
void SharedTessellationCacheStats::newDeletePatchPtr(const size_t ID, const size_t numPatches, const size_t size)
{
assert(ID < numPatches);
if(!cache_new_delete_ptr)
{
mtx.lock();
if(!cache_new_delete_ptr)
{
PRINT(numPatches);
cache_num_patches = numPatches;
cache_new_delete_ptr = new float*[numPatches];
memset(cache_new_delete_ptr,0,sizeof(float*)*numPatches);
}
mtx.unlock();
}
if (cache_new_delete_ptr[ID])
free(cache_new_delete_ptr[ID]);
cache_new_delete_ptr[ID] = (float*)malloc(size);
memset(cache_new_delete_ptr[ID],0,size);
}
};
extern "C" void printTessCacheStats()
{
PRINT("SHARED TESSELLATION CACHE");
embree::SharedTessellationCacheStats::printStats();
embree::SharedTessellationCacheStats::clearStats();
}
<|endoftext|> |
<commit_before>/*
This file is part of Kontact.
Copyright (c) 2003 Tobias Koenig <tokoe@kde.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include <qlabel.h>
#include <qlayout.h>
#include <kdialog.h>
#include <kglobal.h>
#include <kiconloader.h>
#include <klocale.h>
#include <kparts/part.h>
#include <kstandarddirs.h>
#include <kurllabel.h>
#include <qtooltip.h>
#include <libkcal/event.h>
#include <libkcal/resourcecalendar.h>
#include <libkcal/resourcelocal.h>
#include <libkdepim/kpimprefs.h>
#include "korganizeriface_stub.h"
#include "core.h"
#include "plugin.h"
#include "korganizerplugin.h"
#include "korganizer/stdcalendar.h"
#include "summarywidget.h"
SummaryWidget::SummaryWidget( KOrganizerPlugin *plugin, QWidget *parent,
const char *name )
: Kontact::Summary( parent, name ), mPlugin( plugin ), mCalendar( 0 )
{
QVBoxLayout *mainLayout = new QVBoxLayout( this, 3, 3 );
QPixmap icon = KGlobal::iconLoader()->loadIcon( "kontact_date",
KIcon::Desktop, KIcon::SizeMedium );
QWidget *header = createHeader( this, icon, i18n( "Appointments" ) );
mainLayout->addWidget( header );
mLayout = new QGridLayout( mainLayout, 7, 5, 3 );
mLayout->setRowStretch( 6, 1 );
mCalendar = KOrg::StdCalendar::self();
mCalendar->load();
connect( mCalendar, SIGNAL( calendarChanged() ), SLOT( updateView() ) );
connect( mPlugin->core(), SIGNAL( dayChanged( const QDate& ) ),
SLOT( updateView() ) );
updateView();
}
SummaryWidget::~SummaryWidget()
{
}
void SummaryWidget::updateView()
{
mLabels.setAutoDelete( true );
mLabels.clear();
mLabels.setAutoDelete( false );
KIconLoader loader( "korganizer" );
KConfig config( "kcmkorgsummaryrc" );
config.setGroup( "Calendar" );
int days = config.readNumEntry( "DaysToShow", 1 );
QLabel *label = 0;
int counter = 0;
QPixmap pm = loader.loadIcon( "appointment", KIcon::Small );
QDate dt;
for ( dt=QDate::currentDate();
dt<=QDate::currentDate().addDays( days - 1 );
dt=dt.addDays(1) ) {
KCal::Event::List events = mCalendar->events( dt,
KCal::EventSortStartDate,
KCal::SortDirectionAscending );
KCal::Event *ev;
KCal::Event::List::ConstIterator it;
for ( it=events.begin(); it!=events.end(); ++it ) {
ev = *it;
// Count number of days remaining in multiday event
int span=1; int dayof=1;
if ( ev->isMultiDay() ) {
QDate d = ev->dtStart().date();
if ( d < QDate::currentDate() ) {
d = QDate::currentDate();
}
while ( d < ev->dtEnd().date() ) {
if ( d < dt ) {
dayof++;
}
span++;
d=d.addDays( 1 );
}
}
// If this date is part of a floating, multiday event, then we
// only make a print for the first day of the event.
if ( ev->isMultiDay() && ev->doesFloat() && dayof != 1 )break;
// Fill Appointment Pixmap Field
label = new QLabel( this );
label->setPixmap( pm );
label->setMaximumWidth( label->minimumSizeHint().width() );
label->setAlignment( AlignVCenter );
mLayout->addWidget( label, counter, 0 );
mLabels.append( label );
// Fill Event Date Field
bool makeBold = false;
QString datestr;
// Modify event date for printing
QDate sD = QDate::QDate( dt.year(), dt.month(), dt.day() );
if ( ( sD.month() == QDate::currentDate().month() ) &&
( sD.day() == QDate::currentDate().day() ) ) {
datestr = i18n( "Today" );
makeBold = true;
} else if ( ( sD.month() == QDate::currentDate().addDays( 1 ).month() ) &&
( sD.day() == QDate::currentDate().addDays( 1 ).day() ) ) {
datestr = i18n( "Tomorrow" );
} else {
datestr = KGlobal::locale()->formatDate( sD );
}
// Print the date span for multiday, floating events, for the
// first day of the event only.
if ( ev->isMultiDay() && ev->doesFloat() && dayof == 1 && span != 1 ) {
QString endstr = KGlobal::locale()->formatDate( sD.addDays( span-1 ) );
datestr += " -\n " + endstr;
}
label = new QLabel( datestr, this );
label->setAlignment( AlignLeft | AlignVCenter );
if ( makeBold ) {
QFont font = label->font();
font.setBold( true );
label->setFont( font );
}
mLayout->addWidget( label, counter, 1 );
mLabels.append( label );
// Fill Event Summary Field
QString newtext = ev->summary();
if ( ev->isMultiDay() && !ev->doesFloat() ) {
newtext.append( QString(" (%1/%2)").arg( dayof ).arg( span ) );
}
KURLLabel *urlLabel = new KURLLabel( ev->uid(), newtext, this );
urlLabel->setAlignment( urlLabel->alignment() | Qt::WordBreak );
mLayout->addWidget( urlLabel, counter, 2 );
mLabels.append( urlLabel );
if ( !ev->description().isEmpty() ) {
QToolTip::add( urlLabel, ev->description() );
}
// Fill Event Time Range Field (only for non-floating Events)
if ( !ev->doesFloat() ) {
QTime sST = ev->dtStart().time();
QTime sET = ev->dtEnd().time();
if ( ev->isMultiDay() ) {
if ( ev->dtStart().date() < dt ) {
sST = QTime::QTime( 0, 0 );
}
if ( ev->dtEnd().date() > dt ) {
sET = QTime::QTime( 23, 59 );
}
}
datestr = i18n( "Time from - to", "%1 - %2" )
.arg( KGlobal::locale()->formatTime( sST ) )
.arg( KGlobal::locale()->formatTime( sET ) );
label = new QLabel( datestr, this );
label->setAlignment( AlignLeft | AlignVCenter );
mLayout->addWidget( label, counter, 3 );
mLabels.append( label );
}
connect( urlLabel, SIGNAL( leftClickedURL( const QString& ) ),
this, SLOT( selectEvent( const QString& ) ) );
counter++;
}
}
if ( !counter ) {
QLabel *noEvents = new QLabel( i18n( "No appointments pending" ), this );
noEvents->setAlignment( AlignRight | AlignVCenter );
mLayout->addWidget( noEvents, 0, 2 );
mLabels.append( noEvents );
}
for ( label = mLabels.first(); label; label = mLabels.next() )
label->show();
}
void SummaryWidget::selectEvent( const QString &uid )
{
mPlugin->core()->selectPlugin( "kontact_korganizerplugin" ); //ensure loaded
KOrganizerIface_stub iface( "korganizer", "KOrganizerIface" );
iface.editIncidence( uid );
}
QStringList SummaryWidget::configModules() const
{
return QStringList( "kcmkorgsummary.desktop" );
}
#include "summarywidget.moc"
<commit_msg>>1 is better than !=1 in this case.<commit_after>/*
This file is part of Kontact.
Copyright (c) 2003 Tobias Koenig <tokoe@kde.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include <qlabel.h>
#include <qlayout.h>
#include <kdialog.h>
#include <kglobal.h>
#include <kiconloader.h>
#include <klocale.h>
#include <kparts/part.h>
#include <kstandarddirs.h>
#include <kurllabel.h>
#include <qtooltip.h>
#include <libkcal/event.h>
#include <libkcal/resourcecalendar.h>
#include <libkcal/resourcelocal.h>
#include <libkdepim/kpimprefs.h>
#include "korganizeriface_stub.h"
#include "core.h"
#include "plugin.h"
#include "korganizerplugin.h"
#include "korganizer/stdcalendar.h"
#include "summarywidget.h"
SummaryWidget::SummaryWidget( KOrganizerPlugin *plugin, QWidget *parent,
const char *name )
: Kontact::Summary( parent, name ), mPlugin( plugin ), mCalendar( 0 )
{
QVBoxLayout *mainLayout = new QVBoxLayout( this, 3, 3 );
QPixmap icon = KGlobal::iconLoader()->loadIcon( "kontact_date",
KIcon::Desktop, KIcon::SizeMedium );
QWidget *header = createHeader( this, icon, i18n( "Appointments" ) );
mainLayout->addWidget( header );
mLayout = new QGridLayout( mainLayout, 7, 5, 3 );
mLayout->setRowStretch( 6, 1 );
mCalendar = KOrg::StdCalendar::self();
mCalendar->load();
connect( mCalendar, SIGNAL( calendarChanged() ), SLOT( updateView() ) );
connect( mPlugin->core(), SIGNAL( dayChanged( const QDate& ) ),
SLOT( updateView() ) );
updateView();
}
SummaryWidget::~SummaryWidget()
{
}
void SummaryWidget::updateView()
{
mLabels.setAutoDelete( true );
mLabels.clear();
mLabels.setAutoDelete( false );
KIconLoader loader( "korganizer" );
KConfig config( "kcmkorgsummaryrc" );
config.setGroup( "Calendar" );
int days = config.readNumEntry( "DaysToShow", 1 );
QLabel *label = 0;
int counter = 0;
QPixmap pm = loader.loadIcon( "appointment", KIcon::Small );
QDate dt;
for ( dt=QDate::currentDate();
dt<=QDate::currentDate().addDays( days - 1 );
dt=dt.addDays(1) ) {
KCal::Event::List events = mCalendar->events( dt,
KCal::EventSortStartDate,
KCal::SortDirectionAscending );
KCal::Event *ev;
KCal::Event::List::ConstIterator it;
for ( it=events.begin(); it!=events.end(); ++it ) {
ev = *it;
// Count number of days remaining in multiday event
int span=1; int dayof=1;
if ( ev->isMultiDay() ) {
QDate d = ev->dtStart().date();
if ( d < QDate::currentDate() ) {
d = QDate::currentDate();
}
while ( d < ev->dtEnd().date() ) {
if ( d < dt ) {
dayof++;
}
span++;
d=d.addDays( 1 );
}
}
// If this date is part of a floating, multiday event, then we
// only make a print for the first day of the event.
if ( ev->isMultiDay() && ev->doesFloat() && dayof != 1 )break;
// Fill Appointment Pixmap Field
label = new QLabel( this );
label->setPixmap( pm );
label->setMaximumWidth( label->minimumSizeHint().width() );
label->setAlignment( AlignVCenter );
mLayout->addWidget( label, counter, 0 );
mLabels.append( label );
// Fill Event Date Field
bool makeBold = false;
QString datestr;
// Modify event date for printing
QDate sD = QDate::QDate( dt.year(), dt.month(), dt.day() );
if ( ( sD.month() == QDate::currentDate().month() ) &&
( sD.day() == QDate::currentDate().day() ) ) {
datestr = i18n( "Today" );
makeBold = true;
} else if ( ( sD.month() == QDate::currentDate().addDays( 1 ).month() ) &&
( sD.day() == QDate::currentDate().addDays( 1 ).day() ) ) {
datestr = i18n( "Tomorrow" );
} else {
datestr = KGlobal::locale()->formatDate( sD );
}
// Print the date span for multiday, floating events, for the
// first day of the event only.
if ( ev->isMultiDay() && ev->doesFloat() && dayof == 1 && span > 1 ) {
QString endstr = KGlobal::locale()->formatDate( sD.addDays( span-1 ) );
datestr += " -\n " + endstr;
}
label = new QLabel( datestr, this );
label->setAlignment( AlignLeft | AlignVCenter );
if ( makeBold ) {
QFont font = label->font();
font.setBold( true );
label->setFont( font );
}
mLayout->addWidget( label, counter, 1 );
mLabels.append( label );
// Fill Event Summary Field
QString newtext = ev->summary();
if ( ev->isMultiDay() && !ev->doesFloat() ) {
newtext.append( QString(" (%1/%2)").arg( dayof ).arg( span ) );
}
KURLLabel *urlLabel = new KURLLabel( ev->uid(), newtext, this );
urlLabel->setAlignment( urlLabel->alignment() | Qt::WordBreak );
mLayout->addWidget( urlLabel, counter, 2 );
mLabels.append( urlLabel );
if ( !ev->description().isEmpty() ) {
QToolTip::add( urlLabel, ev->description() );
}
// Fill Event Time Range Field (only for non-floating Events)
if ( !ev->doesFloat() ) {
QTime sST = ev->dtStart().time();
QTime sET = ev->dtEnd().time();
if ( ev->isMultiDay() ) {
if ( ev->dtStart().date() < dt ) {
sST = QTime::QTime( 0, 0 );
}
if ( ev->dtEnd().date() > dt ) {
sET = QTime::QTime( 23, 59 );
}
}
datestr = i18n( "Time from - to", "%1 - %2" )
.arg( KGlobal::locale()->formatTime( sST ) )
.arg( KGlobal::locale()->formatTime( sET ) );
label = new QLabel( datestr, this );
label->setAlignment( AlignLeft | AlignVCenter );
mLayout->addWidget( label, counter, 3 );
mLabels.append( label );
}
connect( urlLabel, SIGNAL( leftClickedURL( const QString& ) ),
this, SLOT( selectEvent( const QString& ) ) );
counter++;
}
}
if ( !counter ) {
QLabel *noEvents = new QLabel( i18n( "No appointments pending" ), this );
noEvents->setAlignment( AlignRight | AlignVCenter );
mLayout->addWidget( noEvents, 0, 2 );
mLabels.append( noEvents );
}
for ( label = mLabels.first(); label; label = mLabels.next() )
label->show();
}
void SummaryWidget::selectEvent( const QString &uid )
{
mPlugin->core()->selectPlugin( "kontact_korganizerplugin" ); //ensure loaded
KOrganizerIface_stub iface( "korganizer", "KOrganizerIface" );
iface.editIncidence( uid );
}
QStringList SummaryWidget::configModules() const
{
return QStringList( "kcmkorgsummary.desktop" );
}
#include "summarywidget.moc"
<|endoftext|> |
<commit_before>// Copyright 2022 The Crashpad Authors
//
// 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.
#import "test/ios/host/handler_forbidden_allocators.h"
#include <CoreFoundation/CoreFoundation.h>
#include <malloc/malloc.h>
#include <pthread.h>
#include <limits>
#include "base/mac/mach_logging.h"
#include "client/crashpad_client.h"
#include "util/ios/raw_logging.h"
namespace crashpad {
namespace test {
namespace {
uint64_t g_main_thread = 0;
uint64_t g_mach_exception_thread = 0;
malloc_zone_t g_old_zone;
bool is_handler_thread() {
uint64_t thread_self;
pthread_threadid_np(pthread_self(), &thread_self);
return (thread_self == g_main_thread ||
thread_self == g_mach_exception_thread);
}
void* handler_forbidden_malloc(struct _malloc_zone_t* zone, size_t size) {
if (is_handler_thread()) {
CRASHPAD_RAW_LOG("handler_forbidden_malloc allocator used in handler.");
exit(EXIT_FAILURE);
}
return g_old_zone.malloc(zone, size);
}
void* handler_forbidden_calloc(struct _malloc_zone_t* zone,
size_t num_items,
size_t size) {
if (is_handler_thread()) {
CRASHPAD_RAW_LOG("handler_forbidden_calloc allocator used in handler.");
exit(EXIT_FAILURE);
}
return g_old_zone.calloc(zone, num_items, size);
}
void* handler_forbidden_valloc(struct _malloc_zone_t* zone, size_t size) {
if (is_handler_thread()) {
CRASHPAD_RAW_LOG("handler_forbidden_valloc allocator used in handler.");
exit(EXIT_FAILURE);
}
return g_old_zone.valloc(zone, size);
}
void handler_forbidden_free(struct _malloc_zone_t* zone, void* ptr) {
if (is_handler_thread()) {
CRASHPAD_RAW_LOG("handler_forbidden_free allocator used in handler.");
exit(EXIT_FAILURE);
}
g_old_zone.free(zone, ptr);
}
void* handler_forbidden_realloc(struct _malloc_zone_t* zone,
void* ptr,
size_t size) {
if (is_handler_thread()) {
CRASHPAD_RAW_LOG("handler_forbidden_realloc allocator used in handler.");
exit(EXIT_FAILURE);
}
return g_old_zone.realloc(zone, ptr, size);
}
void handler_forbidden_destroy(struct _malloc_zone_t* zone) {
if (is_handler_thread()) {
CRASHPAD_RAW_LOG("handler_forbidden_destroy allocator used in handler.");
exit(EXIT_FAILURE);
}
g_old_zone.destroy(zone);
}
void* handler_forbidden_memalign(struct _malloc_zone_t* zone,
size_t alignment,
size_t size) {
if (is_handler_thread()) {
CRASHPAD_RAW_LOG("handler_forbidden_memalign allocator used in handler.");
exit(EXIT_FAILURE);
}
return g_old_zone.memalign(zone, alignment, size);
}
unsigned handler_forbidden_batch_malloc(struct _malloc_zone_t* zone,
size_t size,
void** results,
unsigned num_requested) {
if (is_handler_thread()) {
CRASHPAD_RAW_LOG(
"handler_forbidden_batch_malloc allocator used in handler.");
exit(EXIT_FAILURE);
}
return g_old_zone.batch_malloc(zone, size, results, num_requested);
}
void handler_forbidden_batch_free(struct _malloc_zone_t* zone,
void** to_be_freed,
unsigned num_to_be_freed) {
if (is_handler_thread()) {
CRASHPAD_RAW_LOG("handler_forbidden_batch_free allocator used in handler.");
exit(EXIT_FAILURE);
}
g_old_zone.batch_free(zone, to_be_freed, num_to_be_freed);
}
void handler_forbidden_free_definite_size(struct _malloc_zone_t* zone,
void* ptr,
size_t size) {
if (is_handler_thread()) {
CRASHPAD_RAW_LOG(
"handler_forbidden_free_definite_size allocator used in handler.");
exit(EXIT_FAILURE);
}
g_old_zone.free_definite_size(zone, ptr, size);
}
size_t handler_forbidden_pressure_relief(struct _malloc_zone_t* zone,
size_t goal) {
if (is_handler_thread()) {
CRASHPAD_RAW_LOG(
"handler_forbidden_pressure_relief allocator used in handler.");
exit(EXIT_FAILURE);
}
return g_old_zone.pressure_relief(zone, goal);
}
boolean_t handler_forbidden_claimed_address(struct _malloc_zone_t* zone,
void* ptr) {
if (is_handler_thread()) {
CRASHPAD_RAW_LOG(
"handler_forbidden_claimed_address allocator used in handler.");
exit(EXIT_FAILURE);
}
return g_old_zone.claimed_address(zone, ptr);
}
size_t handler_forbidden_size(struct _malloc_zone_t* zone, const void* ptr) {
if (is_handler_thread()) {
CRASHPAD_RAW_LOG("handler_forbidden_size allocator used in handler.");
exit(EXIT_FAILURE);
}
return g_old_zone.size(zone, ptr);
}
bool DeprotectMallocZone(malloc_zone_t* default_zone,
vm_address_t* reprotection_start,
vm_size_t* reprotection_length,
vm_prot_t* reprotection_value) {
mach_port_t unused;
*reprotection_start = reinterpret_cast<vm_address_t>(default_zone);
struct vm_region_basic_info_64 info;
mach_msg_type_number_t count = VM_REGION_BASIC_INFO_COUNT_64;
kern_return_t result = vm_region_64(mach_task_self(),
reprotection_start,
reprotection_length,
VM_REGION_BASIC_INFO_64,
reinterpret_cast<vm_region_info_t>(&info),
&count,
&unused);
if (result != KERN_SUCCESS) {
MACH_LOG(ERROR, result) << "vm_region_64";
return false;
}
// The kernel always returns a null object for VM_REGION_BASIC_INFO_64, but
// balance it with a deallocate in case this ever changes. See
// the VM_REGION_BASIC_INFO_64 case in vm_map_region() in 10.15's
// https://opensource.apple.com/source/xnu/xnu-6153.11.26/osfmk/vm/vm_map.c .
mach_port_deallocate(mach_task_self(), unused);
if (!(info.max_protection & VM_PROT_WRITE)) {
LOG(ERROR) << "Invalid max_protection " << info.max_protection;
return false;
}
// Does the region fully enclose the zone pointers? Possibly unwarranted
// simplification used: using the size of a full version 10 malloc zone rather
// than the actual smaller size if the passed-in zone is not version 10.
DCHECK_LE(*reprotection_start, reinterpret_cast<vm_address_t>(default_zone));
vm_size_t zone_offset = reinterpret_cast<vm_address_t>(default_zone) -
reinterpret_cast<vm_address_t>(*reprotection_start);
DCHECK_LE(zone_offset + sizeof(malloc_zone_t), *reprotection_length);
if (info.protection & VM_PROT_WRITE) {
// No change needed; the zone is already writable.
*reprotection_start = 0;
*reprotection_length = 0;
*reprotection_value = VM_PROT_NONE;
} else {
*reprotection_value = info.protection;
result = vm_protect(mach_task_self(),
*reprotection_start,
*reprotection_length,
false,
info.protection | VM_PROT_WRITE);
if (result != KERN_SUCCESS) {
MACH_LOG(ERROR, result) << "vm_protect";
return false;
}
}
return true;
}
void ReplaceZoneFunctions(malloc_zone_t* zone, const malloc_zone_t* functions) {
// Remove protection.
vm_address_t reprotection_start = 0;
vm_size_t reprotection_length = 0;
vm_prot_t reprotection_value = VM_PROT_NONE;
bool success = DeprotectMallocZone(
zone, &reprotection_start, &reprotection_length, &reprotection_value);
if (!success) {
return;
}
zone->size = functions->size;
zone->malloc = functions->malloc;
zone->calloc = functions->calloc;
zone->valloc = functions->valloc;
zone->free = functions->free;
zone->realloc = functions->realloc;
zone->destroy = functions->destroy;
zone->batch_malloc = functions->batch_malloc;
zone->batch_free = functions->batch_free;
zone->introspect = functions->introspect;
zone->memalign = functions->memalign;
zone->free_definite_size = functions->free_definite_size;
zone->pressure_relief = functions->pressure_relief;
zone->claimed_address = functions->claimed_address;
// Restore protection if it was active.
if (reprotection_start) {
kern_return_t result = vm_protect(mach_task_self(),
reprotection_start,
reprotection_length,
false,
reprotection_value);
if (result != KERN_SUCCESS) {
MACH_LOG(ERROR, result) << "vm_protect";
return;
}
}
}
} // namespace
void ReplaceAllocatorsWithHandlerForbidden() {
pthread_threadid_np(pthread_self(), &g_main_thread);
CrashpadClient crashpad_client;
g_mach_exception_thread = crashpad_client.GetThreadIdForTesting();
malloc_zone_t* default_zone = malloc_default_zone();
memcpy(&g_old_zone, default_zone, sizeof(g_old_zone));
malloc_zone_t new_functions = {};
new_functions.size = handler_forbidden_size;
new_functions.malloc = handler_forbidden_malloc;
new_functions.calloc = handler_forbidden_calloc;
new_functions.valloc = handler_forbidden_valloc;
new_functions.free = handler_forbidden_free;
new_functions.realloc = handler_forbidden_realloc;
new_functions.destroy = handler_forbidden_destroy;
new_functions.batch_malloc = handler_forbidden_batch_malloc;
new_functions.batch_free = handler_forbidden_batch_free;
new_functions.memalign = handler_forbidden_memalign;
new_functions.free_definite_size = handler_forbidden_free_definite_size;
new_functions.pressure_relief = handler_forbidden_pressure_relief;
new_functions.claimed_address = handler_forbidden_claimed_address;
ReplaceZoneFunctions(default_zone, &new_functions);
malloc_zone_t* purgeable_zone = malloc_default_purgeable_zone();
ReplaceZoneFunctions(purgeable_zone, &new_functions);
}
} // namespace test
} // namespace crashpad
<commit_msg>ios: Correct iOS forbidden allocators on iOS 16.1<commit_after>// Copyright 2022 The Crashpad Authors
//
// 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.
#import "test/ios/host/handler_forbidden_allocators.h"
#include <CoreFoundation/CoreFoundation.h>
#include <malloc/malloc.h>
#include <pthread.h>
#include <limits>
#include "base/mac/mach_logging.h"
#include "client/crashpad_client.h"
#include "util/ios/raw_logging.h"
namespace crashpad {
namespace test {
namespace {
uint64_t g_main_thread = 0;
uint64_t g_mach_exception_thread = 0;
malloc_zone_t g_old_zone;
bool is_handler_thread() {
uint64_t thread_self;
pthread_threadid_np(pthread_self(), &thread_self);
return (thread_self == g_main_thread ||
thread_self == g_mach_exception_thread);
}
void* handler_forbidden_malloc(struct _malloc_zone_t* zone, size_t size) {
if (is_handler_thread()) {
CRASHPAD_RAW_LOG("handler_forbidden_malloc allocator used in handler.");
exit(EXIT_FAILURE);
}
return g_old_zone.malloc(zone, size);
}
void* handler_forbidden_calloc(struct _malloc_zone_t* zone,
size_t num_items,
size_t size) {
if (is_handler_thread()) {
CRASHPAD_RAW_LOG("handler_forbidden_calloc allocator used in handler.");
exit(EXIT_FAILURE);
}
return g_old_zone.calloc(zone, num_items, size);
}
void* handler_forbidden_valloc(struct _malloc_zone_t* zone, size_t size) {
if (is_handler_thread()) {
CRASHPAD_RAW_LOG("handler_forbidden_valloc allocator used in handler.");
exit(EXIT_FAILURE);
}
return g_old_zone.valloc(zone, size);
}
void handler_forbidden_free(struct _malloc_zone_t* zone, void* ptr) {
if (is_handler_thread()) {
CRASHPAD_RAW_LOG("handler_forbidden_free allocator used in handler.");
exit(EXIT_FAILURE);
}
g_old_zone.free(zone, ptr);
}
void* handler_forbidden_realloc(struct _malloc_zone_t* zone,
void* ptr,
size_t size) {
if (is_handler_thread()) {
CRASHPAD_RAW_LOG("handler_forbidden_realloc allocator used in handler.");
exit(EXIT_FAILURE);
}
return g_old_zone.realloc(zone, ptr, size);
}
void handler_forbidden_destroy(struct _malloc_zone_t* zone) {
if (is_handler_thread()) {
CRASHPAD_RAW_LOG("handler_forbidden_destroy allocator used in handler.");
exit(EXIT_FAILURE);
}
g_old_zone.destroy(zone);
}
void* handler_forbidden_memalign(struct _malloc_zone_t* zone,
size_t alignment,
size_t size) {
if (is_handler_thread()) {
CRASHPAD_RAW_LOG("handler_forbidden_memalign allocator used in handler.");
exit(EXIT_FAILURE);
}
return g_old_zone.memalign(zone, alignment, size);
}
unsigned handler_forbidden_batch_malloc(struct _malloc_zone_t* zone,
size_t size,
void** results,
unsigned num_requested) {
if (is_handler_thread()) {
CRASHPAD_RAW_LOG(
"handler_forbidden_batch_malloc allocator used in handler.");
exit(EXIT_FAILURE);
}
return g_old_zone.batch_malloc(zone, size, results, num_requested);
}
void handler_forbidden_batch_free(struct _malloc_zone_t* zone,
void** to_be_freed,
unsigned num_to_be_freed) {
if (is_handler_thread()) {
CRASHPAD_RAW_LOG("handler_forbidden_batch_free allocator used in handler.");
exit(EXIT_FAILURE);
}
g_old_zone.batch_free(zone, to_be_freed, num_to_be_freed);
}
void handler_forbidden_free_definite_size(struct _malloc_zone_t* zone,
void* ptr,
size_t size) {
if (is_handler_thread()) {
CRASHPAD_RAW_LOG(
"handler_forbidden_free_definite_size allocator used in handler.");
exit(EXIT_FAILURE);
}
g_old_zone.free_definite_size(zone, ptr, size);
}
size_t handler_forbidden_pressure_relief(struct _malloc_zone_t* zone,
size_t goal) {
if (is_handler_thread()) {
CRASHPAD_RAW_LOG(
"handler_forbidden_pressure_relief allocator used in handler.");
exit(EXIT_FAILURE);
}
return g_old_zone.pressure_relief(zone, goal);
}
boolean_t handler_forbidden_claimed_address(struct _malloc_zone_t* zone,
void* ptr) {
if (is_handler_thread()) {
CRASHPAD_RAW_LOG(
"handler_forbidden_claimed_address allocator used in handler.");
exit(EXIT_FAILURE);
}
return g_old_zone.claimed_address(zone, ptr);
}
#if defined(__IPHONE_16_1) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_16_1
void handler_forbidden_try_free_default(struct _malloc_zone_t* zone,
void* ptr) {
if (is_handler_thread()) {
CRASHPAD_RAW_LOG(
"handler_forbidden_try_free_default allocator used in handler.");
exit(EXIT_FAILURE);
}
g_old_zone.try_free_default(zone, ptr);
}
#endif
size_t handler_forbidden_size(struct _malloc_zone_t* zone, const void* ptr) {
if (is_handler_thread()) {
CRASHPAD_RAW_LOG("handler_forbidden_size allocator used in handler.");
exit(EXIT_FAILURE);
}
return g_old_zone.size(zone, ptr);
}
bool DeprotectMallocZone(malloc_zone_t* default_zone,
vm_address_t* reprotection_start,
vm_size_t* reprotection_length,
vm_prot_t* reprotection_value) {
mach_port_t unused;
*reprotection_start = reinterpret_cast<vm_address_t>(default_zone);
struct vm_region_basic_info_64 info;
mach_msg_type_number_t count = VM_REGION_BASIC_INFO_COUNT_64;
kern_return_t result = vm_region_64(mach_task_self(),
reprotection_start,
reprotection_length,
VM_REGION_BASIC_INFO_64,
reinterpret_cast<vm_region_info_t>(&info),
&count,
&unused);
if (result != KERN_SUCCESS) {
MACH_LOG(ERROR, result) << "vm_region_64";
return false;
}
// The kernel always returns a null object for VM_REGION_BASIC_INFO_64, but
// balance it with a deallocate in case this ever changes. See
// the VM_REGION_BASIC_INFO_64 case in vm_map_region() in 10.15's
// https://opensource.apple.com/source/xnu/xnu-6153.11.26/osfmk/vm/vm_map.c .
mach_port_deallocate(mach_task_self(), unused);
if (!(info.max_protection & VM_PROT_WRITE)) {
LOG(ERROR) << "Invalid max_protection " << info.max_protection;
return false;
}
// Does the region fully enclose the zone pointers? Possibly unwarranted
// simplification used: using the size of a full version 10 malloc zone rather
// than the actual smaller size if the passed-in zone is not version 10.
DCHECK_LE(*reprotection_start, reinterpret_cast<vm_address_t>(default_zone));
vm_size_t zone_offset = reinterpret_cast<vm_address_t>(default_zone) -
reinterpret_cast<vm_address_t>(*reprotection_start);
DCHECK_LE(zone_offset + sizeof(malloc_zone_t), *reprotection_length);
if (info.protection & VM_PROT_WRITE) {
// No change needed; the zone is already writable.
*reprotection_start = 0;
*reprotection_length = 0;
*reprotection_value = VM_PROT_NONE;
} else {
*reprotection_value = info.protection;
result = vm_protect(mach_task_self(),
*reprotection_start,
*reprotection_length,
false,
info.protection | VM_PROT_WRITE);
if (result != KERN_SUCCESS) {
MACH_LOG(ERROR, result) << "vm_protect";
return false;
}
}
return true;
}
void ReplaceZoneFunctions(malloc_zone_t* zone, const malloc_zone_t* functions) {
// Remove protection.
vm_address_t reprotection_start = 0;
vm_size_t reprotection_length = 0;
vm_prot_t reprotection_value = VM_PROT_NONE;
bool success = DeprotectMallocZone(
zone, &reprotection_start, &reprotection_length, &reprotection_value);
if (!success) {
return;
}
zone->size = functions->size;
zone->malloc = functions->malloc;
zone->calloc = functions->calloc;
zone->valloc = functions->valloc;
zone->free = functions->free;
zone->realloc = functions->realloc;
zone->destroy = functions->destroy;
zone->batch_malloc = functions->batch_malloc;
zone->batch_free = functions->batch_free;
zone->introspect = functions->introspect;
zone->memalign = functions->memalign;
zone->free_definite_size = functions->free_definite_size;
zone->pressure_relief = functions->pressure_relief;
zone->claimed_address = functions->claimed_address;
#if defined(__IPHONE_16_1) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_16_1
if (zone->version >= 13 && functions->try_free_default) {
zone->try_free_default = functions->try_free_default;
}
#endif
// Restore protection if it was active.
if (reprotection_start) {
kern_return_t result = vm_protect(mach_task_self(),
reprotection_start,
reprotection_length,
false,
reprotection_value);
if (result != KERN_SUCCESS) {
MACH_LOG(ERROR, result) << "vm_protect";
return;
}
}
}
} // namespace
void ReplaceAllocatorsWithHandlerForbidden() {
pthread_threadid_np(pthread_self(), &g_main_thread);
CrashpadClient crashpad_client;
g_mach_exception_thread = crashpad_client.GetThreadIdForTesting();
malloc_zone_t* default_zone = malloc_default_zone();
memcpy(&g_old_zone, default_zone, sizeof(g_old_zone));
malloc_zone_t new_functions = {};
new_functions.size = handler_forbidden_size;
new_functions.malloc = handler_forbidden_malloc;
new_functions.calloc = handler_forbidden_calloc;
new_functions.valloc = handler_forbidden_valloc;
new_functions.free = handler_forbidden_free;
new_functions.realloc = handler_forbidden_realloc;
new_functions.destroy = handler_forbidden_destroy;
new_functions.batch_malloc = handler_forbidden_batch_malloc;
new_functions.batch_free = handler_forbidden_batch_free;
new_functions.memalign = handler_forbidden_memalign;
new_functions.free_definite_size = handler_forbidden_free_definite_size;
new_functions.pressure_relief = handler_forbidden_pressure_relief;
new_functions.claimed_address = handler_forbidden_claimed_address;
#if defined(__IPHONE_16_1) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_16_1
new_functions.try_free_default = handler_forbidden_try_free_default;
#endif
ReplaceZoneFunctions(default_zone, &new_functions);
vm_address_t* zones;
unsigned int count;
kern_return_t kr =
malloc_get_all_zones(mach_task_self(), nullptr, &zones, &count);
if (kr != KERN_SUCCESS)
return;
for (unsigned int i = 0; i < count; ++i) {
malloc_zone_t* zone = reinterpret_cast<malloc_zone_t*>(zones[i]);
ReplaceZoneFunctions(zone, &new_functions);
}
malloc_zone_t* purgeable_zone = malloc_default_purgeable_zone();
ReplaceZoneFunctions(purgeable_zone, &new_functions);
}
} // namespace test
} // namespace crashpad
<|endoftext|> |
<commit_before>//===-- IPConstantPropagation.cpp - Propagate constants through calls -----===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass implements an _extremely_ simple interprocedural constant
// propagation pass. It could certainly be improved in many different ways,
// like using a worklist. This pass makes arguments dead, but does not remove
// them. The existing dead argument elimination pass should be run after this
// to clean up the mess.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/IPO.h"
#include "llvm/Constants.h"
#include "llvm/Instructions.h"
#include "llvm/Module.h"
#include "llvm/Pass.h"
#include "llvm/Support/CallSite.h"
#include "llvm/ADT/Statistic.h"
using namespace llvm;
namespace {
Statistic<> NumArgumentsProped("ipconstprop",
"Number of args turned into constants");
Statistic<> NumReturnValProped("ipconstprop",
"Number of return values turned into constants");
/// IPCP - The interprocedural constant propagation pass
///
struct IPCP : public ModulePass {
bool runOnModule(Module &M);
private:
bool PropagateConstantsIntoArguments(Function &F);
bool PropagateConstantReturn(Function &F);
};
RegisterOpt<IPCP> X("ipconstprop", "Interprocedural constant propagation");
}
ModulePass *llvm::createIPConstantPropagationPass() { return new IPCP(); }
bool IPCP::runOnModule(Module &M) {
bool Changed = false;
bool LocalChange = true;
// FIXME: instead of using smart algorithms, we just iterate until we stop
// making changes.
while (LocalChange) {
LocalChange = false;
for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
if (!I->isExternal()) {
// Delete any klingons.
I->removeDeadConstantUsers();
if (I->hasInternalLinkage())
LocalChange |= PropagateConstantsIntoArguments(*I);
Changed |= PropagateConstantReturn(*I);
}
Changed |= LocalChange;
}
return Changed;
}
/// PropagateConstantsIntoArguments - Look at all uses of the specified
/// function. If all uses are direct call sites, and all pass a particular
/// constant in for an argument, propagate that constant in as the argument.
///
bool IPCP::PropagateConstantsIntoArguments(Function &F) {
if (F.aempty() || F.use_empty()) return false; // No arguments? Early exit.
std::vector<std::pair<Constant*, bool> > ArgumentConstants;
ArgumentConstants.resize(F.asize());
unsigned NumNonconstant = 0;
for (Value::use_iterator I = F.use_begin(), E = F.use_end(); I != E; ++I)
if (!isa<Instruction>(*I))
return false; // Used by a non-instruction, do not transform
else {
CallSite CS = CallSite::get(cast<Instruction>(*I));
if (CS.getInstruction() == 0 ||
CS.getCalledFunction() != &F)
return false; // Not a direct call site?
// Check out all of the potentially constant arguments
CallSite::arg_iterator AI = CS.arg_begin();
Function::aiterator Arg = F.abegin();
for (unsigned i = 0, e = ArgumentConstants.size(); i != e;
++i, ++AI, ++Arg) {
if (*AI == &F) return false; // Passes the function into itself
if (!ArgumentConstants[i].second) {
if (Constant *C = dyn_cast<Constant>(*AI)) {
if (!ArgumentConstants[i].first)
ArgumentConstants[i].first = C;
else if (ArgumentConstants[i].first != C) {
// Became non-constant
ArgumentConstants[i].second = true;
++NumNonconstant;
if (NumNonconstant == ArgumentConstants.size()) return false;
}
} else if (*AI != &*Arg) { // Ignore recursive calls with same arg
// This is not a constant argument. Mark the argument as
// non-constant.
ArgumentConstants[i].second = true;
++NumNonconstant;
if (NumNonconstant == ArgumentConstants.size()) return false;
}
}
}
}
// If we got to this point, there is a constant argument!
assert(NumNonconstant != ArgumentConstants.size());
Function::aiterator AI = F.abegin();
bool MadeChange = false;
for (unsigned i = 0, e = ArgumentConstants.size(); i != e; ++i, ++AI)
// Do we have a constant argument!?
if (!ArgumentConstants[i].second && !AI->use_empty()) {
Value *V = ArgumentConstants[i].first;
if (V == 0) V = UndefValue::get(AI->getType());
AI->replaceAllUsesWith(V);
++NumArgumentsProped;
MadeChange = true;
}
return MadeChange;
}
// Check to see if this function returns a constant. If so, replace all callers
// that user the return value with the returned valued. If we can replace ALL
// callers,
bool IPCP::PropagateConstantReturn(Function &F) {
if (F.getReturnType() == Type::VoidTy)
return false; // No return value.
// Check to see if this function returns a constant.
Value *RetVal = 0;
for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
if (isa<UndefValue>(RI->getOperand(0))) {
// Ignore.
} else if (Constant *C = dyn_cast<Constant>(RI->getOperand(0))) {
if (RetVal == 0)
RetVal = C;
else if (RetVal != C)
return false; // Does not return the same constant.
} else {
return false; // Does not return a constant.
}
if (RetVal == 0) RetVal = UndefValue::get(F.getReturnType());
// If we got here, the function returns a constant value. Loop over all
// users, replacing any uses of the return value with the returned constant.
bool ReplacedAllUsers = true;
bool MadeChange = false;
for (Value::use_iterator I = F.use_begin(), E = F.use_end(); I != E; ++I)
if (!isa<Instruction>(*I))
ReplacedAllUsers = false;
else {
CallSite CS = CallSite::get(cast<Instruction>(*I));
if (CS.getInstruction() == 0 ||
CS.getCalledFunction() != &F) {
ReplacedAllUsers = false;
} else {
if (!CS.getInstruction()->use_empty()) {
CS.getInstruction()->replaceAllUsesWith(RetVal);
MadeChange = true;
}
}
}
// If we replace all users with the returned constant, and there can be no
// other callers of the function, replace the constant being returned in the
// function with an undef value.
if (ReplacedAllUsers && F.hasInternalLinkage() && !isa<UndefValue>(RetVal)) {
Value *RV = UndefValue::get(RetVal->getType());
for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
RI->setOperand(0, RV);
MadeChange = true;
}
if (MadeChange) ++NumReturnValProped;
return MadeChange;
}
<commit_msg>Only cound if we actually made a change.<commit_after>//===-- IPConstantPropagation.cpp - Propagate constants through calls -----===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass implements an _extremely_ simple interprocedural constant
// propagation pass. It could certainly be improved in many different ways,
// like using a worklist. This pass makes arguments dead, but does not remove
// them. The existing dead argument elimination pass should be run after this
// to clean up the mess.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/IPO.h"
#include "llvm/Constants.h"
#include "llvm/Instructions.h"
#include "llvm/Module.h"
#include "llvm/Pass.h"
#include "llvm/Support/CallSite.h"
#include "llvm/ADT/Statistic.h"
using namespace llvm;
namespace {
Statistic<> NumArgumentsProped("ipconstprop",
"Number of args turned into constants");
Statistic<> NumReturnValProped("ipconstprop",
"Number of return values turned into constants");
/// IPCP - The interprocedural constant propagation pass
///
struct IPCP : public ModulePass {
bool runOnModule(Module &M);
private:
bool PropagateConstantsIntoArguments(Function &F);
bool PropagateConstantReturn(Function &F);
};
RegisterOpt<IPCP> X("ipconstprop", "Interprocedural constant propagation");
}
ModulePass *llvm::createIPConstantPropagationPass() { return new IPCP(); }
bool IPCP::runOnModule(Module &M) {
bool Changed = false;
bool LocalChange = true;
// FIXME: instead of using smart algorithms, we just iterate until we stop
// making changes.
while (LocalChange) {
LocalChange = false;
for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
if (!I->isExternal()) {
// Delete any klingons.
I->removeDeadConstantUsers();
if (I->hasInternalLinkage())
LocalChange |= PropagateConstantsIntoArguments(*I);
Changed |= PropagateConstantReturn(*I);
}
Changed |= LocalChange;
}
return Changed;
}
/// PropagateConstantsIntoArguments - Look at all uses of the specified
/// function. If all uses are direct call sites, and all pass a particular
/// constant in for an argument, propagate that constant in as the argument.
///
bool IPCP::PropagateConstantsIntoArguments(Function &F) {
if (F.aempty() || F.use_empty()) return false; // No arguments? Early exit.
std::vector<std::pair<Constant*, bool> > ArgumentConstants;
ArgumentConstants.resize(F.asize());
unsigned NumNonconstant = 0;
for (Value::use_iterator I = F.use_begin(), E = F.use_end(); I != E; ++I)
if (!isa<Instruction>(*I))
return false; // Used by a non-instruction, do not transform
else {
CallSite CS = CallSite::get(cast<Instruction>(*I));
if (CS.getInstruction() == 0 ||
CS.getCalledFunction() != &F)
return false; // Not a direct call site?
// Check out all of the potentially constant arguments
CallSite::arg_iterator AI = CS.arg_begin();
Function::aiterator Arg = F.abegin();
for (unsigned i = 0, e = ArgumentConstants.size(); i != e;
++i, ++AI, ++Arg) {
if (*AI == &F) return false; // Passes the function into itself
if (!ArgumentConstants[i].second) {
if (Constant *C = dyn_cast<Constant>(*AI)) {
if (!ArgumentConstants[i].first)
ArgumentConstants[i].first = C;
else if (ArgumentConstants[i].first != C) {
// Became non-constant
ArgumentConstants[i].second = true;
++NumNonconstant;
if (NumNonconstant == ArgumentConstants.size()) return false;
}
} else if (*AI != &*Arg) { // Ignore recursive calls with same arg
// This is not a constant argument. Mark the argument as
// non-constant.
ArgumentConstants[i].second = true;
++NumNonconstant;
if (NumNonconstant == ArgumentConstants.size()) return false;
}
}
}
}
// If we got to this point, there is a constant argument!
assert(NumNonconstant != ArgumentConstants.size());
Function::aiterator AI = F.abegin();
bool MadeChange = false;
for (unsigned i = 0, e = ArgumentConstants.size(); i != e; ++i, ++AI)
// Do we have a constant argument!?
if (!ArgumentConstants[i].second && !AI->use_empty()) {
Value *V = ArgumentConstants[i].first;
if (V == 0) V = UndefValue::get(AI->getType());
AI->replaceAllUsesWith(V);
++NumArgumentsProped;
MadeChange = true;
}
return MadeChange;
}
// Check to see if this function returns a constant. If so, replace all callers
// that user the return value with the returned valued. If we can replace ALL
// callers,
bool IPCP::PropagateConstantReturn(Function &F) {
if (F.getReturnType() == Type::VoidTy)
return false; // No return value.
// Check to see if this function returns a constant.
Value *RetVal = 0;
for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
if (isa<UndefValue>(RI->getOperand(0))) {
// Ignore.
} else if (Constant *C = dyn_cast<Constant>(RI->getOperand(0))) {
if (RetVal == 0)
RetVal = C;
else if (RetVal != C)
return false; // Does not return the same constant.
} else {
return false; // Does not return a constant.
}
if (RetVal == 0) RetVal = UndefValue::get(F.getReturnType());
// If we got here, the function returns a constant value. Loop over all
// users, replacing any uses of the return value with the returned constant.
bool ReplacedAllUsers = true;
bool MadeChange = false;
for (Value::use_iterator I = F.use_begin(), E = F.use_end(); I != E; ++I)
if (!isa<Instruction>(*I))
ReplacedAllUsers = false;
else {
CallSite CS = CallSite::get(cast<Instruction>(*I));
if (CS.getInstruction() == 0 ||
CS.getCalledFunction() != &F) {
ReplacedAllUsers = false;
} else {
if (!CS.getInstruction()->use_empty()) {
CS.getInstruction()->replaceAllUsesWith(RetVal);
MadeChange = true;
}
}
}
// If we replace all users with the returned constant, and there can be no
// other callers of the function, replace the constant being returned in the
// function with an undef value.
if (ReplacedAllUsers && F.hasInternalLinkage() && !isa<UndefValue>(RetVal)) {
Value *RV = UndefValue::get(RetVal->getType());
for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
if (RI->getOperand(0) != RV) {
RI->setOperand(0, RV);
MadeChange = true;
}
}
}
if (MadeChange) ++NumReturnValProped;
return MadeChange;
}
<|endoftext|> |
<commit_before>#ifndef KDROPOUTFULLYCONNECTED_HPP
#define KDROPOUTFULLYCONNECTED_HPP
#include <fstream>
#include <random>
#include "Layer.hpp"
class KDropoutFullyConnected : public Layer
{
private:
int K;
std::mt19937 mt;
std::uniform_real_distribution<double> d_rand;
Mat mask;
public:
KDropoutFullyConnected ( int prev_num_map, int prev_num_unit, int num_map, int num_unit,
int K,
const std::function<double(double)>& f,
const std::function<double(double)>& d_f );
void init( std::mt19937& m );
std::vector<std::vector<Mat>> calc_gradient ( const std::vector<Mat>& U, const std::vector<Mat>& delta );
std::vector<Mat> calc_delta ( const std::vector<Mat>& U, const std::vector<Mat>& delta );
void update_W ( const std::vector<std::vector<Mat>>& dW );
std::vector<Mat> apply ( const std::vector<Mat>& U, bool use_func = true );
std::vector<std::vector<Vec>> apply ( const std::vector<std::vector<Vec>>& u, bool use_func = true );
void set_W( const std::string& filename );
void output_W ( const std::string& filename );
};
KDropoutFullyConnected::KDropoutFullyConnected( int prev_num_map, int prev_num_unit,
int num_map, int num_unit,
int K,
const std::function<double(double)>& f,
const std::function<double(double)>& d_f )
{
this->prev_num_map = prev_num_map;
this->prev_num_unit = prev_num_unit;
this->num_map = num_map;
this->num_unit = num_unit;
this->K = K;
mt = std::mt19937(time(NULL));
d_rand = std::uniform_real_distribution<double>(0.0, 1.0);
activate_func = f;
activate_diff_func = d_f;
}
void KDropoutFullyConnected::init ( std::mt19937& m )
{
const double r = sqrt(6.0/(num_unit + prev_num_unit));
std::uniform_real_distribution<double> d_rand(-r, r);
for( int i = 0; i < num_map; ++i ){
W.emplace_back(prev_num_map);
for( int j = 0; j < prev_num_map; ++j ){
W[i][j] = Mat(num_unit, 1+prev_num_unit);
for( int k = 0; k < W[i][j].m; ++k )
for( int l = 0; l < W[i][j].n; ++l )
W[i][j][k][l] = d_rand(m);
}
}
mask = Mat(prev_num_unit, prev_num_map);
for( int i = 0; i < prev_num_unit; ++i )
for( int j = 0; j < prev_num_map; ++j )
mask[i][j] = 1;
}
std::vector<std::vector<KDropoutFullyConnected::Mat>> KDropoutFullyConnected::calc_gradient ( const std::vector<Mat>& U, const std::vector<Mat>& delta )
{
std::vector<std::vector<Mat>> nabla(num_map);
for( int i = 0; i < num_map; ++i ){
nabla[i] = std::vector<Mat>(prev_num_map);
for( int j = 0; j < prev_num_map; ++j )
nabla[i][j] = Mat(W[i][j].m, W[i][j].n);
}
for( int i = 0; i < num_map; ++i )
for( int j = 0; j < prev_num_map; ++j )
for( int k = 0; k < nabla[i][j].m; ++k )
for( int l = 0; l < nabla[i][j].n; ++l )
for( int m = 0; m < delta[i].n; ++m )
nabla[i][j][k][l] += delta[i][k][m]*(
l == 0 ? 1.0 : prev_activate_func(U[j][l-1][m])
);
return nabla;
}
std::vector<KDropoutFullyConnected::Mat> KDropoutFullyConnected::calc_delta ( const std::vector<Mat>& U, const std::vector<Mat>& delta )
{
std::vector<Mat> tmp(prev_num_map), nx_delta(prev_num_map);
for( int i = 0; i < prev_num_map; ++i ){
tmp[i] = Mat(W[0][0].n, delta[0].n);
for( int j = 0; j < num_map; ++j ){
tmp[i] = tmp[i] + Mat::transpose(W[j][i])*delta[j];
}
}
for( int i = 0; i < prev_num_map; ++i )
nx_delta[i] = Mat(tmp[0].m-1, tmp[0].n);
for( int i = 0; i < prev_num_map; ++i )
for( int j = 0; j < tmp[i].m-1; ++j )
for( int k = 0; k < tmp[i].n; ++k )
nx_delta[i][j][k] += mask[j][i]*tmp[i][j+1][k]*prev_activate_diff_func(U[i][j][k]);
return nx_delta;
}
void KDropoutFullyConnected::update_W ( const std::vector<std::vector<Mat>>& dW )
{
for( int i = 0; i < num_map; ++i ){
for( int j = 0; j < prev_num_map; ++j )
W[i][j] = W[i][j] + dW[i][j];
}
}
std::vector<KDropoutFullyConnected::Mat> KDropoutFullyConnected::apply ( const std::vector<Mat>& U, bool use_func )
{
std::vector<Mat> ret(num_map);
std::vector<Mat> V(prev_num_map);
for( int i = 0; i < prev_num_map; ++i ){
std::vector<int> idx(U[i].m);
std::vector<double> val(U[i].m, 0.0);
std::iota(idx.begin(), idx.end(), 0);
for( int j = 0; j < U[i].m; ++j ){
for( int k = 0; k < U[i].n; ++k ){
val[j] += U[i][j][k];
}
val[j] /= U[i].n;
}
std::sort( idx.begin(), idx.end(), [&](int id1, int id2) -> bool {
return val[id1] > val[id2];
});
for( int j = 0; j < K; ++j ) mask[idx[j]][i] = 1.0;
for( int j = K; j < U[i].m; ++j ) mask[idx[j]][i] = 0.0;
}
for( int i = 0; i < prev_num_map; ++i ){
V[i] = Mat(U[i].m+1, U[i].n);
for( int j = 0; j < U[i].n; ++j ) V[i][0][j] = 1.0;
for( int j = 0; j < U[i].m; ++j ){
for( int k = 0; k < U[i].n; ++k ){
V[i][j+1][k] = U[i][j][k]*mask[j][i];
}
}
}
for( int i = 0; i < num_map; ++i ){
ret[i] = Mat(W[i][0].m, V[0].n);
for( int j = 0; j < prev_num_map; ++j ){
ret[i] = ret[i] + W[i][j]*V[j];
}
}
for( int i = 0; i < num_map; ++i )
for( int j = 0; j < ret[i].m; ++j )
for( int k = 0; k < ret[i].n; ++k )
ret[i][j][k] = (use_func ? activate_func(ret[i][j][k]) : ret[i][j][k]);
return ret;
}
std::vector<std::vector<KDropoutFullyConnected::Vec>> KDropoutFullyConnected::apply ( const std::vector<std::vector<Vec>>& u, bool use_func )
{
std::vector<Mat> tmp(prev_num_map);
for( int i = 0; i < prev_num_map; ++i )
tmp[i] = Mat(u[i][0].size(), u.size());
for( int i = 0; i < prev_num_map; ++i )
for( int j = 0; j < u[i][0].size(); ++j )
for( int k = 0; k < u.size(); ++k )
tmp[i][j][k] = u[k][i][j];
auto U = apply(tmp, use_func);
std::vector<std::vector<Vec>> ret(U[0].n);
for( int i = 0; i < U[0].n; ++i ){
ret[i] = std::vector<Vec>(U.size(), Vec(U[0].m));
for( int j = 0; j < U.size(); ++j )
for( int k = 0; k < U[0].m; ++k )
ret[i][j][k] = U[j][k][i];
}
return ret;
}
void KDropoutFullyConnected::set_W ( const std::string& filename )
{
std::ifstream ifs(filename, std::ios::binary);
for( int i = 0; i < num_map; ++i )
for( int j = 0; j < prev_num_map; ++j ){
ifs.read((char*)&W[i][j].m, sizeof(W[i][j].m));
ifs.read((char*)&W[i][j].n, sizeof(W[i][j].n));
for( int k = 0; k < W[i][j].m; ++k )
for( int l = 0; l < W[i][j].n; ++l )
ifs.read((char*)&W[i][j][k][l], sizeof(W[i][j][k][l]));
}
}
void KDropoutFullyConnected::output_W ( const std::string& filename )
{
std::ofstream ofs(filename, std::ios::binary);
for( int i = 0; i < num_map; ++i )
for( int j = 0; j < prev_num_map; ++j ){
ofs.write((char*)&W[i][j].m, sizeof(W[i][j].m));
ofs.write((char*)&W[i][j].n, sizeof(W[i][j].n));
for( int k = 0; k < W[i][j].m; ++k )
for( int l = 0; l < W[i][j].n; ++l )
ofs.write((char*)&W[i][j][k][l], sizeof(W[i][j][k][l]));
}
}
#endif
<commit_msg>Fixed bug in calculation gradient.<commit_after>#ifndef KDROPOUTFULLYCONNECTED_HPP
#define KDROPOUTFULLYCONNECTED_HPP
#include <fstream>
#include <random>
#include "Layer.hpp"
class KDropoutFullyConnected : public Layer
{
private:
int K;
std::mt19937 mt;
std::uniform_real_distribution<double> d_rand;
Mat mask;
public:
KDropoutFullyConnected ( int prev_num_map, int prev_num_unit, int num_map, int num_unit,
int K,
const std::function<double(double)>& f,
const std::function<double(double)>& d_f );
void init( std::mt19937& m );
std::vector<std::vector<Mat>> calc_gradient ( const std::vector<Mat>& U, const std::vector<Mat>& delta );
std::vector<Mat> calc_delta ( const std::vector<Mat>& U, const std::vector<Mat>& delta );
void update_W ( const std::vector<std::vector<Mat>>& dW );
std::vector<Mat> apply ( const std::vector<Mat>& U, bool use_func = true );
std::vector<std::vector<Vec>> apply ( const std::vector<std::vector<Vec>>& u, bool use_func = true );
void set_W( const std::string& filename );
void output_W ( const std::string& filename );
};
KDropoutFullyConnected::KDropoutFullyConnected( int prev_num_map, int prev_num_unit,
int num_map, int num_unit,
int K,
const std::function<double(double)>& f,
const std::function<double(double)>& d_f )
{
this->prev_num_map = prev_num_map;
this->prev_num_unit = prev_num_unit;
this->num_map = num_map;
this->num_unit = num_unit;
this->K = K;
mt = std::mt19937(time(NULL));
d_rand = std::uniform_real_distribution<double>(0.0, 1.0);
activate_func = f;
activate_diff_func = d_f;
}
void KDropoutFullyConnected::init ( std::mt19937& m )
{
const double r = sqrt(6.0/(num_unit + prev_num_unit));
std::uniform_real_distribution<double> d_rand(-r, r);
for( int i = 0; i < num_map; ++i ){
W.emplace_back(prev_num_map);
for( int j = 0; j < prev_num_map; ++j ){
W[i][j] = Mat(num_unit, 1+prev_num_unit);
for( int k = 0; k < W[i][j].m; ++k )
for( int l = 0; l < W[i][j].n; ++l )
W[i][j][k][l] = d_rand(m);
}
}
mask = Mat(prev_num_unit, prev_num_map);
for( int i = 0; i < prev_num_unit; ++i )
for( int j = 0; j < prev_num_map; ++j )
mask[i][j] = 1;
}
std::vector<std::vector<KDropoutFullyConnected::Mat>> KDropoutFullyConnected::calc_gradient ( const std::vector<Mat>& U, const std::vector<Mat>& delta )
{
std::vector<std::vector<Mat>> nabla(num_map);
for( int i = 0; i < num_map; ++i ){
nabla[i] = std::vector<Mat>(prev_num_map);
for( int j = 0; j < prev_num_map; ++j )
nabla[i][j] = Mat(W[i][j].m, W[i][j].n);
}
for( int i = 0; i < num_map; ++i )
for( int j = 0; j < prev_num_map; ++j )
for( int k = 0; k < nabla[i][j].m; ++k )
for( int l = 0; l < nabla[i][j].n; ++l )
for( int m = 0; m < delta[i].n; ++m )
nabla[i][j][k][l] += delta[i][k][m]*(
l == 0 ? 1.0 : mask[l-1][j]*prev_activate_func(U[j][l-1][m])
);
return nabla;
}
std::vector<KDropoutFullyConnected::Mat> KDropoutFullyConnected::calc_delta ( const std::vector<Mat>& U, const std::vector<Mat>& delta )
{
std::vector<Mat> tmp(prev_num_map), nx_delta(prev_num_map);
for( int i = 0; i < prev_num_map; ++i ){
tmp[i] = Mat(W[0][0].n, delta[0].n);
for( int j = 0; j < num_map; ++j ){
tmp[i] = tmp[i] + Mat::transpose(W[j][i])*delta[j];
}
}
for( int i = 0; i < prev_num_map; ++i )
nx_delta[i] = Mat(tmp[0].m-1, tmp[0].n);
for( int i = 0; i < prev_num_map; ++i )
for( int j = 0; j < tmp[i].m-1; ++j )
for( int k = 0; k < tmp[i].n; ++k )
nx_delta[i][j][k] += mask[j][i]*tmp[i][j+1][k]*prev_activate_diff_func(U[i][j][k]);
return nx_delta;
}
void KDropoutFullyConnected::update_W ( const std::vector<std::vector<Mat>>& dW )
{
for( int i = 0; i < num_map; ++i ){
for( int j = 0; j < prev_num_map; ++j )
W[i][j] = W[i][j] + dW[i][j];
}
}
std::vector<KDropoutFullyConnected::Mat> KDropoutFullyConnected::apply ( const std::vector<Mat>& U, bool use_func )
{
std::vector<Mat> ret(num_map);
std::vector<Mat> V(prev_num_map);
for( int i = 0; i < prev_num_map; ++i ){
std::vector<int> idx(U[i].m);
std::vector<double> val(U[i].m, 0.0);
std::iota(idx.begin(), idx.end(), 0);
for( int j = 0; j < U[i].m; ++j ){
for( int k = 0; k < U[i].n; ++k ){
val[j] += U[i][j][k];
}
val[j] /= U[i].n;
}
std::sort( idx.begin(), idx.end(), [&](int id1, int id2) -> bool {
return val[id1] > val[id2];
});
for( int j = 0; j < K; ++j ) mask[idx[j]][i] = 1.0;
for( int j = K; j < U[i].m; ++j ) mask[idx[j]][i] = 0.0;
}
for( int i = 0; i < prev_num_map; ++i ){
V[i] = Mat(U[i].m+1, U[i].n);
for( int j = 0; j < U[i].n; ++j ) V[i][0][j] = 1.0;
for( int j = 0; j < U[i].m; ++j ){
for( int k = 0; k < U[i].n; ++k ){
V[i][j+1][k] = U[i][j][k]*mask[j][i];
}
}
}
for( int i = 0; i < num_map; ++i ){
ret[i] = Mat(W[i][0].m, V[0].n);
for( int j = 0; j < prev_num_map; ++j ){
ret[i] = ret[i] + W[i][j]*V[j];
}
}
for( int i = 0; i < num_map; ++i )
for( int j = 0; j < ret[i].m; ++j )
for( int k = 0; k < ret[i].n; ++k )
ret[i][j][k] = (use_func ? activate_func(ret[i][j][k]) : ret[i][j][k]);
return ret;
}
std::vector<std::vector<KDropoutFullyConnected::Vec>> KDropoutFullyConnected::apply ( const std::vector<std::vector<Vec>>& u, bool use_func )
{
std::vector<Mat> tmp(prev_num_map);
for( int i = 0; i < prev_num_map; ++i )
tmp[i] = Mat(u[i][0].size(), u.size());
for( int i = 0; i < prev_num_map; ++i )
for( int j = 0; j < u[i][0].size(); ++j )
for( int k = 0; k < u.size(); ++k )
tmp[i][j][k] = u[k][i][j];
auto U = apply(tmp, use_func);
std::vector<std::vector<Vec>> ret(U[0].n);
for( int i = 0; i < U[0].n; ++i ){
ret[i] = std::vector<Vec>(U.size(), Vec(U[0].m));
for( int j = 0; j < U.size(); ++j )
for( int k = 0; k < U[0].m; ++k )
ret[i][j][k] = U[j][k][i];
}
return ret;
}
void KDropoutFullyConnected::set_W ( const std::string& filename )
{
std::ifstream ifs(filename, std::ios::binary);
for( int i = 0; i < num_map; ++i )
for( int j = 0; j < prev_num_map; ++j ){
ifs.read((char*)&W[i][j].m, sizeof(W[i][j].m));
ifs.read((char*)&W[i][j].n, sizeof(W[i][j].n));
for( int k = 0; k < W[i][j].m; ++k )
for( int l = 0; l < W[i][j].n; ++l )
ifs.read((char*)&W[i][j][k][l], sizeof(W[i][j][k][l]));
}
}
void KDropoutFullyConnected::output_W ( const std::string& filename )
{
std::ofstream ofs(filename, std::ios::binary);
for( int i = 0; i < num_map; ++i )
for( int j = 0; j < prev_num_map; ++j ){
ofs.write((char*)&W[i][j].m, sizeof(W[i][j].m));
ofs.write((char*)&W[i][j].n, sizeof(W[i][j].n));
for( int k = 0; k < W[i][j].m; ++k )
for( int l = 0; l < W[i][j].n; ++l )
ofs.write((char*)&W[i][j][k][l], sizeof(W[i][j][k][l]));
}
}
#endif
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.