text
stringlengths
54
60.6k
<commit_before>/************************************************************************* * * $RCSfile: SwXTextDefaults.cxx,v $ * * $Revision: 1.11 $ * * last change: $Author: tl $ $Date: 2002-10-16 06:55:14 $ * * 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) * * ************************************************************************/ #ifdef PRECOMPILED #include "core_pch.hxx" #endif #pragma hdrstop #ifndef _SW_XTEXT_DEFAULTS_HXX #include <SwXTextDefaults.hxx> #endif #ifndef _UNOMAP_HXX #include <unomap.hxx> #endif #ifndef SW_UNOMID_HXX #include <unomid.h> #endif #ifndef _VOS_MUTEX_HXX_ #include <vos/mutex.hxx> #endif #ifndef _SV_SVAPP_HXX #include <vcl/svapp.hxx> #endif #ifndef _UNOPRNMS_HXX #include <unoprnms.hxx> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_ #include <com/sun/star/beans/PropertyAttribute.hpp> #endif #ifndef _HINTIDS_HXX #include <hintids.hxx> #endif using namespace rtl; using namespace com::sun::star; using namespace com::sun::star::uno; using namespace com::sun::star::beans; using namespace com::sun::star::lang; // declarations void lcl_setPageDesc(SwDoc*, const uno::Any&, SfxItemSet& ); // from unoobj.cxx #define C2U(cChar) OUString::createFromAscii(cChar) SwXTextDefaults::SwXTextDefaults ( SwDoc * pNewDoc ) : pDoc (pNewDoc) , aPropSet (aSwMapProvider.GetPropertyMap ( PROPERTY_MAP_TEXT_DEFAULT ) ) { } SwXTextDefaults::~SwXTextDefaults () { } Reference< XPropertySetInfo > SAL_CALL SwXTextDefaults::getPropertySetInfo( ) throw(RuntimeException) { static uno::Reference < XPropertySetInfo > xRef = aPropSet.getPropertySetInfo(); return xRef; } void SAL_CALL SwXTextDefaults::setPropertyValue( const OUString& rPropertyName, const Any& aValue ) throw(UnknownPropertyException, PropertyVetoException, IllegalArgumentException, WrappedTargetException, RuntimeException) { vos::OGuard aGuard( Application::GetSolarMutex()); if (!pDoc) throw RuntimeException(); const SfxItemPropertyMap *pMap = SfxItemPropertyMap::GetByName( aPropSet.getPropertyMap(), rPropertyName); if (!pMap) throw UnknownPropertyException(OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Unknown property: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) ); if ( pMap->nFlags & PropertyAttribute::READONLY) throw PropertyVetoException ( OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Property is read-only: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) ); const SfxPoolItem& rItem = pDoc->GetDefault(pMap->nWID); if (RES_PAGEDESC == pMap->nWID && MID_PAGEDESC_PAGEDESCNAME == pMap->nMemberId) { SfxItemSet aSet( pDoc->GetAttrPool(), RES_PAGEDESC, RES_PAGEDESC ); aSet.Put(rItem); lcl_setPageDesc( pDoc, aValue, aSet ); pDoc->SetDefault(aSet.Get(RES_PAGEDESC)); } else { SfxPoolItem * pNewItem = rItem.Clone(); pNewItem->PutValue( aValue, pMap->nMemberId); pDoc->SetDefault(*pNewItem); delete pNewItem; } } Any SAL_CALL SwXTextDefaults::getPropertyValue( const OUString& rPropertyName ) throw(UnknownPropertyException, WrappedTargetException, RuntimeException) { vos::OGuard aGuard( Application::GetSolarMutex()); if (!pDoc) throw RuntimeException(); const SfxItemPropertyMap *pMap = SfxItemPropertyMap::GetByName( aPropSet.getPropertyMap(), rPropertyName); if (!pMap) throw UnknownPropertyException(OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Unknown property: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) ); Any aRet; const SfxPoolItem& rItem = pDoc->GetDefault(pMap->nWID); rItem.QueryValue( aRet, pMap->nMemberId ); return aRet; } void SAL_CALL SwXTextDefaults::addPropertyChangeListener( const OUString& rPropertyName, const Reference< XPropertyChangeListener >& xListener ) throw(UnknownPropertyException, WrappedTargetException, RuntimeException) { DBG_WARNING ( "not implemented" ); } void SAL_CALL SwXTextDefaults::removePropertyChangeListener( const OUString& rPropertyName, const Reference< XPropertyChangeListener >& aListener ) throw(UnknownPropertyException, WrappedTargetException, RuntimeException) { DBG_WARNING ( "not implemented" ); } void SAL_CALL SwXTextDefaults::addVetoableChangeListener( const OUString& rPropertyName, const Reference< XVetoableChangeListener >& aListener ) throw(UnknownPropertyException, WrappedTargetException, RuntimeException) { DBG_WARNING ( "not implemented" ); } void SAL_CALL SwXTextDefaults::removeVetoableChangeListener( const OUString& rPropertyName, const Reference< XVetoableChangeListener >& aListener ) throw(UnknownPropertyException, WrappedTargetException, RuntimeException) { DBG_WARNING ( "not implemented" ); } // XPropertyState PropertyState SAL_CALL SwXTextDefaults::getPropertyState( const OUString& rPropertyName ) throw(UnknownPropertyException, RuntimeException) { vos::OGuard aGuard( Application::GetSolarMutex()); PropertyState eRet = PropertyState_DIRECT_VALUE; if (!pDoc) throw RuntimeException(); const SfxItemPropertyMap *pMap = SfxItemPropertyMap::GetByName( aPropSet.getPropertyMap(), rPropertyName); if (!pMap) throw UnknownPropertyException(OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Unknown property: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) ); if ( pMap->nFlags & PropertyAttribute::READONLY) throw PropertyVetoException ( OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Property is read-only: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) ); const SfxPoolItem& rItem = pDoc->GetDefault(pMap->nWID); if (IsStaticDefaultItem ( &rItem ) ) eRet = PropertyState_DEFAULT_VALUE; return eRet; } Sequence< PropertyState > SAL_CALL SwXTextDefaults::getPropertyStates( const Sequence< OUString >& rPropertyNames ) throw(UnknownPropertyException, RuntimeException) { const sal_Int32 nCount = rPropertyNames.getLength(); const OUString * pNames = rPropertyNames.getConstArray(); Sequence < PropertyState > aRet ( nCount ); PropertyState *pState = aRet.getArray(); for ( sal_Int32 nIndex = 0; nIndex < nCount; nIndex++) pState[nIndex] = getPropertyState( pNames[nIndex] ); return aRet; } void SAL_CALL SwXTextDefaults::setPropertyToDefault( const OUString& rPropertyName ) throw(UnknownPropertyException, RuntimeException) { if (!pDoc) throw RuntimeException(); const SfxItemPropertyMap *pMap = SfxItemPropertyMap::GetByName( aPropSet.getPropertyMap(), rPropertyName); if (!pMap) throw UnknownPropertyException(OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Unknown property: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) ); if ( pMap->nFlags & PropertyAttribute::READONLY) throw PropertyVetoException ( OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Property is read-only: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) ); SfxItemPool rSet (pDoc->GetAttrPool()); rSet.ResetPoolDefaultItem ( pMap->nWID ); } Any SAL_CALL SwXTextDefaults::getPropertyDefault( const OUString& rPropertyName ) throw(UnknownPropertyException, WrappedTargetException, RuntimeException) { if (!pDoc) throw RuntimeException(); const SfxItemPropertyMap *pMap = SfxItemPropertyMap::GetByName( aPropSet.getPropertyMap(), rPropertyName); if (!pMap) throw UnknownPropertyException(OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Unknown property: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) ); if ( pMap->nFlags & PropertyAttribute::READONLY) throw RuntimeException ( OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Property is read-only: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) ); Any aRet; SfxItemPool rSet (pDoc->GetAttrPool()); const SfxPoolItem *pItem = rSet.GetPoolDefaultItem ( pMap->nWID ); pItem->QueryValue( aRet, pMap->nMemberId ); return aRet; } rtl::OUString SAL_CALL SwXTextDefaults::getImplementationName( ) throw (RuntimeException) { return C2U("SwXTextDefaults"); } sal_Bool SAL_CALL SwXTextDefaults::supportsService( const ::rtl::OUString& rServiceName ) throw (RuntimeException) { return rServiceName == C2U("com.sun.star.text.Defaults") || rServiceName == C2U("com.sun.star.style.CharacterProperties") || rServiceName == C2U("com.sun.star.style.CharacterPropertiesAsian") || rServiceName == C2U("com.sun.star.style.CharacterPropertiesComplex") || rServiceName == C2U("com.sun.star.style.ParagraphProperties") || rServiceName == C2U("com.sun.star.style.ParagraphPropertiesAsian") || rServiceName == C2U("com.sun.star.style.ParagraphPropertiesComplex"); } uno::Sequence< ::rtl::OUString > SAL_CALL SwXTextDefaults::getSupportedServiceNames( ) throw (RuntimeException) { uno::Sequence< OUString > aRet(7); OUString* pArr = aRet.getArray(); *pArr++ = C2U("com.sun.star.text.Defaults"); *pArr++ = C2U("com.sun.star.style.CharacterProperties"); *pArr++ = C2U("com.sun.star.style.CharacterPropertiesAsian"); *pArr++ = C2U("com.sun.star.style.CharacterPropertiesComplex"); *pArr++ = C2U("com.sun.star.style.ParagraphProperties"); *pArr++ = C2U("com.sun.star.style.ParagraphPropertiesAsian"); *pArr++ = C2U("com.sun.star.style.ParagraphPropertiesComplex"); return aRet; } <commit_msg>#103124# setPropertyValue for DropCapCharStyleName fixed<commit_after>/************************************************************************* * * $RCSfile: SwXTextDefaults.cxx,v $ * * $Revision: 1.12 $ * * last change: $Author: tl $ $Date: 2002-10-16 08:56:04 $ * * 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) * * ************************************************************************/ #ifdef PRECOMPILED #include "core_pch.hxx" #endif #ifndef _VOS_MUTEX_HXX_ #include <vos/mutex.hxx> #endif #ifndef _SV_SVAPP_HXX #include <vcl/svapp.hxx> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_ #include <com/sun/star/beans/PropertyAttribute.hpp> #endif #pragma hdrstop #ifndef _SW_XTEXT_DEFAULTS_HXX #include <SwXTextDefaults.hxx> #endif #ifndef _SWSTYLENAMEMAPPER_HXX #include <SwStyleNameMapper.hxx> #endif #ifndef _DOCSTYLE_HXX #include <docstyle.hxx> #endif #ifndef _SWDOCSH_HXX #include <docsh.hxx> #endif #ifndef _UNOMAP_HXX #include <unomap.hxx> #endif #ifndef SW_UNOMID_HXX #include <unomid.h> #endif #ifndef _PARATR_HXX #include <paratr.hxx> #endif #ifndef _UNOPRNMS_HXX #include <unoprnms.hxx> #endif #ifndef _HINTIDS_HXX #include <hintids.hxx> #endif using namespace rtl; using namespace com::sun::star; using namespace com::sun::star::uno; using namespace com::sun::star::beans; using namespace com::sun::star::lang; // declarations void lcl_setPageDesc(SwDoc*, const uno::Any&, SfxItemSet& ); // from unoobj.cxx #define C2U(cChar) OUString::createFromAscii(cChar) SwXTextDefaults::SwXTextDefaults ( SwDoc * pNewDoc ) : pDoc (pNewDoc) , aPropSet (aSwMapProvider.GetPropertyMap ( PROPERTY_MAP_TEXT_DEFAULT ) ) { } SwXTextDefaults::~SwXTextDefaults () { } Reference< XPropertySetInfo > SAL_CALL SwXTextDefaults::getPropertySetInfo( ) throw(RuntimeException) { static uno::Reference < XPropertySetInfo > xRef = aPropSet.getPropertySetInfo(); return xRef; } void SAL_CALL SwXTextDefaults::setPropertyValue( const OUString& rPropertyName, const Any& aValue ) throw(UnknownPropertyException, PropertyVetoException, IllegalArgumentException, WrappedTargetException, RuntimeException) { vos::OGuard aGuard( Application::GetSolarMutex()); if (!pDoc) throw RuntimeException(); const SfxItemPropertyMap *pMap = SfxItemPropertyMap::GetByName( aPropSet.getPropertyMap(), rPropertyName); if (!pMap) throw UnknownPropertyException(OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Unknown property: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) ); if ( pMap->nFlags & PropertyAttribute::READONLY) throw PropertyVetoException ( OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Property is read-only: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) ); const SfxPoolItem& rItem = pDoc->GetDefault(pMap->nWID); if (RES_PAGEDESC == pMap->nWID && MID_PAGEDESC_PAGEDESCNAME == pMap->nMemberId) { SfxItemSet aSet( pDoc->GetAttrPool(), RES_PAGEDESC, RES_PAGEDESC ); aSet.Put(rItem); lcl_setPageDesc( pDoc, aValue, aSet ); pDoc->SetDefault(aSet.Get(RES_PAGEDESC)); } else if (RES_PARATR_DROP == pMap->nWID && MID_DROPCAP_CHAR_STYLE_NAME == pMap->nMemberId) { OUString uStyle; if(aValue >>= uStyle) { String sStyle; SwStyleNameMapper::FillUIName(uStyle, sStyle, GET_POOLID_CHRFMT, sal_True ); SwDocStyleSheet* pStyle = (SwDocStyleSheet*)pDoc->GetDocShell()->GetStyleSheetPool()->Find(sStyle, SFX_STYLE_FAMILY_CHAR); SwFmtDrop* pDrop = 0; if(pStyle) { SwDocStyleSheet aStyle( *(SwDocStyleSheet*)pStyle ); pDrop = (SwFmtDrop*)rItem.Clone(); // because rItem ist const... pDrop->SetCharFmt(aStyle.GetCharFmt()); } else throw lang::IllegalArgumentException(); pDoc->SetDefault(*pDrop); delete pDrop; } else throw lang::IllegalArgumentException(); } else { SfxPoolItem * pNewItem = rItem.Clone(); pNewItem->PutValue( aValue, pMap->nMemberId); pDoc->SetDefault(*pNewItem); delete pNewItem; } } Any SAL_CALL SwXTextDefaults::getPropertyValue( const OUString& rPropertyName ) throw(UnknownPropertyException, WrappedTargetException, RuntimeException) { vos::OGuard aGuard( Application::GetSolarMutex()); if (!pDoc) throw RuntimeException(); const SfxItemPropertyMap *pMap = SfxItemPropertyMap::GetByName( aPropSet.getPropertyMap(), rPropertyName); if (!pMap) throw UnknownPropertyException(OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Unknown property: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) ); Any aRet; const SfxPoolItem& rItem = pDoc->GetDefault(pMap->nWID); rItem.QueryValue( aRet, pMap->nMemberId ); return aRet; } void SAL_CALL SwXTextDefaults::addPropertyChangeListener( const OUString& rPropertyName, const Reference< XPropertyChangeListener >& xListener ) throw(UnknownPropertyException, WrappedTargetException, RuntimeException) { DBG_WARNING ( "not implemented" ); } void SAL_CALL SwXTextDefaults::removePropertyChangeListener( const OUString& rPropertyName, const Reference< XPropertyChangeListener >& aListener ) throw(UnknownPropertyException, WrappedTargetException, RuntimeException) { DBG_WARNING ( "not implemented" ); } void SAL_CALL SwXTextDefaults::addVetoableChangeListener( const OUString& rPropertyName, const Reference< XVetoableChangeListener >& aListener ) throw(UnknownPropertyException, WrappedTargetException, RuntimeException) { DBG_WARNING ( "not implemented" ); } void SAL_CALL SwXTextDefaults::removeVetoableChangeListener( const OUString& rPropertyName, const Reference< XVetoableChangeListener >& aListener ) throw(UnknownPropertyException, WrappedTargetException, RuntimeException) { DBG_WARNING ( "not implemented" ); } // XPropertyState PropertyState SAL_CALL SwXTextDefaults::getPropertyState( const OUString& rPropertyName ) throw(UnknownPropertyException, RuntimeException) { vos::OGuard aGuard( Application::GetSolarMutex()); PropertyState eRet = PropertyState_DIRECT_VALUE; if (!pDoc) throw RuntimeException(); const SfxItemPropertyMap *pMap = SfxItemPropertyMap::GetByName( aPropSet.getPropertyMap(), rPropertyName); if (!pMap) throw UnknownPropertyException(OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Unknown property: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) ); if ( pMap->nFlags & PropertyAttribute::READONLY) throw PropertyVetoException ( OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Property is read-only: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) ); const SfxPoolItem& rItem = pDoc->GetDefault(pMap->nWID); if (IsStaticDefaultItem ( &rItem ) ) eRet = PropertyState_DEFAULT_VALUE; return eRet; } Sequence< PropertyState > SAL_CALL SwXTextDefaults::getPropertyStates( const Sequence< OUString >& rPropertyNames ) throw(UnknownPropertyException, RuntimeException) { const sal_Int32 nCount = rPropertyNames.getLength(); const OUString * pNames = rPropertyNames.getConstArray(); Sequence < PropertyState > aRet ( nCount ); PropertyState *pState = aRet.getArray(); for ( sal_Int32 nIndex = 0; nIndex < nCount; nIndex++) pState[nIndex] = getPropertyState( pNames[nIndex] ); return aRet; } void SAL_CALL SwXTextDefaults::setPropertyToDefault( const OUString& rPropertyName ) throw(UnknownPropertyException, RuntimeException) { if (!pDoc) throw RuntimeException(); const SfxItemPropertyMap *pMap = SfxItemPropertyMap::GetByName( aPropSet.getPropertyMap(), rPropertyName); if (!pMap) throw UnknownPropertyException(OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Unknown property: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) ); if ( pMap->nFlags & PropertyAttribute::READONLY) throw PropertyVetoException ( OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Property is read-only: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) ); SfxItemPool rSet (pDoc->GetAttrPool()); rSet.ResetPoolDefaultItem ( pMap->nWID ); } Any SAL_CALL SwXTextDefaults::getPropertyDefault( const OUString& rPropertyName ) throw(UnknownPropertyException, WrappedTargetException, RuntimeException) { if (!pDoc) throw RuntimeException(); const SfxItemPropertyMap *pMap = SfxItemPropertyMap::GetByName( aPropSet.getPropertyMap(), rPropertyName); if (!pMap) throw UnknownPropertyException(OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Unknown property: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) ); if ( pMap->nFlags & PropertyAttribute::READONLY) throw RuntimeException ( OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Property is read-only: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) ); Any aRet; SfxItemPool rSet (pDoc->GetAttrPool()); const SfxPoolItem *pItem = rSet.GetPoolDefaultItem ( pMap->nWID ); pItem->QueryValue( aRet, pMap->nMemberId ); return aRet; } rtl::OUString SAL_CALL SwXTextDefaults::getImplementationName( ) throw (RuntimeException) { return C2U("SwXTextDefaults"); } sal_Bool SAL_CALL SwXTextDefaults::supportsService( const ::rtl::OUString& rServiceName ) throw (RuntimeException) { return rServiceName == C2U("com.sun.star.text.Defaults") || rServiceName == C2U("com.sun.star.style.CharacterProperties") || rServiceName == C2U("com.sun.star.style.CharacterPropertiesAsian") || rServiceName == C2U("com.sun.star.style.CharacterPropertiesComplex") || rServiceName == C2U("com.sun.star.style.ParagraphProperties") || rServiceName == C2U("com.sun.star.style.ParagraphPropertiesAsian") || rServiceName == C2U("com.sun.star.style.ParagraphPropertiesComplex"); } uno::Sequence< ::rtl::OUString > SAL_CALL SwXTextDefaults::getSupportedServiceNames( ) throw (RuntimeException) { uno::Sequence< OUString > aRet(7); OUString* pArr = aRet.getArray(); *pArr++ = C2U("com.sun.star.text.Defaults"); *pArr++ = C2U("com.sun.star.style.CharacterProperties"); *pArr++ = C2U("com.sun.star.style.CharacterPropertiesAsian"); *pArr++ = C2U("com.sun.star.style.CharacterPropertiesComplex"); *pArr++ = C2U("com.sun.star.style.ParagraphProperties"); *pArr++ = C2U("com.sun.star.style.ParagraphPropertiesAsian"); *pArr++ = C2U("com.sun.star.style.ParagraphPropertiesComplex"); return aRet; } <|endoftext|>
<commit_before>#include<chrono> #include<iostream> #include<mutex> #include<random> #include<queue> #include<thread> #include"../header/CThreadPool.h" namespace { std::mutex mut; size_t get() { using namespace std; static mt19937 mu{static_cast<mt19937::result_type>(chrono::high_resolution_clock::now().time_since_epoch().count())}; return mu()%4; } std::size_t add_func(const std::size_t i) { using namespace std; const auto sec{get()}; this_thread::sleep_for(chrono::seconds{sec}); lock_guard<mutex> lock{mut}; cout<<"add - thread "<<i<<" wait "<<sec<<" sec"<<endl; return i; } std::size_t add_and_detach_func(const std::size_t i) { using namespace std; const auto sec{get()}; this_thread::sleep_for(chrono::seconds{sec}); lock_guard<mutex> lock{mut}; cout<<"add_and_detach - thread "<<i<<" wait "<<sec<<" sec"<<endl; return i; } } int main() { using namespace std; nThread::CThreadPool tp{4}; queue<nThread::CThreadPool::thread_id> que; cout<<"stage 1"<<endl; for(size_t i{0};i!=tp.count();++i) tp.add_and_detach(add_and_detach_func,i); tp.join_all(); //this will not block, because you use add_and_detach cout<<"stage 2"<<endl; for(size_t i{0};i!=tp.count();++i) que.push(tp.add(add_func,i)); //tp will block here until add_and_detach_func complete for(size_t i{0};i!=tp.count();++i) { tp.join(que.front()); //tp will block here until the i of thread complete que.pop(); } cout<<"after for loop of join, "<<tp.available()<<" should equal to "<<tp.count()<<endl; cout<<"stage 3"<<endl; for(size_t i{0};i!=tp.count();++i) tp.add_and_detach(add_and_detach_func,i); tp.wait_until_all_available(); //this will block until all detach threads complete add_and_detach_func cout<<"after wait_until_all_available, "<<tp.available()<<" should equal to "<<tp.count()<<endl; cout<<"stage 4"<<endl; for(size_t i{0};i!=tp.count();++i) tp.add(add_func,i); //tp will not block here, because you join all thread tp.join_all(); //tp will block here until add_func complete, it is same as //for(size_t i(0);i!=tp.count();++i) // tp.join(i); cout<<"after join_all, "<<tp.available()<<" should equal to "<<tp.count()<<endl; cout<<"stage 5"<<endl; for(size_t i{0};i!=tp.count();++i) tp.add(add_func,i); cout<<"thread "<<tp.join_any()<<" complete"<<endl; //join any thread without specify which one tp.join_all(); cout<<"after join_all, "<<tp.available()<<" should equal to "<<tp.count()<<endl; cout<<"stage 6"<<endl; for(size_t i{0};i!=tp.count();++i) que.push(tp.add(add_func,i)); tp.join(que.front()); cout<<"after join, "<<tp.available()<<" should equal to "<<1<<endl; tp.join_any(); //calling join prior to join_any is ok //but calling join_any with join (or join_all) is not ok when using multi-thread, such as the code below cout<<"after join_any, "<<tp.available()<<" should equal to "<<2<<endl; //here is an incorrect example //for(size_t i(0);i!=tp.count();++i) // tp.add(add_func,i); //thread thr([&]{tp.join(0);}); //tp.join_any(); //please, don't do this // //do not combine these function together in multi-thread // //use join or join_any each time // //otherwise, it will make some threads which are calling join_any cannot get notification //thr.join(); //however, here is an correct example tp.join_any(); cout<<"after join_any, "<<tp.available()<<" should equal to "<<3<<endl; tp.join_all(); //because, this is in single thread cout<<"after join_all, "<<tp.available()<<" should equal to "<<tp.count()<<endl; cout<<"stage 7"<<endl; for(size_t i{0};i!=tp.count();++i) tp.add(add_func,i); thread thr([&]{tp.join_any();}); tp.join_any(); //ok, no problem cout<<"after join, "<<tp.available()<<" should equal to "<<1<<endl; thr.join(); tp.join_all(); cout<<"after join_all, "<<tp.available()<<" should equal to "<<tp.count()<<endl; //in short, do not call join_any with join and join_all in 2 (or higher) threads //the user has to guarantee that //every threads' join can be called only once after calling assign cout<<"stage 8"<<endl; for(size_t i{0};i!=tp.count();++i) tp.add(add_func,i); tp.join_any(); cout<<"after join, "<<tp.available()<<" should equal to "<<1<<endl; //you don't need to call join_all to guarantee all threads are joining //the destructor of CThreadPool will deal with this //something else you have to notice //CThreadPool::join_all will not block CThreadPool::add, and vice versa }<commit_msg>CThreadPoolItemExecutorDetach and CThreadPoolItemExecutorJoin are different, cannot be replaced with CThreadPoolItemExecutor<commit_after>#include<chrono> #include<iostream> #include<mutex> #include<random> #include<queue> #include<thread> #include"../header/CThreadPool.h" namespace { std::mutex mut; size_t get() { using namespace std; static mt19937 mu{static_cast<mt19937::result_type>(chrono::high_resolution_clock::now().time_since_epoch().count())}; return mu()%4; } std::size_t add_func(const std::size_t i) { using namespace std; const auto sec{get()}; this_thread::sleep_for(chrono::seconds{sec}); lock_guard<mutex> lock{mut}; cout<<"add - thread "<<i<<" wait "<<sec<<" sec"<<endl; return i; } std::size_t add_and_detach_func(const std::size_t i) { using namespace std; const auto sec{get()}; this_thread::sleep_for(chrono::seconds{sec}); lock_guard<mutex> lock{mut}; cout<<"add_and_detach - thread "<<i<<" wait "<<sec<<" sec"<<endl; return i; } } int main() { using namespace std; nThread::CThreadPool tp{4}; queue<nThread::CThreadPool::thread_id> que; cout<<"stage 1"<<endl; for(size_t i{0};i!=tp.count();++i) tp.add_and_detach(add_and_detach_func,i); tp.join_all(); //this will not block, because you use add_and_detach cout<<"stage 2"<<endl; for(size_t i{0};i!=tp.count();++i) que.push(tp.add(add_func,i)); //tp will block here until add_and_detach_func complete for(size_t i{0};i!=tp.count();++i) { tp.join(que.front()); //tp will block here until the i of thread complete que.pop(); } cout<<"stage 3"<<endl; for(size_t i{0};i!=tp.count();++i) tp.add_and_detach(add_and_detach_func,i); tp.wait_until_all_available(); //this will block until all detach threads complete add_and_detach_func cout<<"stage 4"<<endl; for(size_t i{0};i!=tp.count();++i) tp.add(add_func,i); //tp will not block here, because you join all thread tp.join_all(); //tp will block here until add_func complete, it is same as //for(size_t i(0);i!=tp.count();++i) // tp.join(i); cout<<"stage 5"<<endl; for(size_t i{0};i!=tp.count();++i) tp.add(add_func,i); cout<<"thread "<<tp.join_any()<<" complete"<<endl; //join any thread without specify which one tp.join_all(); cout<<"stage 6"<<endl; for(size_t i{0};i!=tp.count();++i) que.push(tp.add(add_func,i)); tp.join(que.front()); tp.join_any(); //calling join prior to join_any is ok //but calling join_any with join (or join_all) is not ok when using multi-thread, such as the code below //here is an incorrect example //for(size_t i(0);i!=tp.count();++i) // tp.add(add_func,i); //thread thr([&]{tp.join(0);}); //tp.join_any(); //please, don't do this // //do not combine these function together in multi-thread // //use join or join_any each time // //otherwise, it will make some threads which are calling join_any cannot get notification //thr.join(); //however, here is an correct example tp.join_any(); tp.join_all(); //because, this is in single thread cout<<"stage 7"<<endl; for(size_t i{0};i!=tp.count();++i) tp.add(add_func,i); thread thr([&]{tp.join_any();}); tp.join_any(); //ok, no problem thr.join(); tp.join_all(); //in short, do not call join_any with join and join_all in 2 (or higher) threads //the user has to guarantee that //every threads' join can be called only once after calling assign cout<<"stage 8"<<endl; for(size_t i{0};i!=tp.count();++i) tp.add(add_func,i); tp.join_any(); //you don't need to call join_all to guarantee all threads are joining //the destructor of CThreadPool will deal with this //something else you have to notice //CThreadPool::join_all will not block CThreadPool::add, and vice versa }<|endoftext|>
<commit_before>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2009 Torus Knot Software Ltd 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 "OgreCgPlugin.h" #include "OgreRoot.h" #include "OgreHighLevelGpuProgramManager.h" #include "OgreCgFxScriptLoader.h" namespace Ogre { const String sPluginName = "Cg Program Manager"; //--------------------------------------------------------------------- CgPlugin::CgPlugin() :mCgProgramFactory(0) { } //--------------------------------------------------------------------- const String& CgPlugin::getName() const { return sPluginName; } //--------------------------------------------------------------------- void CgPlugin::install() { // Create new factory mCgProgramFactory = OGRE_NEW CgProgramFactory(); // Register HighLevelGpuProgramManager::getSingleton().addFactory(mCgProgramFactory); OGRE_NEW CgFxScriptLoader(); } //--------------------------------------------------------------------- void CgPlugin::initialise() { // nothing to do } //--------------------------------------------------------------------- void CgPlugin::shutdown() { // nothing to do } //--------------------------------------------------------------------- void CgPlugin::uninstall() { if (mCgProgramFactory) { OGRE_DELETE CgFxScriptLoader::getSingletonPtr(); // Remove from manager safely if (HighLevelGpuProgramManager::getSingletonPtr()) HighLevelGpuProgramManager::getSingleton().removeFactory(mCgProgramFactory); OGRE_DELETE mCgProgramFactory; mCgProgramFactory = 0; } } } <commit_msg>Fixed so the CG plugin will not register a factory when the GLES2 render system is the active render system.<commit_after>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2009 Torus Knot Software Ltd 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 "OgreCgPlugin.h" #include "OgreRoot.h" #include "OgreHighLevelGpuProgramManager.h" #include "OgreCgFxScriptLoader.h" namespace Ogre { const String sPluginName = "Cg Program Manager"; //--------------------------------------------------------------------- CgPlugin::CgPlugin() :mCgProgramFactory(0) { } //--------------------------------------------------------------------- const String& CgPlugin::getName() const { return sPluginName; } //--------------------------------------------------------------------- void CgPlugin::install() { } //--------------------------------------------------------------------- void CgPlugin::initialise() { // check for gles2 by the glsles factory (this plugin is not supported on embedded systems for now) if (HighLevelGpuProgramManager::getSingleton().isLanguageSupported("glsles") == false) { // Create new factory mCgProgramFactory = OGRE_NEW CgProgramFactory(); // Register HighLevelGpuProgramManager::getSingleton().addFactory(mCgProgramFactory); OGRE_NEW CgFxScriptLoader(); } } //--------------------------------------------------------------------- void CgPlugin::shutdown() { // nothing to do } //--------------------------------------------------------------------- void CgPlugin::uninstall() { if (mCgProgramFactory) { OGRE_DELETE CgFxScriptLoader::getSingletonPtr(); // Remove from manager safely if (HighLevelGpuProgramManager::getSingletonPtr()) HighLevelGpuProgramManager::getSingleton().removeFactory(mCgProgramFactory); OGRE_DELETE mCgProgramFactory; mCgProgramFactory = 0; } } } <|endoftext|>
<commit_before>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2014 Torus Knot Software Ltd 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 "OgreCgPlugin.h" #include "OgreRoot.h" #include "OgreHighLevelGpuProgram.h" #include "OgreHighLevelGpuProgramManager.h" #include "OgreCgFxScriptLoader.h" #include "OgreCgProgramFactory.h" #include "OgreLogManager.h" namespace Ogre { const String sPluginName = "Cg Program Manager"; //--------------------------------------------------------------------- CgPlugin::CgPlugin() :mCgProgramFactory(0) { } //--------------------------------------------------------------------- const String& CgPlugin::getName() const { return sPluginName; } //--------------------------------------------------------------------- void CgPlugin::install() { } //--------------------------------------------------------------------- void CgPlugin::initialise() { // Cg is also not supported on OpenGL 3+ if(Root::getSingletonPtr()->getRenderSystem()->getName().find("OpenGL 3+") != String::npos) { LogManager::getSingleton().logMessage("Disabling Cg Plugin for GL3+"); return; } // Check for gles2 by the glsles factory (this plugin is not supported on embedded systems for now) if (HighLevelGpuProgramManager::getSingleton().isLanguageSupported("glsles") == false) { // Create new factory mCgProgramFactory = OGRE_NEW CgProgramFactory(); // Register HighLevelGpuProgramManager::getSingleton().addFactory(mCgProgramFactory); OGRE_NEW CgFxScriptLoader(); } } //--------------------------------------------------------------------- void CgPlugin::shutdown() { // nothing to do } //--------------------------------------------------------------------- void CgPlugin::uninstall() { if (mCgProgramFactory) { OGRE_DELETE CgFxScriptLoader::getSingletonPtr(); // Remove from manager safely if (HighLevelGpuProgramManager::getSingletonPtr()) HighLevelGpuProgramManager::getSingleton().removeFactory(mCgProgramFactory); OGRE_DELETE mCgProgramFactory; mCgProgramFactory = 0; } } } <commit_msg>CgPlugin: allow loading on GL3Plus<commit_after>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2014 Torus Knot Software Ltd 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 "OgreCgPlugin.h" #include "OgreRoot.h" #include "OgreHighLevelGpuProgram.h" #include "OgreHighLevelGpuProgramManager.h" #include "OgreCgFxScriptLoader.h" #include "OgreCgProgramFactory.h" #include "OgreLogManager.h" namespace Ogre { const String sPluginName = "Cg Program Manager"; //--------------------------------------------------------------------- CgPlugin::CgPlugin() :mCgProgramFactory(0) { } //--------------------------------------------------------------------- const String& CgPlugin::getName() const { return sPluginName; } //--------------------------------------------------------------------- void CgPlugin::install() { } //--------------------------------------------------------------------- void CgPlugin::initialise() { // Check for gles2 by the glsles factory (this plugin is not supported on embedded systems for now) if (HighLevelGpuProgramManager::getSingleton().isLanguageSupported("glsles") == false) { // Create new factory mCgProgramFactory = OGRE_NEW CgProgramFactory(); // Register HighLevelGpuProgramManager::getSingleton().addFactory(mCgProgramFactory); OGRE_NEW CgFxScriptLoader(); } } //--------------------------------------------------------------------- void CgPlugin::shutdown() { // nothing to do } //--------------------------------------------------------------------- void CgPlugin::uninstall() { if (mCgProgramFactory) { OGRE_DELETE CgFxScriptLoader::getSingletonPtr(); // Remove from manager safely if (HighLevelGpuProgramManager::getSingletonPtr()) HighLevelGpuProgramManager::getSingleton().removeFactory(mCgProgramFactory); OGRE_DELETE mCgProgramFactory; mCgProgramFactory = 0; } } } <|endoftext|>
<commit_before>/* * Conway's Game of Life implementation with less than 1KB code. * Prototype is developed first with Arduino then ported to ATtiny84A. * * Description: * - cells are displayed on an 8x8 LED matrix * - initial setup is set through 2 pots (X and Y) and one button to select/unselect a cell * - starting/suspending the game is done by a second push button * - a 3rd pot allows speed tuning * * Circuit: * - MCU is connected to 2 chained 74HC595 SIPO * - First SIPO is connected to matrix columns through 8 330Ohm resistors * - Second SIPO is connected to matrix rows * * Wiring: * - on Arduino UNO: * - D2 is an output connected to both SIPO clock pins * - D3 is an output connected to both SIPO latch pins * - D4 is an output connected to first SIPO serial data input * - TODO LATER other pins for ADC pots and 2 push buttons * - on ATtinyX4 based boards: * - TODO */ #include <avr/interrupt.h> #include <util/delay.h> #include <fastarduino/time.hh> #include "Multiplexer.hh" #include "Buttons.hh" #if defined(ARDUINO_UNO) static constexpr const Board::DigitalPin CLOCK = Board::DigitalPin::D2; static constexpr const Board::DigitalPin LATCH = Board::DigitalPin::D3; static constexpr const Board::DigitalPin DATA = Board::DigitalPin::D4; static constexpr const Board::DigitalPin PREVIOUS = Board::DigitalPin::D5; static constexpr const Board::DigitalPin NEXT = Board::DigitalPin::D6; static constexpr const Board::DigitalPin SELECT = Board::DigitalPin::D7; static constexpr const Board::DigitalPin START_STOP = Board::DigitalPin::D0; #elif defined (BREADBOARD_ATTINYX4) static constexpr const Board::DigitalPin CLOCK = Board::DigitalPin::D0; static constexpr const Board::DigitalPin LATCH = Board::DigitalPin::D1; static constexpr const Board::DigitalPin DATA = Board::DigitalPin::D2; static constexpr const Board::DigitalPin PREVIOUS = Board::DigitalPin::D3; static constexpr const Board::DigitalPin NEXT = Board::DigitalPin::D4; static constexpr const Board::DigitalPin SELECT = Board::DigitalPin::D5; static constexpr const Board::DigitalPin START_STOP = Board::DigitalPin::D6; #else #error "Current target is not yet supported!" #endif // Single port used by this circuit static constexpr const Board::Port PORT = FastPinType<CLOCK>::PORT; // Check at compile time that all pins are on the same port static_assert(FastPinType<LATCH>::PORT == PORT, "LATCH must be on same port as CLOCK"); static_assert(FastPinType<DATA>::PORT == PORT, "DATA must be on same port as CLOCK"); static_assert(FastPinType<PREVIOUS>::PORT == PORT, "PREVIOUS must be on same port as CLOCK"); static_assert(FastPinType<NEXT>::PORT == PORT, "NEXT must be on same port as CLOCK"); static_assert(FastPinType<SELECT>::PORT == PORT, "SELECT must be on same port as CLOCK"); static_assert(FastPinType<START_STOP>::PORT == PORT, "START_STOP must be on same port as CLOCK"); // Timing constants // Multiplexing is done one row every 2ms, ie 8 rows in 16ms static constexpr const uint16_t REFRESH_PERIOD_MS = 2; // Blinking LEDs are toggled every 20 times the display is fully refreshed (ie 20 x 8 x 2ms = 320ms) static constexpr const uint8_t BLINKING_COUNTER = 20; // Buttons debouncing is done on a duration of 20ms static constexpr const uint8_t DEBOUNCE_TIME_MS = 20; static constexpr const uint8_t DEBOUNCE_COUNTER = DEBOUNCE_TIME_MS / REFRESH_PERIOD_MS; static constexpr const uint16_t PROGRESS_PERIOD_MS = 2000; static constexpr const uint16_t PROGRESS_COUNTER = PROGRESS_PERIOD_MS / REFRESH_PERIOD_MS; // Useful constants and types using MULTIPLEXER = Matrix8x8Multiplexer<CLOCK, LATCH, DATA, BLINKING_COUNTER>; static constexpr const uint8_t ROWS = MULTIPLEXER::ROWS; static constexpr const uint8_t COLUMNS = MULTIPLEXER::COLUMNS; // Calculate direction of pins (3 output, 4 input with pullups) static constexpr const uint8_t ALL_DDR = MULTIPLEXER::DDR_MASK; static constexpr const uint8_t BUTTONS_MASK = FastPinType<PREVIOUS>::MASK | FastPinType<NEXT>::MASK | FastPinType<SELECT>::MASK | FastPinType<START_STOP>::MASK; static constexpr const uint8_t ALL_PORT = MULTIPLEXER::PORT_MASK | BUTTONS_MASK; //TODO Make it a template based on game size (num rows, num columns) //TODO Make a class to hold one generation and access its members? class GameOfLife { public: GameOfLife(uint8_t game[ROWS]):_current_generation(game) {} void progress_game() { uint8_t next_generation[ROWS]; for (uint8_t row = 0; row < ROWS; ++row) for (uint8_t col = 0; col < COLUMNS; ++col) { uint8_t count_neighbours = neighbours(row, col); if (count_neighbours == 3) // cell is alive next_generation[row] |= _BV(col); else if (count_neighbours == 4) { // cell state is kept if (_current_generation[row] & _BV(col)) next_generation[row] |= _BV(col); else next_generation[row] &= ~_BV(col); } else // cell state is dead next_generation[row] &= ~_BV(col); } // Copy next generation to current one for (uint8_t row = 0; row < ROWS; ++row) _current_generation[row] = next_generation[row]; } private: static uint8_t neighbours_in_row(uint8_t game_row, uint8_t col) { //TODO possibly optimize by: // - copy row to GPIOR0 // - rotate GPIOR (col+1) times // check individual bits 0, 1 and 2 uint8_t count = (game_row & _BV(col)) ? 1 : 0; if (game_row & _BV(col ? col - 1 : COLUMNS - 1)) ++count; if (game_row & _BV(col == COLUMNS - 1 ? 0 : col + 1)) ++count; return count; } uint8_t neighbours(uint8_t row, uint8_t col) { uint8_t count = neighbours_in_row(row ? _current_generation[row - 1] : _current_generation[ROWS - 1], col); count += neighbours_in_row(row == ROWS - 1 ? _current_generation[0] : _current_generation[row + 1], col); count += neighbours_in_row(_current_generation[row], col); return count; } uint8_t* _current_generation; }; // OPEN POINTS/TODO // - Improve (use templates) to allow larger matrix size (eg 16x8, 16x16) int main() __attribute__((OS_main)); int main() { // Enable interrupts at startup time sei(); // Initialize all pins (only one port) FastPort<PORT>{ALL_DDR, ALL_PORT}; // Initialize Multiplexer MULTIPLEXER mux; //TODO optimize if else maybe // Step #1: Initialize board with 1st generation //=============================================== { Buttons<PORT, BUTTONS_MASK, DEBOUNCE_COUNTER> buttons; uint8_t row = 0; uint8_t col = 0; mux.blinks()[0] = _BV(0); uint8_t last_state = 0; while (true) { // Check button states uint8_t state = buttons.state(); if (state && state != last_state) { // If STOP then setup is finished, skip to next step if (state & FastPinType<START_STOP>::MASK) break; // If SELECT pushed, then change current LED status if (state & FastPinType<SELECT>::MASK) mux.data()[row] ^= _BV(col); // If NEXT/PREVIOUS then update blink if (state & FastPinType<NEXT>::MASK) { mux.blinks()[row] = 0; if (++col == COLUMNS) { col = 0; if (++row == ROWS) row = 0; } mux.blinks()[row] = _BV(col); } if (state & FastPinType<PREVIOUS>::MASK) { mux.blinks()[row] = 0; if (col == 0) { col = COLUMNS -1; if (row == 0) row = ROWS - 1; else --row; } else --col; mux.blinks()[row] = _BV(col); } } last_state = state; mux.blink(); Time::delay_ms(REFRESH_PERIOD_MS); } } // Step #2: Start game //===================== // Initialize game board GameOfLife game{mux.data()}; // Loop to light every LED for one second uint16_t progress_counter = 0; while (true) { mux.refresh(); Time::delay_ms(REFRESH_PERIOD_MS); if (++progress_counter == PROGRESS_COUNTER) { game.progress_game(); progress_counter = 0; //TODO Check if game is finished (ie no more live cell) } } return 0; } <commit_msg>Optimize code size.<commit_after>/* * Conway's Game of Life implementation with less than 1KB code. * Prototype is developed first with Arduino then ported to ATtiny84A. * * Description: * - cells are displayed on an 8x8 LED matrix * - initial setup is set through 2 pots (X and Y) and one button to select/unselect a cell * - starting/suspending the game is done by a second push button * - a 3rd pot allows speed tuning * * Circuit: * - MCU is connected to 2 chained 74HC595 SIPO * - First SIPO is connected to matrix columns through 8 330Ohm resistors * - Second SIPO is connected to matrix rows * * Wiring: * - on Arduino UNO: * - D2 is an output connected to both SIPO clock pins * - D3 is an output connected to both SIPO latch pins * - D4 is an output connected to first SIPO serial data input * - TODO LATER other pins for ADC pots and 2 push buttons * - on ATtinyX4 based boards: * - TODO */ #include <avr/interrupt.h> #include <util/delay.h> #include <fastarduino/time.hh> #include "Multiplexer.hh" #include "Buttons.hh" #if defined(ARDUINO_UNO) static constexpr const Board::DigitalPin CLOCK = Board::DigitalPin::D2; static constexpr const Board::DigitalPin LATCH = Board::DigitalPin::D3; static constexpr const Board::DigitalPin DATA = Board::DigitalPin::D4; static constexpr const Board::DigitalPin PREVIOUS = Board::DigitalPin::D5; static constexpr const Board::DigitalPin NEXT = Board::DigitalPin::D6; static constexpr const Board::DigitalPin SELECT = Board::DigitalPin::D7; static constexpr const Board::DigitalPin START_STOP = Board::DigitalPin::D0; #elif defined (BREADBOARD_ATTINYX4) static constexpr const Board::DigitalPin CLOCK = Board::DigitalPin::D0; static constexpr const Board::DigitalPin LATCH = Board::DigitalPin::D1; static constexpr const Board::DigitalPin DATA = Board::DigitalPin::D2; static constexpr const Board::DigitalPin PREVIOUS = Board::DigitalPin::D3; static constexpr const Board::DigitalPin NEXT = Board::DigitalPin::D4; static constexpr const Board::DigitalPin SELECT = Board::DigitalPin::D5; static constexpr const Board::DigitalPin START_STOP = Board::DigitalPin::D6; #else #error "Current target is not yet supported!" #endif // Single port used by this circuit static constexpr const Board::Port PORT = FastPinType<CLOCK>::PORT; // Check at compile time that all pins are on the same port static_assert(FastPinType<LATCH>::PORT == PORT, "LATCH must be on same port as CLOCK"); static_assert(FastPinType<DATA>::PORT == PORT, "DATA must be on same port as CLOCK"); static_assert(FastPinType<PREVIOUS>::PORT == PORT, "PREVIOUS must be on same port as CLOCK"); static_assert(FastPinType<NEXT>::PORT == PORT, "NEXT must be on same port as CLOCK"); static_assert(FastPinType<SELECT>::PORT == PORT, "SELECT must be on same port as CLOCK"); static_assert(FastPinType<START_STOP>::PORT == PORT, "START_STOP must be on same port as CLOCK"); // Timing constants // Multiplexing is done one row every 2ms, ie 8 rows in 16ms static constexpr const uint16_t REFRESH_PERIOD_MS = 2; // Blinking LEDs are toggled every 20 times the display is fully refreshed (ie 20 x 8 x 2ms = 320ms) static constexpr const uint8_t BLINKING_COUNTER = 20; // Buttons debouncing is done on a duration of 20ms static constexpr const uint8_t DEBOUNCE_TIME_MS = 20; static constexpr const uint8_t DEBOUNCE_COUNTER = DEBOUNCE_TIME_MS / REFRESH_PERIOD_MS; static constexpr const uint16_t PROGRESS_PERIOD_MS = 2000; static constexpr const uint16_t PROGRESS_COUNTER = PROGRESS_PERIOD_MS / REFRESH_PERIOD_MS; // Useful constants and types using MULTIPLEXER = Matrix8x8Multiplexer<CLOCK, LATCH, DATA, BLINKING_COUNTER>; static constexpr const uint8_t ROWS = MULTIPLEXER::ROWS; static constexpr const uint8_t COLUMNS = MULTIPLEXER::COLUMNS; // Calculate direction of pins (3 output, 4 input with pullups) static constexpr const uint8_t ALL_DDR = MULTIPLEXER::DDR_MASK; static constexpr const uint8_t BUTTONS_MASK = FastPinType<PREVIOUS>::MASK | FastPinType<NEXT>::MASK | FastPinType<SELECT>::MASK | FastPinType<START_STOP>::MASK; static constexpr const uint8_t ALL_PORT = MULTIPLEXER::PORT_MASK | BUTTONS_MASK; //TODO Make it a template based on game size (num rows, num columns) //TODO Make a class to hold one generation and access its members? class GameOfLife { public: GameOfLife(uint8_t game[ROWS]):_current_generation(game) {} void progress_game() { uint8_t next_generation[ROWS]; for (uint8_t row = 0; row < ROWS; ++row) for (uint8_t col = 0; col < COLUMNS; ++col) { uint8_t count_neighbours = neighbours(row, col); if (count_neighbours == 3) // cell is alive next_generation[row] |= _BV(col); else if (count_neighbours == 4) { // cell state is kept if (_current_generation[row] & _BV(col)) next_generation[row] |= _BV(col); else next_generation[row] &= ~_BV(col); } else // cell state is dead next_generation[row] &= ~_BV(col); } // Copy next generation to current one for (uint8_t row = 0; row < ROWS; ++row) _current_generation[row] = next_generation[row]; } private: static uint8_t neighbours_in_row(uint8_t game_row, uint8_t col) { //TODO possibly optimize by: // - copy row to GPIOR0 // - rotate GPIOR (col+1) times // check individual bits 0, 1 and 2 uint8_t count = (game_row & _BV(col)) ? 1 : 0; if (game_row & _BV(col ? col - 1 : COLUMNS - 1)) ++count; if (game_row & _BV(col == COLUMNS - 1 ? 0 : col + 1)) ++count; return count; } uint8_t neighbours(uint8_t row, uint8_t col) { uint8_t count = neighbours_in_row(row ? _current_generation[row - 1] : _current_generation[ROWS - 1], col); count += neighbours_in_row(row == ROWS - 1 ? _current_generation[0] : _current_generation[row + 1], col); count += neighbours_in_row(_current_generation[row], col); return count; } uint8_t* _current_generation; }; // OPEN POINTS/TODO // - Improve (use templates) to allow larger matrix size (eg 16x8, 16x16) int main() __attribute__((OS_main)); int main() { // Enable interrupts at startup time sei(); // Initialize all pins (only one port) FastPort<PORT>{ALL_DDR, ALL_PORT}; // Initialize Multiplexer MULTIPLEXER mux; //TODO optimize if else maybe // Step #1: Initialize board with 1st generation //=============================================== { Buttons<PORT, BUTTONS_MASK, DEBOUNCE_COUNTER> buttons; uint8_t row = 0; uint8_t col = 0; mux.blinks()[0] = _BV(0); uint8_t last_state = 0; while (true) { // Check button states uint8_t state = buttons.state(); if (state && state != last_state) { // If STOP then setup is finished, skip to next step if (state & FastPinType<START_STOP>::MASK) break; // If SELECT pushed, then change current LED status if (state & FastPinType<SELECT>::MASK) mux.data()[row] ^= _BV(col); // If NEXT/PREVIOUS then update blink mux.blinks()[row] = 0; if (state & FastPinType<NEXT>::MASK) { if (++col == COLUMNS) { col = 0; if (++row == ROWS) row = 0; } } if (state & FastPinType<PREVIOUS>::MASK) { if (col == 0) { col = COLUMNS -1; if (row == 0) row = ROWS - 1; else --row; } else --col; } mux.blinks()[row] = _BV(col); } last_state = state; mux.blink(); Time::delay_ms(REFRESH_PERIOD_MS); } } // Step #2: Start game //===================== // Initialize game board GameOfLife game{mux.data()}; // Loop to light every LED for one second uint16_t progress_counter = 0; while (true) { mux.refresh(); Time::delay_ms(REFRESH_PERIOD_MS); if (++progress_counter == PROGRESS_COUNTER) { game.progress_game(); progress_counter = 0; //TODO Check if game is finished (ie no more live cell) } } return 0; } <|endoftext|>
<commit_before>#define BT_USE_DOUBLE_PRECISION #include "BulletElement.h" #include "BulletModel.h" using namespace std; namespace DrakeCollision { BulletElement::BulletElement(const Matrix4d& T_elem_to_link, Shape shape, const vector<double>& params) : Element(T_elem_to_link, shape, params) { //DEBUG //std::cout << "BulletElement::BulletElement: START" << std::endl; //END_DEBUG btCollisionShape* bt_shape; switch (shape) { case BOX: //DEBUG //std::cout << "BulletElement::BulletElement: Create BOX ..." << std::endl; //END_DEBUG bt_shape = new btBoxShape( btVector3(params[0]/2,params[1]/2,params[2]/2) ); bt_shape->setMargin(0.0); //DEBUG //std::cout << "BulletElement::BulletElement: Created BOX" << std::endl; //END_DEBUG break; case SPHERE: if (true || params[0] != 0) { //DEBUG //std::cout << "BulletElement::BulletElement: Create SPHERE ..." << std::endl; //END_DEBUG bt_shape = new btSphereShape(params[0]) ; //DEBUG //std::cout << "BulletElement::BulletElement: Created SPHERE" << std::endl; //END_DEBUG } else { //DEBUG //std::cout << "BulletElement::BulletElement: THROW" << std::endl; //END_DEBUG throw zeroRadiusSphereException(); } break; case CYLINDER: //DEBUG //std::cout << "BulletElement::BulletElement: Create CYLINDER ..." << std::endl; //END_DEBUG bt_shape = new btCylinderShapeZ( btVector3(params[0],params[0],params[1]/2) ); bt_shape->setMargin(0.05); //DEBUG //std::cout << "BulletElement::BulletElement: Created CYLINDER ..." << std::endl; //END_DEBUG break; case MESH: //DEBUG //std::cout << "BulletElement::BulletElement: Create MESH ..." << std::endl; //END_DEBUG //bt_shape = new btConvexHullShape( (btScalar*) params.data(), //params.size()/3, //(int) 3*sizeof(double) ); bt_shape = new btConvexHullShape(); bt_shape->setMargin(0.05); for (int i=0; i<params.size(); i+=3){ //DEBUG //std::cout << "BulletElement::BulletElement: Adding point " << i/3 + 1 << std::endl; //END_DEBUG dynamic_cast<btConvexHullShape*>(bt_shape)->addPoint(btVector3(params[i],params[i+1],params[i+2])); } //DEBUG //std::cout << "BulletElement::BulletElement: Created MESH ..." << std::endl; //END_DEBUG break; default: cerr << "Warning: Collision element has an unknown type " << shape << endl; //DEBUG //std::cout << "BulletElement::BulletElement: THROW" << std::endl; //END_DEBUG throw unknownShapeException(shape); break; } //DEBUG //cout << "BulletElement::BulletElement: Creating btCollisionObject" << endl; //END_DEBUG bt_obj = make_shared<btCollisionObject>(); //DEBUG //cout << "BulletElement::BulletElement: Setting bt_shape for bt_ob" << endl; //END_DEBUG bt_obj->setCollisionShape(bt_shape); //DEBUG //cout << "BulletElement::BulletElement: Setting world transform for bt_ob" << endl; //END_DEBUG setWorldTransform(this->T_elem_to_world); //DEBUG //std::cout << "BulletElement::BulletElement: END" << std::endl; //END_DEBUG } void BulletElement::setWorldTransform(const Matrix4d& T) { Element::setWorldTransform(T); btMatrix3x3 rot; btVector3 pos; btTransform btT; rot.setValue( T(0,0), T(0,1), T(0,2), T(1,0), T(1,1), T(1,2), T(2,0), T(2,1), T(2,2) ); btT.setBasis(rot); pos.setValue( T(0,3), T(1,3), T(2,3) ); btT.setOrigin(pos); bt_obj->setWorldTransform(btT); } } <commit_msg>Treat cylinders as capsules.<commit_after>#define BT_USE_DOUBLE_PRECISION #include "BulletElement.h" #include "BulletModel.h" using namespace std; namespace DrakeCollision { BulletElement::BulletElement(const Matrix4d& T_elem_to_link, Shape shape, const vector<double>& params) : Element(T_elem_to_link, shape, params) { //DEBUG //std::cout << "BulletElement::BulletElement: START" << std::endl; //END_DEBUG btCollisionShape* bt_shape; switch (shape) { case BOX: //DEBUG //std::cout << "BulletElement::BulletElement: Create BOX ..." << std::endl; //END_DEBUG bt_shape = new btBoxShape( btVector3(params[0]/2,params[1]/2,params[2]/2) ); bt_shape->setMargin(0.0); //DEBUG //std::cout << "BulletElement::BulletElement: Created BOX" << std::endl; //END_DEBUG break; case SPHERE: if (true || params[0] != 0) { //DEBUG //std::cout << "BulletElement::BulletElement: Create SPHERE ..." << std::endl; //END_DEBUG bt_shape = new btSphereShape(params[0]) ; //DEBUG //std::cout << "BulletElement::BulletElement: Created SPHERE" << std::endl; //END_DEBUG } else { //DEBUG //std::cout << "BulletElement::BulletElement: THROW" << std::endl; //END_DEBUG throw zeroRadiusSphereException(); } break; case CYLINDER: //DEBUG //std::cout << "BulletElement::BulletElement: Create CYLINDER ..." << std::endl; //END_DEBUG //bt_shape = new btCapsuleShapeZ(params[0],params[1]); bt_shape = new btConvexHullShape(); dynamic_cast<btConvexHullShape*>(bt_shape)->addPoint(btVector3(0,0,-params[1]/2)); dynamic_cast<btConvexHullShape*>(bt_shape)->addPoint(btVector3(0,0,params[1]/2)); bt_shape->setMargin(params[0]); //bt_shape = new btCylinderShapeZ( btVector3(params[0],params[0],params[1]/2) ); //bt_shape->setMargin(0.01); //DEBUG //std::cout << "BulletElement::BulletElement: Created CYLINDER ..." << std::endl; //END_DEBUG break; case MESH: //DEBUG //std::cout << "BulletElement::BulletElement: Create MESH ..." << std::endl; //END_DEBUG //bt_shape = new btConvexHullShape( (btScalar*) params.data(), //params.size()/3, //(int) 3*sizeof(double) ); bt_shape = new btConvexHullShape(); bt_shape->setMargin(0.05); for (int i=0; i<params.size(); i+=3){ //DEBUG //std::cout << "BulletElement::BulletElement: Adding point " << i/3 + 1 << std::endl; //END_DEBUG dynamic_cast<btConvexHullShape*>(bt_shape)->addPoint(btVector3(params[i],params[i+1],params[i+2])); } //DEBUG //std::cout << "BulletElement::BulletElement: Created MESH ..." << std::endl; //END_DEBUG break; default: cerr << "Warning: Collision element has an unknown type " << shape << endl; //DEBUG //std::cout << "BulletElement::BulletElement: THROW" << std::endl; //END_DEBUG throw unknownShapeException(shape); break; } //DEBUG //cout << "BulletElement::BulletElement: Creating btCollisionObject" << endl; //END_DEBUG bt_obj = make_shared<btCollisionObject>(); //DEBUG //cout << "BulletElement::BulletElement: Setting bt_shape for bt_ob" << endl; //END_DEBUG bt_obj->setCollisionShape(bt_shape); //DEBUG //cout << "BulletElement::BulletElement: Setting world transform for bt_ob" << endl; //END_DEBUG setWorldTransform(this->T_elem_to_world); //DEBUG //std::cout << "BulletElement::BulletElement: END" << std::endl; //END_DEBUG } void BulletElement::setWorldTransform(const Matrix4d& T) { Element::setWorldTransform(T); btMatrix3x3 rot; btVector3 pos; btTransform btT; rot.setValue( T(0,0), T(0,1), T(0,2), T(1,0), T(1,1), T(1,2), T(2,0), T(2,1), T(2,2) ); btT.setBasis(rot); pos.setValue( T(0,3), T(1,3), T(2,3) ); btT.setOrigin(pos); bt_obj->setWorldTransform(btT); } } <|endoftext|>
<commit_before>/* * Copyright (c) 2015 Florian Behrens * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define BOOST_TEST_DYN_LINK #include <decof/all.h> #include <decof/client_context/client_context.h> #include <boost/test/unit_test.hpp> #include <memory> BOOST_AUTO_TEST_SUITE(object_dictionary) struct fixture { struct my_context_t : public decof::client_context { using decof::client_context::client_context; void get_parameter(const std::string& uri, char separator = ':') { decof::client_context::get_parameter(uri, separator); } }; fixture() : obj_dict("root"), node1(new decof::node("node1", &obj_dict)), node2(new decof::node("node2", node1.get())), param("param", node2.get(), "Hello World"), my_context(new my_context_t(obj_dict)) { } decof::object_dictionary obj_dict; std::unique_ptr<decof::node> node1, node2; decof::managed_readonly_parameter<std::string> param; std::shared_ptr<my_context_t> my_context; }; BOOST_FIXTURE_TEST_CASE(find_root_object, fixture) { try { my_context->get_parameter("root"); } catch (std::exception& ex) { BOOST_FAIL(ex.what()); } catch (...) { BOOST_FAIL("Unknown exception occurred"); } } BOOST_FIXTURE_TEST_CASE(find_child_object, fixture) { try { my_context->get_parameter("root:node1:node2:param"); } catch (std::exception& ex) { BOOST_FAIL(ex.what()); } catch (...) { BOOST_FAIL("Unknown exception occurred"); } } BOOST_FIXTURE_TEST_CASE(find_child_object_with_custom_separator, fixture) { try { my_context->get_parameter("root&node1&node2&param", '&'); } catch (std::exception& ex) { BOOST_FAIL(ex.what()); } catch (...) { BOOST_FAIL("Unknown exception occurred"); } } BOOST_FIXTURE_TEST_CASE(delete_middle_node, fixture) { node1.reset(); node2.reset(); } BOOST_FIXTURE_TEST_CASE(set_parameter_value, fixture) { std::string str("Hello"); param.value(str); BOOST_REQUIRE_EQUAL(str, param.value()); } BOOST_FIXTURE_TEST_CASE(move_parameter_value, fixture) { std::string str("Hello"); std::string str2(str); param.value(std::move(str2)); BOOST_REQUIRE_EQUAL(str, param.value()); BOOST_REQUIRE_NE(str2, param.value()); } BOOST_FIXTURE_TEST_CASE(get_object_dictionary, fixture) { auto od = param.get_object_dictionary(); BOOST_REQUIRE(od != nullptr); BOOST_REQUIRE_EQUAL(od->name(), std::string("root")); } BOOST_FIXTURE_TEST_CASE(get_const_object_dictionary, fixture) { const decof::managed_readonly_parameter<std::string>& rparam = param; auto od = rparam.get_object_dictionary(); BOOST_REQUIRE(od != nullptr); BOOST_REQUIRE_EQUAL(od->name(), std::string("root")); } BOOST_AUTO_TEST_CASE(add_and_remove_child_to_node) { decof::node node("node"); decof::managed_readonly_parameter<bool> parameter("parameter", nullptr); node.add_child(&parameter); BOOST_REQUIRE_EQUAL(node.children().size(), 1); BOOST_REQUIRE_EQUAL(parameter.parent(), &node); node.remove_child(&parameter); BOOST_REQUIRE_EQUAL(node.children().size(), 0); BOOST_REQUIRE(parameter.parent() == nullptr); } BOOST_AUTO_TEST_CASE(set_and_reset_parent) { decof::node node("node"); decof::managed_readonly_parameter<bool> parameter("parameter", nullptr); parameter.reset_parent(&node); BOOST_REQUIRE_EQUAL(node.children().size(), 1); BOOST_REQUIRE_EQUAL(parameter.parent(), &node); parameter.reset_parent(); BOOST_REQUIRE_EQUAL(node.children().size(), 0); BOOST_REQUIRE(parameter.parent() == nullptr); } BOOST_AUTO_TEST_SUITE_END() <commit_msg>Simplified some testcases.<commit_after>/* * Copyright (c) 2015 Florian Behrens * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define BOOST_TEST_DYN_LINK #include <decof/all.h> #include <decof/client_context/client_context.h> #include <boost/test/unit_test.hpp> #include <memory> BOOST_AUTO_TEST_SUITE(object_dictionary) struct fixture { struct my_context_t : public decof::client_context { using decof::client_context::client_context; void get_parameter(const std::string& uri, char separator = ':') { decof::client_context::get_parameter(uri, separator); } }; fixture() : obj_dict("root"), node1(new decof::node("node1", &obj_dict)), node2(new decof::node("node2", node1.get())), param("param", node2.get(), "Hello World"), my_context(new my_context_t(obj_dict)) { } decof::object_dictionary obj_dict; std::unique_ptr<decof::node> node1, node2; decof::managed_readonly_parameter<std::string> param; std::shared_ptr<my_context_t> my_context; }; BOOST_FIXTURE_TEST_CASE(find_root_object, fixture) { my_context->get_parameter("root"); } BOOST_FIXTURE_TEST_CASE(find_child_object, fixture) { my_context->get_parameter("root:node1:node2:param"); } BOOST_FIXTURE_TEST_CASE(find_child_object_with_custom_separator, fixture) { my_context->get_parameter("root&node1&node2&param", '&'); } BOOST_FIXTURE_TEST_CASE(delete_middle_node, fixture) { node1.reset(); node2.reset(); } BOOST_FIXTURE_TEST_CASE(set_parameter_value, fixture) { std::string str("Hello"); param.value(str); BOOST_REQUIRE_EQUAL(str, param.value()); } BOOST_FIXTURE_TEST_CASE(move_parameter_value, fixture) { std::string str("Hello"); std::string str2(str); param.value(std::move(str2)); BOOST_REQUIRE_EQUAL(str, param.value()); BOOST_REQUIRE_NE(str2, param.value()); } BOOST_FIXTURE_TEST_CASE(get_object_dictionary, fixture) { auto od = param.get_object_dictionary(); BOOST_REQUIRE(od != nullptr); BOOST_REQUIRE_EQUAL(od->name(), std::string("root")); } BOOST_FIXTURE_TEST_CASE(get_const_object_dictionary, fixture) { const decof::managed_readonly_parameter<std::string>& rparam = param; auto od = rparam.get_object_dictionary(); BOOST_REQUIRE(od != nullptr); BOOST_REQUIRE_EQUAL(od->name(), std::string("root")); } BOOST_AUTO_TEST_CASE(add_and_remove_child_to_node) { decof::node node("node"); decof::managed_readonly_parameter<bool> parameter("parameter", nullptr); node.add_child(&parameter); BOOST_REQUIRE_EQUAL(node.children().size(), 1); BOOST_REQUIRE_EQUAL(parameter.parent(), &node); node.remove_child(&parameter); BOOST_REQUIRE_EQUAL(node.children().size(), 0); BOOST_REQUIRE(parameter.parent() == nullptr); } BOOST_AUTO_TEST_CASE(set_and_reset_parent) { decof::node node("node"); decof::managed_readonly_parameter<bool> parameter("parameter", nullptr); parameter.reset_parent(&node); BOOST_REQUIRE_EQUAL(node.children().size(), 1); BOOST_REQUIRE_EQUAL(parameter.parent(), &node); parameter.reset_parent(); BOOST_REQUIRE_EQUAL(node.children().size(), 0); BOOST_REQUIRE(parameter.parent() == nullptr); } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>/* Filename: algorithm.cpp Author: Dhruv Somani and Khush Jain */ #include <iostream> #include <sstream> #include <algorithm> #include <string> #include <vector> #include <map> #include <cmath> #include <assert.h> using namespace std; vector<string> solvePuzzle(string state); vector<string> reconstructPath(map<string, string> cameFrom, string current); vector<string> findNeighbors(string state); float calcfScore(string state); string to_string(int i); int main() { // For Testing Purposes, otherwise we don't need this function string state; getline(cin, state); vector<string> solution = solvePuzzle(state); cout << "Solution:" << endl; for (int index = 0; index < solution.size(); index++) cout << solution[index] << endl; return 0; } vector<string> solvePuzzle(string state) { assert (state.length() == 9); vector<string> frontier; vector<string> visited; map<string, string> cameFrom; frontier.push_back(state); map<string, float> fScore; map<string, int> gScore; gScore[state] = 0; while (frontier.size() > 0) { int best_choice = 0; float minimum = 120; for (int index = 0; index < frontier.size(); index++) { if (fScore[frontier[index]] < minimum) { best_choice = index; minimum = fScore[frontier[index]]; } } string curr_state = frontier[best_choice]; frontier.erase(frontier.begin() + best_choice); visited.push_back(curr_state); // DEBUGGING /* cout << endl << curr_state << endl;// << "Visited: "; //for (int index = 0; index < visited.size(); index++) cout << visited[index]; cout << endl << "Frontier: "; for (int index = 0; index < frontier.size(); index++) cout << frontier[index] << " "; cout << endl; */ if (curr_state == "123456780") { vector<string> path = reconstructPath(cameFrom, curr_state); cout << "No. of fScore's Taken: " << fScore.size() << endl; return path; } vector<string> neighbors = findNeighbors(curr_state); for (unsigned int index = 0; index < neighbors.size(); index++) { string neighbor = neighbors[index]; //cout << neighbor; if (find(visited.begin(), visited.end(), neighbor) != visited.end()) { //cout << " terminated in visited." << endl; continue; } if (find(frontier.begin(), frontier.end(), neighbor) == frontier.end()) { //cout << " " << "State not yet Visited. State inserted in Frontier." << endl; frontier.push_back(neighbor); } else if ((gScore[curr_state] + 1) >= gScore[neighbor]) { //cout << " terminated due to idiotic reasons." << endl; continue; } // This path is the best until now. Record it! cameFrom[neighbor] = curr_state; gScore[neighbor] = gScore[curr_state] + 1; fScore[neighbor] = calcfScore(neighbor) + gScore[neighbor]; } // mapping >>>>>>>>>>>>>>>>>>>>>>>>>>> //for (std::map<string,float>::iterator it=fScore.begin(); it!=fScore.end(); ++it) { // std::cout << it->first << " => " << it->second << '\n';} //cout << endl; } return vector<string>(); } vector<string> reconstructPath(map<string, string> cameFrom, string current) { vector<string> totalPath; totalPath.push_back(current); while (cameFrom.find(current) != cameFrom.end()) { current = cameFrom[current]; totalPath.insert(totalPath.begin(), current); } return totalPath; } float calcfScore(string state) { float fScore = 0; string finalState = "123456780"; for (int index = 1; index < 9; index++) { int req_loc = finalState.find(to_string(index)); int loc = state.find(to_string(index)); //cout << index << req_loc << loc << endl; fScore += abs(req_loc % 3 - loc % 3) + abs(static_cast<int>(req_loc/3) - static_cast<int>(loc/3)); for (int smallIndex = (index - 1 - ((index - 1) % 3)); smallIndex < (index - 1 - ((index - 1) % 3)) + 3; smallIndex++) { if (smallIndex == index) continue; if ((smallIndex < index) & (state[smallIndex] > state[index]) & (state[smallIndex] < (index - 1 - ((index - 1) % 3)) + 3)) fScore += 2; if ((smallIndex > index) & (state[smallIndex] < state[index]) & (state[smallIndex] > (index - 1 - ((index - 1) % 3)))) fScore += 2; } } return fScore; } vector<string> findNeighbors(string state) { vector<string> neighbors; int index = state.find('0'); if (index % 3 < 2) { string temp_state = state; temp_state[index] = state[index + 1]; temp_state[index + 1] = '0'; neighbors.push_back(temp_state); } if (index % 3 > 0) { string temp_state = state; temp_state[index] = state[index - 1]; temp_state[index - 1] = '0'; neighbors.push_back(temp_state); } if (index > 2) { string temp_state = state; temp_state[index] = state[index - 3]; temp_state[index - 3] = '0'; neighbors.push_back(temp_state); } if (index < 6) { string temp_state = state; temp_state[index] = state[index + 3]; temp_state[index + 3] = '0'; neighbors.push_back(temp_state); } return neighbors; } string to_string(int i) { stringstream ss; ss << i; return ss.str(); } <commit_msg>First Commit to solving 15-puzzles.<commit_after>/* Filename: algorithm.cpp Author: Dhruv Somani and Khush Jain */ #include <iostream> #include <sstream> #include <algorithm> #include <string> #include <vector> #include <map> #include <cmath> #include <ctype.h> #include <assert.h> using namespace std; vector<string> solve8Puzzle(string state); vector<string> solve15Puzzle(string state); vector<string> reconstructPath(map<string, string> cameFrom, string current); vector<string> find8Neighbors(string state); vector<string> find15Neighbors(string state); float calc8fScore(string state); float calc15fScore(string state); string to_string(int i); int main() { string state; getline(cin, state); cout << endl; vector<string> solution = solve15Puzzle(state); cout << "Solution:" << endl; for (int index = 0; index < solution.size(); index++) cout << solution[index].substr(0, 4) << endl << solution[index].substr(4, 4) << endl << solution[index].substr(8, 4) << endl << solution[index].substr(12, 4) << endl << endl; cout << "Length: " << solution.size() - 1; return 0; } vector<string> solve8Puzzle(string state) { assert (state.length() == 9); vector<string> frontier; vector<string> visited; map<string, string> cameFrom; frontier.push_back(state); map<string, float> fScore; map<string, int> gScore; gScore[state] = 0; while (frontier.size() > 0) { int best_choice = 0; float minimum = 120; for (int index = 0; index < frontier.size(); index++) { if (fScore[frontier[index]] < minimum) { best_choice = index; minimum = fScore[frontier[index]]; } } string curr_state = frontier[best_choice]; frontier.erase(frontier.begin() + best_choice); visited.push_back(curr_state); // DEBUGGING /* cout << endl << curr_state << endl;// << "Visited: "; for (int index = 0; index < visited.size(); index++) cout << visited[index]; cout << endl << "Frontier: "; for (int index = 0; index < frontier.size(); index++) cout << frontier[index] << " "; cout << endl; */ if (curr_state == "123456780") { vector<string> path = reconstructPath(cameFrom, curr_state); cout << "No. of fScore's Taken: " << fScore.size() << endl; return path; } vector<string> neighbors = find8Neighbors(curr_state); for (unsigned int index = 0; index < neighbors.size(); index++) { string neighbor = neighbors[index]; if (find(visited.begin(), visited.end(), neighbor) != visited.end()) continue; if (find(frontier.begin(), frontier.end(), neighbor) == frontier.end())frontier.push_back(neighbor); else if ((gScore[curr_state] + 1) >= gScore[neighbor]) continue; // This path is the best until now. Record it! cameFrom[neighbor] = curr_state; gScore[neighbor] = gScore[curr_state] + 1; fScore[neighbor] = calc8fScore(neighbor) + gScore[neighbor]; } // mapping >>>>>>>>>>>>>>>>>>>>>>>>>>> //for (std::map<string,float>::iterator it=fScore.begin(); it!=fScore.end(); ++it) { // std::cout << it->first << " => " << it->second << '\n';} //cout << endl; } return vector<string>(); } vector<string> solve15Puzzle(string state) { assert (state.length() == 16); for (int i = 0; i < state.length(); i++) state[i] = toupper(static_cast<int>(state[i])); // Capitalizing the string vector<string> frontier; vector<string> visited; map<string, string> cameFrom; frontier.push_back(state); map<string, float> fScore; map<string, int> gScore; gScore[state] = 0; while (frontier.size() > 0) { int best_choice = 0; float minimum = 400; for (int index = 0; index < frontier.size(); index++) { if (fScore[frontier[index]] < minimum) { best_choice = index; minimum = fScore[frontier[index]]; } } string curr_state = frontier[best_choice]; frontier.erase(frontier.begin() + best_choice); visited.push_back(curr_state); // DEBUGGING /* cout << endl << curr_state << endl;// << "Visited: "; for (int index = 0; index < visited.size(); index++) cout << visited[index]; cout << endl << "Frontier: "; for (int index = 0; index < frontier.size(); index++) cout << frontier[index] << " "; cout << endl; */ if (curr_state == "123456789ABCDEF0") { vector<string> path = reconstructPath(cameFrom, curr_state); cout << "No. of fScore's Taken: " << fScore.size() << endl; return path; } vector<string> neighbors = find15Neighbors(curr_state); for (unsigned int index = 0; index < neighbors.size(); index++) { string neighbor = neighbors[index]; if (find(visited.begin(), visited.end(), neighbor) != visited.end()) continue; if (find(frontier.begin(), frontier.end(), neighbor) == frontier.end()) frontier.push_back(neighbor); else if ((gScore[curr_state] + 1) >= gScore[neighbor]) continue; // This path is the best until now. Record it! cameFrom[neighbor] = curr_state; gScore[neighbor] = gScore[curr_state] + 1; fScore[neighbor] = calc15fScore(neighbor) + gScore[neighbor]; } // mapping >>>>>>>>>>>>>>>>>>>>>>>>>>> //for (std::map<string,float>::iterator it=fScore.begin(); it!=fScore.end(); ++it) { // std::cout << it->first << " => " << it->second << '\n';} //cout << endl; } return vector<string>(); } vector<string> reconstructPath(map<string, string> cameFrom, string current) { vector<string> totalPath; totalPath.push_back(current); while (cameFrom.find(current) != cameFrom.end()) { current = cameFrom[current]; totalPath.insert(totalPath.begin(), current); } return totalPath; } float calc8fScore(string state) { float fScore = 0; string finalState = "123456780"; for (int index = 1; index < 9; index++) { int req_loc = finalState.find(to_string(index)); int loc = state.find(to_string(index)); fScore += abs(req_loc % 3 - loc % 3) + abs(static_cast<int>(req_loc/3) - static_cast<int>(loc/3)); for (int smallIndex = (index - 1 - ((index - 1) % 3)); smallIndex < (index - 1 - ((index - 1) % 3)) + 3; smallIndex++) { if (smallIndex == index) continue; if ((smallIndex < index) & (state[smallIndex] > state[index]) & (state[smallIndex] < (index - 1 - ((index - 1) % 3)) + 3)) fScore += 2; if ((smallIndex > index) & (state[smallIndex] < state[index]) & (state[smallIndex] > (index - 1 - ((index - 1) % 3)))) fScore += 2; } } return fScore; } float calc15fScore(string state) { float fScore = 0; string finalState = "123456789ABCDEF0"; for (int index = 1; index < 16; index++) { int req_loc = finalState.find(finalState[index - 1]); int loc = state.find(finalState[index - 1]); fScore += abs(req_loc % 4 - loc % 4) + abs(static_cast<int>(req_loc/4) - static_cast<int>(loc/4)); /* for (int smallIndex = (index - 1 - ((index - 1) % 4)); smallIndex < (index - 1 - ((index - 1) % 4)) + 4; smallIndex++) { if (smallIndex == index) continue; if ((smallIndex < index) & (state[smallIndex] > state[index]) & (state[smallIndex] < (index - 1 - ((index - 1) % 4)) + 4)) fScore += 2; if ((smallIndex > index) & (state[smallIndex] < state[index]) & (state[smallIndex] > (index - 1 - ((index - 1) % 4)))) fScore += 2; } */ } return fScore; } vector<string> find8Neighbors(string state) { vector<string> neighbors; int index = state.find('0'); if (index % 3 < 2) { string temp_state = state; temp_state[index] = state[index + 1]; temp_state[index + 1] = '0'; neighbors.push_back(temp_state); } if (index % 3 > 0) { string temp_state = state; temp_state[index] = state[index - 1]; temp_state[index - 1] = '0'; neighbors.push_back(temp_state); } if (index > 2) { string temp_state = state; temp_state[index] = state[index - 3]; temp_state[index - 3] = '0'; neighbors.push_back(temp_state); } if (index < 6) { string temp_state = state; temp_state[index] = state[index + 3]; temp_state[index + 3] = '0'; neighbors.push_back(temp_state); } return neighbors; } vector<string> find15Neighbors(string state) { vector<string> neighbors; int index = state.find('0'); if (index % 4 < 3) { string temp_state = state; temp_state[index] = state[index + 1]; temp_state[index + 1] = '0'; neighbors.push_back(temp_state); } if (index % 4 > 0) { string temp_state = state; temp_state[index] = state[index - 1]; temp_state[index - 1] = '0'; neighbors.push_back(temp_state); } if (index > 3) { string temp_state = state; temp_state[index] = state[index - 4]; temp_state[index - 4] = '0'; neighbors.push_back(temp_state); } if (index < 12) { string temp_state = state; temp_state[index] = state[index + 4]; temp_state[index + 4] = '0'; neighbors.push_back(temp_state); } return neighbors; } string to_string(int i) { stringstream ss; ss << i; return ss.str(); } <|endoftext|>
<commit_before>/**********************************************************\ tests/SimpleHashTester.cpp \**********************************************************/ #include "TestSettings.h" #ifdef TEST_SIMPLE_HASH #undef NDEBUG #include "../../momo/HashSet.h" #include "../../momo/HashMap.h" #include "../../momo/HashMultiMap.h" #include "../../momo/HashBuckets/BucketLim4.h" #include <string> #include <iostream> #include <random> class SimpleHashTester { private: template<size_t size, size_t alignment> class VarItem { public: template<typename HashBucket> class HashTraits : public momo::HashTraits<VarItem, HashBucket> { public: size_t GetHashCode(const VarItem& key) const { return std::hash<unsigned char>()(key.GetValue()); } bool IsEqual(const VarItem& key1, const VarItem& key2) const { return key1.GetValue() == key2.GetValue(); } }; public: explicit VarItem(unsigned char value) MOMO_NOEXCEPT { *(unsigned char*)&mStorage = value; } unsigned char GetValue() const MOMO_NOEXCEPT { return *(unsigned char*)&mStorage; } private: std::aligned_storage<size, alignment> mStorage; }; public: static void TestAll() { //TestVarAll(); TestStrAll(); } static void TestVarAll() { TestVarHash<momo::HashBucketOneI1>("momo::HashBucketOneI1"); TestVarHash<momo::HashBucketLimP1<1, 1, 32>>("momo::HashBucketLimP1<1, 1, 32>"); TestVarHash<momo::HashBucketLimP1<2, 1, 1>>("momo::HashBucketLimP1<2, 1, 1>"); TestVarHash<momo::HashBucketLimP1<3, 1, 2>>("momo::HashBucketLimP1<3, 1, 2>"); TestVarHash<momo::HashBucketLimP1<4, 1, 4>>("momo::HashBucketLimP1<4, 1, 4>"); TestVarHash<momo::HashBucketLimP1<5, 1, 64>>("momo::HashBucketLimP1<5, 1, 64>"); TestVarHash<momo::HashBucketLimP1<7, 1, 3>>("momo::HashBucketLimP1<7, 1, 3>"); TestVarHash<momo::HashBucketLimP1<10, 1, 127>>("momo::HashBucketLimP1<10, 1, 127>"); TestVarHash<momo::HashBucketLimP1<15, 1, 1>>("momo::HashBucketLimP1<15, 1, 1>"); TestVarHash<momo::HashBucketLimP<1, 32>>("momo::HashBucketLimP<1, 32>"); TestVarHash<momo::HashBucketLimP<2, 1>>("momo::HashBucketLimP<2, 1>"); TestVarHash<momo::HashBucketLimP<3, 2>>("momo::HashBucketLimP<3, 2>"); TestVarHash<momo::HashBucketLimP<4, 4>>("momo::HashBucketLimP<4, 4>"); TestVarHash<momo::HashBucketLimP<5, 64>>("momo::HashBucketLimP<5, 64>"); TestVarHash<momo::HashBucketLimP<7, 3>>("momo::HashBucketLimP<7, 3>"); TestVarHash<momo::HashBucketLimP<10, 127>>("momo::HashBucketLimP<10, 127>"); TestVarHash<momo::HashBucketLimP<15, 1>>("momo::HashBucketLimP<15, 1>"); TestVarHash<momo::HashBucketUnlimP<1, 32>>("momo::HashBucketUnlimP<1, 32>"); TestVarHash<momo::HashBucketUnlimP<2, 1>>("momo::HashBucketUnlimP<2, 1>"); TestVarHash<momo::HashBucketUnlimP<3, 2>>("momo::HashBucketUnlimP<3, 2>"); TestVarHash<momo::HashBucketUnlimP<4, 4>>("momo::HashBucketUnlimP<4, 4>"); TestVarHash<momo::HashBucketUnlimP<5, 64>>("momo::HashBucketUnlimP<5, 64>"); TestVarHash<momo::HashBucketUnlimP<7, 3>>("momo::HashBucketUnlimP<7, 3>"); TestVarHash<momo::HashBucketUnlimP<10, 127>>("momo::HashBucketUnlimP<10, 127>"); TestVarHash<momo::HashBucketUnlimP<15, 1>>("momo::HashBucketUnlimP<15, 1>"); TestVarHash<momo::HashBucketLim4<1, 32>>("momo::HashBucketLim4<1, 32>"); TestVarHash<momo::HashBucketLim4<2, 1>>("momo::HashBucketLim4<2, 1>"); TestVarHash<momo::HashBucketLim4<3, 127>>("momo::HashBucketLim4<3, 127>"); TestVarHash<momo::HashBucketLim4<7, 2>>("momo::HashBucketLim4<7, 2>"); } template<typename HashBucket> static void TestVarHash(const char* bucketName) { TestVarHashSet<HashBucket, VarItem<1, 1>>(bucketName, "VarItem<1, 1>"); TestVarHashSet<HashBucket, VarItem<2, 1>>(bucketName, "VarItem<2, 1>"); } template<typename HashBucket, typename VarItem> static void TestVarHashSet(const char* bucketName, const char* varItemName) { std::cout << bucketName << ": " << varItemName << ": " << std::flush; static const size_t count = 256; static unsigned char array[count]; for (size_t i = 0; i < count; ++i) array[i] = (unsigned char)i; typedef momo::HashSet<VarItem, typename VarItem::template HashTraits<HashBucket>> HashSet; HashSet set; std::shuffle(array, array + count, std::mt19937()); for (unsigned char c : array) assert(set.Insert(VarItem(c)).inserted); assert(set.GetCount() == count); std::shuffle(array, array + count, std::mt19937()); for (unsigned char c : array) assert(set.Remove(VarItem(c))); assert(set.IsEmpty()); std::cout << "ok" << std::endl; } static void TestStrAll() { TestStrHash<momo::HashBucketOneI1>("momo::HashBucketOneI1"); TestStrHash<momo::HashBucketLimP1<>>("momo::HashBucketLimP1<>"); TestStrHash<momo::HashBucketLimP<>>("momo::HashBucketLimP<>"); TestStrHash<momo::HashBucketUnlimP<>>("momo::HashBucketUnlimP<>"); TestStrHash<momo::HashBucketLim4<>>("momo::HashBucketLim4<>"); } template<typename HashBucket> static void TestStrHash(const char* bucketName) { std::cout << bucketName << ": HashSet: " << std::flush; TestStrHashSet<HashBucket>(); std::cout << "ok" << std::endl; std::cout << bucketName << ": HashMap: " << std::flush; TestStrHashMap<HashBucket>(); std::cout << "ok" << std::endl; std::cout << bucketName << ": HashMultiMap: " << std::flush; TestStrHashMultiMap<HashBucket>(); std::cout << "ok" << std::endl; } template<typename HashBucket> static void TestStrHashSet() { typedef momo::HashSet<std::string, momo::HashTraits<std::string, HashBucket>> HashSet; HashSet set; std::string s1 = "s1"; set.Insert(s1); set.Insert("s2"); set.Insert("s3"); set = set; set = std::move(set); assert(set.GetCount() == 3); assert(set.HasKey("s2")); typename HashSet::ConstIterator iter = set.Find("s1"); assert(*iter == "s1"); std::string rs; set.Remove(iter, rs); assert(rs == "s1"); iter = set.Find("s1"); assert(iter == set.GetEnd()); set.Insert(&s1, &s1 + 1); set.Reset(set.Find("s1"), s1); set.Reset(set.Find(s1), "s1", rs); assert(rs == "s1"); set.Reset(set.Find("s2"), "s2"); set.Reset(set.Find("s2"), "s2", rs); assert(rs == "s2"); set.Remove("s2"); set.Reserve(100); assert(set.GetCapacity() >= 100); set.Shrink(); for (const std::string& s : set) assert(s == "s1" || s == "s3"); set.Clear(); assert(set.IsEmpty()); } template<typename HashBucket> static void TestStrHashMap() { typedef momo::HashMap<std::string, std::string, momo::HashTraits<std::string, HashBucket>> HashMap; HashMap map; std::string s1 = "s1"; std::string s2 = "s2"; std::string s3 = "s3"; std::string s4 = "s4"; std::string s5 = "s5"; map.Insert("s1", "s1"); map.Insert("s2", s2); map.Insert(s3, "s3"); map.Insert(s4, s4); map[s5] = "s5"; assert((std::string)map["s5"] == s5); map["s6"] = "s6"; map = map; map = std::move(map); assert(map.GetCount() == 6); assert(map.HasKey(s2)); typename HashMap::ConstIterator iter1 = map.Find(s1); assert(iter1->key == s1 && iter1->value == s1); map.Remove(s1); typename HashMap::Iterator iter2 = map.Find("s5"); assert(iter2->key == s5 && iter2->value == s5); map.Remove(iter2); map.Remove(s3); map.Remove("s4"); map.Reserve(100); assert(map.GetCapacity() >= 100); map.Shrink(); std::pair<std::string, std::string> pair("s4", s4); map.InsertFS(&pair, &pair + 1); map.InsertKV(map.Find(s2), std::next(map.Find(s2))); //? assert(map.GetCount() == 3); map.Remove(s4); for (auto ref : map) assert(ref.value == "s2" || ref.value == "s6"); for (auto ref : (const HashMap&)map) assert(ref.value == "s2" || ref.value == "s6"); assert(map.GetCount() == 2); map.Clear(); assert(map.IsEmpty()); } template<typename HashBucket> static void TestStrHashMultiMap() { typedef momo::HashMultiMap<std::string, std::string, momo::HashTraits<std::string, HashBucket>> HashMultiMap; HashMultiMap mmap(typename HashMultiMap::HashTraits(1)); std::string k1 = "k1"; std::string v1 = "v1"; std::string k2 = "k2"; std::string v2 = "v2"; std::string k3 = "k3"; std::string v3 = "v3"; mmap.Add("k1", "v1"); mmap.Add(k1, "v2"); mmap.Add("k2", v1); mmap.Add(k2, v2); mmap.Add(mmap.InsertKey(k3), "v3"); mmap.Add(mmap.InsertKey("k3"), v3); mmap = mmap; mmap = std::move(mmap); assert(mmap.GetKeyCount() == 3); assert(mmap.GetValueCount() == 6); assert(mmap.HasKey(k2)); mmap.RemoveKey(k1); auto keyIter = mmap.Find(k2); mmap.Remove(keyIter, 0); assert(keyIter->values.GetCount() == 1); for (const std::string& v : keyIter->values) assert(v == v2); for (auto ref : mmap.GetKeyBounds()) assert(ref.key == k2 || ref.key == k3); for (auto ref : ((const HashMultiMap&)mmap).GetKeyBounds()) assert(ref.key == k2 || ref.key == k3); mmap.RemoveValues(keyIter); mmap.RemoveKey(keyIter); mmap.Shrink(); std::pair<std::string, std::string> pair("k3", v3); mmap.AddFS(&pair, &pair + 1); mmap.AddKV(mmap.GetBegin(), mmap.GetBegin()); //? for (auto ref : mmap) assert(ref.key == "k3"); for (auto ref : (const HashMultiMap&)mmap) assert(ref.value == "v3"); assert(mmap.GetKeyCount() == 1); assert(mmap.GetValueCount() == 3); mmap.Clear(); assert(mmap.GetKeyCount() == 0); assert(mmap.GetValueCount() == 0); } }; static int testSimpleHash = (SimpleHashTester::TestAll(), 0); #endif // TEST_SIMPLE_HASH <commit_msg>SimpleHashTester<commit_after>/**********************************************************\ tests/SimpleHashTester.cpp \**********************************************************/ #include "TestSettings.h" #ifdef TEST_SIMPLE_HASH #undef NDEBUG #include "../../momo/HashSet.h" #include "../../momo/HashMap.h" #include "../../momo/HashMultiMap.h" #include "../../momo/HashBuckets/BucketLim4.h" #include <string> #include <iostream> #include <type_traits> #include <random> class SimpleHashTester { private: template<size_t size, size_t alignment> class VarItem { public: template<typename HashBucket> class HashTraits : public momo::HashTraits<VarItem, HashBucket> { public: size_t GetHashCode(const VarItem& key) const { return std::hash<unsigned char>()(key.GetValue()); } bool IsEqual(const VarItem& key1, const VarItem& key2) const { return key1.GetValue() == key2.GetValue(); } }; public: explicit VarItem(unsigned char value) MOMO_NOEXCEPT { *(unsigned char*)&mStorage = value; } unsigned char GetValue() const MOMO_NOEXCEPT { return *(unsigned char*)&mStorage; } private: typename std::aligned_storage<size, alignment>::type mStorage; }; public: static void TestAll() { TestVarAll(); TestStrAll(); } static void TestVarAll() { TestVarHash<momo::HashBucketOneI1>("momo::HashBucketOneI1"); TestVarHash<momo::HashBucketLimP1<1, 1, 32>>("momo::HashBucketLimP1<1, 1, 32>"); TestVarHash<momo::HashBucketLimP1<2, 1, 1>>("momo::HashBucketLimP1<2, 1, 1>"); TestVarHash<momo::HashBucketLimP1<3, 1, 2>>("momo::HashBucketLimP1<3, 1, 2>"); TestVarHash<momo::HashBucketLimP1<4, 1, 4>>("momo::HashBucketLimP1<4, 1, 4>"); TestVarHash<momo::HashBucketLimP1<5, 1, 64>>("momo::HashBucketLimP1<5, 1, 64>"); TestVarHash<momo::HashBucketLimP1<7, 1, 3>>("momo::HashBucketLimP1<7, 1, 3>"); TestVarHash<momo::HashBucketLimP1<10, 1, 127>>("momo::HashBucketLimP1<10, 1, 127>"); TestVarHash<momo::HashBucketLimP1<15, 1, 1>>("momo::HashBucketLimP1<15, 1, 1>"); TestVarHash<momo::HashBucketLimP<1, 32>>("momo::HashBucketLimP<1, 32>"); TestVarHash<momo::HashBucketLimP<2, 1>>("momo::HashBucketLimP<2, 1>"); TestVarHash<momo::HashBucketLimP<3, 2>>("momo::HashBucketLimP<3, 2>"); TestVarHash<momo::HashBucketLimP<4, 4>>("momo::HashBucketLimP<4, 4>"); TestVarHash<momo::HashBucketLimP<5, 64>>("momo::HashBucketLimP<5, 64>"); TestVarHash<momo::HashBucketLimP<7, 3>>("momo::HashBucketLimP<7, 3>"); TestVarHash<momo::HashBucketLimP<10, 127>>("momo::HashBucketLimP<10, 127>"); TestVarHash<momo::HashBucketLimP<15, 1>>("momo::HashBucketLimP<15, 1>"); TestVarHash<momo::HashBucketUnlimP<1, 32>>("momo::HashBucketUnlimP<1, 32>"); TestVarHash<momo::HashBucketUnlimP<2, 1>>("momo::HashBucketUnlimP<2, 1>"); TestVarHash<momo::HashBucketUnlimP<3, 2>>("momo::HashBucketUnlimP<3, 2>"); TestVarHash<momo::HashBucketUnlimP<4, 4>>("momo::HashBucketUnlimP<4, 4>"); TestVarHash<momo::HashBucketUnlimP<5, 64>>("momo::HashBucketUnlimP<5, 64>"); TestVarHash<momo::HashBucketUnlimP<7, 3>>("momo::HashBucketUnlimP<7, 3>"); TestVarHash<momo::HashBucketUnlimP<10, 127>>("momo::HashBucketUnlimP<10, 127>"); TestVarHash<momo::HashBucketUnlimP<15, 1>>("momo::HashBucketUnlimP<15, 1>"); TestVarHash<momo::HashBucketLim4<1, 32>>("momo::HashBucketLim4<1, 32>"); TestVarHash<momo::HashBucketLim4<2, 1>>("momo::HashBucketLim4<2, 1>"); TestVarHash<momo::HashBucketLim4<3, 127>>("momo::HashBucketLim4<3, 127>"); TestVarHash<momo::HashBucketLim4<7, 2>>("momo::HashBucketLim4<7, 2>"); } template<typename HashBucket> static void TestVarHash(const char* bucketName) { TestVarHashSet<HashBucket, VarItem<1, 1>>(bucketName, "VarItem<1, 1>"); TestVarHashSet<HashBucket, VarItem<2, 1>>(bucketName, "VarItem<2, 1>"); } template<typename HashBucket, typename VarItem> static void TestVarHashSet(const char* bucketName, const char* varItemName) { std::cout << bucketName << ": " << varItemName << ": " << std::flush; static const size_t count = 256; static unsigned char array[count]; for (size_t i = 0; i < count; ++i) array[i] = (unsigned char)i; typedef momo::HashSet<VarItem, typename VarItem::template HashTraits<HashBucket>> HashSet; HashSet set; std::shuffle(array, array + count, std::mt19937()); for (unsigned char c : array) assert(set.Insert(VarItem(c)).inserted); assert(set.GetCount() == count); std::shuffle(array, array + count, std::mt19937()); for (unsigned char c : array) assert(set.Remove(VarItem(c))); assert(set.IsEmpty()); std::cout << "ok" << std::endl; } static void TestStrAll() { TestStrHash<momo::HashBucketOneI1>("momo::HashBucketOneI1"); TestStrHash<momo::HashBucketLimP1<>>("momo::HashBucketLimP1<>"); TestStrHash<momo::HashBucketLimP<>>("momo::HashBucketLimP<>"); TestStrHash<momo::HashBucketUnlimP<>>("momo::HashBucketUnlimP<>"); TestStrHash<momo::HashBucketLim4<>>("momo::HashBucketLim4<>"); } template<typename HashBucket> static void TestStrHash(const char* bucketName) { std::cout << bucketName << ": HashSet: " << std::flush; TestStrHashSet<HashBucket>(); std::cout << "ok" << std::endl; std::cout << bucketName << ": HashMap: " << std::flush; TestStrHashMap<HashBucket>(); std::cout << "ok" << std::endl; std::cout << bucketName << ": HashMultiMap: " << std::flush; TestStrHashMultiMap<HashBucket>(); std::cout << "ok" << std::endl; } template<typename HashBucket> static void TestStrHashSet() { typedef momo::HashSet<std::string, momo::HashTraits<std::string, HashBucket>> HashSet; HashSet set; std::string s1 = "s1"; set.Insert(s1); set.Insert("s2"); set.Insert("s3"); set = set; set = std::move(set); assert(set.GetCount() == 3); assert(set.HasKey("s2")); typename HashSet::ConstIterator iter = set.Find("s1"); assert(*iter == "s1"); std::string rs; set.Remove(iter, rs); assert(rs == "s1"); iter = set.Find("s1"); assert(iter == set.GetEnd()); set.Insert(&s1, &s1 + 1); set.Reset(set.Find("s1"), s1); set.Reset(set.Find(s1), "s1", rs); assert(rs == "s1"); set.Reset(set.Find("s2"), "s2"); set.Reset(set.Find("s2"), "s2", rs); assert(rs == "s2"); set.Remove("s2"); set.Reserve(100); assert(set.GetCapacity() >= 100); set.Shrink(); for (const std::string& s : set) assert(s == "s1" || s == "s3"); set.Clear(); assert(set.IsEmpty()); } template<typename HashBucket> static void TestStrHashMap() { typedef momo::HashMap<std::string, std::string, momo::HashTraits<std::string, HashBucket>> HashMap; HashMap map; std::string s1 = "s1"; std::string s2 = "s2"; std::string s3 = "s3"; std::string s4 = "s4"; std::string s5 = "s5"; map.Insert("s1", "s1"); map.Insert("s2", s2); map.Insert(s3, "s3"); map.Insert(s4, s4); map[s5] = "s5"; assert((std::string)map["s5"] == s5); map["s6"] = "s6"; map = map; map = std::move(map); assert(map.GetCount() == 6); assert(map.HasKey(s2)); typename HashMap::ConstIterator iter1 = map.Find(s1); assert(iter1->key == s1 && iter1->value == s1); map.Remove(s1); typename HashMap::Iterator iter2 = map.Find("s5"); assert(iter2->key == s5 && iter2->value == s5); map.Remove(iter2); map.Remove(s3); map.Remove("s4"); map.Reserve(100); assert(map.GetCapacity() >= 100); map.Shrink(); std::pair<std::string, std::string> pair("s4", s4); map.InsertFS(&pair, &pair + 1); map.InsertKV(map.Find(s2), std::next(map.Find(s2))); //? assert(map.GetCount() == 3); map.Remove(s4); for (auto ref : map) assert(ref.value == "s2" || ref.value == "s6"); for (auto ref : (const HashMap&)map) assert(ref.value == "s2" || ref.value == "s6"); assert(map.GetCount() == 2); map.Clear(); assert(map.IsEmpty()); } template<typename HashBucket> static void TestStrHashMultiMap() { typedef momo::HashMultiMap<std::string, std::string, momo::HashTraits<std::string, HashBucket>> HashMultiMap; HashMultiMap mmap(typename HashMultiMap::HashTraits(1)); std::string k1 = "k1"; std::string v1 = "v1"; std::string k2 = "k2"; std::string v2 = "v2"; std::string k3 = "k3"; std::string v3 = "v3"; mmap.Add("k1", "v1"); mmap.Add(k1, "v2"); mmap.Add("k2", v1); mmap.Add(k2, v2); mmap.Add(mmap.InsertKey(k3), "v3"); mmap.Add(mmap.InsertKey("k3"), v3); mmap = mmap; mmap = std::move(mmap); assert(mmap.GetKeyCount() == 3); assert(mmap.GetValueCount() == 6); assert(mmap.HasKey(k2)); mmap.RemoveKey(k1); auto keyIter = mmap.Find(k2); mmap.Remove(keyIter, 0); assert(keyIter->values.GetCount() == 1); for (const std::string& v : keyIter->values) assert(v == v2); for (auto ref : mmap.GetKeyBounds()) assert(ref.key == k2 || ref.key == k3); for (auto ref : ((const HashMultiMap&)mmap).GetKeyBounds()) assert(ref.key == k2 || ref.key == k3); mmap.RemoveValues(keyIter); mmap.RemoveKey(keyIter); mmap.Shrink(); std::pair<std::string, std::string> pair("k3", v3); mmap.AddFS(&pair, &pair + 1); mmap.AddKV(mmap.GetBegin(), mmap.GetBegin()); //? for (auto ref : mmap) assert(ref.key == "k3"); for (auto ref : (const HashMultiMap&)mmap) assert(ref.value == "v3"); assert(mmap.GetKeyCount() == 1); assert(mmap.GetValueCount() == 3); mmap.Clear(); assert(mmap.GetKeyCount() == 0); assert(mmap.GetValueCount() == 0); } }; static int testSimpleHash = (SimpleHashTester::TestAll(), 0); #endif // TEST_SIMPLE_HASH <|endoftext|>
<commit_before>/** * This file contains a parametrizable unit test for algorithms finding cycles * in a directed graph. */ #include <boost/assign.hpp> #include <boost/foreach.hpp> #include <boost/graph/directed_graph.hpp> #include <boost/graph/graph_traits.hpp> #include <boost/graph/graphviz.hpp> #include <boost/graph/properties.hpp> #include <boost/move/utility.hpp> #include <gtest/gtest.h> #include <iostream> #include <utility> #include <vector> namespace d2_test { namespace graph_cycles_test_detail { /** * Visitor transforming each cycle to a sequence made of the properties of the * vertices in the cycle. The transformed cycles are then accumulated into * a `CycleContainer`. * * In other words, it transforms cycles of the form * @code * (edge_descriptor1, edge_descriptor2, ..., edge_descriptorN) * @endcode * * to cycles of the form * @code * ( * (vertex_property1, vertex_property2), * (vertex_property2, vertex_property3), * ..., * (vertex_propertyN-1, vertex_propertyN) * ) * @endcode */ template <typename CycleContainer> class GatherCycles { typedef typename CycleContainer::value_type Cycle; typedef typename Cycle::value_type Edge; CycleContainer& out_; public: explicit GatherCycles(CycleContainer& out) : out_(out) { } template <typename EdgeDescriptorCycle, typename Graph> void cycle(EdgeDescriptorCycle const& cycle, Graph const& graph) const { typedef boost::graph_traits<Graph> Traits; typedef typename Traits::edge_descriptor EdgeDescriptor; typedef typename Traits::vertex_descriptor VertexDescriptor; typedef typename boost::property_map< Graph, boost::vertex_bundle_t >::const_type VertexPropertyMap; typedef typename boost::property_traits< VertexPropertyMap >::value_type VertexProperty; Cycle prop_cycle; BOOST_FOREACH(EdgeDescriptor e, cycle) { VertexDescriptor source = boost::source(e, graph), target = boost::target(e, graph); VertexProperty src = boost::get(boost::vertex_bundle, graph, source), tgt = boost::get(boost::vertex_bundle, graph, target); prop_cycle.insert(prop_cycle.end(), Edge(src, tgt)); } out_.insert(out_.end(), boost::move(prop_cycle)); } }; } // end namespace graph_cycles_test_detail /** * Unit test template for algorithms finding cycles in directed graphs. * * The `TestTraits` template parameters must customize the test using * the following elements: * - A nested type named `algorithm` representing a functor that can be * called like `f(graph, visitor)`. The algorithm must accept a visitor * with the interface of `GatherCycles` above. */ template <typename TestTraits> struct graph_cycles_test : testing::Test { typedef typename TestTraits::algorithm Algorithm; typedef boost::directed_graph<char> Graph; typedef boost::graph_traits<Graph>::vertex_descriptor VertexDescriptor; typedef boost::graph_traits<Graph>::edge_descriptor EdgeDescriptor; typedef std::pair<char, char> Edge; typedef std::vector<Edge> Cycle; typedef std::vector<Cycle> CycleContainer; Graph graph; /** * Runs the algorithm on the graph that should have been built in the * unit test and compares the result of the algorithm with `expected_`. * * If the results don't match, the test fails. */ void validate_found_cycles(CycleContainer const& expected_) { typedef graph_cycles_test_detail::GatherCycles<CycleContainer> Visitor; // Gather the actual cycles in the graph that should have been // constructed in the test. Algorithm()(graph, Visitor(actual)); expected = expected_; ASSERT_TRUE(expected == actual); } void TearDown() { if (HasFailure()) { std::clog << "Expected cycles\n" "---------------\n"; print_cycles(std::clog, expected); std::clog << "\nActual cycles\n" "-------------\n"; print_cycles(std::clog, actual); std::clog << "\nGraph\n" "-----\n"; boost::write_graphviz(std::clog, graph, boost::make_label_writer( boost::get(boost::vertex_bundle, graph))); } } private: CycleContainer expected, actual; static void print_cycles(std::ostream& os, CycleContainer const& cycles) { BOOST_FOREACH(Cycle const& cycle, cycles) { BOOST_FOREACH(Edge const& edge, cycle) os << "(" << edge.first << ", " << edge.second << ") "; os << '\n'; } } }; TYPED_TEST_CASE_P(graph_cycles_test); /** * @internal * Because of Gtest's implementation of template unit tests, which uses * inheritance, we need to import the names of the base class in order * to use them. This macro makes it easy. * * However, note that we still need to use `this->` to access the `graph` * and `validate_found_cycles()` members of `graph_cycles_test`. */ #define D2_I_IMPORT_TEMPLATE_UNIT_TEST_STUFF() \ typedef graph_cycles_test<TypeParam> GraphCycleTest; \ typedef typename GraphCycleTest::VertexDescriptor VertexDescriptor; \ typedef typename GraphCycleTest::EdgeDescriptor EdgeDescriptor; \ typedef typename GraphCycleTest::CycleContainer CycleContainer; \ typedef typename GraphCycleTest::Cycle Cycle; \ typedef typename GraphCycleTest::Edge Edge; \ typedef typename GraphCycleTest::Graph Graph; \ /**/ TYPED_TEST_P(graph_cycles_test, finds_trivial_cycle_AB) { D2_I_IMPORT_TEMPLATE_UNIT_TEST_STUFF() using namespace boost::assign; VertexDescriptor A = add_vertex('A', this->graph); VertexDescriptor B = add_vertex('B', this->graph); add_edge(A, B, this->graph); add_edge(B, A, this->graph); Cycle AB = list_of(Edge('A', 'B')); this->validate_found_cycles(list_of(AB)); } TYPED_TEST_P(graph_cycles_test, finds_both_cycles_ABC) { D2_I_IMPORT_TEMPLATE_UNIT_TEST_STUFF() using namespace boost::assign; VertexDescriptor A = add_vertex('A', this->graph); VertexDescriptor B = add_vertex('B', this->graph); VertexDescriptor C = add_vertex('C', this->graph); add_edge(A, B, this->graph); add_edge(B, C, this->graph); add_edge(C, A, this->graph); add_edge(A, C, this->graph); Cycle ABC = list_of(Edge('A', 'B'))(Edge('B', 'C'))(Edge('C', 'A')); Cycle AC = list_of(Edge('A', 'C'))(Edge('C', 'A')); this->validate_found_cycles(list_of(ABC)(AC)); } #undef D2_I_IMPORT_TEMPLATE_UNIT_TEST_STUFF REGISTER_TYPED_TEST_CASE_P( graph_cycles_test, finds_trivial_cycle_AB, finds_both_cycles_ABC ); } // end namespace d2_test <commit_msg>Use is_cyclic_permutation in the cycle graph test.<commit_after>/** * This file contains a parametrizable unit test for algorithms finding cycles * in a directed graph. */ #include <d2/core/cyclic_permutation.hpp> #include <boost/assign.hpp> #include <boost/foreach.hpp> #include <boost/graph/directed_graph.hpp> #include <boost/graph/graph_traits.hpp> #include <boost/graph/graphviz.hpp> #include <boost/graph/properties.hpp> #include <boost/move/utility.hpp> #include <gtest/gtest.h> #include <iostream> #include <utility> #include <vector> namespace d2_test { namespace graph_cycles_test_detail { /** * Visitor transforming each cycle to a sequence made of the properties of the * vertices in the cycle. The transformed cycles are then accumulated into * a `CycleContainer`. * * In other words, it transforms cycles of the form * @code * (edge_descriptor1, edge_descriptor2, ..., edge_descriptorN) * @endcode * * to cycles of the form * @code * ( * (vertex_property1, vertex_property2), * (vertex_property2, vertex_property3), * ..., * (vertex_propertyN-1, vertex_propertyN) * ) * @endcode */ template <typename CycleContainer> class GatherCycles { typedef typename CycleContainer::value_type Cycle; typedef typename Cycle::value_type Edge; CycleContainer& out_; public: explicit GatherCycles(CycleContainer& out) : out_(out) { } template <typename EdgeDescriptorCycle, typename Graph> void cycle(EdgeDescriptorCycle const& cycle, Graph const& graph) const { typedef boost::graph_traits<Graph> Traits; typedef typename Traits::edge_descriptor EdgeDescriptor; typedef typename Traits::vertex_descriptor VertexDescriptor; typedef typename boost::property_map< Graph, boost::vertex_bundle_t >::const_type VertexPropertyMap; typedef typename boost::property_traits< VertexPropertyMap >::value_type VertexProperty; Cycle prop_cycle; BOOST_FOREACH(EdgeDescriptor e, cycle) { VertexDescriptor source = boost::source(e, graph), target = boost::target(e, graph); VertexProperty src = boost::get(boost::vertex_bundle, graph, source), tgt = boost::get(boost::vertex_bundle, graph, target); prop_cycle.insert(prop_cycle.end(), Edge(src, tgt)); } out_.insert(out_.end(), boost::move(prop_cycle)); } }; } // end namespace graph_cycles_test_detail /** * Unit test template for algorithms finding cycles in directed graphs. * * The `TestTraits` template parameters must customize the test using * the following elements: * - A nested type named `algorithm` representing a functor that can be * called like `f(graph, visitor)`. The algorithm must accept a visitor * with the interface of `GatherCycles` above. */ template <typename TestTraits> struct graph_cycles_test : testing::Test { typedef typename TestTraits::algorithm Algorithm; typedef boost::directed_graph<char> Graph; typedef boost::graph_traits<Graph>::vertex_descriptor VertexDescriptor; typedef boost::graph_traits<Graph>::edge_descriptor EdgeDescriptor; typedef std::pair<char, char> Edge; typedef std::vector<Edge> Cycle; typedef std::vector<Cycle> CycleContainer; Graph graph; /** * Runs the algorithm on the graph that should have been built in the * unit test and compares the result of the algorithm with `expected_`. * * If the results don't match, the test fails. */ void validate_found_cycles(CycleContainer const& expected_) { typedef graph_cycles_test_detail::GatherCycles<CycleContainer> Visitor; // Gather the actual cycles in the graph that should have been // constructed in the test. Algorithm()(graph, Visitor(actual)); expected = expected_; ASSERT_TRUE(d2::core::is_cyclic_permutation(expected, actual)); } void TearDown() { if (HasFailure()) { std::clog << "Expected cycles\n" "---------------\n"; print_cycles(std::clog, expected); std::clog << "\nActual cycles\n" "-------------\n"; print_cycles(std::clog, actual); std::clog << "\nGraph\n" "-----\n"; boost::write_graphviz(std::clog, graph, boost::make_label_writer( boost::get(boost::vertex_bundle, graph))); } } private: CycleContainer expected, actual; static void print_cycles(std::ostream& os, CycleContainer const& cycles) { BOOST_FOREACH(Cycle const& cycle, cycles) { BOOST_FOREACH(Edge const& edge, cycle) os << "(" << edge.first << ", " << edge.second << ") "; os << '\n'; } } }; TYPED_TEST_CASE_P(graph_cycles_test); /** * @internal * Because of Gtest's implementation of template unit tests, which uses * inheritance, we need to import the names of the base class in order * to use them. This macro makes it easy. * * However, note that we still need to use `this->` to access the `graph` * and `validate_found_cycles()` members of `graph_cycles_test`. */ #define D2_I_IMPORT_TEMPLATE_UNIT_TEST_STUFF() \ typedef graph_cycles_test<TypeParam> GraphCycleTest; \ typedef typename GraphCycleTest::VertexDescriptor VertexDescriptor; \ typedef typename GraphCycleTest::EdgeDescriptor EdgeDescriptor; \ typedef typename GraphCycleTest::CycleContainer CycleContainer; \ typedef typename GraphCycleTest::Cycle Cycle; \ typedef typename GraphCycleTest::Edge Edge; \ typedef typename GraphCycleTest::Graph Graph; \ /**/ TYPED_TEST_P(graph_cycles_test, finds_trivial_cycle_AB) { D2_I_IMPORT_TEMPLATE_UNIT_TEST_STUFF() using namespace boost::assign; VertexDescriptor A = add_vertex('A', this->graph); VertexDescriptor B = add_vertex('B', this->graph); add_edge(A, B, this->graph); add_edge(B, A, this->graph); Cycle AB = list_of(Edge('A', 'B')); this->validate_found_cycles(list_of(AB)); } TYPED_TEST_P(graph_cycles_test, finds_both_cycles_ABC) { D2_I_IMPORT_TEMPLATE_UNIT_TEST_STUFF() using namespace boost::assign; VertexDescriptor A = add_vertex('A', this->graph); VertexDescriptor B = add_vertex('B', this->graph); VertexDescriptor C = add_vertex('C', this->graph); add_edge(A, B, this->graph); add_edge(B, C, this->graph); add_edge(C, A, this->graph); add_edge(A, C, this->graph); Cycle ABC = list_of(Edge('A', 'B'))(Edge('B', 'C'))(Edge('C', 'A')); Cycle AC = list_of(Edge('A', 'C'))(Edge('C', 'A')); this->validate_found_cycles(list_of(ABC)(AC)); } #undef D2_I_IMPORT_TEMPLATE_UNIT_TEST_STUFF REGISTER_TYPED_TEST_CASE_P( graph_cycles_test, finds_trivial_cycle_AB, finds_both_cycles_ABC ); } // end namespace d2_test <|endoftext|>
<commit_before><commit_msg>coverity#982642: add missing break<commit_after><|endoftext|>
<commit_before><commit_msg>WaE: compile under product and dbgutil modes<commit_after><|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <iomanip> #include <vector> #include <array> #include <cmath> using namespace std; template <typename T> inline vector<T> read(const string path) { vector<T> buf; std::ifstream ifs(path, ios::binary | ios::ate); const size_t num_bytes = ifs.tellg(); buf.resize(num_bytes / sizeof(T)); ifs.seekg(0); ifs.read(reinterpret_cast<char*>(buf.data()), num_bytes); return buf; } int main(int argc, char* argv[]) { if (argc < 3) { cout << "score sample.bin output.bin" << endl; return 1; } const size_t num_usrs = 2; constexpr array<size_t, num_usrs> qn{{ 12, 60 }}; constexpr array<double, num_usrs> qv{{ 1.0 / qn[0], 1.0 / qn[1] }}; const auto qs = read<array<double, qn.back()>>(argv[1]); const auto ls = read<array<double, qn.back()>>(argv[2]); const auto q = qs.front(); cout.setf(ios::fixed, ios::floatfield); cout << setprecision(8); for (const auto& l : ls) { double s = 0; #pragma unroll for (size_t i = 0, u = 0; u < num_usrs; ++u) { #pragma unroll for (; i < qn[u]; i += 4) { #pragma unroll for (size_t o = i; o < i + 4; ++o) { s += fabs(q[o] - l[o]); } } s = 1 / (1 + s * qv[u]); cout << s; if (u) cout << endl; else cout << '\t'; } } } <commit_msg>Updated score.cpp<commit_after>#include <iostream> #include <fstream> #include <iomanip> #include <vector> #include <array> #include <cmath> using namespace std; template <typename T> inline vector<T> read(const string path) { vector<T> buf; std::ifstream ifs(path, ios::binary | ios::ate); const size_t num_bytes = ifs.tellg(); buf.resize(num_bytes / sizeof(T)); ifs.seekg(0); ifs.read(reinterpret_cast<char*>(buf.data()), num_bytes); return buf; } int main(int argc, char* argv[]) { if (argc < 3) { cout << "score sample.bin output.bin" << endl; return 1; } const size_t num_usrs = 2; constexpr array<size_t, num_usrs> qn{{ 12, 60 }}; constexpr array<double, num_usrs> qv{{ 1.0 / qn[0], 1.0 / qn[1] }}; const auto qs = read<array<double, qn.back()>>(argv[1]); const auto ls = read<array<double, qn.back()>>(argv[2]); cout.setf(ios::fixed, ios::floatfield); cout << setprecision(8); for (const auto& q : qs) { for (const auto& l : ls) { double s = 0; #pragma unroll for (size_t i = 0, u = 0; u < num_usrs; ++u) { const auto qnu = qn[u]; #pragma unroll for (; i < qnu; ++i) { s += fabs(q[i] - l[i]); } s = 1 / (1 + s * qv[u]); cout << s; if (u) cout << endl; else cout << '\t'; } } } } <|endoftext|>
<commit_before>#include "ofxMarkovChain.h" void MarkovChain::setup(transitionMatrix mat, int _state){ transMat = mat; state = _state; } void MarkovChain::load(string filename){ ofFile file; if(!file.open(ofToDataPath(filename))){ ofLog(OF_LOG_ERROR) << "Cannot open \"" << filename << "\""; } ofBuffer buffer = file.readToBuffer(); string line; do{ vector<float> row; line = buffer.getNextLine(); istringstream ss(line); float val; while(ss >> val){ row.push_back(val); } transMat.push_back(row); } while(!buffer.isLastLine()); // logTransitionMatrix(); if(!checkTransitionMatrix()){ ofLog(OF_LOG_ERROR) << "Bad transition matrix"; } } bool MarkovChain::checkTransitionMatrix(){ int nCol = transMat[0].size(); for(int i = 1; i < transMat.size(); ++i){ if(transMat[i].size() != nCol){ ofLog(OF_LOG_ERROR) << "The transition matrix must be a square matrix"; return false; } float sum = 0.0; for(int j = 0; j < transMat[i].size(); ++j){ sum += transMat[i][j]; } if(sum != 1.0){ ofLog(OF_LOG_ERROR) << "The transition matrix must be stochastic\n(the sum of the coefficients in a row must be equal to 1.0)"; return false; } } if(transMat.size() != nCol){ ofLog(OF_LOG_ERROR) << "The transition matrix must be a square matrix"; return false; } else{ return true; } } void MarkovChain::update(){ float f = ofRandom(1.0); float sum = 0.0; int new_state = -1; vector<float> row = transMat[state]; if(f < row[0]){ new_state = 0; } else{ for(int i = 0; i < row.size()-1; ++i){ sum += row[i]; if(f > sum && f < sum+row[i+1]){ new_state = i+1; } } } if(new_state == -1){ new_state = row.size()-1; } state = new_state; } void MarkovChain::setTransitionMatrix(transitionMatrix mat){ transMat = mat; checkTransitionMatrix(); } transitionMatrix MarkovChain::getTransitionMatrix(){ return transMat; } int MarkovChain::getState(){ return state; } int MarkovChain::getStatesNumber(){ return transMat.size(); } void MarkovChain::setProbabilities(int i, vector<float> row){ if(row.size() != transMat[i].size()){ ofLog(OF_LOG_ERROR) << "Bad size for state transition probabilites assignment"; return; } transMat[i] = row; checkTransitionMatrix(); } void MarkovChain::draw(int x, int y){ for(int i = 0; i < transMat.size(); ++i){ if(state == i){ ofSetColor(ofColor(231, 44, 44, 255)); } else{ ofSetColor(ofColor(44, 231, 44, 255)); } ofCircle(x + 25*i, y, 10); ofSetColor(ofColor::black); ofDrawBitmapString(ofToString(i), x+25*i-4, y+4); } } void MarkovChain::logTransitionMatrix(){ stringstream ss; ss << "Transition matrix:\n"; for(int i = 0; i < transMat.size(); ++i){ for(int j = 0; j < transMat[i].size(); ++j){ ss << transMat[i][j] << "\t"; } ss << "\n"; } ofLog() << ss.str(); }<commit_msg>Add compatibility for v0.9.0<commit_after>#include "ofxMarkovChain.h" void MarkovChain::setup(transitionMatrix mat, int _state){ transMat = mat; state = _state; } #if OF_VERSION_MINOR == 8 void MarkovChain::load(string filename){ transMat.clear(); ofFile file; if(!file.open(ofToDataPath(filename))){ ofLog(OF_LOG_ERROR) << "Cannot open \"" << filename << "\""; } ofBuffer buffer = file.readToBuffer(); string line; do{ vector<float> row; line = buffer.getNextLine(); istringstream ss(line); float val; while(ss >> val){ row.push_back(val); } transMat.push_back(row); } while(!buffer.isLastLine()); logTransitionMatrix(); if(!checkTransitionMatrix()){ ofLog(OF_LOG_ERROR) << "Bad transition matrix"; } } #elif OF_VERSION_MINOR > 8 void MarkovChain::load(string filename){ transMat.clear(); ofFile file; if(!file.open(ofToDataPath(filename))){ ofLog(OF_LOG_ERROR) << "Cannot open \"" << filename << "\""; } ofBuffer buffer = file.readToBuffer(); ofBuffer::Lines lines = buffer.getLines(); for(ofBuffer::Line line = lines.begin(); line != lines.end(); ++line){ vector<float> row; istringstream ss(*line); float val; while(ss >> val){ row.push_back(val); } transMat.push_back(row); } logTransitionMatrix(); if(!checkTransitionMatrix()){ ofLog(OF_LOG_ERROR) << "Bad transition matrix"; } } #else ofLogError() << "Unsupported OF version"; #endif bool MarkovChain::checkTransitionMatrix(){ int nCol = transMat[0].size(); for(int i = 1; i < transMat.size(); ++i){ if(transMat[i].size() != nCol){ ofLog(OF_LOG_ERROR) << "The transition matrix must be a square matrix"; return false; } float sum = 0.0; for(int j = 0; j < transMat[i].size(); ++j){ sum += transMat[i][j]; } if(sum != 1.0){ ofLog(OF_LOG_ERROR) << "The transition matrix must be stochastic\n(the sum of the coefficients in a row must be equal to 1.0)"; return false; } } if(transMat.size() != nCol){ ofLog(OF_LOG_ERROR) << "The transition matrix must be a square matrix"; return false; } else{ return true; } } void MarkovChain::update(){ float f = ofRandom(1.0); float sum = 0.0; int new_state = -1; vector<float> row = transMat[state]; if(f < row[0]){ new_state = 0; } else{ for(int i = 0; i < row.size()-1; ++i){ sum += row[i]; if(f > sum && f < sum+row[i+1]){ new_state = i+1; } } } if(new_state == -1){ new_state = row.size()-1; } state = new_state; } void MarkovChain::setTransitionMatrix(transitionMatrix mat){ transMat = mat; checkTransitionMatrix(); } transitionMatrix MarkovChain::getTransitionMatrix(){ return transMat; } int MarkovChain::getState(){ return state; } int MarkovChain::getStatesNumber(){ return transMat.size(); } void MarkovChain::setProbabilities(int i, vector<float> row){ if(row.size() != transMat[i].size()){ ofLog(OF_LOG_ERROR) << "Bad size for state transition probabilites assignment"; return; } transMat[i] = row; checkTransitionMatrix(); } void MarkovChain::draw(int x, int y){ for(int i = 0; i < transMat.size(); ++i){ if(state == i){ ofSetColor(ofColor(231, 44, 44, 255)); } else{ ofSetColor(ofColor(44, 231, 44, 255)); } ofCircle(x + 25*i, y, 10); ofSetColor(ofColor::black); ofDrawBitmapString(ofToString(i), x+25*i-4, y+4); } } void MarkovChain::logTransitionMatrix(){ stringstream ss; ss << "Transition matrix:\n"; for(int i = 0; i < transMat.size(); ++i){ for(int j = 0; j < transMat[i].size(); ++j){ ss << transMat[i][j] << "\t"; } ss << "\n"; } ofLog() << ss.str(); }<|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: xlconst.hxx,v $ * * $Revision: 1.24 $ * * last change: $Author: vg $ $Date: 2005-02-21 13:46:35 $ * * 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 SC_XLCONST_HXX #define SC_XLCONST_HXX #ifndef SC_ADDRESS_HXX #include "address.hxx" #endif // Common ===================================================================== // BIFF versions -------------------------------------------------------------- /** An enumeration for all Excel file format types (BIFF types). */ enum XclBiff { EXC_BIFF2 = 0, /// MS Excel 2.1 EXC_BIFF3, /// MS Excel 3.0 EXC_BIFF4, /// MS Excel 4.0 EXC_BIFF5, /// MS Excel 5.0, MS Excel 7.0 (95) EXC_BIFF8, /// MS Excel 8.0 (97), 9.0 (2000), 10.0 (XP), 11.0 (2003) EXC_BIFF_UNKNOWN /// Unknown BIFF version. }; // Excel sheet dimensions ----------------------------------------------------- const SCCOL EXC_MAXCOL2 = 255; const SCROW EXC_MAXROW2 = 16383; const SCTAB EXC_MAXTAB2 = 0; const SCCOL EXC_MAXCOL3 = EXC_MAXCOL2; const SCROW EXC_MAXROW3 = EXC_MAXROW2; const SCTAB EXC_MAXTAB3 = EXC_MAXTAB2; const SCCOL EXC_MAXCOL4 = EXC_MAXCOL3; const SCROW EXC_MAXROW4 = EXC_MAXROW3; const SCTAB EXC_MAXTAB4 = 32767; const SCCOL EXC_MAXCOL5 = EXC_MAXCOL4; const SCROW EXC_MAXROW5 = EXC_MAXROW4; const SCTAB EXC_MAXTAB5 = EXC_MAXTAB4; const SCCOL EXC_MAXCOL8 = EXC_MAXCOL5; const SCROW EXC_MAXROW8 = 65535; const SCTAB EXC_MAXTAB8 = EXC_MAXTAB5; const sal_uInt16 EXC_NOTAB = SAL_MAX_UINT16; /// An invalid Excel sheet index, for common use. const SCTAB SCTAB_INVALID = SCTAB_MAX; /// An invalid Calc sheet index, for common use. const SCTAB SCTAB_GLOBAL = SCTAB_MAX; /// A Calc sheet index for the workbook globals. // Storage/stream names ------------------------------------------------------- #define EXC_STORAGE_VBA_PROJECT CREATE_STRING( "_VBA_PROJECT_CUR" ) #define EXC_STORAGE_VBA CREATE_STRING( "VBA" ) #define EXC_STREAM_BOOK CREATE_STRING( "Book" ) #define EXC_STREAM_WORKBOOK CREATE_STRING( "Workbook" ) #define EXC_STREAM_CTLS CREATE_STRING( "Ctls" ) // Encoded URLs --------------------------------------------------------------- const sal_Unicode EXC_URLSTART_ENCODED = '\x01'; /// Encoded URL. const sal_Unicode EXC_URLSTART_SELF = '\x02'; /// Reference to own workbook. const sal_Unicode EXC_URLSTART_SELFENCODED = '\x03'; /// Encoded self reference. const sal_Unicode EXC_URLSTART_OWNDOC = '\x04'; /// Reference to own workbook (BIFF5/BIFF7). const sal_Unicode EXC_URL_DOSDRIVE = '\x01'; /// DOS drive letter or UNC server name. const sal_Unicode EXC_URL_DRIVEROOT = '\x02'; /// Root directory of current drive. const sal_Unicode EXC_URL_SUBDIR = '\x03'; /// Directory name delimiter. const sal_Unicode EXC_URL_PARENTDIR = '\x04'; /// Parent directory. const sal_Unicode EXC_URL_RAW = '\x05'; /// Unencoded URL. const sal_Unicode EXC_URL_SHEETNAME = '\x09'; /// Sheet name starts here (BIFF4). const sal_Unicode EXC_DDE_DELIM = '\x03'; /// DDE application-topic delimiter // Error codes ---------------------------------------------------------------- const sal_uInt8 EXC_ERR_NULL = 0x00; const sal_uInt8 EXC_ERR_DIV0 = 0x07; const sal_uInt8 EXC_ERR_VALUE = 0x0F; const sal_uInt8 EXC_ERR_REF = 0x17; const sal_uInt8 EXC_ERR_NAME = 0x1D; const sal_uInt8 EXC_ERR_NUM = 0x24; const sal_uInt8 EXC_ERR_NA = 0x2A; // Cached values list (EXTERNNAME, ptgArray, ...) ----------------------------- const sal_uInt8 EXC_CACHEDVAL_EMPTY = 0x00; const sal_uInt8 EXC_CACHEDVAL_DOUBLE = 0x01; const sal_uInt8 EXC_CACHEDVAL_STRING = 0x02; const sal_uInt8 EXC_CACHEDVAL_BOOL = 0x04; const sal_uInt8 EXC_CACHEDVAL_ERROR = 0x10; // RK values ------------------------------------------------------------------ const sal_Int32 EXC_RK_100FLAG = 0x00000001; const sal_Int32 EXC_RK_INTFLAG = 0x00000002; const sal_Int32 EXC_RK_VALUEMASK = 0xFFFFFFFC; const sal_Int32 EXC_RK_DBL = 0x00000000; const sal_Int32 EXC_RK_DBL100 = EXC_RK_100FLAG; const sal_Int32 EXC_RK_INT = EXC_RK_INTFLAG; const sal_Int32 EXC_RK_INT100 = EXC_RK_100FLAG | EXC_RK_INTFLAG; // Measures ------------------------------------------------------------------- const sal_Int32 EXC_POINTS_PER_INCH = 72; const sal_Int32 EXC_TWIPS_PER_INCH = EXC_POINTS_PER_INCH * 20; const sal_uInt8 EXC_ROT_BOTTOM_TOP = 90; /// Vertical rotation bottom->top. const sal_uInt8 EXC_ROT_TOP_BOTTOM = 180; /// Vertical rotation top->bottom. const sal_uInt8 EXC_ROT_STACKED = 0xFF; /// Characters vertically stacked. // Records (ordered by lowest record ID) ====================================== // (0x0009, 0x0209, 0x0409, 0x0809) BOF --------------------------------------- const sal_uInt16 EXC_ID2_BOF = 0x0009; const sal_uInt16 EXC_ID3_BOF = 0x0209; const sal_uInt16 EXC_ID4_BOF = 0x0409; const sal_uInt16 EXC_ID5_BOF = 0x0809; const sal_uInt16 EXC_BOF_BIFF2 = 0x0200; const sal_uInt16 EXC_BOF_BIFF3 = 0x0300; const sal_uInt16 EXC_BOF_BIFF4 = 0x0400; const sal_uInt16 EXC_BOF_BIFF5 = 0x0500; const sal_uInt16 EXC_BOF_BIFF8 = 0x0600; const sal_uInt16 EXC_BOF_GLOBALS = 0x0005; /// BIFF5-BIFF8 workbook globals. const sal_uInt16 EXC_BOF_VBMODULE = 0x0006; /// BIFF5-BIFF8 Visual BASIC module. const sal_uInt16 EXC_BOF_SHEET = 0x0010; /// Simple worksheet. const sal_uInt16 EXC_BOF_CHART = 0x0020; /// Chart-only sheet. const sal_uInt16 EXC_BOF_MACROSHEET = 0x0040; /// BIFF2-BIFF4 macro sheet. const sal_uInt16 EXC_BOF_WORKSPACE = 0x0100; /// BIFF3-BIFF8 workspace file. // (0x000A) EOF --------------------------------------------------------------- const sal_uInt16 EXC_ID_EOF = 0x000A; // (0x0012) PROTECT ----------------------------------------------------------- const sal_uInt16 EXC_ID_PROTECT = 0x0012; // (0x0013) PASSWORD ---------------------------------------------------------- const sal_uInt16 EXC_ID_PASSWORD = 0x0013; // (0x0019) WINDOWPROTECT ----------------------------------------------------- const sal_uInt16 EXC_ID_WINDOWPROTECT = 0x0019; // (0x0081) WSBOOL ------------------------------------------------------------ const sal_uInt16 EXC_ID_WSBOOL = 0x0081; const sal_uInt16 EXC_WSBOOL_ROWBELOW = 0x0040; const sal_uInt16 EXC_WSBOOL_COLBELOW = 0x0080; const sal_uInt16 EXC_WSBOOL_FITTOPAGE = 0x0100; const sal_uInt16 EXC_WSBOOL_DEFAULTFLAGS = 0x04C1; // (0x008C) COUNTRY ----------------------------------------------------------- const sal_uInt16 EXC_ID_COUNTRY = 0x008C; // (0x009B) FILTERMODE -------------------------------------------------------- const sal_uInt16 EXC_ID_FILTERMODE = 0x009B; // (0x009D) AUTOFILTERINFO ---------------------------------------------------- const sal_uInt16 EXC_ID_AUTOFILTERINFO = 0x009D; // (0x009E) AUTOFILTER -------------------------------------------------------- const sal_uInt16 EXC_ID_AUTOFILTER = 0x009E; // (0x0160) USESELFS ---------------------------------------------------------- const sal_uInt16 EXC_ID_USESELFS = 0x0160; // (0x01AA,0x01AB) USERSVIEWBEGIN, USERSVIEWEND ------------------------------- const sal_uInt16 EXC_ID_USERSVIEWBEGIN = 0x01AA; const sal_uInt16 EXC_ID_USERSVIEWEND = 0x01AB; // ============================================================================ #endif <commit_msg>INTEGRATION: CWS ooo19126 (1.24.146); FILE MERGED 2005/09/05 15:02:59 rt 1.24.146.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: xlconst.hxx,v $ * * $Revision: 1.25 $ * * last change: $Author: rt $ $Date: 2005-09-08 19:35:35 $ * * 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 SC_XLCONST_HXX #define SC_XLCONST_HXX #ifndef SC_ADDRESS_HXX #include "address.hxx" #endif // Common ===================================================================== // BIFF versions -------------------------------------------------------------- /** An enumeration for all Excel file format types (BIFF types). */ enum XclBiff { EXC_BIFF2 = 0, /// MS Excel 2.1 EXC_BIFF3, /// MS Excel 3.0 EXC_BIFF4, /// MS Excel 4.0 EXC_BIFF5, /// MS Excel 5.0, MS Excel 7.0 (95) EXC_BIFF8, /// MS Excel 8.0 (97), 9.0 (2000), 10.0 (XP), 11.0 (2003) EXC_BIFF_UNKNOWN /// Unknown BIFF version. }; // Excel sheet dimensions ----------------------------------------------------- const SCCOL EXC_MAXCOL2 = 255; const SCROW EXC_MAXROW2 = 16383; const SCTAB EXC_MAXTAB2 = 0; const SCCOL EXC_MAXCOL3 = EXC_MAXCOL2; const SCROW EXC_MAXROW3 = EXC_MAXROW2; const SCTAB EXC_MAXTAB3 = EXC_MAXTAB2; const SCCOL EXC_MAXCOL4 = EXC_MAXCOL3; const SCROW EXC_MAXROW4 = EXC_MAXROW3; const SCTAB EXC_MAXTAB4 = 32767; const SCCOL EXC_MAXCOL5 = EXC_MAXCOL4; const SCROW EXC_MAXROW5 = EXC_MAXROW4; const SCTAB EXC_MAXTAB5 = EXC_MAXTAB4; const SCCOL EXC_MAXCOL8 = EXC_MAXCOL5; const SCROW EXC_MAXROW8 = 65535; const SCTAB EXC_MAXTAB8 = EXC_MAXTAB5; const sal_uInt16 EXC_NOTAB = SAL_MAX_UINT16; /// An invalid Excel sheet index, for common use. const SCTAB SCTAB_INVALID = SCTAB_MAX; /// An invalid Calc sheet index, for common use. const SCTAB SCTAB_GLOBAL = SCTAB_MAX; /// A Calc sheet index for the workbook globals. // Storage/stream names ------------------------------------------------------- #define EXC_STORAGE_VBA_PROJECT CREATE_STRING( "_VBA_PROJECT_CUR" ) #define EXC_STORAGE_VBA CREATE_STRING( "VBA" ) #define EXC_STREAM_BOOK CREATE_STRING( "Book" ) #define EXC_STREAM_WORKBOOK CREATE_STRING( "Workbook" ) #define EXC_STREAM_CTLS CREATE_STRING( "Ctls" ) // Encoded URLs --------------------------------------------------------------- const sal_Unicode EXC_URLSTART_ENCODED = '\x01'; /// Encoded URL. const sal_Unicode EXC_URLSTART_SELF = '\x02'; /// Reference to own workbook. const sal_Unicode EXC_URLSTART_SELFENCODED = '\x03'; /// Encoded self reference. const sal_Unicode EXC_URLSTART_OWNDOC = '\x04'; /// Reference to own workbook (BIFF5/BIFF7). const sal_Unicode EXC_URL_DOSDRIVE = '\x01'; /// DOS drive letter or UNC server name. const sal_Unicode EXC_URL_DRIVEROOT = '\x02'; /// Root directory of current drive. const sal_Unicode EXC_URL_SUBDIR = '\x03'; /// Directory name delimiter. const sal_Unicode EXC_URL_PARENTDIR = '\x04'; /// Parent directory. const sal_Unicode EXC_URL_RAW = '\x05'; /// Unencoded URL. const sal_Unicode EXC_URL_SHEETNAME = '\x09'; /// Sheet name starts here (BIFF4). const sal_Unicode EXC_DDE_DELIM = '\x03'; /// DDE application-topic delimiter // Error codes ---------------------------------------------------------------- const sal_uInt8 EXC_ERR_NULL = 0x00; const sal_uInt8 EXC_ERR_DIV0 = 0x07; const sal_uInt8 EXC_ERR_VALUE = 0x0F; const sal_uInt8 EXC_ERR_REF = 0x17; const sal_uInt8 EXC_ERR_NAME = 0x1D; const sal_uInt8 EXC_ERR_NUM = 0x24; const sal_uInt8 EXC_ERR_NA = 0x2A; // Cached values list (EXTERNNAME, ptgArray, ...) ----------------------------- const sal_uInt8 EXC_CACHEDVAL_EMPTY = 0x00; const sal_uInt8 EXC_CACHEDVAL_DOUBLE = 0x01; const sal_uInt8 EXC_CACHEDVAL_STRING = 0x02; const sal_uInt8 EXC_CACHEDVAL_BOOL = 0x04; const sal_uInt8 EXC_CACHEDVAL_ERROR = 0x10; // RK values ------------------------------------------------------------------ const sal_Int32 EXC_RK_100FLAG = 0x00000001; const sal_Int32 EXC_RK_INTFLAG = 0x00000002; const sal_Int32 EXC_RK_VALUEMASK = 0xFFFFFFFC; const sal_Int32 EXC_RK_DBL = 0x00000000; const sal_Int32 EXC_RK_DBL100 = EXC_RK_100FLAG; const sal_Int32 EXC_RK_INT = EXC_RK_INTFLAG; const sal_Int32 EXC_RK_INT100 = EXC_RK_100FLAG | EXC_RK_INTFLAG; // Measures ------------------------------------------------------------------- const sal_Int32 EXC_POINTS_PER_INCH = 72; const sal_Int32 EXC_TWIPS_PER_INCH = EXC_POINTS_PER_INCH * 20; const sal_uInt8 EXC_ROT_BOTTOM_TOP = 90; /// Vertical rotation bottom->top. const sal_uInt8 EXC_ROT_TOP_BOTTOM = 180; /// Vertical rotation top->bottom. const sal_uInt8 EXC_ROT_STACKED = 0xFF; /// Characters vertically stacked. // Records (ordered by lowest record ID) ====================================== // (0x0009, 0x0209, 0x0409, 0x0809) BOF --------------------------------------- const sal_uInt16 EXC_ID2_BOF = 0x0009; const sal_uInt16 EXC_ID3_BOF = 0x0209; const sal_uInt16 EXC_ID4_BOF = 0x0409; const sal_uInt16 EXC_ID5_BOF = 0x0809; const sal_uInt16 EXC_BOF_BIFF2 = 0x0200; const sal_uInt16 EXC_BOF_BIFF3 = 0x0300; const sal_uInt16 EXC_BOF_BIFF4 = 0x0400; const sal_uInt16 EXC_BOF_BIFF5 = 0x0500; const sal_uInt16 EXC_BOF_BIFF8 = 0x0600; const sal_uInt16 EXC_BOF_GLOBALS = 0x0005; /// BIFF5-BIFF8 workbook globals. const sal_uInt16 EXC_BOF_VBMODULE = 0x0006; /// BIFF5-BIFF8 Visual BASIC module. const sal_uInt16 EXC_BOF_SHEET = 0x0010; /// Simple worksheet. const sal_uInt16 EXC_BOF_CHART = 0x0020; /// Chart-only sheet. const sal_uInt16 EXC_BOF_MACROSHEET = 0x0040; /// BIFF2-BIFF4 macro sheet. const sal_uInt16 EXC_BOF_WORKSPACE = 0x0100; /// BIFF3-BIFF8 workspace file. // (0x000A) EOF --------------------------------------------------------------- const sal_uInt16 EXC_ID_EOF = 0x000A; // (0x0012) PROTECT ----------------------------------------------------------- const sal_uInt16 EXC_ID_PROTECT = 0x0012; // (0x0013) PASSWORD ---------------------------------------------------------- const sal_uInt16 EXC_ID_PASSWORD = 0x0013; // (0x0019) WINDOWPROTECT ----------------------------------------------------- const sal_uInt16 EXC_ID_WINDOWPROTECT = 0x0019; // (0x0081) WSBOOL ------------------------------------------------------------ const sal_uInt16 EXC_ID_WSBOOL = 0x0081; const sal_uInt16 EXC_WSBOOL_ROWBELOW = 0x0040; const sal_uInt16 EXC_WSBOOL_COLBELOW = 0x0080; const sal_uInt16 EXC_WSBOOL_FITTOPAGE = 0x0100; const sal_uInt16 EXC_WSBOOL_DEFAULTFLAGS = 0x04C1; // (0x008C) COUNTRY ----------------------------------------------------------- const sal_uInt16 EXC_ID_COUNTRY = 0x008C; // (0x009B) FILTERMODE -------------------------------------------------------- const sal_uInt16 EXC_ID_FILTERMODE = 0x009B; // (0x009D) AUTOFILTERINFO ---------------------------------------------------- const sal_uInt16 EXC_ID_AUTOFILTERINFO = 0x009D; // (0x009E) AUTOFILTER -------------------------------------------------------- const sal_uInt16 EXC_ID_AUTOFILTER = 0x009E; // (0x0160) USESELFS ---------------------------------------------------------- const sal_uInt16 EXC_ID_USESELFS = 0x0160; // (0x01AA,0x01AB) USERSVIEWBEGIN, USERSVIEWEND ------------------------------- const sal_uInt16 EXC_ID_USERSVIEWBEGIN = 0x01AA; const sal_uInt16 EXC_ID_USERSVIEWEND = 0x01AB; // ============================================================================ #endif <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: optab.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2008-01-29 15:32:35 $ * * 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_sc.hxx" #include "op.h" #include "optab.h" // Bearbeitungsfunktion sal_Char *X( sal_Char * ) OPCODE_FKT pOpFkt[ FKT_LIMIT ] = { // Code OP_BOF, // 0 OP_EOF, // 1 NI, // 2 NI, // 3 NI, // 4 NI, // 5 NI, // 6 OP_Window1, // 7 OP_ColumnWidth, // 8 NI, // 9 NI, // 10 OP_NamedRange, // 11 OP_Blank, // 12 OP_Integer, // 13 OP_Number, // 14 OP_Label, // 15 OP_Formula, // 16 NI, // 17 NI, // 18 NI, // 19 NI, // 20 NI, // 21 NI, // 22 NI, // 23 NI, // 24 NI, // 25 NI, // 26 NI, // 27 NI, // 28 NI, // 29 NI, // 30 NI, // 31 NI, // 32 NI, // 33 NI, // 34 NI, // 35 NI, // 36 OP_Footer, // 37 OP_Header, // 38 NI, // 39 OP_Margins, // 40 NI, // 41 NI, // 42 NI, // 43 NI, // 44 NI, // 45 NI, // 46 NI, // 47 NI, // 48 NI, // 49 NI, // 50 NI, // 51 NI, // 52 NI, // 53 NI, // 54 NI, // 55 NI, // 56 NI, // 57 NI, // 58 NI, // 59 NI, // 60 NI, // 61 NI, // 62 NI, // 63 NI, // 64 NI, // 65 NI, // 66 NI, // 67 NI, // 68 NI, // 69 NI, // 70 OP_SymphNamedRange, // 71 NI, // 72 NI, // 73 NI, // 74 NI, // 75 NI, // 76 NI, // 77 NI, // 78 NI, // 79 NI, // 80 NI, // 81 NI, // 82 NI, // 83 NI, // 84 NI, // 85 NI, // 86 NI, // 87 NI, // 88 NI, // 89 NI, // 90 NI, // 91 NI, // 92 NI, // 93 NI, // 94 NI, // 95 NI, // 96 NI, // 97 NI, // 98 NI, // 99 OP_HiddenCols, // 100 }; OPCODE_FKT pOpFkt123[ FKT_LIMIT123 ] = { // Code OP_BOF123, // 0 OP_EOF123, // 1 NI, // 2 NI, // 3 NI, // 4 NI, // 5 NI, // 6 NI, // 7 NI, // 8 NI, // 9 NI, // 10 NI, // 11 NI, // 12 NI, // 13 NI, // 14 NI, // 15 NI, // 16 NI, // 17 NI, // 18 NI, // 19 NI, // 20 NI, // 21 OP_Label123, // 22 NI, // 23 NI, // 24 NI, // 25 NI, // 26 OP_CreatePattern123, // 27 NI, // 28 NI, // 29 NI, // 30 NI, // 31 NI, // 32 NI, // 33 NI, // 34 OP_SheetName123, // 35 NI, // 36 OP_Number123, // 37 OP_Note123, // 38 OP_IEEENumber123, // 39 OP_Formula123, // 40 NI, // 41 NI, // 42 NI, // 43 NI, // 44 NI, // 45 NI, // 46 NI, // 47 NI, // 48 NI, // 49 NI, // 50 NI, // 51 NI, // 52 NI, // 53 NI, // 54 NI, // 55 NI, // 56 NI, // 57 NI, // 58 NI, // 59 NI, // 60 NI, // 61 NI, // 62 NI, // 63 NI, // 64 NI, // 65 NI, // 66 NI, // 67 NI, // 68 NI, // 69 NI, // 70 NI, // 71 NI, // 72 NI, // 73 NI, // 74 NI, // 75 NI, // 76 NI, // 77 NI, // 78 NI, // 79 NI, // 80 NI, // 81 NI, // 82 NI, // 83 NI, // 84 NI, // 85 NI, // 86 NI, // 87 NI, // 88 NI, // 89 NI, // 90 NI, // 91 NI, // 92 NI, // 93 NI, // 94 NI, // 95 NI, // 96 NI, // 97 NI, // 98 NI, // 99 NI // 100 }; <commit_msg>INTEGRATION: CWS changefileheader (1.5.88); FILE MERGED 2008/03/31 17:14:49 rt 1.5.88.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: optab.cxx,v $ * $Revision: 1.6 $ * * 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. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sc.hxx" #include "op.h" #include "optab.h" // Bearbeitungsfunktion sal_Char *X( sal_Char * ) OPCODE_FKT pOpFkt[ FKT_LIMIT ] = { // Code OP_BOF, // 0 OP_EOF, // 1 NI, // 2 NI, // 3 NI, // 4 NI, // 5 NI, // 6 OP_Window1, // 7 OP_ColumnWidth, // 8 NI, // 9 NI, // 10 OP_NamedRange, // 11 OP_Blank, // 12 OP_Integer, // 13 OP_Number, // 14 OP_Label, // 15 OP_Formula, // 16 NI, // 17 NI, // 18 NI, // 19 NI, // 20 NI, // 21 NI, // 22 NI, // 23 NI, // 24 NI, // 25 NI, // 26 NI, // 27 NI, // 28 NI, // 29 NI, // 30 NI, // 31 NI, // 32 NI, // 33 NI, // 34 NI, // 35 NI, // 36 OP_Footer, // 37 OP_Header, // 38 NI, // 39 OP_Margins, // 40 NI, // 41 NI, // 42 NI, // 43 NI, // 44 NI, // 45 NI, // 46 NI, // 47 NI, // 48 NI, // 49 NI, // 50 NI, // 51 NI, // 52 NI, // 53 NI, // 54 NI, // 55 NI, // 56 NI, // 57 NI, // 58 NI, // 59 NI, // 60 NI, // 61 NI, // 62 NI, // 63 NI, // 64 NI, // 65 NI, // 66 NI, // 67 NI, // 68 NI, // 69 NI, // 70 OP_SymphNamedRange, // 71 NI, // 72 NI, // 73 NI, // 74 NI, // 75 NI, // 76 NI, // 77 NI, // 78 NI, // 79 NI, // 80 NI, // 81 NI, // 82 NI, // 83 NI, // 84 NI, // 85 NI, // 86 NI, // 87 NI, // 88 NI, // 89 NI, // 90 NI, // 91 NI, // 92 NI, // 93 NI, // 94 NI, // 95 NI, // 96 NI, // 97 NI, // 98 NI, // 99 OP_HiddenCols, // 100 }; OPCODE_FKT pOpFkt123[ FKT_LIMIT123 ] = { // Code OP_BOF123, // 0 OP_EOF123, // 1 NI, // 2 NI, // 3 NI, // 4 NI, // 5 NI, // 6 NI, // 7 NI, // 8 NI, // 9 NI, // 10 NI, // 11 NI, // 12 NI, // 13 NI, // 14 NI, // 15 NI, // 16 NI, // 17 NI, // 18 NI, // 19 NI, // 20 NI, // 21 OP_Label123, // 22 NI, // 23 NI, // 24 NI, // 25 NI, // 26 OP_CreatePattern123, // 27 NI, // 28 NI, // 29 NI, // 30 NI, // 31 NI, // 32 NI, // 33 NI, // 34 OP_SheetName123, // 35 NI, // 36 OP_Number123, // 37 OP_Note123, // 38 OP_IEEENumber123, // 39 OP_Formula123, // 40 NI, // 41 NI, // 42 NI, // 43 NI, // 44 NI, // 45 NI, // 46 NI, // 47 NI, // 48 NI, // 49 NI, // 50 NI, // 51 NI, // 52 NI, // 53 NI, // 54 NI, // 55 NI, // 56 NI, // 57 NI, // 58 NI, // 59 NI, // 60 NI, // 61 NI, // 62 NI, // 63 NI, // 64 NI, // 65 NI, // 66 NI, // 67 NI, // 68 NI, // 69 NI, // 70 NI, // 71 NI, // 72 NI, // 73 NI, // 74 NI, // 75 NI, // 76 NI, // 77 NI, // 78 NI, // 79 NI, // 80 NI, // 81 NI, // 82 NI, // 83 NI, // 84 NI, // 85 NI, // 86 NI, // 87 NI, // 88 NI, // 89 NI, // 90 NI, // 91 NI, // 92 NI, // 93 NI, // 94 NI, // 95 NI, // 96 NI, // 97 NI, // 98 NI, // 99 NI // 100 }; <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: optab.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2004-11-26 13:51:01 $ * * 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): _______________________________________ * * ************************************************************************/ #ifdef PCH #include "filt_pch.hxx" #endif #pragma hdrstop #include "op.h" #include "optab.h" // Bearbeitungsfunktion sal_Char *X( sal_Char * ) OPCODE_FKT pOpFkt[ FKT_LIMIT ] = { // Code OP_BOF, // 0 OP_EOF, // 1 NI, // 2 NI, // 3 NI, // 4 NI, // 5 NI, // 6 OP_Window1, // 7 OP_ColumnWidth, // 8 NI, // 9 NI, // 10 OP_NamedRange, // 11 OP_Blank, // 12 OP_Integer, // 13 OP_Number, // 14 OP_Label, // 15 OP_Formula, // 16 NI, // 17 NI, // 18 NI, // 19 NI, // 20 NI, // 21 NI, // 22 NI, // 23 NI, // 24 NI, // 25 NI, // 26 NI, // 27 NI, // 28 NI, // 29 NI, // 30 NI, // 31 NI, // 32 NI, // 33 NI, // 34 NI, // 35 NI, // 36 OP_Footer, // 37 OP_Header, // 38 NI, // 39 OP_Margins, // 40 NI, // 41 NI, // 42 NI, // 43 NI, // 44 NI, // 45 NI, // 46 NI, // 47 NI, // 48 NI, // 49 NI, // 50 NI, // 51 NI, // 52 NI, // 53 NI, // 54 NI, // 55 NI, // 56 NI, // 57 NI, // 58 NI, // 59 NI, // 60 NI, // 61 NI, // 62 NI, // 63 NI, // 64 NI, // 65 NI, // 66 NI, // 67 NI, // 68 NI, // 69 NI, // 70 OP_SymphNamedRange, // 71 NI, // 72 NI, // 73 NI, // 74 NI, // 75 NI, // 76 NI, // 77 NI, // 78 NI, // 79 NI, // 80 NI, // 81 NI, // 82 NI, // 83 NI, // 84 NI, // 85 NI, // 86 NI, // 87 NI, // 88 NI, // 89 NI, // 90 NI, // 91 NI, // 92 NI, // 93 NI, // 94 NI, // 95 NI, // 96 NI, // 97 NI, // 98 NI, // 99 OP_HiddenCols, // 100 }; OPCODE_FKT pOpFkt123[ FKT_LIMIT123 ] = { // Code OP_BOF123, // 0 OP_EOF123, // 1 NI, // 2 NI, // 3 NI, // 4 NI, // 5 NI, // 6 NI, // 7 NI, // 8 NI, // 9 NI, // 10 NI, // 11 NI, // 12 NI, // 13 NI, // 14 NI, // 15 NI, // 16 NI, // 17 NI, // 18 NI, // 19 NI, // 20 NI, // 21 OP_Label123, // 22 NI, // 23 NI, // 24 NI, // 25 NI, // 26 OP_CreatePattern123, // 27 NI, // 28 NI, // 29 NI, // 30 NI, // 31 NI, // 32 NI, // 33 NI, // 34 NI, // 35 NI, // 36 OP_Number123, // 37 OP_Note123, // 38 OP_IEEENumber123, // 39 OP_Formula123, // 40 NI, // 41 NI, // 42 NI, // 43 NI, // 44 NI, // 45 NI, // 46 NI, // 47 NI, // 48 NI, // 49 NI, // 50 NI, // 51 NI, // 52 NI, // 53 NI, // 54 NI, // 55 NI, // 56 NI, // 57 NI, // 58 NI, // 59 NI, // 60 NI, // 61 NI, // 62 NI, // 63 NI, // 64 NI, // 65 NI, // 66 NI, // 67 NI, // 68 NI, // 69 NI, // 70 NI, // 71 NI, // 72 NI, // 73 NI, // 74 NI, // 75 NI, // 76 NI, // 77 NI, // 78 NI, // 79 NI, // 80 NI, // 81 NI, // 82 NI, // 83 NI, // 84 NI, // 85 NI, // 86 NI, // 87 NI, // 88 NI, // 89 NI, // 90 NI, // 91 NI, // 92 NI, // 93 NI, // 94 NI, // 95 NI, // 96 NI, // 97 NI, // 98 NI, // 99 NI // 100 }; <commit_msg>INTEGRATION: CWS ooo19126 (1.2.236); FILE MERGED 2005/09/05 15:03:09 rt 1.2.236.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: optab.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-08 19:43:16 $ * * 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 * ************************************************************************/ #ifdef PCH #include "filt_pch.hxx" #endif #pragma hdrstop #include "op.h" #include "optab.h" // Bearbeitungsfunktion sal_Char *X( sal_Char * ) OPCODE_FKT pOpFkt[ FKT_LIMIT ] = { // Code OP_BOF, // 0 OP_EOF, // 1 NI, // 2 NI, // 3 NI, // 4 NI, // 5 NI, // 6 OP_Window1, // 7 OP_ColumnWidth, // 8 NI, // 9 NI, // 10 OP_NamedRange, // 11 OP_Blank, // 12 OP_Integer, // 13 OP_Number, // 14 OP_Label, // 15 OP_Formula, // 16 NI, // 17 NI, // 18 NI, // 19 NI, // 20 NI, // 21 NI, // 22 NI, // 23 NI, // 24 NI, // 25 NI, // 26 NI, // 27 NI, // 28 NI, // 29 NI, // 30 NI, // 31 NI, // 32 NI, // 33 NI, // 34 NI, // 35 NI, // 36 OP_Footer, // 37 OP_Header, // 38 NI, // 39 OP_Margins, // 40 NI, // 41 NI, // 42 NI, // 43 NI, // 44 NI, // 45 NI, // 46 NI, // 47 NI, // 48 NI, // 49 NI, // 50 NI, // 51 NI, // 52 NI, // 53 NI, // 54 NI, // 55 NI, // 56 NI, // 57 NI, // 58 NI, // 59 NI, // 60 NI, // 61 NI, // 62 NI, // 63 NI, // 64 NI, // 65 NI, // 66 NI, // 67 NI, // 68 NI, // 69 NI, // 70 OP_SymphNamedRange, // 71 NI, // 72 NI, // 73 NI, // 74 NI, // 75 NI, // 76 NI, // 77 NI, // 78 NI, // 79 NI, // 80 NI, // 81 NI, // 82 NI, // 83 NI, // 84 NI, // 85 NI, // 86 NI, // 87 NI, // 88 NI, // 89 NI, // 90 NI, // 91 NI, // 92 NI, // 93 NI, // 94 NI, // 95 NI, // 96 NI, // 97 NI, // 98 NI, // 99 OP_HiddenCols, // 100 }; OPCODE_FKT pOpFkt123[ FKT_LIMIT123 ] = { // Code OP_BOF123, // 0 OP_EOF123, // 1 NI, // 2 NI, // 3 NI, // 4 NI, // 5 NI, // 6 NI, // 7 NI, // 8 NI, // 9 NI, // 10 NI, // 11 NI, // 12 NI, // 13 NI, // 14 NI, // 15 NI, // 16 NI, // 17 NI, // 18 NI, // 19 NI, // 20 NI, // 21 OP_Label123, // 22 NI, // 23 NI, // 24 NI, // 25 NI, // 26 OP_CreatePattern123, // 27 NI, // 28 NI, // 29 NI, // 30 NI, // 31 NI, // 32 NI, // 33 NI, // 34 NI, // 35 NI, // 36 OP_Number123, // 37 OP_Note123, // 38 OP_IEEENumber123, // 39 OP_Formula123, // 40 NI, // 41 NI, // 42 NI, // 43 NI, // 44 NI, // 45 NI, // 46 NI, // 47 NI, // 48 NI, // 49 NI, // 50 NI, // 51 NI, // 52 NI, // 53 NI, // 54 NI, // 55 NI, // 56 NI, // 57 NI, // 58 NI, // 59 NI, // 60 NI, // 61 NI, // 62 NI, // 63 NI, // 64 NI, // 65 NI, // 66 NI, // 67 NI, // 68 NI, // 69 NI, // 70 NI, // 71 NI, // 72 NI, // 73 NI, // 74 NI, // 75 NI, // 76 NI, // 77 NI, // 78 NI, // 79 NI, // 80 NI, // 81 NI, // 82 NI, // 83 NI, // 84 NI, // 85 NI, // 86 NI, // 87 NI, // 88 NI, // 89 NI, // 90 NI, // 91 NI, // 92 NI, // 93 NI, // 94 NI, // 95 NI, // 96 NI, // 97 NI, // 98 NI, // 99 NI // 100 }; <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: xmlwrap.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: nn $ $Date: 2000-12-02 16:27:42 $ * * 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): _______________________________________ * * ************************************************************************/ #ifdef PCH #include "filt_pch.hxx" #endif #pragma hdrstop // INCLUDE --------------------------------------------------------------- #include <rsc/rscsfx.hxx> #include <sfx2/docfile.hxx> #include <sfx2/objsh.hxx> #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #include <vos/xception.hxx> #include <comphelper/processfactory.hxx> #include <unotools/streamwrap.hxx> #include <xmloff/xmlkywd.hxx> #include <com/sun/star/xml/sax/XErrorHandler.hpp> #include <com/sun/star/xml/sax/XEntityResolver.hpp> #include <com/sun/star/xml/sax/InputSource.hpp> #include <com/sun/star/xml/sax/XDTDHandler.hpp> #include <com/sun/star/xml/sax/XParser.hpp> #include <com/sun/star/io/XActiveDataSource.hpp> #include <com/sun/star/io/XActiveDataControl.hpp> #include <com/sun/star/document/XDocumentInfoSupplier.hpp> #include <com/sun/star/frame/XModel.hpp> #include "document.hxx" #include "xmlwrap.hxx" #include "xmlimprt.hxx" #include "xmlexprt.hxx" using namespace com::sun::star; // ----------------------------------------------------------------------- ScXMLImportWrapper::ScXMLImportWrapper(ScDocument& rD, SfxMedium& rM) : rDoc(rD), rMedium(rM) { } sal_Bool ScXMLImportWrapper::Import() { uno::Reference<lang::XMultiServiceFactory> xServiceFactory = comphelper::getProcessServiceFactory(); DBG_ASSERT( xServiceFactory.is(), "got no service manager" ); if( !xServiceFactory.is() ) return sal_False; // Get data source ... uno::Reference< io::XActiveDataSource > xSource; uno::Reference< uno::XInterface > xPipe; xml::sax::InputSource aParserInput; aParserInput.sSystemId = OUString(rMedium.GetName()); SvStorageStreamRef xDocStream; SvStorage *pStorage = rMedium.GetStorage(); if( pStorage ) { OUString sDocName( RTL_CONSTASCII_USTRINGPARAM( "Content" ) ); xDocStream = pStorage->OpenStream( sDocName, STREAM_READ | STREAM_NOCREATE ); xDocStream->SetBufferSize( 16*1024 ); aParserInput.aInputStream = new utl::OInputStreamWrapper( *xDocStream ); } else { // if there is a medium and if this medium has a load environment, // we get an active data source from the medium. rMedium.GetInStream()->Seek( 0 ); xSource = rMedium.GetDataSource(); DBG_ASSERT( xSource.is(), "got no data source from medium" ); if( !xSource.is() ) return sal_False; // get a pipe for connecting the data source to the parser xPipe = xServiceFactory->createInstance( OUString::createFromAscii("com.sun.star.io.Pipe") ); DBG_ASSERT( xPipe.is(), "XMLReader::Read: com.sun.star.io.Pipe service missing" ); if( !xPipe.is() ) return sal_False; // connect pipe's output stream to the data source uno::Reference<io::XOutputStream> xPipeOutput( xPipe, uno::UNO_QUERY ); xSource->setOutputStream( xPipeOutput ); aParserInput.aInputStream = uno::Reference< io::XInputStream >( xPipe, uno::UNO_QUERY ); } // get parser uno::Reference<uno::XInterface> xXMLParser = xServiceFactory->createInstance( OUString(RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.xml.sax.Parser" )) ); DBG_ASSERT( xXMLParser.is(), "com.sun.star.xml.sax.Parser service missing" ); if( !xXMLParser.is() ) return sal_False; sal_uInt16 nStyleFamilyMask(0); // USHORT nStyleFamilyMask = SFX_STYLE_FAMILY_ALL; sal_Bool bLoadDoc(sal_True); // BOOL bInsert; // if( aOpt.IsFmtsOnly() ) // { // bLoadDoc = FALSE; // bInsert = aOpt.IsMerge(); // nStyleFamilyMask = 0U; // if( aOpt.IsFrmFmts() ) // nStyleFamilyMask |= SFX_STYLE_FAMILY_FRAME; // if( aOpt.IsPageDescs() ) // nStyleFamilyMask |= SFX_STYLE_FAMILY_PAGE; // if( aOpt.IsTxtFmts() ) // nStyleFamilyMask |= (SFX_STYLE_FAMILY_CHAR|SFX_STYLE_FAMILY_PARA); // if( aOpt.IsNumRules() ) // nStyleFamilyMask |= SFX_STYLE_FAMILY_PSEUDO; // } // else // { // bLoadDoc = TRUE; // bInsert = bInsertMode; // nStyleFamilyMask = SFX_STYLE_FAMILY_ALL; // } // aOpt.ResetAllFmtsOnly(); // get filter SfxObjectShell* pObjSh = rDoc.GetDocumentShell(); if ( pObjSh ) { uno::Reference<frame::XModel> xModel = pObjSh->GetModel(); uno::Reference<xml::sax::XDocumentHandler> xFilter = new ScXMLImport( xModel, bLoadDoc, nStyleFamilyMask); // connect parser and filter uno::Reference<xml::sax::XParser> xParser( xXMLParser, uno::UNO_QUERY ); xParser->setDocumentHandler( xFilter ); // parse if( xSource.is() ) { uno::Reference<io::XActiveDataControl> xSourceControl( xSource, uno::UNO_QUERY ); if( xSourceControl.is() ) xSourceControl->start(); } sal_Bool bRetval(sal_True); try { xParser->parseStream( aParserInput ); } catch( xml::sax::SAXParseException e ) { bRetval = sal_False; } catch( xml::sax::SAXException e ) { bRetval = sal_False; } catch( io::IOException e ) { bRetval = sal_False; } return bRetval; } return sal_False; } sal_Bool ScXMLImportWrapper::Export() { uno::Reference<lang::XMultiServiceFactory> xServiceFactory = comphelper::getProcessServiceFactory(); DBG_ASSERT( xServiceFactory.is(), "got no service manager" ); if( !xServiceFactory.is() ) return sal_False; uno::Reference<uno::XInterface> xWriter = xServiceFactory->createInstance( OUString(RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.xml.sax.Writer" )) ); DBG_ASSERT( xWriter.is(), "com.sun.star.xml.sax.Writer service missing" ); if(!xWriter.is()) return sal_False; uno::Reference<io::XOutputStream> xOut; SvStorageStreamRef xDocStream; SvStorage *pStorage = rMedium.GetStorage(); if( pStorage ) { OUString sDocName( RTL_CONSTASCII_USTRINGPARAM( "Content" ) ); xDocStream = pStorage->OpenStream( sDocName, STREAM_WRITE | STREAM_SHARE_DENYWRITE ); xDocStream->SetBufferSize( 16*1024 ); xOut = new utl::OOutputStreamWrapper( *xDocStream ); } else { xOut = rMedium.GetDataSink(); } uno::Reference<io::XActiveDataSource> xSrc( xWriter, uno::UNO_QUERY ); xSrc->setOutputStream( xOut ); uno::Reference<xml::sax::XDocumentHandler> xHandler( xWriter, uno::UNO_QUERY ); OUString sFileName = rMedium.GetName(); SfxObjectShell* pObjSh = rDoc.GetDocumentShell(); if ( pObjSh ) { pObjSh->UpdateDocInfoForSave(); // update information uno::Reference<frame::XModel> xModel = pObjSh->GetModel(); ScXMLExport *pExp = new ScXMLExport( xModel, sFileName, xHandler, sal_False ); sal_Bool bRet = (0 == pExp->exportDoc( sXML_spreadsheet )); delete pExp; return bRet; } // later: give string descriptor as parameter for doc type return sal_False; } <commit_msg>#80795#: Create Package instead of OLE storage<commit_after>/************************************************************************* * * $RCSfile: xmlwrap.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: mib $ $Date: 2000-12-03 08:53:31 $ * * 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): _______________________________________ * * ************************************************************************/ #ifdef PCH #include "filt_pch.hxx" #endif #pragma hdrstop // INCLUDE --------------------------------------------------------------- #include <rsc/rscsfx.hxx> #include <sfx2/docfile.hxx> #include <sfx2/objsh.hxx> #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #include <vos/xception.hxx> #include <comphelper/processfactory.hxx> #include <unotools/streamwrap.hxx> #include <xmloff/xmlkywd.hxx> #include <com/sun/star/xml/sax/XErrorHandler.hpp> #include <com/sun/star/xml/sax/XEntityResolver.hpp> #include <com/sun/star/xml/sax/InputSource.hpp> #include <com/sun/star/xml/sax/XDTDHandler.hpp> #include <com/sun/star/xml/sax/XParser.hpp> #include <com/sun/star/io/XActiveDataSource.hpp> #include <com/sun/star/io/XActiveDataControl.hpp> #include <com/sun/star/document/XDocumentInfoSupplier.hpp> #include <com/sun/star/frame/XModel.hpp> #include "document.hxx" #include "xmlwrap.hxx" #include "xmlimprt.hxx" #include "xmlexprt.hxx" using namespace com::sun::star; // ----------------------------------------------------------------------- ScXMLImportWrapper::ScXMLImportWrapper(ScDocument& rD, SfxMedium& rM) : rDoc(rD), rMedium(rM) { } sal_Bool ScXMLImportWrapper::Import() { uno::Reference<lang::XMultiServiceFactory> xServiceFactory = comphelper::getProcessServiceFactory(); DBG_ASSERT( xServiceFactory.is(), "got no service manager" ); if( !xServiceFactory.is() ) return sal_False; // Get data source ... uno::Reference< io::XActiveDataSource > xSource; uno::Reference< uno::XInterface > xPipe; xml::sax::InputSource aParserInput; aParserInput.sSystemId = OUString(rMedium.GetName()); SvStorageStreamRef xDocStream; SvStorage *pStorage = rMedium.GetStorage(); if( pStorage ) { OUString sDocName( RTL_CONSTASCII_USTRINGPARAM( "Content" ) ); xDocStream = pStorage->OpenStream( sDocName, STREAM_READ | STREAM_NOCREATE ); xDocStream->SetBufferSize( 16*1024 ); aParserInput.aInputStream = new utl::OInputStreamWrapper( *xDocStream ); } else { // if there is a medium and if this medium has a load environment, // we get an active data source from the medium. rMedium.GetInStream()->Seek( 0 ); xSource = rMedium.GetDataSource(); DBG_ASSERT( xSource.is(), "got no data source from medium" ); if( !xSource.is() ) return sal_False; // get a pipe for connecting the data source to the parser xPipe = xServiceFactory->createInstance( OUString::createFromAscii("com.sun.star.io.Pipe") ); DBG_ASSERT( xPipe.is(), "XMLReader::Read: com.sun.star.io.Pipe service missing" ); if( !xPipe.is() ) return sal_False; // connect pipe's output stream to the data source uno::Reference<io::XOutputStream> xPipeOutput( xPipe, uno::UNO_QUERY ); xSource->setOutputStream( xPipeOutput ); aParserInput.aInputStream = uno::Reference< io::XInputStream >( xPipe, uno::UNO_QUERY ); } // get parser uno::Reference<uno::XInterface> xXMLParser = xServiceFactory->createInstance( OUString(RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.xml.sax.Parser" )) ); DBG_ASSERT( xXMLParser.is(), "com.sun.star.xml.sax.Parser service missing" ); if( !xXMLParser.is() ) return sal_False; sal_uInt16 nStyleFamilyMask(0); // USHORT nStyleFamilyMask = SFX_STYLE_FAMILY_ALL; sal_Bool bLoadDoc(sal_True); // BOOL bInsert; // if( aOpt.IsFmtsOnly() ) // { // bLoadDoc = FALSE; // bInsert = aOpt.IsMerge(); // nStyleFamilyMask = 0U; // if( aOpt.IsFrmFmts() ) // nStyleFamilyMask |= SFX_STYLE_FAMILY_FRAME; // if( aOpt.IsPageDescs() ) // nStyleFamilyMask |= SFX_STYLE_FAMILY_PAGE; // if( aOpt.IsTxtFmts() ) // nStyleFamilyMask |= (SFX_STYLE_FAMILY_CHAR|SFX_STYLE_FAMILY_PARA); // if( aOpt.IsNumRules() ) // nStyleFamilyMask |= SFX_STYLE_FAMILY_PSEUDO; // } // else // { // bLoadDoc = TRUE; // bInsert = bInsertMode; // nStyleFamilyMask = SFX_STYLE_FAMILY_ALL; // } // aOpt.ResetAllFmtsOnly(); // get filter SfxObjectShell* pObjSh = rDoc.GetDocumentShell(); if ( pObjSh ) { uno::Reference<frame::XModel> xModel = pObjSh->GetModel(); uno::Reference<xml::sax::XDocumentHandler> xFilter = new ScXMLImport( xModel, bLoadDoc, nStyleFamilyMask); // connect parser and filter uno::Reference<xml::sax::XParser> xParser( xXMLParser, uno::UNO_QUERY ); xParser->setDocumentHandler( xFilter ); // parse if( xSource.is() ) { uno::Reference<io::XActiveDataControl> xSourceControl( xSource, uno::UNO_QUERY ); if( xSourceControl.is() ) xSourceControl->start(); } sal_Bool bRetval(sal_True); try { xParser->parseStream( aParserInput ); } catch( xml::sax::SAXParseException e ) { bRetval = sal_False; } catch( xml::sax::SAXException e ) { bRetval = sal_False; } catch( io::IOException e ) { bRetval = sal_False; } return bRetval; } return sal_False; } sal_Bool ScXMLImportWrapper::Export() { uno::Reference<lang::XMultiServiceFactory> xServiceFactory = comphelper::getProcessServiceFactory(); DBG_ASSERT( xServiceFactory.is(), "got no service manager" ); if( !xServiceFactory.is() ) return sal_False; uno::Reference<uno::XInterface> xWriter = xServiceFactory->createInstance( OUString(RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.xml.sax.Writer" )) ); DBG_ASSERT( xWriter.is(), "com.sun.star.xml.sax.Writer service missing" ); if(!xWriter.is()) return sal_False; uno::Reference<io::XOutputStream> xOut; SvStorageStreamRef xDocStream; SvStorage *pStorage = rMedium.GetOutputStorage( sal_True ); if( pStorage ) { OUString sDocName( RTL_CONSTASCII_USTRINGPARAM( "Content" ) ); xDocStream = pStorage->OpenStream( sDocName, STREAM_WRITE | STREAM_SHARE_DENYWRITE ); xDocStream->SetBufferSize( 16*1024 ); xOut = new utl::OOutputStreamWrapper( *xDocStream ); } else { xOut = rMedium.GetDataSink(); } uno::Reference<io::XActiveDataSource> xSrc( xWriter, uno::UNO_QUERY ); xSrc->setOutputStream( xOut ); uno::Reference<xml::sax::XDocumentHandler> xHandler( xWriter, uno::UNO_QUERY ); OUString sFileName = rMedium.GetName(); SfxObjectShell* pObjSh = rDoc.GetDocumentShell(); if ( pObjSh ) { pObjSh->UpdateDocInfoForSave(); // update information uno::Reference<frame::XModel> xModel = pObjSh->GetModel(); ScXMLExport *pExp = new ScXMLExport( xModel, sFileName, xHandler, sal_False ); sal_Bool bRet = (0 == pExp->exportDoc( sXML_spreadsheet )); delete pExp; return bRet; } // later: give string descriptor as parameter for doc type return sal_False; } <|endoftext|>
<commit_before><commit_msg>coverity#1242417 Logically dead code<commit_after><|endoftext|>
<commit_before>// $Id: openBruker2DFile.C,v 1.2 2000/11/28 17:38:31 anhi Exp $ #include <BALL/MOLVIEW/GUI/DIALOGS/openBruker2DFile.h> using std::istream; using std::ostream; namespace BALL { namespace MOLVIEW { OpenBruker2DFile::OpenBruker2DFile(QWidget* parent, const char* name) : FileDialog("Import Bruker2D File", QFileDialog::ExistingFile, parent, name) { QStringList string_list; string_list = "Bruker2D-directories (*.*)"; setFilters(string_list); } OpenBruker2DFile::~OpenBruker2DFile() { #ifdef BALL_VIEW_DEBUG cout << "Destructing object " << (void *)this << " of class " << RTTI::getName<OpenBruker2DFile>() << endl; #endif } void OpenBruker2DFile::initializeWidget(MainControl& main_control) { main_control.insertMenuEntry(MainControl::FILE_IMPORT, "&Bruker2D File", this, SLOT(exec()), CTRL+Key_B); } void OpenBruker2DFile::finalizeWidget(MainControl& main_control) { main_control.removeMenuEntry (MainControl::FILE_IMPORT, "&Bruker2D File", this, SLOT(exec()), CTRL+Key_B); } void OpenBruker2DFile::openFile_() { // notify the main window WindowMessage window_message; window_message.setStatusBar("reading Bruker2D file..."); notify_(window_message); // reading the file Bruker2D *myfile = new Bruker2D(); String mydir = getExistingDirectory().latin1(); try { myfile->read(mydir); } catch(...) { Log.info() << "> read Bruker2D file failed." << endl; delete myfile; return; } // writing info to log Log.info() << "> Bruker file " << myfile << " succesfully read." << endl; // notify main window NewRegularData2DMessage new_message; new_message.setComposite((Composite *)myfile->GetData()); new_message.setCompositeName(mydir); notify_(new_message); // notify main window window_message.setStatusBar(""); notify_(window_message); } } } <commit_msg>*** empty log message ***<commit_after>// $Id: openBruker2DFile.C,v 1.3 2000/12/14 18:45:55 anhi Exp $ #include <BALL/MOLVIEW/GUI/DIALOGS/openBruker2DFile.h> using std::istream; using std::ostream; namespace BALL { namespace MOLVIEW { OpenBruker2DFile::OpenBruker2DFile(QWidget* parent, const char* name) : FileDialog("Import Bruker2D File", QFileDialog::ExistingFile, parent, name) { QStringList string_list; string_list = "Bruker2D-files (2rr)"; setFilters(string_list); } OpenBruker2DFile::~OpenBruker2DFile() { #ifdef BALL_VIEW_DEBUG cout << "Destructing object " << (void *)this << " of class " << RTTI::getName<OpenBruker2DFile>() << endl; #endif } void OpenBruker2DFile::initializeWidget(MainControl& main_control) { main_control.insertMenuEntry(MainControl::FILE_IMPORT, "&Bruker2D File", this, SLOT(exec()), CTRL+Key_B); } void OpenBruker2DFile::finalizeWidget(MainControl& main_control) { main_control.removeMenuEntry (MainControl::FILE_IMPORT, "&Bruker2D File", this, SLOT(exec()), CTRL+Key_B); } void OpenBruker2DFile::openFile_() { // notify the main window WindowMessage window_message; window_message.setStatusBar("reading Bruker2D file..."); notify_(window_message); // reading the file Bruker2D *myfile = new Bruker2D(); String mydir = dirPath().latin1(); try { myfile->read(mydir); // TEST!!! // myfile->save("/home/andreas/nmrtest", 0, 90, 500, 400); } catch(...) { Log.info() << "> read Bruker2D file failed." << endl; delete myfile; return; } // writing info to log Log.info() << "> Bruker file " << mydir << " succesfully read." << endl; // notify main window NewRegularData2DMessage new_message; new_message.setComposite((Composite *)myfile->GetData()); new_message.setCompositeName(mydir); notify_(new_message); // notify main window window_message.setStatusBar(""); notify_(window_message); } } } <|endoftext|>
<commit_before>/** * Copyright (C) 2014, BMW Car IT GmbH * Author: Jonas Sticha (Jonas.Sticha@bmw-carit.de) * * This software is licensed under BSD 3-clause License * (see http://spdx.org/licenses/BSD-3-Clause). **/ #include "OneShotLatencyMeasurer.h" #include <sys/mman.h> #include <rt_tests_support/Logger.h> #include <rt_tests_support/PlotDataFileCreator.h> #define NANO_TO_MICRO_DIVISOR 1000 #define SEC_TO_NANOSEC_MULTIPLIER 1000000000 OneShotLatencyMeasurer::OneShotLatencyMeasurer(Config* config) : loopLength(config->loops), timeoutNanoseconds(config->timeout_us*1000), timeoutSeconds(((double)timeoutNanoseconds)/SEC_TO_NANOSEC_MULTIPLIER), nodeHandle(config->nodeHandle), callbackCalled(false), callbackTs(), loopCounter(0), lockMemory(config->testnodeRT), latencyData(new MeasurementDataEvaluator(loopLength)), reportedLatencyData(new MeasurementDataEvaluator(loopLength)), differenceData(new MeasurementDataEvaluator(loopLength)) { } void OneShotLatencyMeasurer::measure() { measureOneshotTimerLatencies(); latencyData->analyzeData(); reportedLatencyData->analyzeData(); differenceData->analyzeData(); } void OneShotLatencyMeasurer::measureOneshotTimerLatencies() { if(lockMemory) { if(mlockall(MCL_CURRENT|MCL_FUTURE) != 0) { Logger::ERROR("Could'nt lock memory! Aborting..."); exit(1); } } loopCounter = 0; ros::Timer rosTimer = nodeHandle->createTimer(ros::Duration(0.01), &OneShotLatencyMeasurer::timerCallback, this, true); spinUntilCallbackCalled(); long latencyTempNs = 0; struct timespec startTs; for(loopCounter = 0; loopCounter < loopLength; loopCounter++) { rosTimer.setPeriod(ros::Duration(timeoutSeconds)); clock_gettime(clock_id, &startTs); rosTimer.start(); spinUntilCallbackCalled(); latencyTempNs = ((callbackTs.tv_sec - startTs.tv_sec) * SEC_TO_NANOSEC_MULTIPLIER) + (callbackTs.tv_nsec - startTs.tv_nsec); latencyTempNs -= timeoutNanoseconds; latencyData->getData()[loopCounter] = latencyTempNs/NANO_TO_MICRO_DIVISOR; differenceData->getData()[loopCounter] = reportedLatencyData->getData()[loopCounter] - latencyData->getData()[loopCounter]; } if(lockMemory) { munlockall(); } } MeasurementDataEvaluator* OneShotLatencyMeasurer::getMeasuredLatencyData() { return latencyData; } MeasurementDataEvaluator* OneShotLatencyMeasurer::getReportedLatencyData() { return reportedLatencyData; } MeasurementDataEvaluator* OneShotLatencyMeasurer::getLatencyDifferenceData() { return differenceData; } std::string OneShotLatencyMeasurer::getMeasurementSummary() { std::stringstream ss; ss << "Measurement results with a loop length of " << loopLength << " and a timeout of " << (int) (timeoutNanoseconds/1000) << " us:" << std::endl; ss <<"Measured:\tMIN: " << latencyData->getMinValue() << "us \tAVG: " << latencyData->getAvgValue() << "us \tMAX: " << latencyData->getMaxValue() << "us"; ss << std::endl; ss <<"Reported:\tMIN: " << reportedLatencyData->getMinValue() << "us \tAVG: " << reportedLatencyData->getAvgValue() << "us \tMAX: "; ss << reportedLatencyData->getMaxValue() << "us" << std::endl; ss << "Difference:\tMIN: " << differenceData->getMinValue() << "us\tAVG: " << differenceData->getAvgValue() << "us\tMAX: " << differenceData->getMaxValue() << "us"; ss << std::endl; return ss.str(); } void OneShotLatencyMeasurer::printMeasurementResults() { std::stringstream measurementSummary(getMeasurementSummary()); while(!measurementSummary.eof() && !measurementSummary.fail()) { char line[512]; measurementSummary.getline(line, 512); if(line[0] != '\0') { Logger::INFO(line); } } } void OneShotLatencyMeasurer::saveMeasuredLatencyGnuplotData() { saveGnuplotData(Config::getConfig()->getFilename()+"-measured", latencyData); } void OneShotLatencyMeasurer::saveReportedLatencyGnuplotData() { saveGnuplotData(Config::getConfig()->getFilename()+"-reported", reportedLatencyData); } void OneShotLatencyMeasurer::saveDiffGnuplotData() { saveGnuplotData(Config::getConfig()->getFilename()+"-diff", differenceData); } void OneShotLatencyMeasurer::saveGnuplotData(std::string filename, MeasurementDataEvaluator* measurementData) { Config* config = Config::getConfig(); std::stringstream ss; ss << "set title \"" << config-> getTitle() << "\"" << std::endl; ss << "set xlabel \"Latency in micro seconds - MIN: "; ss << measurementData->getMinValue() << "us AVG: " << measurementData->getAvgValue() << "us MAX: " << measurementData->getMaxValue() << "us\"" << std::endl; ss << "set ylabel \"Number of latency samples\"" << std::endl << "set yrange [0.7:]" << std::endl << "set logscale y" << std::endl; int xrange = measurementData->getMaxValue() + 50; if(measurementData->getMaxValue() < 400) { xrange = 400; } ss << "set xrange [1:" << xrange << "]" << std::endl << "set xtics add(500, 1000)" << std::endl; ss << "set terminal jpeg size 1920,1080" << std::endl; ss << "set output \"" << filename << ".jpg\"" << std::endl; ss << "plot \"-\" u 1:2 t 'Latency_Occurrence' w steps" << std::endl; ss << "# Plot data for gnuplot" << std::endl; std::stringstream measurementSummary(getMeasurementSummary()); while(!measurementSummary.eof() && !measurementSummary.fail()) { char line[512]; measurementSummary.getline(line, 512); if(line[0] != '\0') { ss << "# " << line << std::endl; } } PlotDataFileCreator plotter; plotter.createPlottableDatafile(filename+".log", ss.str(), measurementData); } void OneShotLatencyMeasurer::timerCallback(const ros::TimerEvent& te) { clock_gettime(clock_id, &callbackTs); long latencyReportedTemp = ((te.current_real.sec - te.current_expected.sec) * SEC_TO_NANOSEC_MULTIPLIER) + (te.current_real.nsec - te.current_expected.nsec); reportedLatencyData->getData()[loopCounter] = latencyReportedTemp/NANO_TO_MICRO_DIVISOR; callbackCalled = true; } void OneShotLatencyMeasurer::spinUntilCallbackCalled() { callbackCalled = false; while(!callbackCalled && ros::ok()) { ros::spinOnce(); } } OneShotLatencyMeasurer::~OneShotLatencyMeasurer() { delete latencyData, reportedLatencyData, differenceData; } <commit_msg>timer_tests/OneShotLatencyMeasurer: Minor refactoring<commit_after>/** * Copyright (C) 2014, BMW Car IT GmbH * Author: Jonas Sticha (Jonas.Sticha@bmw-carit.de) * * This software is licensed under BSD 3-clause License * (see http://spdx.org/licenses/BSD-3-Clause). **/ #include "OneShotLatencyMeasurer.h" #include <sys/mman.h> #include <rt_tests_support/Logger.h> #include <rt_tests_support/PlotDataFileCreator.h> #define NANO_TO_MICRO_DIVISOR 1000 #define SEC_TO_NANOSEC_MULTIPLIER 1000000000 OneShotLatencyMeasurer::OneShotLatencyMeasurer(Config* config) : loopLength(config->loops), timeoutNanoseconds(config->timeout_us*1000), timeoutSeconds(((double)timeoutNanoseconds)/SEC_TO_NANOSEC_MULTIPLIER), nodeHandle(config->nodeHandle), callbackCalled(false), callbackTs(), loopCounter(0), lockMemory(config->testnodeRT), latencyData(new MeasurementDataEvaluator(loopLength)), reportedLatencyData(new MeasurementDataEvaluator(loopLength)), differenceData(new MeasurementDataEvaluator(loopLength)) { } void OneShotLatencyMeasurer::measure() { if(lockMemory) { if(mlockall(MCL_CURRENT|MCL_FUTURE) != 0) { Logger::ERROR("Could'nt lock memory! Aborting..."); exit(1); } } measureOneshotTimerLatencies(); if(lockMemory) { munlockall(); } latencyData->analyzeData(); reportedLatencyData->analyzeData(); differenceData->analyzeData(); } void OneShotLatencyMeasurer::measureOneshotTimerLatencies() { loopCounter = 0; ros::Timer rosTimer = nodeHandle->createTimer(ros::Duration(0.01), &OneShotLatencyMeasurer::timerCallback, this, true); spinUntilCallbackCalled(); long latencyTempNs = 0; struct timespec startTs; for(loopCounter = 0; loopCounter < loopLength; loopCounter++) { rosTimer.setPeriod(ros::Duration(timeoutSeconds)); clock_gettime(clock_id, &startTs); rosTimer.start(); spinUntilCallbackCalled(); latencyTempNs = ((callbackTs.tv_sec - startTs.tv_sec) * SEC_TO_NANOSEC_MULTIPLIER) + (callbackTs.tv_nsec - startTs.tv_nsec); latencyTempNs -= timeoutNanoseconds; latencyData->getData()[loopCounter] = latencyTempNs/NANO_TO_MICRO_DIVISOR; differenceData->getData()[loopCounter] = reportedLatencyData->getData()[loopCounter] - latencyData->getData()[loopCounter]; } } MeasurementDataEvaluator* OneShotLatencyMeasurer::getMeasuredLatencyData() { return latencyData; } MeasurementDataEvaluator* OneShotLatencyMeasurer::getReportedLatencyData() { return reportedLatencyData; } MeasurementDataEvaluator* OneShotLatencyMeasurer::getLatencyDifferenceData() { return differenceData; } std::string OneShotLatencyMeasurer::getMeasurementSummary() { std::stringstream ss; ss << "Measurement results with a loop length of " << loopLength << " and a timeout of " << (int) (timeoutNanoseconds/1000) << " us:" << std::endl; ss <<"Measured:\tMIN: " << latencyData->getMinValue() << "us \tAVG: " << latencyData->getAvgValue() << "us \tMAX: " << latencyData->getMaxValue() << "us"; ss << std::endl; ss <<"Reported:\tMIN: " << reportedLatencyData->getMinValue() << "us \tAVG: " << reportedLatencyData->getAvgValue() << "us \tMAX: "; ss << reportedLatencyData->getMaxValue() << "us" << std::endl; ss << "Difference:\tMIN: " << differenceData->getMinValue() << "us\tAVG: " << differenceData->getAvgValue() << "us\tMAX: " << differenceData->getMaxValue() << "us"; ss << std::endl; return ss.str(); } void OneShotLatencyMeasurer::printMeasurementResults() { std::stringstream measurementSummary(getMeasurementSummary()); while(!measurementSummary.eof() && !measurementSummary.fail()) { char line[512]; measurementSummary.getline(line, 512); if(line[0] != '\0') { Logger::INFO(line); } } } void OneShotLatencyMeasurer::saveMeasuredLatencyGnuplotData() { saveGnuplotData(Config::getConfig()->getFilename()+"-measured", latencyData); } void OneShotLatencyMeasurer::saveReportedLatencyGnuplotData() { saveGnuplotData(Config::getConfig()->getFilename()+"-reported", reportedLatencyData); } void OneShotLatencyMeasurer::saveDiffGnuplotData() { saveGnuplotData(Config::getConfig()->getFilename()+"-diff", differenceData); } void OneShotLatencyMeasurer::saveGnuplotData(std::string filename, MeasurementDataEvaluator* measurementData) { Config* config = Config::getConfig(); std::stringstream ss; ss << "set title \"" << config-> getTitle() << "\"" << std::endl; ss << "set xlabel \"Latency in micro seconds - MIN: "; ss << measurementData->getMinValue() << "us AVG: " << measurementData->getAvgValue() << "us MAX: " << measurementData->getMaxValue() << "us\"" << std::endl; ss << "set ylabel \"Number of latency samples\"" << std::endl << "set yrange [0.7:]" << std::endl << "set logscale y" << std::endl; int xrange = measurementData->getMaxValue() + 50; if(measurementData->getMaxValue() < 400) { xrange = 400; } ss << "set xrange [1:" << xrange << "]" << std::endl << "set xtics add(500, 1000)" << std::endl; ss << "set terminal jpeg size 1920,1080" << std::endl; ss << "set output \"" << filename << ".jpg\"" << std::endl; ss << "plot \"-\" u 1:2 t 'Latency_Occurrence' w steps" << std::endl; ss << "# Plot data for gnuplot" << std::endl; std::stringstream measurementSummary(getMeasurementSummary()); while(!measurementSummary.eof() && !measurementSummary.fail()) { char line[512]; measurementSummary.getline(line, 512); if(line[0] != '\0') { ss << "# " << line << std::endl; } } PlotDataFileCreator plotter; plotter.createPlottableDatafile(filename+".log", ss.str(), measurementData); } void OneShotLatencyMeasurer::timerCallback(const ros::TimerEvent& te) { clock_gettime(clock_id, &callbackTs); long latencyReportedTemp = ((te.current_real.sec - te.current_expected.sec) * SEC_TO_NANOSEC_MULTIPLIER) + (te.current_real.nsec - te.current_expected.nsec); reportedLatencyData->getData()[loopCounter] = latencyReportedTemp/NANO_TO_MICRO_DIVISOR; callbackCalled = true; } void OneShotLatencyMeasurer::spinUntilCallbackCalled() { callbackCalled = false; while(!callbackCalled && ros::ok()) { ros::spinOnce(); } } OneShotLatencyMeasurer::~OneShotLatencyMeasurer() { delete latencyData, reportedLatencyData, differenceData; } <|endoftext|>
<commit_before>#include <Arduino.h> #define LED_PIN 13 #define IN1_PIN 3 #define IN2_PIN 5 #define IN3_PIN 6 #define IN4_PIN 9 void setup() { pinMode(LED_PIN,OUTPUT); pinMode(IN1_PIN,OUTPUT); pinMode(IN2_PIN,OUTPUT); pinMode(IN3_PIN,OUTPUT); pinMode(IN4_PIN,OUTPUT); } void loop() { digitalWrite(LED_PIN,HIGH); digitalWrite(IN1_PIN,HIGH); for(int i = 0; i < 256; i++){ analogWrite(IN2_PIN,i); delay(10); } digitalWrite(LED_PIN,HIGH); digitalWrite(IN2_PIN,HIGH); for(int i = 0; i < 256; i++){ analogWrite(IN1_PIN,i); delay(10); } digitalWrite(LED_PIN,HIGH); digitalWrite(IN3_PIN,HIGH); for(int i = 0; i < 256; i++){ analogWrite(IN4_PIN,i); delay(10); } digitalWrite(LED_PIN,HIGH); digitalWrite(IN4_PIN,HIGH); for(int i = 0; i < 256; i++){ analogWrite(IN3_PIN,i); delay(10); } } <commit_msg>rosserial node init<commit_after>#include <Arduino.h> #include <ros.h> #include <std_msgs/Int16.h> #include <mec/Command.h> //#include "motor.h" #define LED_PIN 13 #define IN1_PIN 3 #define IN2_PIN 5 #define IN3_PIN 6 #define IN4_PIN 9 ros::NodeHandle nh; void commandCallback( const mec::Command& msg){ if(msg.data > 0){ } //digital() } ros::Subscriber<mec::Command> commandSub("/controls",&commandCallback); void setup() { pinMode(LED_PIN,OUTPUT); pinMode(IN1_PIN,OUTPUT); pinMode(IN2_PIN,OUTPUT); pinMode(IN3_PIN,OUTPUT); pinMode(IN4_PIN,OUTPUT); nh.initNode(); nh.subscribe(commandSub); } void loop() { nh.spinOnce(); digitalWrite(LED_PIN,!digitalRead(LED_PIN)); } <|endoftext|>
<commit_before>// Copyright 2017 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. // /////////////////////////////////////////////////////////////////////////////// #include "tink/subtle/ecdsa_verify_boringssl.h" #include "absl/strings/str_cat.h" #include "openssl/bn.h" #include "openssl/ec.h" #include "openssl/ecdsa.h" #include "openssl/evp.h" #include "openssl/mem.h" #include "tink/subtle/common_enums.h" #include "tink/subtle/subtle_util_boringssl.h" #include "tink/util/errors.h" namespace crypto { namespace tink { namespace subtle { namespace { // Transforms ECDSA IEEE_P1363 signature encoding to DER encoding. // // The IEEE_P1363 signature's format is r || s, where r and s are zero-padded // and have the same size in bytes as the order of the curve. For example, for // NIST P-256 curve, r and s are zero-padded to 32 bytes. // // The DER signature is encoded using ASN.1 // (https://tools.ietf.org/html/rfc5480#appendix-A): ECDSA-Sig-Value :: = // SEQUENCE { r INTEGER, s INTEGER }. In particular, the encoding is: 0x30 || // totalLength || 0x02 || r's length || r || 0x02 || s's length || s. crypto::tink::util::StatusOr<std::string> IeeeToDer(absl::string_view ieee, const EC_KEY* key) { size_t field_size_in_bytes = (EC_GROUP_get_degree(EC_KEY_get0_group(key)) + 7) / 8; if (ieee.size() != field_size_in_bytes * 2) { return util::Status(util::error::INVALID_ARGUMENT, "Signature is not valid."); } bssl::UniquePtr<ECDSA_SIG> ecdsa(ECDSA_SIG_new()); auto status_or_r = SubtleUtilBoringSSL::str2bn(ieee.substr(0, ieee.size() / 2)); if (!status_or_r.ok()) { return status_or_r.status(); } auto status_or_s = SubtleUtilBoringSSL::str2bn( ieee.substr(ieee.size() / 2, ieee.size() / 2)); if (!status_or_s.ok()) { return status_or_s.status(); } if (1 != ECDSA_SIG_set0(ecdsa.get(), status_or_r.ValueOrDie().get(), status_or_s.ValueOrDie().get())) { return util::Status(util::error::INTERNAL, "ECDSA_SIG_set0 error."); } // ECDSA_SIG_set0 takes ownership of s and r's pointers. status_or_r.ValueOrDie().release(); status_or_s.ValueOrDie().release(); uint8_t* der = nullptr; bssl::UniquePtr<uint8_t> unique(der); size_t der_len; if (!ECDSA_SIG_to_bytes(&der, &der_len, ecdsa.get())) { return util::Status(util::error::INVALID_ARGUMENT, "ECDSA_SIG_to_bytes error"); } return std::string(reinterpret_cast<char*>(der), der_len); } } // namespace // static util::StatusOr<std::unique_ptr<EcdsaVerifyBoringSsl>> EcdsaVerifyBoringSsl::New( const SubtleUtilBoringSSL::EcKey& ec_key, HashType hash_type, EcdsaSignatureEncoding encoding) { // Check curve. auto group_result(SubtleUtilBoringSSL::GetEcGroup(ec_key.curve)); if (!group_result.ok()) return group_result.status(); bssl::UniquePtr<EC_GROUP> group(group_result.ValueOrDie()); bssl::UniquePtr<EC_KEY> key(EC_KEY_new()); EC_KEY_set_group(key.get(), group.get()); // Check key. auto ec_point_result = SubtleUtilBoringSSL::GetEcPoint(ec_key.curve, ec_key.pub_x, ec_key.pub_y); if (!ec_point_result.ok()) return ec_point_result.status(); bssl::UniquePtr<EC_POINT> pub_key(ec_point_result.ValueOrDie()); if (!EC_KEY_set_public_key(key.get(), pub_key.get())) { return util::Status(util::error::INVALID_ARGUMENT, absl::StrCat("Invalid public key: ", SubtleUtilBoringSSL::GetErrors())); } return New(std::move(key), hash_type, encoding); } // static util::StatusOr<std::unique_ptr<EcdsaVerifyBoringSsl>> EcdsaVerifyBoringSsl::New( bssl::UniquePtr<EC_KEY> ec_key, HashType hash_type, EcdsaSignatureEncoding encoding) { // Check hash. auto hash_status = SubtleUtilBoringSSL::ValidateSignatureHash(hash_type); if (!hash_status.ok()) { return hash_status; } auto hash_result = SubtleUtilBoringSSL::EvpHash(hash_type); if (!hash_result.ok()) return hash_result.status(); const EVP_MD* hash = hash_result.ValueOrDie(); std::unique_ptr<EcdsaVerifyBoringSsl> verify( new EcdsaVerifyBoringSsl(ec_key.release(), hash, encoding)); return std::move(verify); } EcdsaVerifyBoringSsl::EcdsaVerifyBoringSsl(EC_KEY* key, const EVP_MD* hash, EcdsaSignatureEncoding encoding) : key_(key), hash_(hash), encoding_(encoding) {} util::Status EcdsaVerifyBoringSsl::Verify( absl::string_view signature, absl::string_view data) const { // BoringSSL expects a non-null pointer for data, // regardless of whether the size is 0. data = SubtleUtilBoringSSL::EnsureNonNull(data); // Compute the digest. unsigned int digest_size; uint8_t digest[EVP_MAX_MD_SIZE]; if (1 != EVP_Digest(data.data(), data.size(), digest, &digest_size, hash_, nullptr)) { return util::Status(util::error::INTERNAL, "Could not compute digest."); } std::string derSig(signature); if (encoding_ == subtle::EcdsaSignatureEncoding::IEEE_P1363) { auto status_or_der = IeeeToDer(signature, key_.get()); if (!status_or_der.ok()) { return status_or_der.status(); } derSig = status_or_der.ValueOrDie(); } // Verify the signature. if (1 != ECDSA_verify(0 /* unused */, digest, digest_size, reinterpret_cast<const uint8_t*>(derSig.data()), derSig.size(), key_.get())) { // signature is invalid return util::Status(util::error::INVALID_ARGUMENT, "Signature is not valid."); } // signature is valid return util::Status::OK; } } // namespace subtle } // namespace tink } // namespace crypto <commit_msg>Fix a memory leak in the conversion of IeeeToDer signatures.<commit_after>// Copyright 2017 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. // /////////////////////////////////////////////////////////////////////////////// #include "tink/subtle/ecdsa_verify_boringssl.h" #include "absl/strings/str_cat.h" #include "openssl/bn.h" #include "openssl/ec.h" #include "openssl/ecdsa.h" #include "openssl/evp.h" #include "openssl/mem.h" #include "tink/subtle/common_enums.h" #include "tink/subtle/subtle_util_boringssl.h" #include "tink/util/errors.h" namespace crypto { namespace tink { namespace subtle { namespace { // Transforms ECDSA IEEE_P1363 signature encoding to DER encoding. // // The IEEE_P1363 signature's format is r || s, where r and s are zero-padded // and have the same size in bytes as the order of the curve. For example, for // NIST P-256 curve, r and s are zero-padded to 32 bytes. // // The DER signature is encoded using ASN.1 // (https://tools.ietf.org/html/rfc5480#appendix-A): ECDSA-Sig-Value :: = // SEQUENCE { r INTEGER, s INTEGER }. In particular, the encoding is: 0x30 || // totalLength || 0x02 || r's length || r || 0x02 || s's length || s. crypto::tink::util::StatusOr<std::string> IeeeToDer(absl::string_view ieee, const EC_KEY* key) { size_t field_size_in_bytes = (EC_GROUP_get_degree(EC_KEY_get0_group(key)) + 7) / 8; if (ieee.size() != field_size_in_bytes * 2) { return util::Status(util::error::INVALID_ARGUMENT, "Signature is not valid."); } bssl::UniquePtr<ECDSA_SIG> ecdsa(ECDSA_SIG_new()); auto status_or_r = SubtleUtilBoringSSL::str2bn(ieee.substr(0, ieee.size() / 2)); if (!status_or_r.ok()) { return status_or_r.status(); } auto status_or_s = SubtleUtilBoringSSL::str2bn( ieee.substr(ieee.size() / 2, ieee.size() / 2)); if (!status_or_s.ok()) { return status_or_s.status(); } if (1 != ECDSA_SIG_set0(ecdsa.get(), status_or_r.ValueOrDie().get(), status_or_s.ValueOrDie().get())) { return util::Status(util::error::INTERNAL, "ECDSA_SIG_set0 error."); } // ECDSA_SIG_set0 takes ownership of s and r's pointers. status_or_r.ValueOrDie().release(); status_or_s.ValueOrDie().release(); uint8_t* der = nullptr; size_t der_len; if (!ECDSA_SIG_to_bytes(&der, &der_len, ecdsa.get())) { return util::Status(util::error::INVALID_ARGUMENT, "ECDSA_SIG_to_bytes error"); } std::string result = std::string(reinterpret_cast<char*>(der), der_len); OPENSSL_free(der); return result; } } // namespace // static util::StatusOr<std::unique_ptr<EcdsaVerifyBoringSsl>> EcdsaVerifyBoringSsl::New( const SubtleUtilBoringSSL::EcKey& ec_key, HashType hash_type, EcdsaSignatureEncoding encoding) { // Check curve. auto group_result(SubtleUtilBoringSSL::GetEcGroup(ec_key.curve)); if (!group_result.ok()) return group_result.status(); bssl::UniquePtr<EC_GROUP> group(group_result.ValueOrDie()); bssl::UniquePtr<EC_KEY> key(EC_KEY_new()); EC_KEY_set_group(key.get(), group.get()); // Check key. auto ec_point_result = SubtleUtilBoringSSL::GetEcPoint(ec_key.curve, ec_key.pub_x, ec_key.pub_y); if (!ec_point_result.ok()) return ec_point_result.status(); bssl::UniquePtr<EC_POINT> pub_key(ec_point_result.ValueOrDie()); if (!EC_KEY_set_public_key(key.get(), pub_key.get())) { return util::Status(util::error::INVALID_ARGUMENT, absl::StrCat("Invalid public key: ", SubtleUtilBoringSSL::GetErrors())); } return New(std::move(key), hash_type, encoding); } // static util::StatusOr<std::unique_ptr<EcdsaVerifyBoringSsl>> EcdsaVerifyBoringSsl::New( bssl::UniquePtr<EC_KEY> ec_key, HashType hash_type, EcdsaSignatureEncoding encoding) { // Check hash. auto hash_status = SubtleUtilBoringSSL::ValidateSignatureHash(hash_type); if (!hash_status.ok()) { return hash_status; } auto hash_result = SubtleUtilBoringSSL::EvpHash(hash_type); if (!hash_result.ok()) return hash_result.status(); const EVP_MD* hash = hash_result.ValueOrDie(); std::unique_ptr<EcdsaVerifyBoringSsl> verify( new EcdsaVerifyBoringSsl(ec_key.release(), hash, encoding)); return std::move(verify); } EcdsaVerifyBoringSsl::EcdsaVerifyBoringSsl(EC_KEY* key, const EVP_MD* hash, EcdsaSignatureEncoding encoding) : key_(key), hash_(hash), encoding_(encoding) {} util::Status EcdsaVerifyBoringSsl::Verify( absl::string_view signature, absl::string_view data) const { // BoringSSL expects a non-null pointer for data, // regardless of whether the size is 0. data = SubtleUtilBoringSSL::EnsureNonNull(data); // Compute the digest. unsigned int digest_size; uint8_t digest[EVP_MAX_MD_SIZE]; if (1 != EVP_Digest(data.data(), data.size(), digest, &digest_size, hash_, nullptr)) { return util::Status(util::error::INTERNAL, "Could not compute digest."); } std::string derSig(signature); if (encoding_ == subtle::EcdsaSignatureEncoding::IEEE_P1363) { auto status_or_der = IeeeToDer(signature, key_.get()); if (!status_or_der.ok()) { return status_or_der.status(); } derSig = status_or_der.ValueOrDie(); } // Verify the signature. if (1 != ECDSA_verify(0 /* unused */, digest, digest_size, reinterpret_cast<const uint8_t*>(derSig.data()), derSig.size(), key_.get())) { // signature is invalid return util::Status(util::error::INVALID_ARGUMENT, "Signature is not valid."); } // signature is valid return util::Status::OK; } } // namespace subtle } // namespace tink } // namespace crypto <|endoftext|>
<commit_before>//================================================== // Copyright (c) 2015 Deividas Kazlauskas // // See the file license.txt for copying permission. //================================================== /* * ===================================================================================== * * Filename: Variadic.hpp * * Description: Variadic utilities * * Version: 1.0 * Created: 05/25/2014 03:11:34 PM * Compiler: gcc * * Author: David Kazlauskas (dk), david@templatious.org * * ===================================================================================== */ #ifndef VARIADIC_HXND7XSS #define VARIADIC_HXND7XSS #include <cstddef> #include <utility> #include <typeindex> namespace templatious { namespace util { template <class T, class... Args> T&& getFirst(T&& t, Args&&... args) { return t; } template <class... T> struct GetFrist; template <class T> struct GetFrist<T> { typedef T type; }; template <class T,class... Tail> struct GetFrist<T,Tail...> { typedef T type; }; template <int i> struct GetNth; template <int n,class... Args> auto getNth(Args&&... args) -> decltype( GetNth<n>::get( std::forward<Args>(args)...) ) { static_assert(n >= 0,"Index cannot be negative."); static_assert(n < sizeof...(Args), "Asked element is out of bounds"); return GetNth<n>::get( std::forward<Args>(args)...); } template <int i> struct GetNth { template <class T,class... Args> static auto get(T&& first,Args&&... args) -> decltype( GetNth<i - 1>::get( std::forward<Args>(args)...)) { return GetNth<i - 1>::get( std::forward<Args>(args)...); } }; template <> struct GetNth<0> { template <class T,class... Args> static auto get(T&& first,Args&&... args) -> decltype( std::forward<T>(first) ) { return std::forward<T>(first); } }; template <int i,class Type> size_t hashType() { size_t toShift = std::type_index(typeid(Type)).hash_code(); return (toShift >> i) | (toShift << (sizeof(toShift) - i)); } template <int i,class... Args> struct HashCounter; template <int i,class A,class... Tail> struct HashCounter<i,A,Tail...> { typedef HashCounter<i+1,Tail...> TailCounter; static size_t hash() { return hashType<i,A>() ^ TailCounter::hash(); } }; template <int i,class A> struct HashCounter<i,A> { static size_t hash() { return hashType<i,A>(); } }; template <class... Args> size_t hashTypes() { return HashCounter<0,Args...>::hash(); } } } #endif /* end of include guard: VARIADIC_HXND7XSS */ <commit_msg>clang warning about shift + has fix<commit_after>//================================================== // Copyright (c) 2015 Deividas Kazlauskas // // See the file license.txt for copying permission. //================================================== /* * ===================================================================================== * * Filename: Variadic.hpp * * Description: Variadic utilities * * Version: 1.0 * Created: 05/25/2014 03:11:34 PM * Compiler: gcc * * Author: David Kazlauskas (dk), david@templatious.org * * ===================================================================================== */ #ifndef VARIADIC_HXND7XSS #define VARIADIC_HXND7XSS #include <cstddef> #include <utility> #include <typeindex> namespace templatious { namespace util { template <class T, class... Args> T&& getFirst(T&& t, Args&&... args) { return t; } template <class... T> struct GetFrist; template <class T> struct GetFrist<T> { typedef T type; }; template <class T,class... Tail> struct GetFrist<T,Tail...> { typedef T type; }; template <int i> struct GetNth; template <int n,class... Args> auto getNth(Args&&... args) -> decltype( GetNth<n>::get( std::forward<Args>(args)...) ) { static_assert(n >= 0,"Index cannot be negative."); static_assert(n < sizeof...(Args), "Asked element is out of bounds"); return GetNth<n>::get( std::forward<Args>(args)...); } template <int i> struct GetNth { template <class T,class... Args> static auto get(T&& first,Args&&... args) -> decltype( GetNth<i - 1>::get( std::forward<Args>(args)...)) { return GetNth<i - 1>::get( std::forward<Args>(args)...); } }; template <> struct GetNth<0> { template <class T,class... Args> static auto get(T&& first,Args&&... args) -> decltype( std::forward<T>(first) ) { return std::forward<T>(first); } }; // no warning about shift overflow template <int i> struct RightShiftSide { static size_t leftShift(size_t hash) { return (hash << (sizeof(hash)*CHAR_BIT - i)); } }; template <> struct RightShiftSide<0> { static size_t leftShift(size_t) { return 0; } }; template <int i,class Type> size_t hashType() { size_t toShift = std::type_index(typeid(Type)).hash_code(); typedef RightShiftSide<i> Shifter; return (toShift >> i) | Shifter::leftShift(toShift); } template <int i,class... Args> struct HashCounter; template <int i,class A,class... Tail> struct HashCounter<i,A,Tail...> { typedef HashCounter<i+1,Tail...> TailCounter; static size_t hash() { return hashType<i,A>() ^ TailCounter::hash(); } }; template <int i,class A> struct HashCounter<i,A> { static size_t hash() { return hashType<i,A>(); } }; template <class... Args> size_t hashTypes() { return HashCounter<0,Args...>::hash(); } } } #endif /* end of include guard: VARIADIC_HXND7XSS */ <|endoftext|>
<commit_before> struct FLV_Pack { int len; int buf; bool isKeyframe; char * data; };//FLV_Pack char FLVHeader[13]; bool All_Hell_Broke_Loose = false; //checks FLV Header for correctness //returns true if everything is alright, false otherwise bool FLV_Checkheader(char * header){ if (header[0] != 'F') return false; if (header[1] != 'L') return false; if (header[2] != 'V') return false; if (header[8] != 0x09) return false; if (header[9] != 0) return false; if (header[10] != 0) return false; if (header[11] != 0) return false; if (header[12] != 0) return false; return true; }//FLV_Checkheader //returns true if header is an FLV header bool FLV_Isheader(char * header){ if (header[0] != 'F') return false; if (header[1] != 'L') return false; if (header[2] != 'V') return false; return true; }//FLV_Isheader bool ReadUntil(char * buffer, unsigned int count, unsigned int & sofar, int sock){ if (sofar >= count){return true;} int r = 0; r = DDV_iread(buffer + sofar,count-sofar,sock); if (r < 0){ if (errno != EWOULDBLOCK){ All_Hell_Broke_Loose = true; fprintf(stderr, "ReadUntil fail: %s. All Hell Broke Loose!\n", strerror(errno)); } return false; } sofar += r; if (sofar >= count){return true;} return false; } //gets a packet, storing in given FLV_Pack pointer. //will assign pointer if null //resizes FLV_Pack data field bigger if data doesn't fit // (does not auto-shrink for speed!) bool FLV_GetPacket(FLV_Pack *& p, int sock){ int preflags = fcntl(sock, F_GETFL, 0); int postflags = preflags | O_NONBLOCK; fcntl(sock, F_SETFL, postflags); static bool done = true; static unsigned int sofar = 0; if (!p){p = (FLV_Pack*)calloc(1, sizeof(FLV_Pack));} if (p->buf < 15){p->data = (char*)realloc(p->data, 15); p->buf = 15;} if (done){ //read a header if (ReadUntil(p->data, 11, sofar, sock)){ //if its a correct FLV header, throw away and read tag header if (FLV_Isheader(p->data)){ if (ReadUntil(p->data, 13, sofar, sock)){ if (FLV_Checkheader(p->data)){ sofar = 0; memcpy(FLVHeader, p->data, 13); }else{ All_Hell_Broke_Loose = true; fprintf(stderr, "Invalid FLV header. All Hell Broke Loose!\n"); } } }else{ //if a tag header, calculate length and read tag body p->len = p->data[3] + 15; p->len += (p->data[2] << 8); p->len += (p->data[1] << 16); fprintf(stderr, "Tag of len %i\n", p->len); if (p->buf < p->len){p->data = (char*)realloc(p->data, p->len);p->buf = p->len;} done = false; } } }else{ //read tag body if (ReadUntil(p->data, p->len, sofar, sock)){ //calculate keyframeness, next time read header again, return true p->isKeyframe = false; if ((p->data[0] == 0x09) && (((p->data[11] & 0xf0) >> 4) == 1)){p->isKeyframe = true;} done = true; sofar = 0; fcntl(sock, F_SETFL, preflags); return true; } } fcntl(sock, F_SETFL, preflags); return false; }//FLV_GetPacket <commit_msg>Minder debugging<commit_after> struct FLV_Pack { int len; int buf; bool isKeyframe; char * data; };//FLV_Pack char FLVHeader[13]; bool All_Hell_Broke_Loose = false; //checks FLV Header for correctness //returns true if everything is alright, false otherwise bool FLV_Checkheader(char * header){ if (header[0] != 'F') return false; if (header[1] != 'L') return false; if (header[2] != 'V') return false; if (header[8] != 0x09) return false; if (header[9] != 0) return false; if (header[10] != 0) return false; if (header[11] != 0) return false; if (header[12] != 0) return false; return true; }//FLV_Checkheader //returns true if header is an FLV header bool FLV_Isheader(char * header){ if (header[0] != 'F') return false; if (header[1] != 'L') return false; if (header[2] != 'V') return false; return true; }//FLV_Isheader bool ReadUntil(char * buffer, unsigned int count, unsigned int & sofar, int sock){ if (sofar >= count){return true;} int r = 0; r = DDV_iread(buffer + sofar,count-sofar,sock); if (r < 0){ if (errno != EWOULDBLOCK){ All_Hell_Broke_Loose = true; fprintf(stderr, "ReadUntil fail: %s. All Hell Broke Loose!\n", strerror(errno)); } return false; } sofar += r; if (sofar >= count){return true;} return false; } //gets a packet, storing in given FLV_Pack pointer. //will assign pointer if null //resizes FLV_Pack data field bigger if data doesn't fit // (does not auto-shrink for speed!) bool FLV_GetPacket(FLV_Pack *& p, int sock){ static bool done = true; static unsigned int sofar = 0; if (!p){p = (FLV_Pack*)calloc(1, sizeof(FLV_Pack));} if (p->buf < 15){p->data = (char*)realloc(p->data, 15); p->buf = 15;} if (done){ //read a header if (ReadUntil(p->data, 11, sofar, sock)){ //if its a correct FLV header, throw away and read tag header if (FLV_Isheader(p->data)){ if (ReadUntil(p->data, 13, sofar, sock)){ if (FLV_Checkheader(p->data)){ sofar = 0; memcpy(FLVHeader, p->data, 13); }else{ All_Hell_Broke_Loose = true; fprintf(stderr, "Invalid FLV header. All Hell Broke Loose!\n"); } } }else{ //if a tag header, calculate length and read tag body p->len = p->data[3] + 15; p->len += (p->data[2] << 8); p->len += (p->data[1] << 16); //fprintf(stderr, "Tag of len %i\n", p->len); if (p->buf < p->len){p->data = (char*)realloc(p->data, p->len);p->buf = p->len;} done = false; } } }else{ //read tag body if (ReadUntil(p->data, p->len, sofar, sock)){ //calculate keyframeness, next time read header again, return true p->isKeyframe = false; if ((p->data[0] == 0x09) && (((p->data[11] & 0xf0) >> 4) == 1)){p->isKeyframe = true;} done = true; sofar = 0; return true; } } return false; }//FLV_GetPacket <|endoftext|>
<commit_before>/* * Copyright (c) 2016 Nathan Lowe * * 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. * * crypto.cpp - An implementation of DES in ECB mode */ #include "stdafx.h" #include "crypto.h" #include "Boxes.h" #include "DESMath.h" #include "ExitCodes.h" #include <iostream> #include <fstream> #include <chrono> inline uint64_t permute(uint64_t in, const uint8_t* table, size_t inputSize, size_t outputSize) { uint64_t out = 0; for(size_t i = 0; i < outputSize; i++) { out |= ((in >> (inputSize - table[outputSize - 1 - i])) & 1) << i; } return out; } inline uint64_t substitute(uint64_t in) { auto b1 = extract6(in, 1); auto b2 = extract6(in, 2); auto b3 = extract6(in, 3); auto b4 = extract6(in, 4); auto b5 = extract6(in, 5); auto b6 = extract6(in, 6); auto b7 = extract6(in, 7); auto b8 = extract6(in, 8); return S[0][srow(b1)][scol(b1)] << 28 | S[1][srow(b2)][scol(b2)] << 24 | S[2][srow(b3)][scol(b3)] << 20 | S[3][srow(b4)][scol(b4)] << 16 | S[4][srow(b5)][scol(b5)] << 12 | S[5][srow(b6)][scol(b6)] << 8 | S[6][srow(b7)][scol(b7)] << 4 | S[7][srow(b8)][scol(b8)]; } void computeRoundKeys(uint64_t key, uint64_t (&keys)[16]) { // Initialize the key // 1. Compress and Permute the key into 56 bits // 2. Split the key into two 28 bit halves uint64_t keyLeft, keyRight; split56(permute(key, KeyPC64To56, 64, 56), keyLeft, keyRight); for(auto i = 0; i < 16; i++) { rotL28(keyLeft, RotationSchedule[i]); rotL28(keyRight, RotationSchedule[i]); keys[i] = permute(join56(keyLeft, keyRight), KeyPC56To48, 56, 48); } } uint64_t TransformBlock(uint64_t block, uint64_t (&keys)[16], DES::Action action) { // Perform the initial permutation on the plaintext auto permutedBlock = permute(block, InitalBlockPermutation, 64, 64); // Split the plaintext into 32 bit left and right halves uint64_t left, right; // Perform the initial permutation split64(permutedBlock, left, right); // 16 fistel rounds for(auto i = 0; i < 16; i++) { // Expand and permute the right half of the block to 48 bits auto expandedRightHalf = permute(right, BlockPE32To48, 32, 48) & MASK48; // XOR with the round key auto roundKey = keys[action == DES::Action::ENCRYPT ? i : 15-i]; expandedRightHalf ^= roundKey; // Substitute via S-Boxes auto substituted = substitute(expandedRightHalf); // Perform the final permutation auto ciphertext = permute(substituted, BlockP32, 32, 32) & MASK32; // XOR with the left half ciphertext ^= left; // Swap the half-blocks for the next round left = right; right = ciphertext; } auto finalBlock = join64(right, left); return permute(finalBlock, FinalBlockPermutation, 64, 64); } int DES::EncryptFile(std::string inputFile, std::string outputFile, uint64_t key, Mode mode, Optional<uint64_t> CBCInitialVector) { std::ifstream reader; reader.open(inputFile, std::ios::binary | std::ios::ate | std::ios::in); if(!reader.good()) { std::cerr << "Unable to open file for read: " << inputFile << std::endl; return EXIT_ERR_BAD_INPUT; } size_t len = reader.tellg(); if (len > MASK31) { std::cerr << "Input file too large according to spec. Must be less than 2GiB" << std::endl; return EXIT_ERR_TOO_BIG; } reader.seekg(0, std::ios::beg); std::ofstream writer; writer.open(outputFile, std::ios::binary | std::ios::out); if(!writer.good()) { std::cerr << "Unable to open file for write: " << outputFile << std::endl; reader.close(); return EXIT_ERR_BAD_OUTPUT; } auto start = std::chrono::high_resolution_clock::now(); uint64_t keys[16]; computeRoundKeys(key, keys); // Write the length of the file so we can determine how much padding we used when decrypting auto headerBlock = join64(RandomHalfBlock(), len); // Used in CBC mode only uint64_t previousBlock; if(CBCInitialVector.HasValue()) { previousBlock = CBCInitialVector.GetValue(); headerBlock ^= previousBlock; } auto encryptedHeader = TransformBlock(headerBlock, keys, DES::Action::ENCRYPT); previousBlock = encryptedHeader; auto outputBuffer = _byteswap_uint64(encryptedHeader); // Write encrypted header writer.write(reinterpret_cast<const char*>(&outputBuffer), DES_BLOCK_SIZE_BYTES); auto needsPadding = len % 8 != 0; // Read file into memory auto bytes = new uint64_t[ len/8 + (needsPadding ? 1 : 0)]{ 0 }; if(needsPadding) { // Initialize the last block to a random block for padding // The high bytes will be overwritten with actual data bytes[len/8] = RandomBlock(); } reader.read(reinterpret_cast<char*>(bytes), len); reader.close(); size_t written = 0; size_t currentBlock = 0; while(written < len) { uint64_t block; block = _byteswap_uint64(bytes[currentBlock++]); written += DES_BLOCK_SIZE_BYTES; if(CBCInitialVector.HasValue()) { block ^= previousBlock; } auto encryptedBlock = TransformBlock(block, keys, DES::Action::ENCRYPT); if(CBCInitialVector.HasValue()) { previousBlock = encryptedBlock; } outputBuffer = _byteswap_uint64(encryptedBlock); // Write block writer.write(reinterpret_cast<const char*>(&outputBuffer), DES_BLOCK_SIZE_BYTES); } writer.flush(); writer.close(); auto end = std::chrono::high_resolution_clock::now(); // Convert to floating point milliseconds std::chrono::duration<double, std::milli> duration = end - start; std::cout << "Encrypted " << currentBlock << " blocks in " << duration.count() << "ms" << std::endl; delete[] bytes; return EXIT_SUCCESS; } int DES::DecryptFile(std::string inputFile, std::string outputFile, uint64_t key, Mode mode, Optional<uint64_t> CBCInitialVector) { std::ifstream reader; reader.open(inputFile, std::ios::binary | std::ios::ate | std::ios::in); if(!reader.good()) { std::cerr << "Unable to open file for read: " << inputFile << std::endl; return EXIT_ERR_BAD_INPUT; } size_t len = reader.tellg(); len -= DES_BLOCK_SIZE_BYTES; if (len > MASK31) { std::cerr << "Input file too large according to spec. Must be less than 2GiB" << std::endl; return EXIT_ERR_TOO_BIG; } if(len % 8 != 0) { std::cerr << "Input file not 64-bit aligned" << std::endl; return EXIT_ERR_BAD_INPUT; } reader.seekg(0, std::ios::beg); std::ofstream writer; writer.open(outputFile, std::ios::binary | std::ios::out); if(!writer.good()) { std::cerr << "Unable to open file for write: " << outputFile << std::endl; reader.close(); return EXIT_ERR_BAD_OUTPUT; } auto start = std::chrono::high_resolution_clock::now(); auto bytes = new uint64_t[len/8]; uint64_t keys[16]; computeRoundKeys(key, keys); char rawheader[8] = { 0 }; reader.read(rawheader, DES_BLOCK_SIZE_BYTES); reader.read(reinterpret_cast<char*>(bytes), len); // Read the length of the file so we can determine how much padding we used when encrypting auto headerBlock = extract64FromBuff(rawheader, 0); auto decryptedHeader = TransformBlock(headerBlock, keys, DES::Action::DECRYPT); // Used in CBC mode only uint64_t previousBlock; if(CBCInitialVector.HasValue()) { previousBlock = CBCInitialVector.GetValue(); headerBlock ^= previousBlock; } previousBlock = decryptedHeader; // How much padding did we use? auto padding = len - (decryptedHeader & MASK32); size_t written = 0; size_t currentBlock = 0; while(written != len) { auto block = _byteswap_uint64(bytes[currentBlock++]); written += DES_BLOCK_SIZE_BYTES; auto decryptedBlock = TransformBlock(block, keys, DES::Action::DECRYPT); if(CBCInitialVector.HasValue()) { decryptedBlock ^= previousBlock; previousBlock = decryptedBlock; } auto isPaddingBlock = written == len && padding > 0; auto outputBuffer = _byteswap_uint64(decryptedBlock); writer.write(reinterpret_cast<const char*>(&outputBuffer), isPaddingBlock ? 8-padding : DES_BLOCK_SIZE_BYTES); } auto end = std::chrono::high_resolution_clock::now(); // Convert to floating point milliseconds std::chrono::duration<double, std::milli> duration = end - start; std::cout << "Decrypted " << currentBlock << " blocks in " << duration.count() << "ms" << std::endl; delete[] bytes; return EXIT_SUCCESS; } <commit_msg>Fix CBC Mode (Fixes #4)<commit_after>/* * Copyright (c) 2016 Nathan Lowe * * 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. * * crypto.cpp - An implementation of DES in ECB mode */ #include "stdafx.h" #include "crypto.h" #include "Boxes.h" #include "DESMath.h" #include "ExitCodes.h" #include <iostream> #include <fstream> #include <chrono> inline uint64_t permute(uint64_t in, const uint8_t* table, size_t inputSize, size_t outputSize) { uint64_t out = 0; for(size_t i = 0; i < outputSize; i++) { out |= ((in >> (inputSize - table[outputSize - 1 - i])) & 1) << i; } return out; } inline uint64_t substitute(uint64_t in) { auto b1 = extract6(in, 1); auto b2 = extract6(in, 2); auto b3 = extract6(in, 3); auto b4 = extract6(in, 4); auto b5 = extract6(in, 5); auto b6 = extract6(in, 6); auto b7 = extract6(in, 7); auto b8 = extract6(in, 8); return S[0][srow(b1)][scol(b1)] << 28 | S[1][srow(b2)][scol(b2)] << 24 | S[2][srow(b3)][scol(b3)] << 20 | S[3][srow(b4)][scol(b4)] << 16 | S[4][srow(b5)][scol(b5)] << 12 | S[5][srow(b6)][scol(b6)] << 8 | S[6][srow(b7)][scol(b7)] << 4 | S[7][srow(b8)][scol(b8)]; } void computeRoundKeys(uint64_t key, uint64_t (&keys)[16]) { // Initialize the key // 1. Compress and Permute the key into 56 bits // 2. Split the key into two 28 bit halves uint64_t keyLeft, keyRight; split56(permute(key, KeyPC64To56, 64, 56), keyLeft, keyRight); for(auto i = 0; i < 16; i++) { rotL28(keyLeft, RotationSchedule[i]); rotL28(keyRight, RotationSchedule[i]); keys[i] = permute(join56(keyLeft, keyRight), KeyPC56To48, 56, 48); } } uint64_t TransformBlock(uint64_t block, uint64_t (&keys)[16], DES::Action action) { // Perform the initial permutation on the plaintext auto permutedBlock = permute(block, InitalBlockPermutation, 64, 64); // Split the plaintext into 32 bit left and right halves uint64_t left, right; // Perform the initial permutation split64(permutedBlock, left, right); // 16 fistel rounds for(auto i = 0; i < 16; i++) { // Expand and permute the right half of the block to 48 bits auto expandedRightHalf = permute(right, BlockPE32To48, 32, 48) & MASK48; // XOR with the round key auto roundKey = keys[action == DES::Action::ENCRYPT ? i : 15-i]; expandedRightHalf ^= roundKey; // Substitute via S-Boxes auto substituted = substitute(expandedRightHalf); // Perform the final permutation auto ciphertext = permute(substituted, BlockP32, 32, 32) & MASK32; // XOR with the left half ciphertext ^= left; // Swap the half-blocks for the next round left = right; right = ciphertext; } auto finalBlock = join64(right, left); return permute(finalBlock, FinalBlockPermutation, 64, 64); } int DES::EncryptFile(std::string inputFile, std::string outputFile, uint64_t key, Mode mode, Optional<uint64_t> CBCInitialVector) { std::ifstream reader; reader.open(inputFile, std::ios::binary | std::ios::ate | std::ios::in); if(!reader.good()) { std::cerr << "Unable to open file for read: " << inputFile << std::endl; return EXIT_ERR_BAD_INPUT; } size_t len = reader.tellg(); if (len > MASK31) { std::cerr << "Input file too large according to spec. Must be less than 2GiB" << std::endl; return EXIT_ERR_TOO_BIG; } reader.seekg(0, std::ios::beg); std::ofstream writer; writer.open(outputFile, std::ios::binary | std::ios::out); if(!writer.good()) { std::cerr << "Unable to open file for write: " << outputFile << std::endl; reader.close(); return EXIT_ERR_BAD_OUTPUT; } auto start = std::chrono::high_resolution_clock::now(); uint64_t keys[16]; computeRoundKeys(key, keys); // Write the length of the file so we can determine how much padding we used when decrypting auto headerBlock = join64(RandomHalfBlock(), len); // Used in CBC mode only if(CBCInitialVector.HasValue()) { headerBlock ^= CBCInitialVector.GetValue(); } auto encryptedHeader = TransformBlock(headerBlock, keys, DES::Action::ENCRYPT); auto previousBlock = encryptedHeader; auto outputBuffer = _byteswap_uint64(encryptedHeader); // Write encrypted header writer.write(reinterpret_cast<const char*>(&outputBuffer), DES_BLOCK_SIZE_BYTES); auto needsPadding = len % 8 != 0; // Read file into memory auto bytes = new uint64_t[ len/8 + (needsPadding ? 1 : 0)]{ 0 }; if(needsPadding) { // Initialize the last block to a random block for padding // The high bytes will be overwritten with actual data bytes[len/8] = RandomBlock(); } reader.read(reinterpret_cast<char*>(bytes), len); reader.close(); size_t written = 0; size_t currentBlock = 0; while(written < len) { uint64_t block; block = _byteswap_uint64(bytes[currentBlock++]); written += DES_BLOCK_SIZE_BYTES; if(CBCInitialVector.HasValue()) { block ^= previousBlock; } auto encryptedBlock = TransformBlock(block, keys, DES::Action::ENCRYPT); if(CBCInitialVector.HasValue()) { previousBlock = encryptedBlock; } outputBuffer = _byteswap_uint64(encryptedBlock); // Write block writer.write(reinterpret_cast<const char*>(&outputBuffer), DES_BLOCK_SIZE_BYTES); } writer.flush(); writer.close(); auto end = std::chrono::high_resolution_clock::now(); // Convert to floating point milliseconds std::chrono::duration<double, std::milli> duration = end - start; std::cout << "Encrypted " << currentBlock << " blocks in " << duration.count() << "ms" << std::endl; delete[] bytes; return EXIT_SUCCESS; } int DES::DecryptFile(std::string inputFile, std::string outputFile, uint64_t key, Mode mode, Optional<uint64_t> CBCInitialVector) { std::ifstream reader; reader.open(inputFile, std::ios::binary | std::ios::ate | std::ios::in); if(!reader.good()) { std::cerr << "Unable to open file for read: " << inputFile << std::endl; return EXIT_ERR_BAD_INPUT; } size_t len = reader.tellg(); len -= DES_BLOCK_SIZE_BYTES; if (len > MASK31) { std::cerr << "Input file too large according to spec. Must be less than 2GiB" << std::endl; return EXIT_ERR_TOO_BIG; } if(len % 8 != 0) { std::cerr << "Input file not 64-bit aligned" << std::endl; return EXIT_ERR_BAD_INPUT; } reader.seekg(0, std::ios::beg); std::ofstream writer; writer.open(outputFile, std::ios::binary | std::ios::out); if(!writer.good()) { std::cerr << "Unable to open file for write: " << outputFile << std::endl; reader.close(); return EXIT_ERR_BAD_OUTPUT; } auto start = std::chrono::high_resolution_clock::now(); auto bytes = new uint64_t[len/8]; uint64_t keys[16]; computeRoundKeys(key, keys); char rawheader[8] = { 0 }; reader.read(rawheader, DES_BLOCK_SIZE_BYTES); reader.read(reinterpret_cast<char*>(bytes), len); // Read the length of the file so we can determine how much padding we used when encrypting auto headerBlock = extract64FromBuff(rawheader, 0); auto decryptedHeader = TransformBlock(headerBlock, keys, DES::Action::DECRYPT); // Used in CBC mode only if(CBCInitialVector.HasValue()) { decryptedHeader ^= CBCInitialVector.GetValue(); } auto previousBlock = headerBlock; // How much padding did we use? auto padding = len - (decryptedHeader & MASK32); size_t written = 0; size_t currentBlock = 0; while(written != len) { auto block = _byteswap_uint64(bytes[currentBlock++]); written += DES_BLOCK_SIZE_BYTES; auto decryptedBlock = TransformBlock(block, keys, DES::Action::DECRYPT); if(CBCInitialVector.HasValue()) { decryptedBlock ^= previousBlock; } previousBlock = block; auto isPaddingBlock = written == len && padding > 0; auto outputBuffer = _byteswap_uint64(decryptedBlock); writer.write(reinterpret_cast<const char*>(&outputBuffer), isPaddingBlock ? 8-padding : DES_BLOCK_SIZE_BYTES); } auto end = std::chrono::high_resolution_clock::now(); // Convert to floating point milliseconds std::chrono::duration<double, std::milli> duration = end - start; std::cout << "Decrypted " << currentBlock << " blocks in " << duration.count() << "ms" << std::endl; delete[] bytes; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/*************************************************************************** copyright : (C) 2002, 2003 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * * USA * ***************************************************************************/ #include <tdebug.h> #include <tfile.h> #include "id3v1tag.h" #include "id3v1genres.h" using namespace TagLib; using namespace ID3v1; class ID3v1::Tag::TagPrivate { public: TagPrivate() : file(0), tagOffset(-1), track(0), genre(255) {} File *file; long tagOffset; String title; String artist; String album; String year; String comment; uchar track; uchar genre; static const StringHandler *stringHandler; }; const ID3v1::StringHandler *ID3v1::Tag::TagPrivate::stringHandler = new StringHandler; //////////////////////////////////////////////////////////////////////////////// // StringHandler implementation //////////////////////////////////////////////////////////////////////////////// String ID3v1::StringHandler::parse(const ByteVector &data) const { return String(data, String::Latin1); } ByteVector ID3v1::StringHandler::render(const String &s) const { return s.data(String::Latin1); } //////////////////////////////////////////////////////////////////////////////// // public methods //////////////////////////////////////////////////////////////////////////////// ID3v1::Tag::Tag() : TagLib::Tag() { d = new TagPrivate; } ID3v1::Tag::Tag(File *file, long tagOffset) : TagLib::Tag() { d = new TagPrivate; d->file = file; d->tagOffset = tagOffset; read(); } ID3v1::Tag::~Tag() { delete d; } ByteVector ID3v1::Tag::render() const { ByteVector data; data.append(fileIdentifier()); data.append(TagPrivate::stringHandler->render(d->title).resize(30)); data.append(TagPrivate::stringHandler->render(d->artist).resize(30)); data.append(TagPrivate::stringHandler->render(d->album).resize(30)); data.append(TagPrivate::stringHandler->render(d->year).resize(4)); data.append(TagPrivate::stringHandler->render(d->comment).resize(28)); data.append(char(0)); data.append(char(d->track)); data.append(char(d->genre)); return data; } ByteVector ID3v1::Tag::fileIdentifier() { return ByteVector::fromCString("TAG"); } String ID3v1::Tag::title() const { return d->title; } String ID3v1::Tag::artist() const { return d->artist; } String ID3v1::Tag::album() const { return d->album; } String ID3v1::Tag::comment() const { return d->comment; } String ID3v1::Tag::genre() const { return ID3v1::genre(d->genre); } TagLib::uint ID3v1::Tag::year() const { return d->year.toInt(); } TagLib::uint ID3v1::Tag::track() const { return d->track; } void ID3v1::Tag::setTitle(const String &s) { d->title = s; } void ID3v1::Tag::setArtist(const String &s) { d->artist = s; } void ID3v1::Tag::setAlbum(const String &s) { d->album = s; } void ID3v1::Tag::setComment(const String &s) { d->comment = s; } void ID3v1::Tag::setGenre(const String &s) { d->genre = ID3v1::genreIndex(s); } void ID3v1::Tag::setYear(uint i) { d->year = String::number(i); } void ID3v1::Tag::setTrack(uint i) { d->track = i; } void ID3v1::Tag::setStringHandler(const StringHandler *handler) { delete TagPrivate::stringHandler; TagPrivate::stringHandler = handler; } //////////////////////////////////////////////////////////////////////////////// // protected methods //////////////////////////////////////////////////////////////////////////////// void ID3v1::Tag::read() { if(d->file && d->file->isValid()) { d->file->seek(d->tagOffset); // read the tag -- always 128 bytes ByteVector data = d->file->readBlock(128); // some initial sanity checking if(data.size() == 128 && data.mid(0, 3) == "TAG") parse(data); else debug("ID3v1 tag is not valid or could not be read at the specified offset."); } } void ID3v1::Tag::parse(const ByteVector &data) { int offset = 3; d->title = TagPrivate::stringHandler->parse(data.mid(offset, 30)); offset += 30; d->artist = TagPrivate::stringHandler->parse(data.mid(offset, 30)); offset += 30; d->album = TagPrivate::stringHandler->parse(data.mid(offset, 30)); offset += 30; d->year = TagPrivate::stringHandler->parse(data.mid(offset, 4)); offset += 4; // Check for ID3v1.1 -- Note that ID3v1 *does not* support "track zero" -- this // is not a bug in TagLib. Since a zeroed byte is what we would expect to // indicate the end of a C-String, specifically the comment string, a value of // zero must be assumed to be just that. if(data[offset + 28] == 0 && data[offset + 29] != 0) { // ID3v1.1 detected d->comment = TagPrivate::stringHandler->parse(data.mid(offset, 28)); d->track = uchar(data[offset + 29]); } else d->comment = data.mid(offset, 30); offset += 30; d->genre = uchar(data[offset]); } <commit_msg>Don't write a track number if the track is larger than 255.<commit_after>/*************************************************************************** copyright : (C) 2002, 2003 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * * USA * ***************************************************************************/ #include <tdebug.h> #include <tfile.h> #include "id3v1tag.h" #include "id3v1genres.h" using namespace TagLib; using namespace ID3v1; class ID3v1::Tag::TagPrivate { public: TagPrivate() : file(0), tagOffset(-1), track(0), genre(255) {} File *file; long tagOffset; String title; String artist; String album; String year; String comment; uchar track; uchar genre; static const StringHandler *stringHandler; }; const ID3v1::StringHandler *ID3v1::Tag::TagPrivate::stringHandler = new StringHandler; //////////////////////////////////////////////////////////////////////////////// // StringHandler implementation //////////////////////////////////////////////////////////////////////////////// String ID3v1::StringHandler::parse(const ByteVector &data) const { return String(data, String::Latin1); } ByteVector ID3v1::StringHandler::render(const String &s) const { return s.data(String::Latin1); } //////////////////////////////////////////////////////////////////////////////// // public methods //////////////////////////////////////////////////////////////////////////////// ID3v1::Tag::Tag() : TagLib::Tag() { d = new TagPrivate; } ID3v1::Tag::Tag(File *file, long tagOffset) : TagLib::Tag() { d = new TagPrivate; d->file = file; d->tagOffset = tagOffset; read(); } ID3v1::Tag::~Tag() { delete d; } ByteVector ID3v1::Tag::render() const { ByteVector data; data.append(fileIdentifier()); data.append(TagPrivate::stringHandler->render(d->title).resize(30)); data.append(TagPrivate::stringHandler->render(d->artist).resize(30)); data.append(TagPrivate::stringHandler->render(d->album).resize(30)); data.append(TagPrivate::stringHandler->render(d->year).resize(4)); data.append(TagPrivate::stringHandler->render(d->comment).resize(28)); data.append(char(0)); data.append(char(d->track)); data.append(char(d->genre)); return data; } ByteVector ID3v1::Tag::fileIdentifier() { return ByteVector::fromCString("TAG"); } String ID3v1::Tag::title() const { return d->title; } String ID3v1::Tag::artist() const { return d->artist; } String ID3v1::Tag::album() const { return d->album; } String ID3v1::Tag::comment() const { return d->comment; } String ID3v1::Tag::genre() const { return ID3v1::genre(d->genre); } TagLib::uint ID3v1::Tag::year() const { return d->year.toInt(); } TagLib::uint ID3v1::Tag::track() const { return d->track; } void ID3v1::Tag::setTitle(const String &s) { d->title = s; } void ID3v1::Tag::setArtist(const String &s) { d->artist = s; } void ID3v1::Tag::setAlbum(const String &s) { d->album = s; } void ID3v1::Tag::setComment(const String &s) { d->comment = s; } void ID3v1::Tag::setGenre(const String &s) { d->genre = ID3v1::genreIndex(s); } void ID3v1::Tag::setYear(uint i) { d->year = String::number(i); } void ID3v1::Tag::setTrack(uint i) { d->track = i < 256 ? i : 0; } void ID3v1::Tag::setStringHandler(const StringHandler *handler) { delete TagPrivate::stringHandler; TagPrivate::stringHandler = handler; } //////////////////////////////////////////////////////////////////////////////// // protected methods //////////////////////////////////////////////////////////////////////////////// void ID3v1::Tag::read() { if(d->file && d->file->isValid()) { d->file->seek(d->tagOffset); // read the tag -- always 128 bytes ByteVector data = d->file->readBlock(128); // some initial sanity checking if(data.size() == 128 && data.mid(0, 3) == "TAG") parse(data); else debug("ID3v1 tag is not valid or could not be read at the specified offset."); } } void ID3v1::Tag::parse(const ByteVector &data) { int offset = 3; d->title = TagPrivate::stringHandler->parse(data.mid(offset, 30)); offset += 30; d->artist = TagPrivate::stringHandler->parse(data.mid(offset, 30)); offset += 30; d->album = TagPrivate::stringHandler->parse(data.mid(offset, 30)); offset += 30; d->year = TagPrivate::stringHandler->parse(data.mid(offset, 4)); offset += 4; // Check for ID3v1.1 -- Note that ID3v1 *does not* support "track zero" -- this // is not a bug in TagLib. Since a zeroed byte is what we would expect to // indicate the end of a C-String, specifically the comment string, a value of // zero must be assumed to be just that. if(data[offset + 28] == 0 && data[offset + 29] != 0) { // ID3v1.1 detected d->comment = TagPrivate::stringHandler->parse(data.mid(offset, 28)); d->track = uchar(data[offset + 29]); } else d->comment = data.mid(offset, 30); offset += 30; d->genre = uchar(data[offset]); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: NameContainer.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: vg $ $Date: 2007-05-22 18:19:47 $ * * 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 _CHART2_NAMECONTAINER_HXX #define _CHART2_NAMECONTAINER_HXX #ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_ #include <com/sun/star/container/XNameContainer.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_ #include <com/sun/star/uno/XComponentContext.hpp> #endif #ifndef _COM_SUN_STAR_UTIL_XCLONEABLE_HPP_ #include <com/sun/star/util/XCloneable.hpp> #endif #ifndef _CPPUHELPER_IMPLBASE3_HXX_ #include <cppuhelper/implbase3.hxx> #endif #include <map> //............................................................................. namespace chart { //............................................................................. class NameContainer : public ::cppu::WeakImplHelper3< ::com::sun::star::container::XNameContainer , ::com::sun::star::lang::XServiceInfo , ::com::sun::star::util::XCloneable > { public: NameContainer( const ::com::sun::star::uno::Type& rType, const rtl::OUString& rServicename, const rtl::OUString& rImplementationName ); explicit NameContainer( const NameContainer & rOther ); virtual ~NameContainer(); // XServiceInfo virtual ::rtl::OUString SAL_CALL getImplementationName( ) throw(::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw(::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( ) throw(::com::sun::star::uno::RuntimeException); // XNameContainer virtual void SAL_CALL insertByName( const rtl::OUString& aName, const com::sun::star::uno::Any& aElement ) throw( com::sun::star::lang::IllegalArgumentException, com::sun::star::container::ElementExistException, com::sun::star::lang::WrappedTargetException, com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeByName( const rtl::OUString& Name ) throw( com::sun::star::container::NoSuchElementException, com::sun::star::lang::WrappedTargetException, com::sun::star::uno::RuntimeException); // XNameReplace virtual void SAL_CALL replaceByName( const rtl::OUString& aName, const com::sun::star::uno::Any& aElement ) throw( com::sun::star::lang::IllegalArgumentException, com::sun::star::container::NoSuchElementException, com::sun::star::lang::WrappedTargetException, com::sun::star::uno::RuntimeException); // XNameAccess virtual com::sun::star::uno::Any SAL_CALL getByName( const rtl::OUString& aName ) throw( com::sun::star::container::NoSuchElementException, com::sun::star::lang::WrappedTargetException, com::sun::star::uno::RuntimeException); virtual com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL getElementNames( ) throw( com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL hasByName( const rtl::OUString& aName ) throw( com::sun::star::uno::RuntimeException); // XElementAccess virtual sal_Bool SAL_CALL hasElements( ) throw( com::sun::star::uno::RuntimeException); virtual com::sun::star::uno::Type SAL_CALL getElementType( ) throw( com::sun::star::uno::RuntimeException); // XCloneable virtual ::com::sun::star::uno::Reference< ::com::sun::star::util::XCloneable > SAL_CALL createClone() throw (::com::sun::star::uno::RuntimeException); private: //methods NameContainer();//no default contructor private: //member const ::com::sun::star::uno::Type m_aType; const rtl::OUString m_aServicename; const rtl::OUString m_aImplementationName; typedef ::std::map< ::rtl::OUString, com::sun::star::uno::Any > tContentMap; tContentMap m_aMap; }; //............................................................................. } //namespace chart //............................................................................. #endif <commit_msg>INTEGRATION: CWS chart07 (1.2.12); FILE MERGED 2007/07/10 14:42:15 bm 1.2.12.1: #i69281# warnings removed<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: NameContainer.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2007-07-25 08:46:57 $ * * 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 _CHART2_NAMECONTAINER_HXX #define _CHART2_NAMECONTAINER_HXX #ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_ #include <com/sun/star/container/XNameContainer.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_ #include <com/sun/star/uno/XComponentContext.hpp> #endif #ifndef _COM_SUN_STAR_UTIL_XCLONEABLE_HPP_ #include <com/sun/star/util/XCloneable.hpp> #endif #ifndef _CPPUHELPER_IMPLBASE3_HXX_ #include <cppuhelper/implbase3.hxx> #endif #include <map> //............................................................................. namespace chart { //............................................................................. namespace impl { typedef ::cppu::WeakImplHelper3< ::com::sun::star::container::XNameContainer, ::com::sun::star::lang::XServiceInfo, ::com::sun::star::util::XCloneable > NameContainer_Base; } class NameContainer : public impl::NameContainer_Base { public: NameContainer( const ::com::sun::star::uno::Type& rType, const rtl::OUString& rServicename, const rtl::OUString& rImplementationName ); explicit NameContainer( const NameContainer & rOther ); virtual ~NameContainer(); // XServiceInfo virtual ::rtl::OUString SAL_CALL getImplementationName( ) throw(::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw(::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( ) throw(::com::sun::star::uno::RuntimeException); // XNameContainer virtual void SAL_CALL insertByName( const rtl::OUString& aName, const com::sun::star::uno::Any& aElement ) throw( com::sun::star::lang::IllegalArgumentException, com::sun::star::container::ElementExistException, com::sun::star::lang::WrappedTargetException, com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeByName( const rtl::OUString& Name ) throw( com::sun::star::container::NoSuchElementException, com::sun::star::lang::WrappedTargetException, com::sun::star::uno::RuntimeException); // XNameReplace virtual void SAL_CALL replaceByName( const rtl::OUString& aName, const com::sun::star::uno::Any& aElement ) throw( com::sun::star::lang::IllegalArgumentException, com::sun::star::container::NoSuchElementException, com::sun::star::lang::WrappedTargetException, com::sun::star::uno::RuntimeException); // XNameAccess virtual com::sun::star::uno::Any SAL_CALL getByName( const rtl::OUString& aName ) throw( com::sun::star::container::NoSuchElementException, com::sun::star::lang::WrappedTargetException, com::sun::star::uno::RuntimeException); virtual com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL getElementNames( ) throw( com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL hasByName( const rtl::OUString& aName ) throw( com::sun::star::uno::RuntimeException); // XElementAccess virtual sal_Bool SAL_CALL hasElements( ) throw( com::sun::star::uno::RuntimeException); virtual com::sun::star::uno::Type SAL_CALL getElementType( ) throw( com::sun::star::uno::RuntimeException); // XCloneable virtual ::com::sun::star::uno::Reference< ::com::sun::star::util::XCloneable > SAL_CALL createClone() throw (::com::sun::star::uno::RuntimeException); private: //methods NameContainer();//no default contructor private: //member const ::com::sun::star::uno::Type m_aType; const rtl::OUString m_aServicename; const rtl::OUString m_aImplementationName; typedef ::std::map< ::rtl::OUString, com::sun::star::uno::Any > tContentMap; tContentMap m_aMap; }; //............................................................................. } //namespace chart //............................................................................. #endif <|endoftext|>
<commit_before>/** * @author Mike Bogochow * @version 2.4.0, Dec 8, 2015 * * @file Bidder.cpp * * Bidder class implementation */ #include "Bidder.h" #include "../lib_graphs/Graph.h" #include "../lib_graphs/Subgraph.h" #include "../lib_graphs/SpanningTree.h" #include "../lib_graphs/Path.h" //#include "../lib_graphs/defs.h" #include "../lib_auction/AuctionDefs.h" #include "../lib_auction/DebugPrinter.h" #include "MBUtils.h" #include <boost/lexical_cast.hpp> #include <algorithm> // std::remove #include <chrono> #include <thread> Bidder::Bidder(void) { m_iterations = 0; // g = new Graph(__edges, __num_edges, __weights, __num_nodes); // // // TODO add me to the graph // // allocated.reserve(__num_nodes); // unallocated.reserve(__num_nodes); // // for (Vertex i = 0; i < __num_nodes; i++) // unallocated.push_back(i); g = nullptr; rtc = 0; roundNumber = 0; roundUpdated = false; winnerUpdated = false; id = -1; } Bidder::~Bidder(void) { delete g; } bool Bidder::OnNewMail(MOOSMSG_LIST &NewMail) { bool ret = AuctionMOOSApp::OnNewMail(NewMail); MOOSMSG_LIST::reverse_iterator p; for(p = NewMail.rbegin(); p != NewMail.rend(); p++) { CMOOSMsg &msg = *p; std::string key = msg.GetKey(); MOOSTrace("key=%s, g==nullptr=%s\n", msg.GetString().c_str(), boost::lexical_cast<std::string>(g==nullptr).c_str()); if (key == MVAR_BID_TARGETS && g == nullptr) // ignore if already have g { std::string sTargets = msg.GetString(); pathFromString(sTargets, targets); size_t numTargets = targets.size(); std::vector<Edge> edges; std::vector<mbogo_weight_t> weights; connectEdges(targets, edges, weights); g = new Graph(edges.data(), edges.size(), weights.data(), numTargets); // TODO add me to the graph allocated.reserve(numTargets); unallocated.reserve(numTargets); for (Vertex i = 0; i < numTargets; i++) unallocated.push_back(i); } else if (key == MVAR_BID_START) { size_t num = boost::lexical_cast<size_t>(msg.GetString()); if (num > roundNumber) // ignore duplicate messages { if (num != roundNumber + 1) { MOOSTrace("WARNING: received round number %i while on round %i", num, roundNumber); } roundUpdated = true; roundNumber = num; dp.dprintf(LVL_MIN_VERB, "Got %s mail: %i\n", MVAR_BID_START.c_str(), num); } } else if (key == MVAR_BID_WINNER) { winnerUpdated = true; winningBid = winningBidFromString(msg.GetString()); dp.dprintf(LVL_MIN_VERB, "Got %s mail: %s\n", MVAR_BID_WINNER.c_str(), winningBid); } } return ret; } bool Bidder::Iterate(void) { bool ret = AuctionMOOSApp::Iterate(); if (g != nullptr) { if (winnerUpdated) { if (winningBid.winner == id) { allocated.push_back(winningBid.target); rtc += winningBid.bid; } unallocated.erase( std::remove(unallocated.begin(), unallocated.end(), winningBid.target), unallocated.end()); winnerUpdated = false; } dp.dprintf(LVL_MAX_VERB, "roundNum <= numNodes (%lu <= %lu)?\n", roundNumber, g->getNumVertices()); if (roundNumber <= g->getNumVertices()) { if (roundUpdated) { performBiddingRound(); roundUpdated = false; } } else { assert(unallocated.size() == 0); performFinalCalc(); // Exit pBidder doNotify("EXITED_NORMALLY", "pBidder"); // Ensure all data makes it to the MOOSDB std::this_thread::sleep_for(std::chrono::seconds(10)); exit(0); } } return ret; } void Bidder::performBiddingRound(void) { // Bidding round Bid currentBid = std::make_pair(MAX_VERTEX, MAX_WEIGHT); Graph *sub; // Iterate through unallocated nodes to find bid for (std::vector<Vertex>::iterator t = unallocated.begin(); t != unallocated.end(); t++) { Path *path; SpanningTree *tree; mbogo_weight_t cost; mbogo_weight_t bid; std::vector<Vertex> possibleAllocation; possibleAllocation.reserve(allocated.size() + 1); possibleAllocation = allocated; dp.dprintf(LVL_BID, "Adding %s for possible allocation\n", boost::lexical_cast<std::string>(*t).c_str()); possibleAllocation.push_back(*t); // Catch simple cases for efficiency if (possibleAllocation.size() == 1) { cost = bid = 0; } else if (possibleAllocation.size() == 2) { path = Path::fromPair( std::make_pair(possibleAllocation.front(), possibleAllocation.back())); cost = path->getTotalCost(g->getGraph()); bid = cost - rtc; delete path; } else { sub = g->getSubgraph(possibleAllocation); dp.dprintf(LVL_BID, "Subgraph:\n%s\n", sub->toString().c_str()); tree = SpanningTree::fromGraph(sub->getGraph()); dp.dprintf(LVL_BID, "Spanning Tree:\n%s\n", tree->toString().c_str()); path = Path::fromTree(tree); dp.dprintf(LVL_BID, "Path:\n%s\n", path->toString().c_str()); cost = path->getTotalCost(g->getGraph()); bid = cost - rtc; delete path; delete tree; delete sub; } dp.dprintf(LVL_BID, "bid[%lu_%s]=%s (cost-rtc)=(%s-%s)\n", roundNumber, boost::lexical_cast<std::string>(*t).c_str(), boost::lexical_cast<std::string>(bid).c_str(), boost::lexical_cast<std::string>(cost).c_str(), boost::lexical_cast<std::string>(rtc).c_str() ); if (currentBid.second > bid && bid >= 0) currentBid = std::make_pair(*t, bid); dp.dprintf(LVL_BID, "cur_bid=%s:%s\n", boost::lexical_cast<std::string>(currentBid.first).c_str(), boost::lexical_cast<std::string>(currentBid.second).c_str()); } assert(currentBid.first != MAX_VERTEX && currentBid.second != MAX_WEIGHT); // Send bid to MOOSDB doNotify(getBidVar(id), bidToString(currentBid)); } void Bidder::performFinalCalc(void) { // Do final cost calculation and submit path Subgraph *sub = Subgraph::fromGraph(g, allocated); SpanningTree *tree = SpanningTree::fromGraph(sub->getGraph()); Path *path = Path::fromTree(tree); Loc *locs = new Loc[path->getLength()]; // Debug output DebugLevel LVL_FINAL_PATH = LVL_MID_VERB; if (dp.isValidLevel(LVL_FINAL_PATH)) // extra check to avoid extra work { dp.dprintf(LVL_FINAL_PATH, "Final allocated:\n"); int count = 0; for (std::vector<Vertex>::iterator it = allocated.begin(); it != allocated.end(); it++) { dp.dprintf(LVL_FINAL_PATH, "\tallocated[%i]:%s\n", count++, boost::lexical_cast<std::string>(*it).c_str()); } dp.dprintf(LVL_FINAL_PATH, "Final path:\n%s\n", path->toString().c_str()); } // Convert the path indices to those in the origin graph path->convertPath(sub->getParentIndices()); dp.dprintf(LVL_FINAL_PATH, "Converted path:\n%s\n", path->toString().c_str()); // Get the coordinates of the vertices path->getLocations(__locations, locs); // Send the path to the MOOSDB doNotify(getPathVar(id), getPathVarVal(pathToString(locs, path->getLength()))); delete sub; delete tree; delete path; delete locs; } bool Bidder::OnStartUp(void) { bool ret; // Read the DebugOutput configuration field int debugLevel; if (!m_MissionReader.GetConfigurationParam("DebugOutput", debugLevel)) debugLevel = LVL_OFF; dp.setLevel((DebugLevel)debugLevel); ret = AuctionMOOSApp::OnStartUp(); // Read the AgentID configuration field if (!m_MissionReader.GetConfigurationParam("AgentID", id)) { MOOSTrace("Warning: parameter 'AgentID' not specified.\n"); MOOSTrace("Terminating\n"); exit(-1); } RegisterVariables(); return ret; } bool Bidder::OnConnectToServer(void) { bool ret = AuctionMOOSApp::OnConnectToServer(); RegisterVariables(); return ret; } void Bidder::RegisterVariables(void) { m_Comms.Register("BID_WINNER", 0); m_Comms.Register("BID_START", 0); } <commit_msg>Fixed debug output and registered for targets<commit_after>/** * @author Mike Bogochow * @version 2.4.0, Dec 8, 2015 * * @file Bidder.cpp * * Bidder class implementation */ #include "Bidder.h" #include "../lib_graphs/Graph.h" #include "../lib_graphs/Subgraph.h" #include "../lib_graphs/SpanningTree.h" #include "../lib_graphs/Path.h" //#include "../lib_graphs/defs.h" #include "../lib_auction/AuctionDefs.h" #include "../lib_auction/DebugPrinter.h" #include "MBUtils.h" #include <boost/lexical_cast.hpp> #include <algorithm> // std::remove #include <chrono> #include <thread> Bidder::Bidder(void) { m_iterations = 0; // g = new Graph(__edges, __num_edges, __weights, __num_nodes); // // // TODO add me to the graph // // allocated.reserve(__num_nodes); // unallocated.reserve(__num_nodes); // // for (Vertex i = 0; i < __num_nodes; i++) // unallocated.push_back(i); g = nullptr; rtc = 0; roundNumber = 0; roundUpdated = false; winnerUpdated = false; id = -1; } Bidder::~Bidder(void) { delete g; } bool Bidder::OnNewMail(MOOSMSG_LIST &NewMail) { bool ret = AuctionMOOSApp::OnNewMail(NewMail); MOOSMSG_LIST::reverse_iterator p; for(p = NewMail.rbegin(); p != NewMail.rend(); p++) { CMOOSMsg &msg = *p; std::string key = msg.GetKey(); MOOSTrace("key=%s, g==nullptr=%s\n", key.c_str(), boost::lexical_cast<std::string>(g==nullptr).c_str()); if (key == MVAR_BID_TARGETS && g == nullptr) // ignore if already have g { std::string sTargets = msg.GetString(); pathFromString(sTargets, targets); size_t numTargets = targets.size(); std::vector<Edge> edges; std::vector<mbogo_weight_t> weights; connectEdges(targets, edges, weights); g = new Graph(edges.data(), edges.size(), weights.data(), numTargets); // TODO add me to the graph allocated.reserve(numTargets); unallocated.reserve(numTargets); for (Vertex i = 0; i < numTargets; i++) unallocated.push_back(i); } else if (key == MVAR_BID_START) { size_t num = boost::lexical_cast<size_t>(msg.GetString()); if (num > roundNumber) // ignore duplicate messages { if (num != roundNumber + 1) { MOOSTrace("WARNING: received round number %i while on round %i", num, roundNumber); } roundUpdated = true; roundNumber = num; dp.dprintf(LVL_MIN_VERB, "Got %s mail: %i\n", MVAR_BID_START.c_str(), num); } } else if (key == MVAR_BID_WINNER) { winnerUpdated = true; winningBid = winningBidFromString(msg.GetString()); dp.dprintf(LVL_MIN_VERB, "Got %s mail: %s\n", MVAR_BID_WINNER.c_str(), winningBid); } } return ret; } bool Bidder::Iterate(void) { bool ret = AuctionMOOSApp::Iterate(); if (g != nullptr) { if (winnerUpdated) { if (winningBid.winner == id) { allocated.push_back(winningBid.target); rtc += winningBid.bid; } unallocated.erase( std::remove(unallocated.begin(), unallocated.end(), winningBid.target), unallocated.end()); winnerUpdated = false; } dp.dprintf(LVL_MAX_VERB, "roundNum <= numNodes (%lu <= %lu)?\n", roundNumber, g->getNumVertices()); if (roundNumber <= g->getNumVertices()) { if (roundUpdated) { performBiddingRound(); roundUpdated = false; } } else { assert(unallocated.size() == 0); performFinalCalc(); // Exit pBidder doNotify("EXITED_NORMALLY", "pBidder"); // Ensure all data makes it to the MOOSDB std::this_thread::sleep_for(std::chrono::seconds(10)); exit(0); } } return ret; } void Bidder::performBiddingRound(void) { // Bidding round Bid currentBid = std::make_pair(MAX_VERTEX, MAX_WEIGHT); Graph *sub; // Iterate through unallocated nodes to find bid for (std::vector<Vertex>::iterator t = unallocated.begin(); t != unallocated.end(); t++) { Path *path; SpanningTree *tree; mbogo_weight_t cost; mbogo_weight_t bid; std::vector<Vertex> possibleAllocation; possibleAllocation.reserve(allocated.size() + 1); possibleAllocation = allocated; dp.dprintf(LVL_BID, "Adding %s for possible allocation\n", boost::lexical_cast<std::string>(*t).c_str()); possibleAllocation.push_back(*t); // Catch simple cases for efficiency if (possibleAllocation.size() == 1) { cost = bid = 0; } else if (possibleAllocation.size() == 2) { path = Path::fromPair( std::make_pair(possibleAllocation.front(), possibleAllocation.back())); cost = path->getTotalCost(g->getGraph()); bid = cost - rtc; delete path; } else { sub = g->getSubgraph(possibleAllocation); dp.dprintf(LVL_BID, "Subgraph:\n%s\n", sub->toString().c_str()); tree = SpanningTree::fromGraph(sub->getGraph()); dp.dprintf(LVL_BID, "Spanning Tree:\n%s\n", tree->toString().c_str()); path = Path::fromTree(tree); dp.dprintf(LVL_BID, "Path:\n%s\n", path->toString().c_str()); cost = path->getTotalCost(g->getGraph()); bid = cost - rtc; delete path; delete tree; delete sub; } dp.dprintf(LVL_BID, "bid[%lu_%s]=%s (cost-rtc)=(%s-%s)\n", roundNumber, boost::lexical_cast<std::string>(*t).c_str(), boost::lexical_cast<std::string>(bid).c_str(), boost::lexical_cast<std::string>(cost).c_str(), boost::lexical_cast<std::string>(rtc).c_str() ); if (currentBid.second > bid && bid >= 0) currentBid = std::make_pair(*t, bid); dp.dprintf(LVL_BID, "cur_bid=%s:%s\n", boost::lexical_cast<std::string>(currentBid.first).c_str(), boost::lexical_cast<std::string>(currentBid.second).c_str()); } assert(currentBid.first != MAX_VERTEX && currentBid.second != MAX_WEIGHT); // Send bid to MOOSDB doNotify(getBidVar(id), bidToString(currentBid)); } void Bidder::performFinalCalc(void) { // Do final cost calculation and submit path Subgraph *sub = Subgraph::fromGraph(g, allocated); SpanningTree *tree = SpanningTree::fromGraph(sub->getGraph()); Path *path = Path::fromTree(tree); Loc *locs = new Loc[path->getLength()]; // Debug output DebugLevel LVL_FINAL_PATH = LVL_MID_VERB; if (dp.isValidLevel(LVL_FINAL_PATH)) // extra check to avoid extra work { dp.dprintf(LVL_FINAL_PATH, "Final allocated:\n"); int count = 0; for (std::vector<Vertex>::iterator it = allocated.begin(); it != allocated.end(); it++) { dp.dprintf(LVL_FINAL_PATH, "\tallocated[%i]:%s\n", count++, boost::lexical_cast<std::string>(*it).c_str()); } dp.dprintf(LVL_FINAL_PATH, "Final path:\n%s\n", path->toString().c_str()); } // Convert the path indices to those in the origin graph path->convertPath(sub->getParentIndices()); dp.dprintf(LVL_FINAL_PATH, "Converted path:\n%s\n", path->toString().c_str()); // Get the coordinates of the vertices path->getLocations(__locations, locs); // Send the path to the MOOSDB doNotify(getPathVar(id), getPathVarVal(pathToString(locs, path->getLength()))); delete sub; delete tree; delete path; delete locs; } bool Bidder::OnStartUp(void) { bool ret; // Read the DebugOutput configuration field int debugLevel; if (!m_MissionReader.GetConfigurationParam("DebugOutput", debugLevel)) debugLevel = LVL_OFF; dp.setLevel((DebugLevel)debugLevel); ret = AuctionMOOSApp::OnStartUp(); // Read the AgentID configuration field if (!m_MissionReader.GetConfigurationParam("AgentID", id)) { MOOSTrace("Warning: parameter 'AgentID' not specified.\n"); MOOSTrace("Terminating\n"); exit(-1); } RegisterVariables(); return ret; } bool Bidder::OnConnectToServer(void) { bool ret = AuctionMOOSApp::OnConnectToServer(); RegisterVariables(); return ret; } void Bidder::RegisterVariables(void) { m_Comms.Register(MVAR_BID_WINNER, 0); m_Comms.Register(MVAR_BID_START, 0); m_Comms.Register(MVAR_BID_TARGETS, 0); } <|endoftext|>
<commit_before>/* * LoginConn.cpp * * Created on: 2013-6-21 * Author: ziteng@mogujie.com */ #include "LoginConn.h" #include "IM.Server.pb.h" #include "IM.Other.pb.h" #include "IM.Login.pb.h" #include "public_define.h" using namespace IM::BaseDefine; static ConnMap_t g_client_conn_map; static ConnMap_t g_msg_serv_conn_map; static uint32_t g_total_online_user_cnt = 0; // 并发在线总人数 map<uint32_t, msg_serv_info_t*> g_msg_serv_info; void login_conn_timer_callback(void* callback_data, uint8_t msg, uint32_t handle, void* pParam) { uint64_t cur_time = get_tick_count(); for (ConnMap_t::iterator it = g_client_conn_map.begin(); it != g_client_conn_map.end(); ) { ConnMap_t::iterator it_old = it; it++; CLoginConn* pConn = (CLoginConn*)it_old->second; pConn->OnTimer(cur_time); } for (ConnMap_t::iterator it = g_msg_serv_conn_map.begin(); it != g_msg_serv_conn_map.end(); ) { ConnMap_t::iterator it_old = it; it++; CLoginConn* pConn = (CLoginConn*)it_old->second; pConn->OnTimer(cur_time); } } void init_login_conn() { netlib_register_timer(login_conn_timer_callback, NULL, 1000); } CLoginConn::CLoginConn() { } CLoginConn::~CLoginConn() { } void CLoginConn::Close() { if (m_handle != NETLIB_INVALID_HANDLE) { netlib_close(m_handle); if (m_conn_type == LOGIN_CONN_TYPE_CLIENT) { g_client_conn_map.erase(m_handle); } else { g_msg_serv_conn_map.erase(m_handle); // remove all user count from this message server map<uint32_t, msg_serv_info_t*>::iterator it = g_msg_serv_info.find(m_handle); if (it != g_msg_serv_info.end()) { msg_serv_info_t* pMsgServInfo = it->second; g_total_online_user_cnt -= pMsgServInfo->cur_conn_cnt; log("onclose from MsgServer: %s:%u ", pMsgServInfo->hostname.c_str(), pMsgServInfo->port); delete pMsgServInfo; g_msg_serv_info.erase(it); } } } ReleaseRef(); } void CLoginConn::OnConnect2(net_handle_t handle, int conn_type) { m_handle = handle; m_conn_type = conn_type; ConnMap_t* conn_map = &g_msg_serv_conn_map; if (conn_type == LOGIN_CONN_TYPE_CLIENT) { conn_map = &g_client_conn_map; }else conn_map->insert(make_pair(handle, this)); netlib_option(handle, NETLIB_OPT_SET_CALLBACK, (void*)imconn_callback); netlib_option(handle, NETLIB_OPT_SET_CALLBACK_DATA, (void*)conn_map); } void CLoginConn::OnClose() { Close(); } void CLoginConn::OnTimer(uint64_t curr_tick) { if (m_conn_type == LOGIN_CONN_TYPE_CLIENT) { if (curr_tick > m_last_recv_tick + CLIENT_TIMEOUT) { Close(); } } else { if (curr_tick > m_last_send_tick + SERVER_HEARTBEAT_INTERVAL) { IM::Other::IMHeartBeat msg; CImPdu pdu; pdu.SetPBMsg(&msg); pdu.SetServiceId(SID_OTHER); pdu.SetCommandId(CID_OTHER_HEARTBEAT); SendPdu(&pdu); } if (curr_tick > m_last_recv_tick + SERVER_TIMEOUT) { log("connection to MsgServer timeout "); Close(); } } } void CLoginConn::HandlePdu(CImPdu* pPdu) { switch (pPdu->GetCommandId()) { case CID_OTHER_HEARTBEAT: break; case CID_OTHER_MSG_SERV_INFO: _HandleMsgServInfo(pPdu); break; case CID_OTHER_USER_CNT_UPDATE: _HandleUserCntUpdate(pPdu); break; case CID_LOGIN_REQ_MSGSERVER: _HandleMsgServRequest(pPdu); break; default: log("wrong msg, cmd id=%d ", pPdu->GetCommandId()); break; } } void CLoginConn::_HandleMsgServInfo(CImPdu* pPdu) { msg_serv_info_t* pMsgServInfo = new msg_serv_info_t; IM::Server::IMMsgServInfo msg; msg.ParseFromArray(pPdu->GetBodyData(), pPdu->GetBodyLength()); pMsgServInfo->ip_addr1 = msg.ip1(); pMsgServInfo->ip_addr2 = msg.ip2(); pMsgServInfo->port = msg.port(); pMsgServInfo->max_conn_cnt = msg.max_conn_cnt(); pMsgServInfo->cur_conn_cnt = msg.cur_conn_cnt(); pMsgServInfo->hostname = msg.host_name(); g_msg_serv_info.insert(make_pair(m_handle, pMsgServInfo)); g_total_online_user_cnt += pMsgServInfo->cur_conn_cnt; log("MsgServInfo, ip_addr1=%s, ip_addr2=%s, port=%d, max_conn_cnt=%d, cur_conn_cnt=%d, "\ "hostname: %s. ", pMsgServInfo->ip_addr1.c_str(), pMsgServInfo->ip_addr2.c_str(), pMsgServInfo->port,pMsgServInfo->max_conn_cnt, pMsgServInfo->cur_conn_cnt, pMsgServInfo->hostname.c_str()); } void CLoginConn::_HandleUserCntUpdate(CImPdu* pPdu) { map<uint32_t, msg_serv_info_t*>::iterator it = g_msg_serv_info.find(m_handle); if (it != g_msg_serv_info.end()) { msg_serv_info_t* pMsgServInfo = it->second; IM::Server::IMUserCntUpdate msg; msg.ParseFromArray(pPdu->GetBodyData(), pPdu->GetBodyLength()); uint32_t action = msg.user_action(); if (action == USER_CNT_INC) { pMsgServInfo->cur_conn_cnt++; g_total_online_user_cnt++; } else { pMsgServInfo->cur_conn_cnt--; g_total_online_user_cnt--; } log("%s:%d, cur_cnt=%u, total_cnt=%u ", pMsgServInfo->hostname.c_str(), pMsgServInfo->port, pMsgServInfo->cur_conn_cnt, g_total_online_user_cnt); } } void CLoginConn::_HandleMsgServRequest(CImPdu* pPdu) { IM::Login::IMMsgServReq msg; msg.ParseFromArray(pPdu->GetBodyData(), pPdu->GetBodyLength()); log("HandleMsgServReq. "); // no MessageServer available if (g_msg_serv_info.size() == 0) { IM::Login::IMMsgServRsp msg; msg.set_result_code(::IM::BaseDefine::REFUSE_REASON_NO_MSG_SERVER); CImPdu pdu; pdu.SetPBMsg(&msg); pdu.SetServiceId(SID_LOGIN); pdu.SetCommandId(CID_LOGIN_RES_MSGSERVER); pdu.SetSeqNum(pPdu->GetSeqNum()); SendPdu(&pdu); Close(); return; } // return a message server with minimum concurrent connection count msg_serv_info_t* pMsgServInfo; uint32_t min_user_cnt = (uint32_t)-1; map<uint32_t, msg_serv_info_t*>::iterator it_min_conn = g_msg_serv_info.end(),it; for (it = g_msg_serv_info.begin() ; it != g_msg_serv_info.end(); it++) { pMsgServInfo = it->second; if ( (pMsgServInfo->cur_conn_cnt < pMsgServInfo->max_conn_cnt) && (pMsgServInfo->cur_conn_cnt < min_user_cnt)) { it_min_conn = it; min_user_cnt = pMsgServInfo->cur_conn_cnt; } } if (it_min_conn == g_msg_serv_info.end()) { log("All TCP MsgServer are full "); IM::Login::IMMsgServRsp msg; msg.set_result_code(::IM::BaseDefine::REFUSE_REASON_MSG_SERVER_FULL); CImPdu pdu; pdu.SetPBMsg(&msg); pdu.SetServiceId(SID_LOGIN); pdu.SetCommandId(CID_LOGIN_RES_MSGSERVER); pdu.SetSeqNum(pPdu->GetSeqNum()); SendPdu(&pdu); } else { IM::Login::IMMsgServRsp msg; msg.set_result_code(::IM::BaseDefine::REFUSE_REASON_NONE); msg.set_prior_ip(it_min_conn->second->ip_addr1); msg.set_backip_ip(it_min_conn->second->ip_addr2); msg.set_port(it_min_conn->second->port); CImPdu pdu; pdu.SetPBMsg(&msg); pdu.SetServiceId(SID_LOGIN); pdu.SetCommandId(CID_LOGIN_RES_MSGSERVER); pdu.SetSeqNum(pPdu->GetSeqNum()); SendPdu(&pdu); } Close(); // after send MsgServResponse, active close the connection } <commit_msg>[CMT]add comment<commit_after>/* * LoginConn.cpp * * Created on: 2013-6-21 * Author: ziteng@mogujie.com */ #include "LoginConn.h" #include "IM.Server.pb.h" #include "IM.Other.pb.h" #include "IM.Login.pb.h" #include "public_define.h" using namespace IM::BaseDefine; static ConnMap_t g_client_conn_map; static ConnMap_t g_msg_serv_conn_map; static uint32_t g_total_online_user_cnt = 0; // 并发在线总人数 map<uint32_t, msg_serv_info_t*> g_msg_serv_info; //--> foreach conn in conn_map do OnTimer() : process timeout or send heartbeat msg void login_conn_timer_callback(void* callback_data, uint8_t msg, uint32_t handle, void* pParam) { uint64_t cur_time = get_tick_count(); for (ConnMap_t::iterator it = g_client_conn_map.begin(); it != g_client_conn_map.end(); ) { ConnMap_t::iterator it_old = it; it++; CLoginConn* pConn = (CLoginConn*)it_old->second; pConn->OnTimer(cur_time); } for (ConnMap_t::iterator it = g_msg_serv_conn_map.begin(); it != g_msg_serv_conn_map.end(); ) { ConnMap_t::iterator it_old = it; it++; CLoginConn* pConn = (CLoginConn*)it_old->second; pConn->OnTimer(cur_time); } } void init_login_conn() { netlib_register_timer(login_conn_timer_callback, NULL, 1000); } CLoginConn::CLoginConn() { } CLoginConn::~CLoginConn() { } void CLoginConn::Close() { if (m_handle != NETLIB_INVALID_HANDLE) { netlib_close(m_handle); if (m_conn_type == LOGIN_CONN_TYPE_CLIENT) { g_client_conn_map.erase(m_handle); } else { g_msg_serv_conn_map.erase(m_handle); // remove all user count from this message server map<uint32_t, msg_serv_info_t*>::iterator it = g_msg_serv_info.find(m_handle); if (it != g_msg_serv_info.end()) { msg_serv_info_t* pMsgServInfo = it->second; g_total_online_user_cnt -= pMsgServInfo->cur_conn_cnt; log("onclose from MsgServer: %s:%u ", pMsgServInfo->hostname.c_str(), pMsgServInfo->port); delete pMsgServInfo; g_msg_serv_info.erase(it); } } } ReleaseRef(); } //--> insert pair into conn_map and reset basesock's callback function and data void CLoginConn::OnConnect2(net_handle_t handle, int conn_type) { m_handle = handle; m_conn_type = conn_type; ConnMap_t* conn_map = &g_msg_serv_conn_map; if (conn_type == LOGIN_CONN_TYPE_CLIENT) { conn_map = &g_client_conn_map; }else conn_map->insert(make_pair(handle, this)); netlib_option(handle, NETLIB_OPT_SET_CALLBACK, (void*)imconn_callback); netlib_option(handle, NETLIB_OPT_SET_CALLBACK_DATA, (void*)conn_map); } void CLoginConn::OnClose() { Close(); } //--> on timer : check timeout or send heartbeat msg void CLoginConn::OnTimer(uint64_t curr_tick) { if (m_conn_type == LOGIN_CONN_TYPE_CLIENT) { if (curr_tick > m_last_recv_tick + CLIENT_TIMEOUT) { Close(); } } else { if (curr_tick > m_last_send_tick + SERVER_HEARTBEAT_INTERVAL) { IM::Other::IMHeartBeat msg; CImPdu pdu; pdu.SetPBMsg(&msg); pdu.SetServiceId(SID_OTHER); pdu.SetCommandId(CID_OTHER_HEARTBEAT); SendPdu(&pdu); } if (curr_tick > m_last_recv_tick + SERVER_TIMEOUT) { log("connection to MsgServer timeout "); Close(); } } } //--> according pdu's commandid handle pdu void CLoginConn::HandlePdu(CImPdu* pPdu) { switch (pPdu->GetCommandId()) { case CID_OTHER_HEARTBEAT: break; case CID_OTHER_MSG_SERV_INFO: _HandleMsgServInfo(pPdu); break; case CID_OTHER_USER_CNT_UPDATE: _HandleUserCntUpdate(pPdu); break; case CID_LOGIN_REQ_MSGSERVER: _HandleMsgServRequest(pPdu); break; default: log("wrong msg, cmd id=%d ", pPdu->GetCommandId()); break; } } //--> insert msg server info from pdu to g_msg_serv_info void CLoginConn::_HandleMsgServInfo(CImPdu* pPdu) { msg_serv_info_t* pMsgServInfo = new msg_serv_info_t; IM::Server::IMMsgServInfo msg; msg.ParseFromArray(pPdu->GetBodyData(), pPdu->GetBodyLength()); pMsgServInfo->ip_addr1 = msg.ip1(); pMsgServInfo->ip_addr2 = msg.ip2(); pMsgServInfo->port = msg.port(); pMsgServInfo->max_conn_cnt = msg.max_conn_cnt(); pMsgServInfo->cur_conn_cnt = msg.cur_conn_cnt(); pMsgServInfo->hostname = msg.host_name(); g_msg_serv_info.insert(make_pair(m_handle, pMsgServInfo)); g_total_online_user_cnt += pMsgServInfo->cur_conn_cnt; log("MsgServInfo, ip_addr1=%s, ip_addr2=%s, port=%d, max_conn_cnt=%d, cur_conn_cnt=%d, "\ "hostname: %s. ", pMsgServInfo->ip_addr1.c_str(), pMsgServInfo->ip_addr2.c_str(), pMsgServInfo->port,pMsgServInfo->max_conn_cnt, pMsgServInfo->cur_conn_cnt, pMsgServInfo->hostname.c_str()); } //--> update msg server info item according to pdu's user_action void CLoginConn::_HandleUserCntUpdate(CImPdu* pPdu) { map<uint32_t, msg_serv_info_t*>::iterator it = g_msg_serv_info.find(m_handle); if (it != g_msg_serv_info.end()) { msg_serv_info_t* pMsgServInfo = it->second; IM::Server::IMUserCntUpdate msg; msg.ParseFromArray(pPdu->GetBodyData(), pPdu->GetBodyLength()); uint32_t action = msg.user_action(); if (action == USER_CNT_INC) { pMsgServInfo->cur_conn_cnt++; g_total_online_user_cnt++; } else { pMsgServInfo->cur_conn_cnt--; g_total_online_user_cnt--; } log("%s:%d, cur_cnt=%u, total_cnt=%u ", pMsgServInfo->hostname.c_str(), pMsgServInfo->port, pMsgServInfo->cur_conn_cnt, g_total_online_user_cnt); } } //--> request msg server ; send pdu's content socket for ack void CLoginConn::_HandleMsgServRequest(CImPdu* pPdu) { IM::Login::IMMsgServReq msg; msg.ParseFromArray(pPdu->GetBodyData(), pPdu->GetBodyLength()); log("HandleMsgServReq. "); // no MessageServer available if (g_msg_serv_info.size() == 0) { IM::Login::IMMsgServRsp msg; msg.set_result_code(::IM::BaseDefine::REFUSE_REASON_NO_MSG_SERVER); CImPdu pdu; pdu.SetPBMsg(&msg); pdu.SetServiceId(SID_LOGIN); pdu.SetCommandId(CID_LOGIN_RES_MSGSERVER); pdu.SetSeqNum(pPdu->GetSeqNum()); SendPdu(&pdu); Close(); return; } // return a message server with minimum concurrent connection count msg_serv_info_t* pMsgServInfo; uint32_t min_user_cnt = (uint32_t)-1; map<uint32_t, msg_serv_info_t*>::iterator it_min_conn = g_msg_serv_info.end(),it; for (it = g_msg_serv_info.begin() ; it != g_msg_serv_info.end(); it++) { pMsgServInfo = it->second; if ( (pMsgServInfo->cur_conn_cnt < pMsgServInfo->max_conn_cnt) && (pMsgServInfo->cur_conn_cnt < min_user_cnt)) { it_min_conn = it; min_user_cnt = pMsgServInfo->cur_conn_cnt; } } if (it_min_conn == g_msg_serv_info.end()) { log("All TCP MsgServer are full "); IM::Login::IMMsgServRsp msg; msg.set_result_code(::IM::BaseDefine::REFUSE_REASON_MSG_SERVER_FULL); CImPdu pdu; pdu.SetPBMsg(&msg); pdu.SetServiceId(SID_LOGIN); pdu.SetCommandId(CID_LOGIN_RES_MSGSERVER); pdu.SetSeqNum(pPdu->GetSeqNum()); SendPdu(&pdu); } else { IM::Login::IMMsgServRsp msg; msg.set_result_code(::IM::BaseDefine::REFUSE_REASON_NONE); msg.set_prior_ip(it_min_conn->second->ip_addr1); msg.set_backip_ip(it_min_conn->second->ip_addr2); msg.set_port(it_min_conn->second->port); CImPdu pdu; pdu.SetPBMsg(&msg); pdu.SetServiceId(SID_LOGIN); pdu.SetCommandId(CID_LOGIN_RES_MSGSERVER); pdu.SetSeqNum(pPdu->GetSeqNum()); SendPdu(&pdu); } Close(); // after send MsgServResponse, active close the connection } <|endoftext|>
<commit_before>/* Copyright 2020 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/xla/pjrt/tpu_client.h" #include <memory> #include <string> #include <utility> #include <vector> #include "absl/container/inlined_vector.h" #include "absl/status/status.h" #include "tensorflow/compiler/xla/client/client_library.h" #include "tensorflow/compiler/xla/pjrt/local_device_state.h" #include "tensorflow/compiler/xla/pjrt/pjrt_stream_executor_client.h" #include "tensorflow/compiler/xla/pjrt/tracked_device_buffer.h" #include "tensorflow/compiler/xla/pjrt/utils.h" #include "tensorflow/compiler/xla/service/shaped_buffer.h" #include "tensorflow/compiler/xla/service/tpu_computation_placer.h" #include "tensorflow/compiler/xla/shape.h" #include "tensorflow/compiler/xla/shape_util.h" #include "tensorflow/compiler/xla/status.h" #include "tensorflow/compiler/xla/util.h" #include "tensorflow/core/platform/casts.h" #include "tensorflow/core/platform/errors.h" #include "tensorflow/core/tpu/tpu_initializer_helper.h" #include "tensorflow/stream_executor/device_memory.h" #include "tensorflow/stream_executor/lib/statusor.h" #include "tensorflow/stream_executor/stream.h" #include "tensorflow/stream_executor/tpu/tpu_executable.h" #include "tensorflow/stream_executor/tpu/tpu_executable_interface.h" #include "tensorflow/stream_executor/tpu/tpu_executor_interface.h" #include "tensorflow/stream_executor/tpu/tpu_platform_interface.h" #include "tensorflow/stream_executor/tpu/tpu_stream.h" namespace tf_tpu = tensorflow::tpu; namespace xla { namespace { class TpuDeviceState : public LocalDeviceState { public: TpuDeviceState(se::StreamExecutor* executor, LocalClient* client, int max_inflight_computations); Status ThenMemcpyDeviceToDevice(se::Stream* transfer_stream, se::Stream* dst_stream, se::DeviceMemoryBase src_buffer, se::DeviceMemoryBase dst_buffer) override; }; TpuDeviceState::TpuDeviceState(se::StreamExecutor* executor, LocalClient* client, int max_inflight_computations) : LocalDeviceState(executor, client, LocalDeviceState::kAsynchronous, max_inflight_computations, /*allow_event_reuse=*/false, /*use_callback_stream=*/true) {} Status TpuDeviceState::ThenMemcpyDeviceToDevice( se::Stream* transfer_stream, se::Stream* dst_stream, se::DeviceMemoryBase src_buffer, se::DeviceMemoryBase dst_buffer) { auto* transfer_tpu_stream = tensorflow::down_cast<tf_tpu::TpuStream*>( transfer_stream->implementation()); TF_RETURN_IF_ERROR(transfer_tpu_stream->EnqueueOnTpuDeviceSendRecvLocal( src_buffer, dst_buffer)); return OkStatus(); } } // namespace PjRtTpuClient::PjRtTpuClient( LocalClient* client, std::vector<std::unique_ptr<PjRtStreamExecutorDevice>> devices, int process_index) : PjRtStreamExecutorClient(TpuName(), client, std::move(devices), process_index, /*allocator=*/nullptr, /*host_memory_allocator=*/nullptr, /*should_stage_host_to_device_transfers=*/false, /*gpu_run_options=*/nullptr), platform_version_([]() { // Example platform version string: // libtpu version 0.0.1 // Built on Mar 4 2021 15:25:57 (1614900357) cl/360760169 tf_tpu::TpuPlatformInterface* platform = tf_tpu::TpuPlatformInterface::GetRegisteredPlatform(); TpuRuntimeVersion version = platform->version(); return absl::StrCat( "libtpu version ", absl::StrJoin(version.version, "."), "\n", absl::string_view(version.metadata, version.metadata_size)); }()) { // We always initialize the tpu client even if libtpu isn't linked in or // initialized. if (tf_tpu::ExecutorApiFn()->TpuAsyncCollectiveOffloadHelper_InitFn != nullptr) { tf_tpu::ExecutorApiFn()->TpuAsyncCollectiveOffloadHelper_InitFn(); } } PjRtTpuClient::~PjRtTpuClient() { if (tf_tpu::ExecutorApiFn()->TpuAsyncCollectiveOffloadHelper_ShutdownFn != nullptr) { tf_tpu::ExecutorApiFn()->TpuAsyncCollectiveOffloadHelper_ShutdownFn(); } } StatusOr<DeviceAssignment> PjRtTpuClient::GetDefaultDeviceAssignment( int num_replicas, int num_partitions) const { tf_tpu::TpuPlatformInterface* platform = tf_tpu::TpuPlatformInterface::GetRegisteredPlatform(); tf_tpu::TpuHostLocationExternal host = platform->GetTpuHostLocation(); int num_local_devices = host.Cores(kTensorCore).size(); if (num_replicas * num_partitions <= num_local_devices) { return tf_tpu::TpuComputationPlacer::AssignLocalDevices(host, num_replicas, num_partitions); } // Fallback to default global device assignment if we can't run locally. return PjRtStreamExecutorClient::GetDefaultDeviceAssignment(num_replicas, num_partitions); } StatusOr<std::optional<std::string>> PjRtTpuClient::ExecutableFingerprint( const PjRtExecutable& executable) const { if (executable.client() != this) { return InvalidArgument( "Passed executable from different client (platform '%s') to " "PjRtTpuClient::ExecutableFingerprint", executable.client()->platform_name()); } if (executable.num_partitions() > 1) { LOG(INFO) << "ExecutableFingerprint not fully implemented for MPMD " "executables, fingerprint may not be unique."; } xla::TpuExecutableInterface* tpu_executable = tensorflow::down_cast<xla::TpuExecutableInterface*>( tensorflow::down_cast<const PjRtStreamExecutorExecutable*>( &executable) ->executables()[0] ->executable()); return std::optional<std::string>(tpu_executable->fingerprint()); } StatusOr<std::string> PjRtTpuClient::SerializeExecutable( const PjRtExecutable& executable) const { const PjRtStreamExecutorExecutable* se_executable = tensorflow::down_cast<const PjRtStreamExecutorExecutable*>(&executable); if (se_executable->executables().size() > 1) { return Unimplemented( "PjRtTpuClient::SerializeExecutable unimplemented for MPMD " "executables"); } const TpuExecutable* tpu_executable = tensorflow::down_cast<const TpuExecutable*>( se_executable->executables()[0]->executable()); return tpu_executable->Serialize(); } StatusOr<std::unique_ptr<PjRtExecutable>> PjRtTpuClient::DeserializeExecutable( absl::string_view serialized, CompileOptions options) { TF_ASSIGN_OR_RETURN(std::unique_ptr<TpuExecutable> tpu_executable, TpuExecutable::Deserialize(serialized)); TF_ASSIGN_OR_RETURN(ExecutableExtras extras, GetExecutableExtras(&options)); // TODO(skyewm): can we streamline this? e.g. removing proto serialization XlaComputation computation(tpu_executable->module().ToProto()); TF_ASSIGN_OR_RETURN(ProgramShape program_shape, computation.GetProgramShape()); std::vector<const Shape*> unused_argument_layout_pointers; TF_RETURN_IF_ERROR(DetermineArgumentLayoutsFromCompileOptions( computation, [local_client = client()](Shape shape) { return local_client->backend() .transfer_manager() ->ChooseCompactLayoutForShape(shape); }, options.argument_layouts, &options.executable_build_options, &unused_argument_layout_pointers)); auto local_executable = std::make_unique<LocalExecutable>( std::move(tpu_executable), client_->mutable_backend(), options.executable_build_options); std::vector<std::unique_ptr<LocalExecutable>> local_executables; local_executables.emplace_back(std::move(local_executable)); auto pjrt_executable = std::make_unique<PjRtStreamExecutorExecutable>( std::move(local_executables), options.parameter_is_tupled_arguments, std::move(extras.device_assignment), std::move(extras.addressable_device_logical_ids), std::move(extras.addressable_devices), this); TF_RETURN_IF_ERROR( pjrt_executable->SetUpDonation(options.parameter_is_tupled_arguments)); return std::unique_ptr<PjRtExecutable>(std::move(pjrt_executable)); } static StatusOr<std::vector<std::unique_ptr<PjRtStreamExecutorDevice>>> GetTpuDevices( LocalClient* client, std::vector<std::unique_ptr<LocalDeviceState>> local_device_states) { std::vector<std::unique_ptr<PjRtStreamExecutorDevice>> devices; tf_tpu::TpuTopologyExternal topology = tf_tpu::TpuPlatformInterface::GetRegisteredPlatform()->topology(); std::map<int, int> core_id_to_device_ordinal; for (int i = 0; i < client->device_count(); ++i) { se::StreamExecutor* executor = client->backend().stream_executor(i).ValueOrDie(); tf_tpu::TpuExecutorInterface* tpu_executor = tensorflow::down_cast<tf_tpu::TpuExecutorInterface*>( executor->implementation()); core_id_to_device_ordinal[tpu_executor->GetCoreLocationExternal().Id()] = i; } for (const tf_tpu::TpuCoreLocationExternal& core : topology.cores(TpuCoreTypeEnum::kTensorCore)) { auto it = core_id_to_device_ordinal.find(core.Id()); int device_ordinal = (it != core_id_to_device_ordinal.end()) ? it->second : -1; int process_index = topology.IdForHost(core.host_coordinates()); const tf_tpu::TpuDimensionsExternal coords = core.chip_coordinates(); std::array<int, 3> coords_array = {coords.x, coords.y, coords.z}; std::unique_ptr<LocalDeviceState> local_device_state; if (device_ordinal >= 0) { local_device_state = std::move(local_device_states[device_ordinal]); } auto device = std::make_unique<PjRtTpuDevice>( core, std::move(local_device_state), process_index, coords_array, std::string(tf_tpu::TpuVersionEnumToString(topology.version()))); devices.push_back(std::move(device)); } return devices; } StatusOr<std::shared_ptr<PjRtClient>> GetTpuClient( int max_inflight_computations, absl::Duration init_retry_timeout) { #if !defined(PLATFORM_GOOGLE) || defined(LIBTPU_ON_GCE) TF_RETURN_IF_ERROR(tensorflow::tpu::FindAndLoadTpuLibrary()); #endif tf_tpu::TpuPlatformInterface* platform = tf_tpu::TpuPlatformInterface::GetRegisteredPlatform( /*initialize_platform=*/true, /*num_tries=*/1); if (platform == nullptr) { return InvalidArgument("TpuPlatform is not available."); } // NOTE: We retry in a loop since some pod failures are transient (e.g. some // RPCs may timeout waiting for other hosts to come up, but will succeed // at a later point if retried). auto start = absl::Now(); while (true) { Status status = platform->Initialize({}); if (status.ok()) { break; } // TODO(b/165870356): refactor this loop to be // while(!platform->Initialized()) once the Initialized() function works // correctly, and remove this check. The platform may already be initialized // when running internally. if (status.code() == tensorflow::error::ALREADY_EXISTS) { LOG(INFO) << "TpuPlatform already initialized, continuing..."; break; } LOG(INFO) << "TPU platform initialization failed: " << status; if ((absl::Now() - start) >= init_retry_timeout) { return status; } absl::SleepFor(absl::Microseconds(10)); } CHECK(platform->Initialized()); if (platform->VisibleDeviceCount() <= 0) { return InvalidArgument("No TPU devices found."); } LocalClientOptions options; options.set_platform(platform); TF_ASSIGN_OR_RETURN(LocalClient * client, ClientLibrary::GetOrCreateLocalClient(options)); std::vector<std::unique_ptr<LocalDeviceState>> local_device_states; local_device_states.reserve(client->device_count()); for (int i = 0; i < client->device_count(); ++i) { se::StreamExecutor* executor = client->backend().stream_executor(i).ValueOrDie(); local_device_states.push_back(std::make_unique<TpuDeviceState>( executor, client, max_inflight_computations)); } TF_ASSIGN_OR_RETURN(auto devices, GetTpuDevices(client, std::move(local_device_states))); int process_index = platform->GetTpuHostLocation().Id(); return std::shared_ptr<PjRtClient>(std::make_unique<PjRtTpuClient>( client, std::move(devices), process_index)); } } // namespace xla <commit_msg>Narrow the scope of FindAndLoadTpuLibrary() calls<commit_after>/* Copyright 2020 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/xla/pjrt/tpu_client.h" #include <memory> #include <string> #include <utility> #include <vector> #include "absl/container/inlined_vector.h" #include "absl/status/status.h" #include "tensorflow/compiler/xla/client/client_library.h" #include "tensorflow/compiler/xla/pjrt/local_device_state.h" #include "tensorflow/compiler/xla/pjrt/pjrt_stream_executor_client.h" #include "tensorflow/compiler/xla/pjrt/tracked_device_buffer.h" #include "tensorflow/compiler/xla/pjrt/utils.h" #include "tensorflow/compiler/xla/service/shaped_buffer.h" #include "tensorflow/compiler/xla/service/tpu_computation_placer.h" #include "tensorflow/compiler/xla/shape.h" #include "tensorflow/compiler/xla/shape_util.h" #include "tensorflow/compiler/xla/status.h" #include "tensorflow/compiler/xla/util.h" #include "tensorflow/core/platform/casts.h" #include "tensorflow/core/platform/errors.h" #include "tensorflow/core/tpu/tpu_initializer_helper.h" #include "tensorflow/stream_executor/device_memory.h" #include "tensorflow/stream_executor/lib/statusor.h" #include "tensorflow/stream_executor/stream.h" #include "tensorflow/stream_executor/tpu/tpu_executable.h" #include "tensorflow/stream_executor/tpu/tpu_executable_interface.h" #include "tensorflow/stream_executor/tpu/tpu_executor_interface.h" #include "tensorflow/stream_executor/tpu/tpu_platform_interface.h" #include "tensorflow/stream_executor/tpu/tpu_stream.h" namespace tf_tpu = tensorflow::tpu; namespace xla { namespace { class TpuDeviceState : public LocalDeviceState { public: TpuDeviceState(se::StreamExecutor* executor, LocalClient* client, int max_inflight_computations); Status ThenMemcpyDeviceToDevice(se::Stream* transfer_stream, se::Stream* dst_stream, se::DeviceMemoryBase src_buffer, se::DeviceMemoryBase dst_buffer) override; }; TpuDeviceState::TpuDeviceState(se::StreamExecutor* executor, LocalClient* client, int max_inflight_computations) : LocalDeviceState(executor, client, LocalDeviceState::kAsynchronous, max_inflight_computations, /*allow_event_reuse=*/false, /*use_callback_stream=*/true) {} Status TpuDeviceState::ThenMemcpyDeviceToDevice( se::Stream* transfer_stream, se::Stream* dst_stream, se::DeviceMemoryBase src_buffer, se::DeviceMemoryBase dst_buffer) { auto* transfer_tpu_stream = tensorflow::down_cast<tf_tpu::TpuStream*>( transfer_stream->implementation()); TF_RETURN_IF_ERROR(transfer_tpu_stream->EnqueueOnTpuDeviceSendRecvLocal( src_buffer, dst_buffer)); return OkStatus(); } } // namespace PjRtTpuClient::PjRtTpuClient( LocalClient* client, std::vector<std::unique_ptr<PjRtStreamExecutorDevice>> devices, int process_index) : PjRtStreamExecutorClient(TpuName(), client, std::move(devices), process_index, /*allocator=*/nullptr, /*host_memory_allocator=*/nullptr, /*should_stage_host_to_device_transfers=*/false, /*gpu_run_options=*/nullptr), platform_version_([]() { // Example platform version string: // libtpu version 0.0.1 // Built on Mar 4 2021 15:25:57 (1614900357) cl/360760169 tf_tpu::TpuPlatformInterface* platform = tf_tpu::TpuPlatformInterface::GetRegisteredPlatform(); TpuRuntimeVersion version = platform->version(); return absl::StrCat( "libtpu version ", absl::StrJoin(version.version, "."), "\n", absl::string_view(version.metadata, version.metadata_size)); }()) { // We always initialize the tpu client even if libtpu isn't linked in or // initialized. if (tf_tpu::ExecutorApiFn()->TpuAsyncCollectiveOffloadHelper_InitFn != nullptr) { tf_tpu::ExecutorApiFn()->TpuAsyncCollectiveOffloadHelper_InitFn(); } } PjRtTpuClient::~PjRtTpuClient() { if (tf_tpu::ExecutorApiFn()->TpuAsyncCollectiveOffloadHelper_ShutdownFn != nullptr) { tf_tpu::ExecutorApiFn()->TpuAsyncCollectiveOffloadHelper_ShutdownFn(); } } StatusOr<DeviceAssignment> PjRtTpuClient::GetDefaultDeviceAssignment( int num_replicas, int num_partitions) const { tf_tpu::TpuPlatformInterface* platform = tf_tpu::TpuPlatformInterface::GetRegisteredPlatform(); tf_tpu::TpuHostLocationExternal host = platform->GetTpuHostLocation(); int num_local_devices = host.Cores(kTensorCore).size(); if (num_replicas * num_partitions <= num_local_devices) { return tf_tpu::TpuComputationPlacer::AssignLocalDevices(host, num_replicas, num_partitions); } // Fallback to default global device assignment if we can't run locally. return PjRtStreamExecutorClient::GetDefaultDeviceAssignment(num_replicas, num_partitions); } StatusOr<std::optional<std::string>> PjRtTpuClient::ExecutableFingerprint( const PjRtExecutable& executable) const { if (executable.client() != this) { return InvalidArgument( "Passed executable from different client (platform '%s') to " "PjRtTpuClient::ExecutableFingerprint", executable.client()->platform_name()); } if (executable.num_partitions() > 1) { LOG(INFO) << "ExecutableFingerprint not fully implemented for MPMD " "executables, fingerprint may not be unique."; } xla::TpuExecutableInterface* tpu_executable = tensorflow::down_cast<xla::TpuExecutableInterface*>( tensorflow::down_cast<const PjRtStreamExecutorExecutable*>( &executable) ->executables()[0] ->executable()); return std::optional<std::string>(tpu_executable->fingerprint()); } StatusOr<std::string> PjRtTpuClient::SerializeExecutable( const PjRtExecutable& executable) const { const PjRtStreamExecutorExecutable* se_executable = tensorflow::down_cast<const PjRtStreamExecutorExecutable*>(&executable); if (se_executable->executables().size() > 1) { return Unimplemented( "PjRtTpuClient::SerializeExecutable unimplemented for MPMD " "executables"); } const TpuExecutable* tpu_executable = tensorflow::down_cast<const TpuExecutable*>( se_executable->executables()[0]->executable()); return tpu_executable->Serialize(); } StatusOr<std::unique_ptr<PjRtExecutable>> PjRtTpuClient::DeserializeExecutable( absl::string_view serialized, CompileOptions options) { TF_ASSIGN_OR_RETURN(std::unique_ptr<TpuExecutable> tpu_executable, TpuExecutable::Deserialize(serialized)); TF_ASSIGN_OR_RETURN(ExecutableExtras extras, GetExecutableExtras(&options)); // TODO(skyewm): can we streamline this? e.g. removing proto serialization XlaComputation computation(tpu_executable->module().ToProto()); TF_ASSIGN_OR_RETURN(ProgramShape program_shape, computation.GetProgramShape()); std::vector<const Shape*> unused_argument_layout_pointers; TF_RETURN_IF_ERROR(DetermineArgumentLayoutsFromCompileOptions( computation, [local_client = client()](Shape shape) { return local_client->backend() .transfer_manager() ->ChooseCompactLayoutForShape(shape); }, options.argument_layouts, &options.executable_build_options, &unused_argument_layout_pointers)); auto local_executable = std::make_unique<LocalExecutable>( std::move(tpu_executable), client_->mutable_backend(), options.executable_build_options); std::vector<std::unique_ptr<LocalExecutable>> local_executables; local_executables.emplace_back(std::move(local_executable)); auto pjrt_executable = std::make_unique<PjRtStreamExecutorExecutable>( std::move(local_executables), options.parameter_is_tupled_arguments, std::move(extras.device_assignment), std::move(extras.addressable_device_logical_ids), std::move(extras.addressable_devices), this); TF_RETURN_IF_ERROR( pjrt_executable->SetUpDonation(options.parameter_is_tupled_arguments)); return std::unique_ptr<PjRtExecutable>(std::move(pjrt_executable)); } static StatusOr<std::vector<std::unique_ptr<PjRtStreamExecutorDevice>>> GetTpuDevices( LocalClient* client, std::vector<std::unique_ptr<LocalDeviceState>> local_device_states) { std::vector<std::unique_ptr<PjRtStreamExecutorDevice>> devices; tf_tpu::TpuTopologyExternal topology = tf_tpu::TpuPlatformInterface::GetRegisteredPlatform()->topology(); std::map<int, int> core_id_to_device_ordinal; for (int i = 0; i < client->device_count(); ++i) { se::StreamExecutor* executor = client->backend().stream_executor(i).ValueOrDie(); tf_tpu::TpuExecutorInterface* tpu_executor = tensorflow::down_cast<tf_tpu::TpuExecutorInterface*>( executor->implementation()); core_id_to_device_ordinal[tpu_executor->GetCoreLocationExternal().Id()] = i; } for (const tf_tpu::TpuCoreLocationExternal& core : topology.cores(TpuCoreTypeEnum::kTensorCore)) { auto it = core_id_to_device_ordinal.find(core.Id()); int device_ordinal = (it != core_id_to_device_ordinal.end()) ? it->second : -1; int process_index = topology.IdForHost(core.host_coordinates()); const tf_tpu::TpuDimensionsExternal coords = core.chip_coordinates(); std::array<int, 3> coords_array = {coords.x, coords.y, coords.z}; std::unique_ptr<LocalDeviceState> local_device_state; if (device_ordinal >= 0) { local_device_state = std::move(local_device_states[device_ordinal]); } auto device = std::make_unique<PjRtTpuDevice>( core, std::move(local_device_state), process_index, coords_array, std::string(tf_tpu::TpuVersionEnumToString(topology.version()))); devices.push_back(std::move(device)); } return devices; } StatusOr<std::shared_ptr<PjRtClient>> GetTpuClient( int max_inflight_computations, absl::Duration init_retry_timeout) { #if !defined(PLATFORM_GOOGLE) || defined(LIBTPU_STATIC) TF_RETURN_IF_ERROR(tensorflow::tpu::FindAndLoadTpuLibrary()); #endif tf_tpu::TpuPlatformInterface* platform = tf_tpu::TpuPlatformInterface::GetRegisteredPlatform( /*initialize_platform=*/true, /*num_tries=*/1); if (platform == nullptr) { return InvalidArgument("TpuPlatform is not available."); } // NOTE: We retry in a loop since some pod failures are transient (e.g. some // RPCs may timeout waiting for other hosts to come up, but will succeed // at a later point if retried). auto start = absl::Now(); while (true) { Status status = platform->Initialize({}); if (status.ok()) { break; } // TODO(b/165870356): refactor this loop to be // while(!platform->Initialized()) once the Initialized() function works // correctly, and remove this check. The platform may already be initialized // when running internally. if (status.code() == tensorflow::error::ALREADY_EXISTS) { LOG(INFO) << "TpuPlatform already initialized, continuing..."; break; } LOG(INFO) << "TPU platform initialization failed: " << status; if ((absl::Now() - start) >= init_retry_timeout) { return status; } absl::SleepFor(absl::Microseconds(10)); } CHECK(platform->Initialized()); if (platform->VisibleDeviceCount() <= 0) { return InvalidArgument("No TPU devices found."); } LocalClientOptions options; options.set_platform(platform); TF_ASSIGN_OR_RETURN(LocalClient * client, ClientLibrary::GetOrCreateLocalClient(options)); std::vector<std::unique_ptr<LocalDeviceState>> local_device_states; local_device_states.reserve(client->device_count()); for (int i = 0; i < client->device_count(); ++i) { se::StreamExecutor* executor = client->backend().stream_executor(i).ValueOrDie(); local_device_states.push_back(std::make_unique<TpuDeviceState>( executor, client, max_inflight_computations)); } TF_ASSIGN_OR_RETURN(auto devices, GetTpuDevices(client, std::move(local_device_states))); int process_index = platform->GetTpuHostLocation().Id(); return std::shared_ptr<PjRtClient>(std::make_unique<PjRtTpuClient>( client, std::move(devices), process_index)); } } // namespace xla <|endoftext|>
<commit_before>/*! * Copyright (c) 2017 by Contributors * \file arg_binder.cc * \brief Helper utility to match and bind arguments. */ #include <tvm/ir.h> #include <tvm/ir_pass.h> #include <tvm/runtime/device_api.h> #include "./ir_util.h" #include "./arg_binder.h" #include "../arithmetic/compute_expr.h" namespace tvm { namespace ir { void BinderAddAssert(Expr cond, const std::string& arg_name, std::vector<Stmt>* asserts) { Expr scond = Simplify(cond); if (is_zero(scond)) { LOG(FATAL) << "Bind have an unmet assertion: " << cond << ", " << " on argument " << arg_name; } if (!is_one(scond)) { std::ostringstream os; os << "Argument " << arg_name << " has an unsatisfied constraint"; asserts->emplace_back(AssertStmt::make(scond, os.str(), Evaluate::make(0))); } } bool ArgBinder::Bind_(const Expr& arg, const Expr& value, const std::string& arg_name, bool with_lets) { CHECK_EQ(arg.type(), value.type()); if (const Variable* v = arg.as<Variable>()) { auto it = def_map_->find(v); if (it == def_map_->end()) { Var v_arg(arg.node_); defs_.emplace_back(v_arg); if (with_lets) { (*def_map_)[v] = arg; init_nest_.emplace_back(LetStmt::make(v_arg, value, Evaluate::make(0))); } else { (*def_map_)[v] = value; } return true; } else { BinderAddAssert(it->second == value, arg_name, &asserts_); } } else { BinderAddAssert(arg == value, arg_name, &asserts_); } return false; } void ArgBinder::Bind(const Expr& arg, const Expr& value, const std::string& arg_name, bool with_let) { Bind_(arg, value, arg_name, with_let); } void ArgBinder::BindArray(const Array<Expr>& arg, const Array<Expr>& value, const std::string& arg_name) { CHECK_EQ(arg.size(), value.size()) << "Argument " << arg_name << " array size mismatch"; for (size_t i = 0; i < arg.size(); ++i) { std::ostringstream os; os << arg_name << "[" << i << "]"; this->Bind(arg[i], value[i], os.str()); } } void ArgBinder::BindBuffer(const Buffer& arg, const Buffer& value, const std::string& arg_name, bool fuzzy_match) { CHECK_EQ(arg->scope, value->scope) << "Argument " << arg_name << " Buffer bind scope mismatch"; CHECK_EQ(arg->dtype, value->dtype) << "Argument " << arg_name << " Buffer bind data type mismatch"; if (value->data_alignment % arg->data_alignment != 0) { LOG(WARNING) << "Trying to bind buffer to another one with lower alignment requirement " << " required_alignment=" << arg->data_alignment << ", provided_alignment=" << value->data_alignment; } // bind pointer and offset. if (is_zero(arg->elem_offset)) { CHECK(is_zero(value->elem_offset)) << "Trying to bind a Buffer with offset into one without offset"; } this->Bind(arg->data, value->data, arg_name + ".data"); if (Bind_(arg->elem_offset, value->elem_offset, arg_name + ".elem_offset", false)) { if (arg->offset_factor > 1) { Expr offset = value->elem_offset; Expr factor = make_const(offset.type(), arg->offset_factor); Expr zero = make_zero(offset.type()); BinderAddAssert(offset % factor == zero, arg_name + ".elem_offset", &asserts_); } } if (arg->shape.size() < value->shape.size()) { CHECK(fuzzy_match) << "Argument " << arg_name << " size mismatch"; size_t diff = value->shape.size() - arg->shape.size(); for (size_t i = 0; i < diff; ++i) { CHECK(is_one(value->shape[i])) << "Argument " << arg_name << " shape mismatch" << arg->shape << " vs " << value->shape; } for (size_t i = 0; i < arg->shape.size(); ++i) { std::ostringstream os; os << arg_name << ".shape[" << i << "]"; this->Bind(arg->shape[i], value->shape[i + diff], os.str()); } if (value->strides.size() != 0) { CHECK_EQ(arg->strides.size(), arg->shape.size()); CHECK_EQ(value->strides.size(), value->shape.size()); for (size_t i = 0; i < arg->strides.size(); ++i) { std::ostringstream os; os << arg_name << ".strides[" << i << "]"; this->Bind(arg->strides[i], value->strides[i + diff], os.str()); } } } else { this->BindArray(arg->shape, value->shape, arg_name + ".shape"); this->BindArray(arg->strides, value->strides, arg_name + ".strides"); } } inline Expr TVMArrayGet(Type t, Var arr, intrinsic::TVMStructFieldKind kind) { return TVMStructGet(t, arr, 0, kind); } void ArgBinder::BindDLTensor(const Buffer& buffer, const Expr& device_type, const Expr& device_id, const Var& handle, const std::string& arg_name) { const Type tvm_shape_type = TVMShapeIndexType(); const Type tvm_ndim_type = Int(32); const Stmt nop = Evaluate::make(0); // dimension checks Expr v_ndim = TVMArrayGet(tvm_ndim_type, handle, intrinsic::kArrNDim); Expr a_ndim = make_const(tvm_ndim_type, static_cast<int64_t>(buffer->shape.size())); std::ostringstream ndim_err_msg; ndim_err_msg << arg_name << ".ndim is expected to equal " << buffer->shape.size(); asserts_.emplace_back(AssertStmt::make(a_ndim == v_ndim, ndim_err_msg.str(), nop)); // type checks Type dtype = buffer->dtype; std::ostringstream type_err_msg; type_err_msg << arg_name << ".dtype is expected to be " << dtype; Expr cond = (TVMArrayGet(UInt(8), handle, intrinsic::kArrTypeCode) == UIntImm::make(UInt(8), dtype.code()) && TVMArrayGet(UInt(8), handle, intrinsic::kArrTypeBits) == UIntImm::make(UInt(8), dtype.bits()) && TVMArrayGet(UInt(16), handle, intrinsic::kArrTypeLanes) == UIntImm::make(UInt(16), dtype.lanes())); asserts_.emplace_back(AssertStmt::make(cond, type_err_msg.str(), nop)); // data field if (Bind_(buffer->data, TVMArrayGet(Handle(), handle, intrinsic::kArrData), arg_name + ".data", true)) { Var vptr(buffer->data); def_handle_dtype_.Set(vptr, make_const(buffer->dtype, 0)); // mark alignment of external bufs init_nest_.emplace_back(AttrStmt::make( vptr, ir::attr::storage_alignment, IntImm::make(Int(32), buffer->data_alignment), nop)); } Var v_shape(arg_name + ".shape", Handle()); def_handle_dtype_.Set(v_shape, make_const(tvm_shape_type, 0)); init_nest_.emplace_back(LetStmt::make( v_shape, TVMArrayGet(Handle(), handle, intrinsic::kArrShape), nop)); for (size_t k = 0; k < buffer->shape.size(); ++k) { std::ostringstream field_name; field_name << v_shape->name_hint << '[' << k << ']'; Bind_(buffer->shape[k], cast(buffer->shape[k].type(), Load::make(tvm_shape_type, v_shape, IntImm::make(Int(32), k), const_true(1))), field_name.str(), true); } // strides field Var v_strides(arg_name + ".strides", Handle()); def_handle_dtype_.Set(v_strides, make_const(tvm_shape_type, 0)); init_nest_.emplace_back(LetStmt::make( v_strides, TVMArrayGet(Handle(), handle, intrinsic::kArrStrides), nop)); if (buffer->strides.size() == 0) { // Assert the buffer is compact Type stype = buffer->DefaultIndexType(); Expr expect_stride = make_const(stype, 1); Array<Expr> conds; for (size_t i = buffer->shape.size(); i != 0; --i) { size_t k = i - 1; Expr svalue = cast( stype, Load::make(tvm_shape_type, v_strides, IntImm::make(Int(32), k), const_true(1))); conds.push_back(expect_stride == svalue); expect_stride = expect_stride * buffer->shape[k]; } std::ostringstream stride_err_msg; stride_err_msg << arg_name << ".strides:" << " expected to be compact array"; if (conds.size() != 0) { Stmt check = AssertStmt::make(arith::ComputeReduce<ir::And>(conds, Expr()), stride_err_msg.str(), Evaluate::make(0)); Expr is_null = Call::make( Bool(1), intrinsic::tvm_handle_is_null, {v_strides}, Call::PureIntrinsic); check = IfThenElse::make(Not::make(is_null), check, Stmt()); init_nest_.emplace_back(Block::make(check, Evaluate::make(0))); } } else { for (size_t k = 0; k < buffer->strides.size(); ++k) { std::ostringstream field_name; field_name << v_strides->name_hint << '[' << k << ']'; Bind_(buffer->strides[k], cast(buffer->shape[k].type(), Load::make(tvm_shape_type, v_strides, IntImm::make(Int(32), k), const_true(1))), field_name.str(), true); } } // Byte_offset field. int data_bytes = GetVectorBytes(buffer->dtype); int64_t const_offset; if (arith::GetConst(buffer->elem_offset, &const_offset)) { Bind_(make_const(UInt(64), const_offset * data_bytes), TVMArrayGet(UInt(64), handle, intrinsic::kArrByteOffset), arg_name + ".byte_offset", true); } else { if (Bind_(buffer->elem_offset, cast(buffer->elem_offset.type(), (TVMArrayGet(UInt(64), handle, intrinsic::kArrByteOffset) / make_const(UInt(64), data_bytes))), arg_name + ".elem_offset", true)) { if (buffer->offset_factor > 1) { Expr offset = buffer->elem_offset; Expr factor = make_const(offset.type(), buffer->offset_factor); Expr zero = make_zero(offset.type()); BinderAddAssert(offset % factor == zero, arg_name + ".elem_offset", &asserts_); } } } // device info. Bind_(device_type, TVMArrayGet(Int(32), handle, intrinsic::kArrDeviceType), arg_name + ".device_type", true); Bind_(device_id, TVMArrayGet(Int(32), handle, intrinsic::kArrDeviceId), arg_name + ".device_id", true); } } // namespace ir } // namespace tvm <commit_msg>Assert dont crash on null strides (#976)<commit_after>/*! * Copyright (c) 2017 by Contributors * \file arg_binder.cc * \brief Helper utility to match and bind arguments. */ #include <tvm/ir.h> #include <tvm/ir_pass.h> #include <tvm/runtime/device_api.h> #include "./ir_util.h" #include "./arg_binder.h" #include "../arithmetic/compute_expr.h" namespace tvm { namespace ir { void BinderAddAssert(Expr cond, const std::string& arg_name, std::vector<Stmt>* asserts) { Expr scond = Simplify(cond); if (is_zero(scond)) { LOG(FATAL) << "Bind have an unmet assertion: " << cond << ", " << " on argument " << arg_name; } if (!is_one(scond)) { std::ostringstream os; os << "Argument " << arg_name << " has an unsatisfied constraint"; asserts->emplace_back(AssertStmt::make(scond, os.str(), Evaluate::make(0))); } } bool ArgBinder::Bind_(const Expr& arg, const Expr& value, const std::string& arg_name, bool with_lets) { CHECK_EQ(arg.type(), value.type()); if (const Variable* v = arg.as<Variable>()) { auto it = def_map_->find(v); if (it == def_map_->end()) { Var v_arg(arg.node_); defs_.emplace_back(v_arg); if (with_lets) { (*def_map_)[v] = arg; init_nest_.emplace_back(LetStmt::make(v_arg, value, Evaluate::make(0))); } else { (*def_map_)[v] = value; } return true; } else { BinderAddAssert(it->second == value, arg_name, &asserts_); } } else { BinderAddAssert(arg == value, arg_name, &asserts_); } return false; } void ArgBinder::Bind(const Expr& arg, const Expr& value, const std::string& arg_name, bool with_let) { Bind_(arg, value, arg_name, with_let); } void ArgBinder::BindArray(const Array<Expr>& arg, const Array<Expr>& value, const std::string& arg_name) { CHECK_EQ(arg.size(), value.size()) << "Argument " << arg_name << " array size mismatch"; for (size_t i = 0; i < arg.size(); ++i) { std::ostringstream os; os << arg_name << "[" << i << "]"; this->Bind(arg[i], value[i], os.str()); } } void ArgBinder::BindBuffer(const Buffer& arg, const Buffer& value, const std::string& arg_name, bool fuzzy_match) { CHECK_EQ(arg->scope, value->scope) << "Argument " << arg_name << " Buffer bind scope mismatch"; CHECK_EQ(arg->dtype, value->dtype) << "Argument " << arg_name << " Buffer bind data type mismatch"; if (value->data_alignment % arg->data_alignment != 0) { LOG(WARNING) << "Trying to bind buffer to another one with lower alignment requirement " << " required_alignment=" << arg->data_alignment << ", provided_alignment=" << value->data_alignment; } // bind pointer and offset. if (is_zero(arg->elem_offset)) { CHECK(is_zero(value->elem_offset)) << "Trying to bind a Buffer with offset into one without offset"; } this->Bind(arg->data, value->data, arg_name + ".data"); if (Bind_(arg->elem_offset, value->elem_offset, arg_name + ".elem_offset", false)) { if (arg->offset_factor > 1) { Expr offset = value->elem_offset; Expr factor = make_const(offset.type(), arg->offset_factor); Expr zero = make_zero(offset.type()); BinderAddAssert(offset % factor == zero, arg_name + ".elem_offset", &asserts_); } } if (arg->shape.size() < value->shape.size()) { CHECK(fuzzy_match) << "Argument " << arg_name << " size mismatch"; size_t diff = value->shape.size() - arg->shape.size(); for (size_t i = 0; i < diff; ++i) { CHECK(is_one(value->shape[i])) << "Argument " << arg_name << " shape mismatch" << arg->shape << " vs " << value->shape; } for (size_t i = 0; i < arg->shape.size(); ++i) { std::ostringstream os; os << arg_name << ".shape[" << i << "]"; this->Bind(arg->shape[i], value->shape[i + diff], os.str()); } if (value->strides.size() != 0) { CHECK_EQ(arg->strides.size(), arg->shape.size()); CHECK_EQ(value->strides.size(), value->shape.size()); for (size_t i = 0; i < arg->strides.size(); ++i) { std::ostringstream os; os << arg_name << ".strides[" << i << "]"; this->Bind(arg->strides[i], value->strides[i + diff], os.str()); } } } else { this->BindArray(arg->shape, value->shape, arg_name + ".shape"); this->BindArray(arg->strides, value->strides, arg_name + ".strides"); } } inline Expr TVMArrayGet(Type t, Var arr, intrinsic::TVMStructFieldKind kind) { return TVMStructGet(t, arr, 0, kind); } void ArgBinder::BindDLTensor(const Buffer& buffer, const Expr& device_type, const Expr& device_id, const Var& handle, const std::string& arg_name) { const Type tvm_shape_type = TVMShapeIndexType(); const Type tvm_ndim_type = Int(32); const Stmt nop = Evaluate::make(0); // dimension checks Expr v_ndim = TVMArrayGet(tvm_ndim_type, handle, intrinsic::kArrNDim); Expr a_ndim = make_const(tvm_ndim_type, static_cast<int64_t>(buffer->shape.size())); std::ostringstream ndim_err_msg; ndim_err_msg << arg_name << ".ndim is expected to equal " << buffer->shape.size(); asserts_.emplace_back(AssertStmt::make(a_ndim == v_ndim, ndim_err_msg.str(), nop)); // type checks Type dtype = buffer->dtype; std::ostringstream type_err_msg; type_err_msg << arg_name << ".dtype is expected to be " << dtype; Expr cond = (TVMArrayGet(UInt(8), handle, intrinsic::kArrTypeCode) == UIntImm::make(UInt(8), dtype.code()) && TVMArrayGet(UInt(8), handle, intrinsic::kArrTypeBits) == UIntImm::make(UInt(8), dtype.bits()) && TVMArrayGet(UInt(16), handle, intrinsic::kArrTypeLanes) == UIntImm::make(UInt(16), dtype.lanes())); asserts_.emplace_back(AssertStmt::make(cond, type_err_msg.str(), nop)); // data field if (Bind_(buffer->data, TVMArrayGet(Handle(), handle, intrinsic::kArrData), arg_name + ".data", true)) { Var vptr(buffer->data); def_handle_dtype_.Set(vptr, make_const(buffer->dtype, 0)); // mark alignment of external bufs init_nest_.emplace_back(AttrStmt::make( vptr, ir::attr::storage_alignment, IntImm::make(Int(32), buffer->data_alignment), nop)); } Var v_shape(arg_name + ".shape", Handle()); def_handle_dtype_.Set(v_shape, make_const(tvm_shape_type, 0)); init_nest_.emplace_back(LetStmt::make( v_shape, TVMArrayGet(Handle(), handle, intrinsic::kArrShape), nop)); for (size_t k = 0; k < buffer->shape.size(); ++k) { std::ostringstream field_name; field_name << v_shape->name_hint << '[' << k << ']'; Bind_(buffer->shape[k], cast(buffer->shape[k].type(), Load::make(tvm_shape_type, v_shape, IntImm::make(Int(32), k), const_true(1))), field_name.str(), true); } // strides field Var v_strides(arg_name + ".strides", Handle()); def_handle_dtype_.Set(v_strides, make_const(tvm_shape_type, 0)); init_nest_.emplace_back(LetStmt::make( v_strides, TVMArrayGet(Handle(), handle, intrinsic::kArrStrides), nop)); Expr is_null = Call::make( Bool(1), intrinsic::tvm_handle_is_null, {v_strides}, Call::PureIntrinsic); if (buffer->strides.size() == 0) { // Assert the buffer is compact Type stype = buffer->DefaultIndexType(); Expr expect_stride = make_const(stype, 1); Array<Expr> conds; for (size_t i = buffer->shape.size(); i != 0; --i) { size_t k = i - 1; Expr svalue = cast( stype, Load::make(tvm_shape_type, v_strides, IntImm::make(Int(32), k), const_true(1))); conds.push_back(expect_stride == svalue); expect_stride = expect_stride * buffer->shape[k]; } std::ostringstream stride_err_msg; stride_err_msg << arg_name << ".strides:" << " expected to be compact array"; if (conds.size() != 0) { Stmt check = AssertStmt::make(arith::ComputeReduce<ir::And>(conds, Expr()), stride_err_msg.str(), Evaluate::make(0)); check = IfThenElse::make(Not::make(is_null), check, Stmt()); init_nest_.emplace_back(Block::make(check, Evaluate::make(0))); } } else { std::ostringstream stride_null_err_msg; stride_null_err_msg << arg_name << ".strides: expected non-null strides."; asserts_.emplace_back(AssertStmt::make(Not::make(is_null), stride_null_err_msg.str(), nop)); for (size_t k = 0; k < buffer->strides.size(); ++k) { std::ostringstream field_name; field_name << v_strides->name_hint << '[' << k << ']'; Bind_(buffer->strides[k], cast(buffer->shape[k].type(), Load::make(tvm_shape_type, v_strides, IntImm::make(Int(32), k), const_true(1))), field_name.str(), true); } } // Byte_offset field. int data_bytes = GetVectorBytes(buffer->dtype); int64_t const_offset; if (arith::GetConst(buffer->elem_offset, &const_offset)) { Bind_(make_const(UInt(64), const_offset * data_bytes), TVMArrayGet(UInt(64), handle, intrinsic::kArrByteOffset), arg_name + ".byte_offset", true); } else { if (Bind_(buffer->elem_offset, cast(buffer->elem_offset.type(), (TVMArrayGet(UInt(64), handle, intrinsic::kArrByteOffset) / make_const(UInt(64), data_bytes))), arg_name + ".elem_offset", true)) { if (buffer->offset_factor > 1) { Expr offset = buffer->elem_offset; Expr factor = make_const(offset.type(), buffer->offset_factor); Expr zero = make_zero(offset.type()); BinderAddAssert(offset % factor == zero, arg_name + ".elem_offset", &asserts_); } } } // device info. Bind_(device_type, TVMArrayGet(Int(32), handle, intrinsic::kArrDeviceType), arg_name + ".device_type", true); Bind_(device_id, TVMArrayGet(Int(32), handle, intrinsic::kArrDeviceId), arg_name + ".device_id", true); } } // namespace ir } // namespace tvm <|endoftext|>
<commit_before>// Scintilla source code edit control /** @file CallTip.cxx ** Code for displaying call tips. **/ // Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org> // The License.txt file describes the conditions under which this software may be distributed. #include <stdlib.h> #include <string.h> #include "Platform.h" #include "Scintilla.h" #include "CallTip.h" CallTip::CallTip() { wCallTip = 0; inCallTipMode = false; posStartCallTip = 0; val = 0; xUp = -100; xDown = -100; lineHeight = 1; startHighlight = 0; endHighlight = 0; colourBG.desired = ColourDesired(0xff, 0xff, 0xff); colourUnSel.desired = ColourDesired(0x80, 0x80, 0x80); colourSel.desired = ColourDesired(0, 0, 0x80); colourShade.desired = ColourDesired(0, 0, 0); colourLight.desired = ColourDesired(0xc0, 0xc0, 0xc0); } CallTip::~CallTip() { font.Release(); wCallTip.Destroy(); delete []val; val = 0; } const int widthArrow = 14; void CallTip::RefreshColourPalette(Palette &pal, bool want) { pal.WantFind(colourBG, want); pal.WantFind(colourUnSel, want); pal.WantFind(colourSel, want); pal.WantFind(colourShade, want); pal.WantFind(colourLight, want); } void CallTip::DrawChunk(Surface *surface, int &x, const char *s, int posStart, int posEnd, int ytext, PRectangle rcClient, bool highlight, bool draw) { s += posStart; int len = posEnd - posStart; int maxEnd = 0; int ends[10]; for (int i=0;i<len;i++) { if (s[i] <= '\002') { if (i > 0) ends[maxEnd++] = i; ends[maxEnd++] = i+1; } } ends[maxEnd++] = len; int startSeg = 0; int xEnd; for (int seg = 0; seg<maxEnd; seg++) { int endSeg = ends[seg]; if (endSeg > startSeg) { if (s[startSeg] <= '\002') { xEnd = x + widthArrow; offsetMain = xEnd; if (draw) { const int halfWidth = widthArrow / 2 - 3; const int centreX = x + widthArrow / 2 - 1; const int centreY = (rcClient.top + rcClient.bottom) / 2; rcClient.left = x; rcClient.right = xEnd; surface->FillRectangle(rcClient, colourBG.allocated); PRectangle rcClientInner(rcClient.left+1, rcClient.top+1, rcClient.right-2, rcClient.bottom-1); surface->FillRectangle(rcClientInner, colourUnSel.allocated); if (s[startSeg] == '\001') { // Up arrow Point pts[] = { Point(centreX - halfWidth, centreY + halfWidth / 2), Point(centreX + halfWidth, centreY + halfWidth / 2), Point(centreX, centreY - halfWidth + halfWidth / 2), }; surface->Polygon(pts, sizeof(pts) / sizeof(pts[0]), colourBG.allocated, colourBG.allocated); } else { // Down arrow Point pts[] = { Point(centreX - halfWidth, centreY - halfWidth / 2), Point(centreX + halfWidth, centreY - halfWidth / 2), Point(centreX, centreY + halfWidth - halfWidth / 2), }; surface->Polygon(pts, sizeof(pts) / sizeof(pts[0]), colourBG.allocated, colourBG.allocated); } } else { if (s[startSeg] == '\001') { xUp = x+1; } else { xDown = x+1; } } } else { xEnd = x + surface->WidthText(font, s+startSeg, endSeg - startSeg); if (draw) { rcClient.left = x; rcClient.right = xEnd; surface->DrawTextNoClip(rcClient, font, ytext, s+startSeg, endSeg - startSeg, highlight ? colourSel.allocated : colourUnSel.allocated, colourBG.allocated); } } x = xEnd; startSeg = endSeg; } } } int CallTip::PaintContents(Surface *surfaceWindow, bool draw) { PRectangle rcClientPos = wCallTip.GetClientPosition(); PRectangle rcClientSize(0, 0, rcClientPos.right - rcClientPos.left, rcClientPos.bottom - rcClientPos.top); PRectangle rcClient(1, 1, rcClientSize.right - 1, rcClientSize.bottom - 1); // To make a nice small call tip window, it is only sized to fit most normal characters without accents int ascent = surfaceWindow->Ascent(font) - surfaceWindow->InternalLeading(font); // For each line... // Draw the definition in three parts: before highlight, highlighted, after highlight int ytext = rcClient.top + ascent + 1; rcClient.bottom = ytext + surfaceWindow->Descent(font) + 1; char *chunkVal = val; bool moreChunks = true; int maxWidth = 0; while (moreChunks) { char *chunkEnd = strchr(chunkVal, '\n'); if (chunkEnd == NULL) { chunkEnd = chunkVal + strlen(chunkVal); moreChunks = false; } int chunkOffset = chunkVal - val; int chunkLength = chunkEnd - chunkVal; int chunkEndOffset = chunkOffset + chunkLength; int thisStartHighlight = Platform::Maximum(startHighlight, chunkOffset); thisStartHighlight = Platform::Minimum(thisStartHighlight, chunkEndOffset); thisStartHighlight -= chunkOffset; int thisEndHighlight = Platform::Maximum(endHighlight, chunkOffset); thisEndHighlight = Platform::Minimum(thisEndHighlight, chunkEndOffset); thisEndHighlight -= chunkOffset; rcClient.top = ytext - ascent - 1; int x = 5; DrawChunk(surfaceWindow, x, chunkVal, 0, thisStartHighlight, ytext, rcClient, false, draw); DrawChunk(surfaceWindow, x, chunkVal, thisStartHighlight, thisEndHighlight, ytext, rcClient, true, draw); DrawChunk(surfaceWindow, x, chunkVal, thisEndHighlight, chunkLength, ytext, rcClient, false, draw); chunkVal = chunkEnd + 1; ytext += lineHeight; rcClient.bottom += lineHeight; maxWidth = Platform::Maximum(maxWidth, x); } return maxWidth; } void CallTip::PaintCT(Surface *surfaceWindow) { if (!val) return; PRectangle rcClientPos = wCallTip.GetClientPosition(); PRectangle rcClientSize(0, 0, rcClientPos.right - rcClientPos.left, rcClientPos.bottom - rcClientPos.top); PRectangle rcClient(1, 1, rcClientSize.right - 1, rcClientSize.bottom - 1); surfaceWindow->FillRectangle(rcClient, colourBG.allocated); offsetMain = 5; PaintContents(surfaceWindow, true); // Draw a raised border around the edges of the window surfaceWindow->MoveTo(0, rcClientSize.bottom - 1); surfaceWindow->PenColour(colourShade.allocated); surfaceWindow->LineTo(rcClientSize.right - 1, rcClientSize.bottom - 1); surfaceWindow->LineTo(rcClientSize.right - 1, 0); surfaceWindow->PenColour(colourLight.allocated); surfaceWindow->LineTo(0, 0); surfaceWindow->LineTo(0, rcClientSize.bottom - 1); } void CallTip::MouseClick(Point pt) { clickPlace = 0; if (pt.y < lineHeight) { if ((pt.x > xUp) && (pt.x < xUp + widthArrow - 2)) { clickPlace = 1; } else if ((pt.x > xDown) && (pt.x < xDown + widthArrow - 2)) { clickPlace = 2; } } } PRectangle CallTip::CallTipStart(int pos, Point pt, const char *defn, const char *faceName, int size, int codePage_, Window &wParent) { clickPlace = 0; if (val) delete []val; val = new char[strlen(defn) + 1]; if (!val) return PRectangle(); strcpy(val, defn); codePage = codePage_; Surface *surfaceMeasure = Surface::Allocate(); if (!surfaceMeasure) return PRectangle(); surfaceMeasure->Init(wParent.GetID()); surfaceMeasure->SetUnicodeMode(SC_CP_UTF8 == codePage); surfaceMeasure->SetDBCSMode(codePage); startHighlight = 0; endHighlight = 0; inCallTipMode = true; posStartCallTip = pos; int deviceHeight = surfaceMeasure->DeviceHeightFont(size); font.Create(faceName, SC_CHARSET_DEFAULT, deviceHeight, false, false); // Look for multiple lines in the text // Only support \n here - simply means container must avoid \r! int numLines = 1; const char *newline; const char *look = val; xUp = -100; xDown = -100; offsetMain = 5; int width = PaintContents(surfaceMeasure, false) + 5; while ((newline = strchr(look, '\n')) != NULL) { look = newline + 1; numLines++; } lineHeight = surfaceMeasure->Height(font); // Extra line for border and an empty line at top and bottom int height = lineHeight * numLines - surfaceMeasure->InternalLeading(font) + 2 + 2; delete surfaceMeasure; return PRectangle(pt.x - offsetMain, pt.y + 1, pt.x + width - offsetMain, pt.y + 1 + height); } void CallTip::CallTipCancel() { inCallTipMode = false; if (wCallTip.Created()) { wCallTip.Destroy(); } } void CallTip::SetHighlight(int start, int end) { // Avoid flashing by checking something has really changed if ((start != startHighlight) || (end != endHighlight)) { startHighlight = start; endHighlight = end; if (wCallTip.Created()) { wCallTip.InvalidateAll(); } } } <commit_msg>Fixed bug where characters >= 128 were being displayed as down arrows.<commit_after>// Scintilla source code edit control /** @file CallTip.cxx ** Code for displaying call tips. **/ // Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org> // The License.txt file describes the conditions under which this software may be distributed. #include <stdlib.h> #include <string.h> #include "Platform.h" #include "Scintilla.h" #include "CallTip.h" CallTip::CallTip() { wCallTip = 0; inCallTipMode = false; posStartCallTip = 0; val = 0; xUp = -100; xDown = -100; lineHeight = 1; startHighlight = 0; endHighlight = 0; colourBG.desired = ColourDesired(0xff, 0xff, 0xff); colourUnSel.desired = ColourDesired(0x80, 0x80, 0x80); colourSel.desired = ColourDesired(0, 0, 0x80); colourShade.desired = ColourDesired(0, 0, 0); colourLight.desired = ColourDesired(0xc0, 0xc0, 0xc0); } CallTip::~CallTip() { font.Release(); wCallTip.Destroy(); delete []val; val = 0; } const int widthArrow = 14; void CallTip::RefreshColourPalette(Palette &pal, bool want) { pal.WantFind(colourBG, want); pal.WantFind(colourUnSel, want); pal.WantFind(colourSel, want); pal.WantFind(colourShade, want); pal.WantFind(colourLight, want); } static bool IsArrowCharacter(char ch) { return (ch >= 0) && (ch <= '\002'); } void CallTip::DrawChunk(Surface *surface, int &x, const char *s, int posStart, int posEnd, int ytext, PRectangle rcClient, bool highlight, bool draw) { s += posStart; int len = posEnd - posStart; int maxEnd = 0; int ends[10]; for (int i=0;i<len;i++) { if (IsArrowCharacter(s[i])) { if (i > 0) ends[maxEnd++] = i; ends[maxEnd++] = i+1; } } ends[maxEnd++] = len; int startSeg = 0; int xEnd; for (int seg = 0; seg<maxEnd; seg++) { int endSeg = ends[seg]; if (endSeg > startSeg) { if (IsArrowCharacter(s[startSeg])) { xEnd = x + widthArrow; offsetMain = xEnd; if (draw) { const int halfWidth = widthArrow / 2 - 3; const int centreX = x + widthArrow / 2 - 1; const int centreY = (rcClient.top + rcClient.bottom) / 2; rcClient.left = x; rcClient.right = xEnd; surface->FillRectangle(rcClient, colourBG.allocated); PRectangle rcClientInner(rcClient.left+1, rcClient.top+1, rcClient.right-2, rcClient.bottom-1); surface->FillRectangle(rcClientInner, colourUnSel.allocated); if (s[startSeg] == '\001') { // Up arrow Point pts[] = { Point(centreX - halfWidth, centreY + halfWidth / 2), Point(centreX + halfWidth, centreY + halfWidth / 2), Point(centreX, centreY - halfWidth + halfWidth / 2), }; surface->Polygon(pts, sizeof(pts) / sizeof(pts[0]), colourBG.allocated, colourBG.allocated); } else { // Down arrow Point pts[] = { Point(centreX - halfWidth, centreY - halfWidth / 2), Point(centreX + halfWidth, centreY - halfWidth / 2), Point(centreX, centreY + halfWidth - halfWidth / 2), }; surface->Polygon(pts, sizeof(pts) / sizeof(pts[0]), colourBG.allocated, colourBG.allocated); } } else { if (s[startSeg] == '\001') { xUp = x+1; } else { xDown = x+1; } } } else { xEnd = x + surface->WidthText(font, s+startSeg, endSeg - startSeg); if (draw) { rcClient.left = x; rcClient.right = xEnd; surface->DrawTextNoClip(rcClient, font, ytext, s+startSeg, endSeg - startSeg, highlight ? colourSel.allocated : colourUnSel.allocated, colourBG.allocated); } } x = xEnd; startSeg = endSeg; } } } int CallTip::PaintContents(Surface *surfaceWindow, bool draw) { PRectangle rcClientPos = wCallTip.GetClientPosition(); PRectangle rcClientSize(0, 0, rcClientPos.right - rcClientPos.left, rcClientPos.bottom - rcClientPos.top); PRectangle rcClient(1, 1, rcClientSize.right - 1, rcClientSize.bottom - 1); // To make a nice small call tip window, it is only sized to fit most normal characters without accents int ascent = surfaceWindow->Ascent(font) - surfaceWindow->InternalLeading(font); // For each line... // Draw the definition in three parts: before highlight, highlighted, after highlight int ytext = rcClient.top + ascent + 1; rcClient.bottom = ytext + surfaceWindow->Descent(font) + 1; char *chunkVal = val; bool moreChunks = true; int maxWidth = 0; while (moreChunks) { char *chunkEnd = strchr(chunkVal, '\n'); if (chunkEnd == NULL) { chunkEnd = chunkVal + strlen(chunkVal); moreChunks = false; } int chunkOffset = chunkVal - val; int chunkLength = chunkEnd - chunkVal; int chunkEndOffset = chunkOffset + chunkLength; int thisStartHighlight = Platform::Maximum(startHighlight, chunkOffset); thisStartHighlight = Platform::Minimum(thisStartHighlight, chunkEndOffset); thisStartHighlight -= chunkOffset; int thisEndHighlight = Platform::Maximum(endHighlight, chunkOffset); thisEndHighlight = Platform::Minimum(thisEndHighlight, chunkEndOffset); thisEndHighlight -= chunkOffset; rcClient.top = ytext - ascent - 1; int x = 5; DrawChunk(surfaceWindow, x, chunkVal, 0, thisStartHighlight, ytext, rcClient, false, draw); DrawChunk(surfaceWindow, x, chunkVal, thisStartHighlight, thisEndHighlight, ytext, rcClient, true, draw); DrawChunk(surfaceWindow, x, chunkVal, thisEndHighlight, chunkLength, ytext, rcClient, false, draw); chunkVal = chunkEnd + 1; ytext += lineHeight; rcClient.bottom += lineHeight; maxWidth = Platform::Maximum(maxWidth, x); } return maxWidth; } void CallTip::PaintCT(Surface *surfaceWindow) { if (!val) return; PRectangle rcClientPos = wCallTip.GetClientPosition(); PRectangle rcClientSize(0, 0, rcClientPos.right - rcClientPos.left, rcClientPos.bottom - rcClientPos.top); PRectangle rcClient(1, 1, rcClientSize.right - 1, rcClientSize.bottom - 1); surfaceWindow->FillRectangle(rcClient, colourBG.allocated); offsetMain = 5; PaintContents(surfaceWindow, true); // Draw a raised border around the edges of the window surfaceWindow->MoveTo(0, rcClientSize.bottom - 1); surfaceWindow->PenColour(colourShade.allocated); surfaceWindow->LineTo(rcClientSize.right - 1, rcClientSize.bottom - 1); surfaceWindow->LineTo(rcClientSize.right - 1, 0); surfaceWindow->PenColour(colourLight.allocated); surfaceWindow->LineTo(0, 0); surfaceWindow->LineTo(0, rcClientSize.bottom - 1); } void CallTip::MouseClick(Point pt) { clickPlace = 0; if (pt.y < lineHeight) { if ((pt.x > xUp) && (pt.x < xUp + widthArrow - 2)) { clickPlace = 1; } else if ((pt.x > xDown) && (pt.x < xDown + widthArrow - 2)) { clickPlace = 2; } } } PRectangle CallTip::CallTipStart(int pos, Point pt, const char *defn, const char *faceName, int size, int codePage_, Window &wParent) { clickPlace = 0; if (val) delete []val; val = new char[strlen(defn) + 1]; if (!val) return PRectangle(); strcpy(val, defn); codePage = codePage_; Surface *surfaceMeasure = Surface::Allocate(); if (!surfaceMeasure) return PRectangle(); surfaceMeasure->Init(wParent.GetID()); surfaceMeasure->SetUnicodeMode(SC_CP_UTF8 == codePage); surfaceMeasure->SetDBCSMode(codePage); startHighlight = 0; endHighlight = 0; inCallTipMode = true; posStartCallTip = pos; int deviceHeight = surfaceMeasure->DeviceHeightFont(size); font.Create(faceName, SC_CHARSET_DEFAULT, deviceHeight, false, false); // Look for multiple lines in the text // Only support \n here - simply means container must avoid \r! int numLines = 1; const char *newline; const char *look = val; xUp = -100; xDown = -100; offsetMain = 5; int width = PaintContents(surfaceMeasure, false) + 5; while ((newline = strchr(look, '\n')) != NULL) { look = newline + 1; numLines++; } lineHeight = surfaceMeasure->Height(font); // Extra line for border and an empty line at top and bottom int height = lineHeight * numLines - surfaceMeasure->InternalLeading(font) + 2 + 2; delete surfaceMeasure; return PRectangle(pt.x - offsetMain, pt.y + 1, pt.x + width - offsetMain, pt.y + 1 + height); } void CallTip::CallTipCancel() { inCallTipMode = false; if (wCallTip.Created()) { wCallTip.Destroy(); } } void CallTip::SetHighlight(int start, int end) { // Avoid flashing by checking something has really changed if ((start != startHighlight) || (end != endHighlight)) { startHighlight = start; endHighlight = end; if (wCallTip.Created()) { wCallTip.InvalidateAll(); } } } <|endoftext|>
<commit_before>// RUN: %clang_cc1 -fsyntax-only -std=c++11 -verify %s // expected-no-diagnostics // NOTE: This file intentionally uses DOS-style line endings to test // that we don't propagate them into string literals as per [lex.string]p4. constexpr const char* p = R"(a\ b c)"; static_assert(p[0] == 'a', ""); static_assert(p[1] == '\\', ""); static_assert(p[2] == '\n', ""); static_assert(p[3] == 'b', ""); static_assert(p[4] == '\n', ""); static_assert(p[5] == 'c', ""); static_assert(p[6] == '\0', ""); <commit_msg>Convert test/CXX/lex/lex.literal/lex.string/p4.cpp back to DOS line endings, since the file is supposed to have them, according to its comments. Also set its svn:eol-style property. Noticed by Nico Weber.<commit_after>// RUN: %clang_cc1 -fsyntax-only -std=c++11 -verify %s // expected-no-diagnostics // NOTE: This file intentionally uses DOS-style line endings to test // that we don't propagate them into string literals as per [lex.string]p4. constexpr const char* p = R"(a\ b c)"; static_assert(p[0] == 'a', ""); static_assert(p[1] == '\\', ""); static_assert(p[2] == '\n', ""); static_assert(p[3] == 'b', ""); static_assert(p[4] == '\n', ""); static_assert(p[5] == 'c', ""); static_assert(p[6] == '\0', ""); <|endoftext|>
<commit_before>// Copyright (C) 2011 - 2015 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and The University // of Manchester. // All rights reserved. #include "CQTaskMethodWidget.h" #include "qtUtilities.h" #include "copasi.h" #include "utilities/CCopasiTask.h" #include "utilities/CCopasiMethod.h" #include "utilities/utility.h" CQTaskMethodWidget::CQTaskMethodWidget(QWidget* parent, Qt::WindowFlags f): QWidget(parent, f), mpTask(NULL), mpMethod(NULL), mpActiveMethod(NULL), mMethodHistory(), mShowMethods(false), mShowMethodParameters(false) { setupUi(this); mpTableParameter->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents); mpTableParameter->horizontalHeader()->setResizeMode(QHeaderView::ResizeToContents); mpTableParameter->horizontalHeader()->hide(); mpLblMethod->hide(); mpBoxMethod->hide(); mpLblParameter->hide(); mpTableParameter->hide(); } CQTaskMethodWidget::~CQTaskMethodWidget() { clearHistory(); pdelete(mpActiveMethod); } void CQTaskMethodWidget::changeMethod(int /* index */) { if (mpTask == NULL) return; // We update the active methods parameters if (mShowMethodParameters) { unsigned C_INT32 i; QString Value; for (i = 0; i < mpActiveMethod->size(); i++) { if (!mpTableParameter->item(i, 0)) continue; Value = mpTableParameter->item(i, 0)->text(); setParameterValue(mpActiveMethod, i, Value); } } CCopasiMethod::SubType Type = toEnum(TO_UTF8(mpBoxMethod->currentText()), CCopasiMethod::SubTypeName, CCopasiMethod::unset); setActiveMethod(Type); loadMethod(); return; } void CQTaskMethodWidget::setTask(CCopasiTask * pTask) { mpTask = pTask; if (mpTask != NULL) { mpMethod = mpTask->getMethod(); if (mpMethod != NULL) { setActiveMethod(mpMethod->getSubType()); *mpActiveMethod = *mpMethod; } } else { mpMethod = NULL; mpActiveMethod = NULL; } } void CQTaskMethodWidget::setValidMethods(const unsigned int * validMethods) { unsigned C_INT32 i; for (i = 0; validMethods[i] != CCopasiMethod::unset; i++) mpBoxMethod->insertItem(mpBoxMethod->count(), FROM_UTF8(CCopasiMethod::SubTypeName[validMethods[i]])); if (i > 0) { mShowMethods = true; mpLblMethod->show(); mpBoxMethod->show(); connect(mpBoxMethod, SIGNAL(activated(int)), this, SLOT(changeMethod(int))); } else { mShowMethods = false; mpLblMethod->hide(); mpBoxMethod->hide(); disconnect(mpBoxMethod, SIGNAL(activated(int)), this, SLOT(changeMethod(int))); } } void CQTaskMethodWidget::showMethodParameters(const bool & show) { mShowMethodParameters = show; if (mShowMethodParameters) { mpLblParameter->show(); mpTableParameter->show(); } else { mpLblParameter->hide(); mpTableParameter->hide(); } } bool CQTaskMethodWidget::loadMethod() { if (!mpTask) return false; if (!mpActiveMethod) return false; if (mShowMethods) { mpBoxMethod->setCurrentIndex(mpBoxMethod->findText(FROM_UTF8(CCopasiMethod::SubTypeName[mpActiveMethod->getSubType()]))); } if (mShowMethodParameters) { QString Value; mpTableParameter->setRowCount((int) mpActiveMethod->size()); unsigned C_INT32 i; CCopasiParameter::Type Type; for (i = 0; i < mpActiveMethod->size(); i++) { // create item of the current row and give it a name mpTableParameter->setVerticalHeaderItem(i, new QTableWidgetItem()); mpTableParameter->verticalHeaderItem(i)->setText(FROM_UTF8(mpActiveMethod->getName(i))); Value = getParameterValue(mpActiveMethod, i, &Type); QTableWidgetItem *pValueItem = new QTableWidgetItem(); pValueItem->setData(Qt::EditRole, QVariant(Value)); pValueItem->setTextAlignment(Qt::AlignRight); mpTableParameter->setItem(i, 0, pValueItem); } } mpTableParameter->resizeColumnsToContents(); return true; } bool CQTaskMethodWidget::saveMethod() { if (!mpTask) return false; const CCopasiMethod * pMethod = mpTask->getMethod(); if (!pMethod) return false; bool changed = false; if (mShowMethods) { if (pMethod->getSubType() != mpActiveMethod->getSubType()) { mpTask->setMethodType(mpActiveMethod->getSubType()); mpMethod = mpTask->getMethod(); changed = true; } } if (mShowMethodParameters) { unsigned C_INT32 i; QString Value; CCopasiParameter::Type Type; for (i = 0; i < mpActiveMethod->size(); i++) { if (!mpTableParameter->item(i, 0)) continue; Value = mpTableParameter->item(i, 0)->text(); if (Value != getParameterValue(mpActiveMethod, i, &Type)) { setParameterValue(mpActiveMethod, i, Value); changed = true; } } } if (changed) { *mpMethod = *mpActiveMethod; } return changed; } void CQTaskMethodWidget::addToHistory(CCopasiMethod * pMethod) { if (pMethod == NULL) { return; } std::map< CCopasiMethod::SubType, CCopasiMethod * >::iterator found = mMethodHistory.find(pMethod->getSubType()); if (found != mMethodHistory.end()) { if (found->second != pMethod) { delete found->second; found->second = pMethod; } return; } mMethodHistory[pMethod->getSubType()] = pMethod; } void CQTaskMethodWidget::removeFromHistory(CCopasiMethod * pMethod) { if (pMethod == NULL) { return; } std::map< CCopasiMethod::SubType, CCopasiMethod * >::iterator found = mMethodHistory.find(pMethod->getSubType()); if (found != mMethodHistory.end()) { mMethodHistory.erase(found); } } CCopasiMethod * CQTaskMethodWidget::getFromHistory(const CCopasiMethod::SubType & Type) const { std::map< CCopasiMethod::SubType, CCopasiMethod * >::const_iterator found = mMethodHistory.find(Type); if (found != mMethodHistory.end()) { return found->second; } return NULL; } void CQTaskMethodWidget::setActiveMethod(const CCopasiMethod::SubType & Type) { mpActiveMethod = getFromHistory(Type); if (mpActiveMethod == NULL) { mpActiveMethod = mpTask->createMethod(Type); addToHistory(mpActiveMethod); } assert(mpActiveMethod != NULL); return; } void CQTaskMethodWidget::clearHistory() { std::map< CCopasiMethod::SubType, CCopasiMethod * >::iterator it = mMethodHistory.begin(); std::map< CCopasiMethod::SubType, CCopasiMethod * >::iterator end = mMethodHistory.end(); for (; it != end; ++it) { delete it->second; } mMethodHistory.clear(); } <commit_msg>- issue 2120: active method is deleted with history<commit_after>// Copyright (C) 2011 - 2015 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and The University // of Manchester. // All rights reserved. #include "CQTaskMethodWidget.h" #include "qtUtilities.h" #include "copasi.h" #include "utilities/CCopasiTask.h" #include "utilities/CCopasiMethod.h" #include "utilities/utility.h" CQTaskMethodWidget::CQTaskMethodWidget(QWidget* parent, Qt::WindowFlags f): QWidget(parent, f), mpTask(NULL), mpMethod(NULL), mpActiveMethod(NULL), mMethodHistory(), mShowMethods(false), mShowMethodParameters(false) { setupUi(this); mpTableParameter->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents); mpTableParameter->horizontalHeader()->setResizeMode(QHeaderView::ResizeToContents); mpTableParameter->horizontalHeader()->hide(); mpLblMethod->hide(); mpBoxMethod->hide(); mpLblParameter->hide(); mpTableParameter->hide(); } CQTaskMethodWidget::~CQTaskMethodWidget() { clearHistory(); } void CQTaskMethodWidget::changeMethod(int /* index */) { if (mpTask == NULL) return; // We update the active methods parameters if (mShowMethodParameters) { unsigned C_INT32 i; QString Value; for (i = 0; i < mpActiveMethod->size(); i++) { if (!mpTableParameter->item(i, 0)) continue; Value = mpTableParameter->item(i, 0)->text(); setParameterValue(mpActiveMethod, i, Value); } } CCopasiMethod::SubType Type = toEnum(TO_UTF8(mpBoxMethod->currentText()), CCopasiMethod::SubTypeName, CCopasiMethod::unset); setActiveMethod(Type); loadMethod(); return; } void CQTaskMethodWidget::setTask(CCopasiTask * pTask) { mpTask = pTask; if (mpTask != NULL) { mpMethod = mpTask->getMethod(); if (mpMethod != NULL) { setActiveMethod(mpMethod->getSubType()); *mpActiveMethod = *mpMethod; } } else { mpMethod = NULL; mpActiveMethod = NULL; } } void CQTaskMethodWidget::setValidMethods(const unsigned int * validMethods) { unsigned C_INT32 i; for (i = 0; validMethods[i] != CCopasiMethod::unset; i++) mpBoxMethod->insertItem(mpBoxMethod->count(), FROM_UTF8(CCopasiMethod::SubTypeName[validMethods[i]])); if (i > 0) { mShowMethods = true; mpLblMethod->show(); mpBoxMethod->show(); connect(mpBoxMethod, SIGNAL(activated(int)), this, SLOT(changeMethod(int))); } else { mShowMethods = false; mpLblMethod->hide(); mpBoxMethod->hide(); disconnect(mpBoxMethod, SIGNAL(activated(int)), this, SLOT(changeMethod(int))); } } void CQTaskMethodWidget::showMethodParameters(const bool & show) { mShowMethodParameters = show; if (mShowMethodParameters) { mpLblParameter->show(); mpTableParameter->show(); } else { mpLblParameter->hide(); mpTableParameter->hide(); } } bool CQTaskMethodWidget::loadMethod() { if (!mpTask) return false; if (!mpActiveMethod) return false; if (mShowMethods) { mpBoxMethod->setCurrentIndex(mpBoxMethod->findText(FROM_UTF8(CCopasiMethod::SubTypeName[mpActiveMethod->getSubType()]))); } if (mShowMethodParameters) { QString Value; mpTableParameter->setRowCount((int) mpActiveMethod->size()); unsigned C_INT32 i; CCopasiParameter::Type Type; for (i = 0; i < mpActiveMethod->size(); i++) { // create item of the current row and give it a name mpTableParameter->setVerticalHeaderItem(i, new QTableWidgetItem()); mpTableParameter->verticalHeaderItem(i)->setText(FROM_UTF8(mpActiveMethod->getName(i))); Value = getParameterValue(mpActiveMethod, i, &Type); QTableWidgetItem *pValueItem = new QTableWidgetItem(); pValueItem->setData(Qt::EditRole, QVariant(Value)); pValueItem->setTextAlignment(Qt::AlignRight); mpTableParameter->setItem(i, 0, pValueItem); } } mpTableParameter->resizeColumnsToContents(); return true; } bool CQTaskMethodWidget::saveMethod() { if (!mpTask) return false; const CCopasiMethod * pMethod = mpTask->getMethod(); if (!pMethod) return false; bool changed = false; if (mShowMethods) { if (pMethod->getSubType() != mpActiveMethod->getSubType()) { mpTask->setMethodType(mpActiveMethod->getSubType()); mpMethod = mpTask->getMethod(); changed = true; } } if (mShowMethodParameters) { unsigned C_INT32 i; QString Value; CCopasiParameter::Type Type; for (i = 0; i < mpActiveMethod->size(); i++) { if (!mpTableParameter->item(i, 0)) continue; Value = mpTableParameter->item(i, 0)->text(); if (Value != getParameterValue(mpActiveMethod, i, &Type)) { setParameterValue(mpActiveMethod, i, Value); changed = true; } } } if (changed) { *mpMethod = *mpActiveMethod; } return changed; } void CQTaskMethodWidget::addToHistory(CCopasiMethod * pMethod) { if (pMethod == NULL) { return; } std::map< CCopasiMethod::SubType, CCopasiMethod * >::iterator found = mMethodHistory.find(pMethod->getSubType()); if (found != mMethodHistory.end()) { if (found->second != pMethod) { delete found->second; found->second = pMethod; } return; } mMethodHistory[pMethod->getSubType()] = pMethod; } void CQTaskMethodWidget::removeFromHistory(CCopasiMethod * pMethod) { if (pMethod == NULL) { return; } std::map< CCopasiMethod::SubType, CCopasiMethod * >::iterator found = mMethodHistory.find(pMethod->getSubType()); if (found != mMethodHistory.end()) { mMethodHistory.erase(found); } } CCopasiMethod * CQTaskMethodWidget::getFromHistory(const CCopasiMethod::SubType & Type) const { std::map< CCopasiMethod::SubType, CCopasiMethod * >::const_iterator found = mMethodHistory.find(Type); if (found != mMethodHistory.end()) { return found->second; } return NULL; } void CQTaskMethodWidget::setActiveMethod(const CCopasiMethod::SubType & Type) { mpActiveMethod = getFromHistory(Type); if (mpActiveMethod == NULL) { mpActiveMethod = mpTask->createMethod(Type); addToHistory(mpActiveMethod); } assert(mpActiveMethod != NULL); return; } void CQTaskMethodWidget::clearHistory() { std::map< CCopasiMethod::SubType, CCopasiMethod * >::iterator it = mMethodHistory.begin(); std::map< CCopasiMethod::SubType, CCopasiMethod * >::iterator end = mMethodHistory.end(); for (; it != end; ++it) { delete it->second; } mMethodHistory.clear(); } <|endoftext|>
<commit_before> /* * * Copyright 2016, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include "test/cpp/util/test_credentials_provider.h" #include <unordered_map> #include <grpc++/impl/sync.h> #include <grpc/support/sync.h> #include "test/core/end2end/data/ssl_test_data.h" namespace { using grpc::ChannelArguments; using grpc::ChannelCredentials; using grpc::InsecureChannelCredentials; using grpc::InsecureServerCredentials; using grpc::ServerCredentials; using grpc::SslCredentialsOptions; using grpc::SslServerCredentialsOptions; using grpc::testing::CredentialTypeProvider; // Provide test credentials. Thread-safe. class CredentialsProvider { public: virtual ~CredentialsProvider() {} virtual void AddSecureType( const grpc::string& type, std::unique_ptr<CredentialTypeProvider> type_provider) = 0; virtual std::shared_ptr<ChannelCredentials> GetChannelCredentials( const grpc::string& type, ChannelArguments* args) = 0; virtual std::shared_ptr<ServerCredentials> GetServerCredentials( const grpc::string& type) = 0; virtual std::vector<grpc::string> GetSecureCredentialsTypeList() = 0; }; class DefaultCredentialsProvider : public CredentialsProvider { public: ~DefaultCredentialsProvider() override {} void AddSecureType( const grpc::string& type, std::unique_ptr<CredentialTypeProvider> type_provider) override { // This clobbers any existing entry for type, except the defaults, which // can't be clobbered. grpc::unique_lock<grpc::mutex> lock(mu_); added_secure_types_[type] = std::move(type_provider); } std::shared_ptr<ChannelCredentials> GetChannelCredentials( const grpc::string& type, ChannelArguments* args) override { if (type == grpc::testing::kInsecureCredentialsType) { return InsecureChannelCredentials(); } else if (type == grpc::testing::kTlsCredentialsType) { SslCredentialsOptions ssl_opts = {test_root_cert, "", ""}; args->SetSslTargetNameOverride("foo.test.google.fr"); return SslCredentials(ssl_opts); } else { grpc::unique_lock<grpc::mutex> lock(mu_); auto it(added_secure_types_.find(type)); if (it == added_secure_types_.end()) { gpr_log(GPR_ERROR, "Unsupported credentials type %s.", type.c_str()); return nullptr; } return it->second->GetChannelCredentials(args); } } std::shared_ptr<ServerCredentials> GetServerCredentials( const grpc::string& type) override { if (type == grpc::testing::kInsecureCredentialsType) { return InsecureServerCredentials(); } else if (type == grpc::testing::kTlsCredentialsType) { SslServerCredentialsOptions::PemKeyCertPair pkcp = {test_server1_key, test_server1_cert}; SslServerCredentialsOptions ssl_opts; ssl_opts.pem_root_certs = ""; ssl_opts.pem_key_cert_pairs.push_back(pkcp); return SslServerCredentials(ssl_opts); } else { grpc::unique_lock<grpc::mutex> lock(mu_); auto it(added_secure_types_.find(type)); if (it == added_secure_types_.end()) { gpr_log(GPR_ERROR, "Unsupported credentials type %s.", type.c_str()); return nullptr; } return it->second->GetServerCredentials(); } } std::vector<grpc::string> GetSecureCredentialsTypeList() override { std::vector<grpc::string> types; types.push_back(grpc::testing::kTlsCredentialsType); grpc::unique_lock<grpc::mutex> lock(mu_); for (const auto& type_pair : added_secure_types_) { types.push_back(type_pair.first); } return types; } private: grpc::mutex mu_; std::unordered_map<grpc::string, std::unique_ptr<CredentialTypeProvider> > added_secure_types_; }; gpr_once g_once_init_provider = GPR_ONCE_INIT; CredentialsProvider* g_provider = nullptr; void CreateDefaultProvider() { g_provider = new DefaultCredentialsProvider; } CredentialsProvider* GetProvider() { gpr_once_init(&g_once_init_provider, &CreateDefaultProvider); return g_provider; } } // namespace namespace grpc { namespace testing { void AddSecureType(const grpc::string& type, std::unique_ptr<CredentialTypeProvider> type_provider) { GetProvider()->AddSecureType(type, std::move(type_provider)); } std::shared_ptr<ChannelCredentials> GetChannelCredentials( const grpc::string& type, ChannelArguments* args) { return GetProvider()->GetChannelCredentials(type, args); } std::shared_ptr<ServerCredentials> GetServerCredentials( const grpc::string& type) { return GetProvider()->GetServerCredentials(type); } std::vector<grpc::string> GetSecureCredentialsTypeList() { return GetProvider()->GetSecureCredentialsTypeList(); } } // namespace testing } // namespace grpc <commit_msg>Enforce gcc-4.4 compatibility on test_credentials_provider by changing a map to 2 vectors. Additional minor changes needed (e.g., override->GRPC_OVERRIDE, nullptr->grpc::nullptr)<commit_after> /* * * Copyright 2016, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include "test/cpp/util/test_credentials_provider.h" #include <unordered_map> #include <grpc++/impl/sync.h> #include <grpc/support/sync.h> #include "test/core/end2end/data/ssl_test_data.h" namespace { using grpc::ChannelArguments; using grpc::ChannelCredentials; using grpc::InsecureChannelCredentials; using grpc::InsecureServerCredentials; using grpc::ServerCredentials; using grpc::SslCredentialsOptions; using grpc::SslServerCredentialsOptions; using grpc::testing::CredentialTypeProvider; // Provide test credentials. Thread-safe. class CredentialsProvider { public: virtual ~CredentialsProvider() {} virtual void AddSecureType( const grpc::string& type, std::unique_ptr<CredentialTypeProvider> type_provider) = 0; virtual std::shared_ptr<ChannelCredentials> GetChannelCredentials( const grpc::string& type, ChannelArguments* args) = 0; virtual std::shared_ptr<ServerCredentials> GetServerCredentials( const grpc::string& type) = 0; virtual std::vector<grpc::string> GetSecureCredentialsTypeList() = 0; }; class DefaultCredentialsProvider : public CredentialsProvider { public: ~DefaultCredentialsProvider() GRPC_OVERRIDE {} void AddSecureType(const grpc::string& type, std::unique_ptr<CredentialTypeProvider> type_provider) GRPC_OVERRIDE { // This clobbers any existing entry for type, except the defaults, which // can't be clobbered. grpc::unique_lock<grpc::mutex> lock(mu_); auto it = std::find(added_secure_type_names_.begin(), added_secure_type_names_.end(), type); if (it == added_secure_type_names_.end()) { added_secure_type_names_.push_back(type); added_secure_type_providers_.push_back(std::move(type_provider)); } else { added_secure_type_providers_[it - added_secure_type_names_.begin()] = std::move(type_provider); } } std::shared_ptr<ChannelCredentials> GetChannelCredentials( const grpc::string& type, ChannelArguments* args) GRPC_OVERRIDE { if (type == grpc::testing::kInsecureCredentialsType) { return InsecureChannelCredentials(); } else if (type == grpc::testing::kTlsCredentialsType) { SslCredentialsOptions ssl_opts = {test_root_cert, "", ""}; args->SetSslTargetNameOverride("foo.test.google.fr"); return SslCredentials(ssl_opts); } else { grpc::unique_lock<grpc::mutex> lock(mu_); auto it(std::find(added_secure_type_names_.begin(), added_secure_type_names_.end(), type)); if (it == added_secure_type_names_.end()) { gpr_log(GPR_ERROR, "Unsupported credentials type %s.", type.c_str()); return grpc::nullptr; } return added_secure_type_providers_[it - added_secure_type_names_.begin()] ->GetChannelCredentials(args); } } std::shared_ptr<ServerCredentials> GetServerCredentials( const grpc::string& type) GRPC_OVERRIDE { if (type == grpc::testing::kInsecureCredentialsType) { return InsecureServerCredentials(); } else if (type == grpc::testing::kTlsCredentialsType) { SslServerCredentialsOptions::PemKeyCertPair pkcp = {test_server1_key, test_server1_cert}; SslServerCredentialsOptions ssl_opts; ssl_opts.pem_root_certs = ""; ssl_opts.pem_key_cert_pairs.push_back(pkcp); return SslServerCredentials(ssl_opts); } else { grpc::unique_lock<grpc::mutex> lock(mu_); auto it(std::find(added_secure_type_names_.begin(), added_secure_type_names_.end(), type)); if (it == added_secure_type_names_.end()) { gpr_log(GPR_ERROR, "Unsupported credentials type %s.", type.c_str()); return grpc::nullptr; } return added_secure_type_providers_[it - added_secure_type_names_.begin()] ->GetServerCredentials(); } } std::vector<grpc::string> GetSecureCredentialsTypeList() GRPC_OVERRIDE { std::vector<grpc::string> types; types.push_back(grpc::testing::kTlsCredentialsType); grpc::unique_lock<grpc::mutex> lock(mu_); for (auto it = added_secure_type_names_.begin(); it != added_secure_type_names_.end(); it++) { types.push_back(*it); } return types; } private: grpc::mutex mu_; std::vector<grpc::string> added_secure_type_names_; std::vector<std::unique_ptr<CredentialTypeProvider>> added_secure_type_providers_; }; gpr_once g_once_init_provider = GPR_ONCE_INIT; CredentialsProvider* g_provider = grpc::nullptr; void CreateDefaultProvider() { g_provider = new DefaultCredentialsProvider; } CredentialsProvider* GetProvider() { gpr_once_init(&g_once_init_provider, &CreateDefaultProvider); return g_provider; } } // namespace namespace grpc { namespace testing { void AddSecureType(const grpc::string& type, std::unique_ptr<CredentialTypeProvider> type_provider) { GetProvider()->AddSecureType(type, std::move(type_provider)); } std::shared_ptr<ChannelCredentials> GetChannelCredentials( const grpc::string& type, ChannelArguments* args) { return GetProvider()->GetChannelCredentials(type, args); } std::shared_ptr<ServerCredentials> GetServerCredentials( const grpc::string& type) { return GetProvider()->GetServerCredentials(type); } std::vector<grpc::string> GetSecureCredentialsTypeList() { return GetProvider()->GetSecureCredentialsTypeList(); } } // namespace testing } // namespace grpc <|endoftext|>
<commit_before>// Copyright (c) 2008-2010 Kent State University // Copyright (c) 2011 Texas A&M University // // This file is distributed under the MIT License. See the accompanying file // LICENSE.txt or http://www.opensource.org/licenses/mit-license.php for terms // and conditions. #ifndef ORIGIN_ITERATOR_HPP #define ORIGIN_ITERATOR_HPP #include <iterator> #include <origin/concepts.hpp> namespace origin { // Separate the checking of static requirements out of the Readable concept. // This prevents compiler errors when associated types aren't found. If // associated types can't be found, then the requirements will obviously // fail to pass. template<typename Iter, bool Types> struct Readable_requirements { static constexpr bool check() { return false; } }; template<typename Iter> struct Readable_requirements<Iter, true> { static constexpr bool check() { return Has_dereference<Iter>() && Convertible<Dereference_result<Iter>, Value_type<Iter> const&>(); } }; // Allows the following expression: Value_type<Iter> const& x = *i. template<typename Iter> struct Readable_concept { static constexpr bool check() { return Readable_requirements<Iter, Has_value_type<Iter>()>::check(); } static bool test(Iter i) { Value_type<Iter> const& x = *i; // NOTE: Not an axiom. return true; } }; template<typename Iter> constexpr bool Readable() { return Readable_concept<Iter>::check(); } // An iterator is Move_writable if the expression '*i = move(x)' is valid. template<typename Iter, typename T> struct Move_writable_concept { static constexpr bool check() { return Movable<T>() && Has_dereference<Iter>() && Assignable<Dereference_result<Iter>, T&&>(); } static bool test(Iter i, T x) { *i = std::move(x); // NOTE: Not an axiom. return true; } }; template<typename Iter, typename T> constexpr bool Move_writable() { return Move_writable_concept<Iter, T>::check(); } // An iterator is writable if the expression '*i = x' is valid. template<typename Iter, typename T> struct Writable_concept { static constexpr bool check() { return Copyable<T>() && Move_writable<Iter, T>() && Assignable<Dereference_result<Iter>, T const&>(); } static bool test() { // FIXME: Write semantics return true; } }; template<typename Iter, typename T> constexpr bool Writable() { return Writable_concept<Iter, T>::check(); } // Incrementable types // A weakly incrementable type is a semiregular type that can be pre- and // post-incremented. Neither operation is requireed to be equality // preserving, and the result of post-increment is unspecified. template<typename I> struct Weakly_incrementable_concept { static constexpr bool check() { return Semiregular<I>() && Has_distance_type<I>() // I& == { ++i } && Has_pre_increment<I>() && Same<Pre_increment_result<I>, I&>() // i++ && Has_post_increment<I>(); } // FIXME: Write semantics? Not sure if it's really possible. }; template<typename I> constexpr bool Weakly_incrementable() { return Weakly_incrementable_concept<I>::check(); } // An Incrementable type is a Regular, weakly incrementable type with // equality preserving pre- and post-increment operations. template<typename I> struct Incrementable_concept { static constexpr bool check() { return Regular<I> && Weakly_incrementable<I>() // I == { i++ } && Same<Post_increment_result<I>, I>(); } }; template<typename I> constexpr bool Incrementable() { return Incrementable_concept<I>::check(); } // Iterators // The following concept classes and predicates are define checking // capabilities for iterator concepts. // Iterator categories // // Every iterator type explicitly describes its category, one of the // std::*_iterator_tag classes. For user-defined iterators, this is provided // as a nested type name (i.e., Iter::iterator_category). For pointers, the // category is random access. // Safely deduce a custom iterator category as a nested type. template<typename Iter> struct get_iterator_category { private: template<typename X> static typename X::iterator_category check(X&&); template<typename X> static typename std::iterator_traits<X*>::iterator_category check(X*); static subst_failure check(...); public: using type = decltype(check(std::declval<Iter>())); }; // An alias for the category of Iter. template<typename Iter> using Iterator_category = typename get_iterator_category<Iter>::type; // Return true if the iterator category is valid. template<typename Iter> constexpr bool Has_iterator_category() { return Subst_succeeded<Iterator_category<Iter>>(); } // Return an iterator category that is not more derived than the given limit. // For example, if Tag is "random access" and Limit is "forward", this will // return limit. // // Note that this does not guarantee that limit is actually derived from // Tag. That's just assumed. // // TODO: This seems like it could generalize to any Tag hierarchy. Consider // how this might be done (in terms of lattices?) and then move the // generalized solution into Traits or Concepts. template<typename Tag, typename Limit> using Clamp_iterator_category = If< Derived<Iterator_category<Tag>, Limit>(), Limit, Iterator_category<Tag> >; // Returns true if Iter has all of the associated iterator types. template<typename Iter> constexpr bool Has_iterator_types() { return Has_iterator_category<Iter>() && Has_value_type<Iter>() && Has_distance_type<Iter>(); } // Return true if T is an iterator. Here, T is an iterator if it has all of // the requisite associated types. template<typename T> constexpr bool Iterator() { return Has_iterator_types<T>(); } // An alias for the associated reference type of the iterator. This supports // writing backwards compatible iterators where the reference type is // actually named even though it should be deduced as decltype(*i). template<typename Iter> using Iterator_reference = typename std::iterator_traits<Iter>::reference; // An alias for the associated pointer type of the iterator. This supports // writing backwards compatible iterators where the reference type is // actually named even though it is never used in any STL algorithms. Note // that the pointer type cannot be deduced as decltype(&*i). template<typename Iter> using Iterator_pointer = typename std::iterator_traits<Iter>::pointer; // Input iterators // Unlike the TR, we start with Input_iterators, not Incrementable types. // Also, there is no such thing as a weak input iterator. We always assume // equality exists. // // FIXME: How closely should this follow the TR? template<typename Iter, bool Prereqs> struct Input_iterator_requirements { static constexpr bool check() { return false; } }; template<typename Iter> struct Input_iterator_requirements<Iter, true> { static constexpr bool check() { return Derived<Iterator_category<Iter>, std::input_iterator_tag>() && Equality_comparable<Iter>() && Weakly_incrementable<Iter>() && Readable<Post_increment_result<Iter>>(); } }; // An input iterator... template<typename Iter> struct Input_iterator_concept { static constexpr bool check() { return Input_iterator_requirements< Iter, Regular<Iter>() && Readable<Iter>() && Has_iterator_types<Iter>() >::check(); } static bool test() { // FIXME: Write semantics. return true; } }; template<typename Iter> constexpr bool Input_iterator() { return Input_iterator_concept<Iter>::check(); } // Forward Iterators // A forward iterator is an input iterator with a regular post-increment // operation. This guarantees that multiple passes of a range may be made // and that multiple iterators into the range may be used. // A helper class for checking syntactic requirements. template<typename Iter, bool Prereqs> struct Forward_iterator_requirements { static constexpr bool check() { return false; } }; template<typename Iter> struct Forward_iterator_requirements<Iter, true> { static constexpr bool check() { return Derived<Iterator_category<Iter>, std::forward_iterator_tag>() && Incrementable<Iter>() && Readable<Iter>(); } }; // The specification of forward iterators. template<typename Iter> struct Forward_iterator_concept { static constexpr bool check() { return Forward_iterator_requirements< Iter, Input_iterator<Iter>() >::check(); } static bool test() { // FIXME: Write semantics. return true; } }; // Return true if Iter is a forward iterator. template<typename Iter> constexpr bool Forward_iterator() { return Forward_iterator_concept<Iter>::check(); } // Bidirectional Iterators // A bidirectional iterator is a forward iterator that can also move // backwards using decrement operators. // A helper class for checking syntactic requirements. template<typename Iter, bool Prereqs> struct Bidirectional_iterator_requirements { static constexpr bool check() { return false; } }; template<typename Iter> struct Bidirectional_iterator_requirements<Iter, true> { static constexpr bool check() { return Derived<Iterator_category<Iter>, std::bidirectional_iterator_tag>() // Iter& == { --i } && Has_pre_decrement<Iter>() && Same<Pre_decrement_result<Iter>, Iter&>() // Iter == { i-- } && Has_post_decrement<Iter>() && Same<Post_decrement_result<Iter>, Iter>(); } }; // A bidirectional iterators... template<typename Iter> struct Bidirectional_iterator_concept { static constexpr bool check() { return Bidirectional_iterator_requirements< Iter, Forward_iterator<Iter>() >::check(); } static bool test() { // FIXME: Write semantics. return true; } }; template<typename Iter> constexpr bool Bidirectional_iterator() { return Bidirectional_iterator_concept<Iter>::check(); }; // Random Access Iterators // A random access iterator is a bidirectional iterator that can advance // any number of steps in constant time. // A helper class for checking syntactic requirements. template<typename Iter, bool Prereqs> struct Random_access_iterator_requirements { static constexpr bool check() { return false; } }; template<typename Iter> struct Random_access_iterator_requirements<Iter, true> { static constexpr bool check() { return Derived<Iterator_category<Iter>, std::random_access_iterator_tag>() && Signed<Distance_type<Iter>>() // Iter& == { i += n } && Has_plus_assign<Iter, Distance_type<Iter>>() && Same<Plus_assign_result<Iter, Distance_type<Iter>>, Iter&>() // Iter& == { i -= n } && Has_minus_assign<Iter, Distance_type<Iter>>() && Same<Minus_assign_result<Iter, Distance_type<Iter>>, Iter&>() // Iter == { i + n } && Has_plus<Iter, Distance_type<Iter>>() && Same<Plus_result<Iter, Distance_type<Iter>>, Iter>() // Iter == { n + i } && Has_plus<Distance_type<Iter>, Iter>() && Same<Plus_result<Distance_type<Iter>, Iter>, Iter>() // Iter == { i - n } && Has_minus<Iter, Distance_type<Iter>>() && Same<Minus_result<Iter, Distance_type<Iter>>, Iter>() // Distance_type<Iter> == { i - j } && Has_minus<Iter>() && Same<Minus_result<Iter>, Distance_type<Iter>>() // decltype(*i) == { i[n] } && Has_subscript<Iter, Distance_type<Iter>>() && Same<Subscript_result<Iter, Distance_type<Iter>>, Dereference_result<Iter>>(); } }; // The specification of random access iterators. template<typename Iter> struct Random_access_iterator_concept { static constexpr bool check() { return Random_access_iterator_requirements< Iter, Bidirectional_iterator<Iter>() >::check(); } static bool test() { // FIXME: Write semantics return true; } }; // Returns true if Iter is random access iterator. template<typename Iter> constexpr bool Random_access_iterator() { return Random_access_iterator_concept<Iter>::check(); }; // Mutable Iterators // There are two kinds of mutable iterators: Permutable iterators allow // values to be exchanged (moved). Mutable iterators allow values to be // replaced (copied). Note that mutable iterators are also permutable. // Permutable and mutable iterators are forward iterators. // Permutable Iterators // A permutable iterator allows values to be exchanged (moved) between // different iterators without copying. This also includes moving values // into temporary values. // A helper function for checking requirements. template<typename Iter, bool Prereqs> struct Permutable_iterator_requirements { static bool constexpr check() { return false; } }; template<typename Iter> struct Permutable_iterator_requirements<Iter, true> { static bool constexpr check() { return Move_writable<Iter, Value_type<Iter>>(); } }; // The specification of permutable iterators. template<typename Iter> struct Permutable_iterator_concept { static bool constexpr check() { return Permutable_iterator_requirements< Iter, Forward_iterator<Iter>() >::check(); } }; // Return true if Iter is permutable. template<typename Iter> constexpr bool Permutable_iterator() { return Permutable_iterator_concept<Iter>::check(); } // Mutable Iterators // A mutable iterator allows its referenced values to be re-assigned to new // values (through copies). Note that mutable iterators are also permutable. // A helper function for checking requirements. template<typename Iter, bool Prereqs> struct Mutable_iterator_requirements { static bool constexpr check() { return false; } }; template<typename Iter> struct Mutable_iterator_requirements<Iter, true> { static bool constexpr check() { return Writable<Iter, Value_type<Iter>>(); } }; // The specification of mutable iterators. template<typename Iter> struct Mutable_iterator_concept { static bool constexpr check() { return Mutable_iterator_requirements< Iter, Permutable_iterator<Iter>() >::check(); } }; // Return true if Iter is mutable. template<typename Iter> constexpr bool Mutable_iterator() { return Mutable_iterator_concept<Iter>::check(); } } // namespace origin #endif <commit_msg>Adding std_* iterator operations to the library.<commit_after>// Copyright (c) 2008-2010 Kent State University // Copyright (c) 2011 Texas A&M University // // This file is distributed under the MIT License. See the accompanying file // LICENSE.txt or http://www.opensource.org/licenses/mit-license.php for terms // and conditions. #ifndef ORIGIN_ITERATOR_HPP #define ORIGIN_ITERATOR_HPP #include <iterator> #include <origin/concepts.hpp> namespace origin { // Separate the checking of static requirements out of the Readable concept. // This prevents compiler errors when associated types aren't found. If // associated types can't be found, then the requirements will obviously // fail to pass. template<typename Iter, bool Types> struct Readable_requirements { static constexpr bool check() { return false; } }; template<typename Iter> struct Readable_requirements<Iter, true> { static constexpr bool check() { return Has_dereference<Iter>() && Convertible<Dereference_result<Iter>, Value_type<Iter> const&>(); } }; // Allows the following expression: Value_type<Iter> const& x = *i. template<typename Iter> struct Readable_concept { static constexpr bool check() { return Readable_requirements<Iter, Has_value_type<Iter>()>::check(); } static bool test(Iter i) { Value_type<Iter> const& x = *i; // NOTE: Not an axiom. return true; } }; template<typename Iter> constexpr bool Readable() { return Readable_concept<Iter>::check(); } // An iterator is Move_writable if the expression '*i = move(x)' is valid. template<typename Iter, typename T> struct Move_writable_concept { static constexpr bool check() { return Movable<T>() && Has_dereference<Iter>() && Assignable<Dereference_result<Iter>, T&&>(); } static bool test(Iter i, T x) { *i = std::move(x); // NOTE: Not an axiom. return true; } }; template<typename Iter, typename T> constexpr bool Move_writable() { return Move_writable_concept<Iter, T>::check(); } // An iterator is writable if the expression '*i = x' is valid. template<typename Iter, typename T> struct Writable_concept { static constexpr bool check() { return Copyable<T>() && Move_writable<Iter, T>() && Assignable<Dereference_result<Iter>, T const&>(); } static bool test() { // FIXME: Write semantics return true; } }; template<typename Iter, typename T> constexpr bool Writable() { return Writable_concept<Iter, T>::check(); } // Incrementable types // A weakly incrementable type is a semiregular type that can be pre- and // post-incremented. Neither operation is requireed to be equality // preserving, and the result of post-increment is unspecified. template<typename I> struct Weakly_incrementable_concept { static constexpr bool check() { return Semiregular<I>() && Has_distance_type<I>() // I& == { ++i } && Has_pre_increment<I>() && Same<Pre_increment_result<I>, I&>() // i++ && Has_post_increment<I>(); } // FIXME: Write semantics? Not sure if it's really possible. }; template<typename I> constexpr bool Weakly_incrementable() { return Weakly_incrementable_concept<I>::check(); } // An Incrementable type is a Regular, weakly incrementable type with // equality preserving pre- and post-increment operations. template<typename I> struct Incrementable_concept { static constexpr bool check() { return Regular<I>() && Weakly_incrementable<I>() // I == { i++ } && Same<Post_increment_result<I>, I>(); } }; template<typename I> constexpr bool Incrementable() { return Incrementable_concept<I>::check(); } // Iterators // The following concept classes and predicates are define checking // capabilities for iterator concepts. // Iterator categories // // Every iterator type explicitly describes its category, one of the // std::*_iterator_tag classes. For user-defined iterators, this is provided // as a nested type name (i.e., Iter::iterator_category). For pointers, the // category is random access. // Safely deduce a custom iterator category as a nested type. template<typename Iter> struct get_iterator_category { private: template<typename X> static typename X::iterator_category check(X&&); template<typename X> static typename std::iterator_traits<X*>::iterator_category check(X*); static subst_failure check(...); public: using type = decltype(check(std::declval<Iter>())); }; // An alias for the category of Iter. template<typename Iter> using Iterator_category = typename get_iterator_category<Iter>::type; // Return true if the iterator category is valid. template<typename Iter> constexpr bool Has_iterator_category() { return Subst_succeeded<Iterator_category<Iter>>(); } // Return an iterator category that is not more derived than the given limit. // For example, if Tag is "random access" and Limit is "forward", this will // return limit. // // Note that this does not guarantee that limit is actually derived from // Tag. That's just assumed. // // TODO: This seems like it could generalize to any Tag hierarchy. Consider // how this might be done (in terms of lattices?) and then move the // generalized solution into Traits or Concepts. template<typename Tag, typename Limit> using Clamp_iterator_category = If< Derived<Iterator_category<Tag>, Limit>(), Limit, Iterator_category<Tag> >; // Returns true if Iter has all of the associated iterator types. template<typename Iter> constexpr bool Has_iterator_types() { return Has_iterator_category<Iter>() && Has_value_type<Iter>() && Has_distance_type<Iter>(); } // Return true if T is an iterator. Here, T is an iterator if it has all of // the requisite associated types. template<typename T> constexpr bool Iterator() { return Has_iterator_types<T>(); } // An alias for the associated reference type of the iterator. This supports // writing backwards compatible iterators where the reference type is // actually named even though it should be deduced as decltype(*i). template<typename Iter> using Iterator_reference = typename std::iterator_traits<Iter>::reference; // An alias for the associated pointer type of the iterator. This supports // writing backwards compatible iterators where the reference type is // actually named even though it is never used in any STL algorithms. Note // that the pointer type cannot be deduced as decltype(&*i). template<typename Iter> using Iterator_pointer = typename std::iterator_traits<Iter>::pointer; // Input iterators // Unlike the TR, we start with Input_iterators, not Incrementable types. // Also, there is no such thing as a weak input iterator. We always assume // equality exists. // // FIXME: How closely should this follow the TR? template<typename Iter, bool Prereqs> struct Input_iterator_requirements { static constexpr bool check() { return false; } }; template<typename Iter> struct Input_iterator_requirements<Iter, true> { static constexpr bool check() { return Derived<Iterator_category<Iter>, std::input_iterator_tag>() && Equality_comparable<Iter>() && Weakly_incrementable<Iter>() && Readable<Post_increment_result<Iter>>(); } }; // An input iterator... template<typename Iter> struct Input_iterator_concept { static constexpr bool check() { return Input_iterator_requirements< Iter, Regular<Iter>() && Readable<Iter>() && Has_iterator_types<Iter>() >::check(); } static bool test() { // FIXME: Write semantics. return true; } }; template<typename Iter> constexpr bool Input_iterator() { return Input_iterator_concept<Iter>::check(); } // Forward Iterators // A forward iterator is an input iterator with a regular post-increment // operation. This guarantees that multiple passes of a range may be made // and that multiple iterators into the range may be used. // A helper class for checking syntactic requirements. template<typename Iter, bool Prereqs> struct Forward_iterator_requirements { static constexpr bool check() { return false; } }; template<typename Iter> struct Forward_iterator_requirements<Iter, true> { static constexpr bool check() { return Derived<Iterator_category<Iter>, std::forward_iterator_tag>() && Incrementable<Iter>() && Readable<Iter>(); } }; // The specification of forward iterators. template<typename Iter> struct Forward_iterator_concept { static constexpr bool check() { return Forward_iterator_requirements< Iter, Input_iterator<Iter>() >::check(); } static bool test() { // FIXME: Write semantics. return true; } }; // Return true if Iter is a forward iterator. template<typename Iter> constexpr bool Forward_iterator() { return Forward_iterator_concept<Iter>::check(); } // Bidirectional Iterators // A bidirectional iterator is a forward iterator that can also move // backwards using decrement operators. // A helper class for checking syntactic requirements. template<typename Iter, bool Prereqs> struct Bidirectional_iterator_requirements { static constexpr bool check() { return false; } }; template<typename Iter> struct Bidirectional_iterator_requirements<Iter, true> { static constexpr bool check() { return Derived<Iterator_category<Iter>, std::bidirectional_iterator_tag>() // Iter& == { --i } && Has_pre_decrement<Iter>() && Same<Pre_decrement_result<Iter>, Iter&>() // Iter == { i-- } && Has_post_decrement<Iter>() && Same<Post_decrement_result<Iter>, Iter>(); } }; // A bidirectional iterators... template<typename Iter> struct Bidirectional_iterator_concept { static constexpr bool check() { return Bidirectional_iterator_requirements< Iter, Forward_iterator<Iter>() >::check(); } static bool test() { // FIXME: Write semantics. return true; } }; template<typename Iter> constexpr bool Bidirectional_iterator() { return Bidirectional_iterator_concept<Iter>::check(); }; // Random Access Iterators // A random access iterator is a bidirectional iterator that can advance // any number of steps in constant time. // A helper class for checking syntactic requirements. template<typename Iter, bool Prereqs> struct Random_access_iterator_requirements { static constexpr bool check() { return false; } }; template<typename Iter> struct Random_access_iterator_requirements<Iter, true> { static constexpr bool check() { return Derived<Iterator_category<Iter>, std::random_access_iterator_tag>() && Signed<Distance_type<Iter>>() // Iter& == { i += n } && Has_plus_assign<Iter, Distance_type<Iter>>() && Same<Plus_assign_result<Iter, Distance_type<Iter>>, Iter&>() // Iter& == { i -= n } && Has_minus_assign<Iter, Distance_type<Iter>>() && Same<Minus_assign_result<Iter, Distance_type<Iter>>, Iter&>() // Iter == { i + n } && Has_plus<Iter, Distance_type<Iter>>() && Same<Plus_result<Iter, Distance_type<Iter>>, Iter>() // Iter == { n + i } && Has_plus<Distance_type<Iter>, Iter>() && Same<Plus_result<Distance_type<Iter>, Iter>, Iter>() // Iter == { i - n } && Has_minus<Iter, Distance_type<Iter>>() && Same<Minus_result<Iter, Distance_type<Iter>>, Iter>() // Distance_type<Iter> == { i - j } && Has_minus<Iter>() && Same<Minus_result<Iter>, Distance_type<Iter>>() // decltype(*i) == { i[n] } && Has_subscript<Iter, Distance_type<Iter>>() && Same<Subscript_result<Iter, Distance_type<Iter>>, Dereference_result<Iter>>(); } }; // The specification of random access iterators. template<typename Iter> struct Random_access_iterator_concept { static constexpr bool check() { return Random_access_iterator_requirements< Iter, Bidirectional_iterator<Iter>() >::check(); } static bool test() { // FIXME: Write semantics return true; } }; // Returns true if Iter is random access iterator. template<typename Iter> constexpr bool Random_access_iterator() { return Random_access_iterator_concept<Iter>::check(); }; // Mutable Iterators // There are two kinds of mutable iterators: Permutable iterators allow // values to be exchanged (moved). Mutable iterators allow values to be // replaced (copied). Note that mutable iterators are also permutable. // Permutable and mutable iterators are forward iterators. // Permutable Iterators // A permutable iterator allows values to be exchanged (moved) between // different iterators without copying. This also includes moving values // into temporary values. // A helper function for checking requirements. template<typename Iter, bool Prereqs> struct Permutable_iterator_requirements { static bool constexpr check() { return false; } }; template<typename Iter> struct Permutable_iterator_requirements<Iter, true> { static bool constexpr check() { return Move_writable<Iter, Value_type<Iter>>(); } }; // The specification of permutable iterators. template<typename Iter> struct Permutable_iterator_concept { static bool constexpr check() { return Permutable_iterator_requirements< Iter, Forward_iterator<Iter>() >::check(); } }; // Return true if Iter is permutable. template<typename Iter> constexpr bool Permutable_iterator() { return Permutable_iterator_concept<Iter>::check(); } // Mutable Iterators // A mutable iterator allows its referenced values to be re-assigned to new // values (through copies). Note that mutable iterators are also permutable. // A helper function for checking requirements. template<typename Iter, bool Prereqs> struct Mutable_iterator_requirements { static bool constexpr check() { return false; } }; template<typename Iter> struct Mutable_iterator_requirements<Iter, true> { static bool constexpr check() { return Writable<Iter, Value_type<Iter>>(); } }; // The specification of mutable iterators. template<typename Iter> struct Mutable_iterator_concept { static bool constexpr check() { return Mutable_iterator_requirements< Iter, Permutable_iterator<Iter>() >::check(); } }; // Return true if Iter is mutable. template<typename Iter> constexpr bool Mutable_iterator() { return Mutable_iterator_concept<Iter>::check(); } // Iterator operations // // The standard iterator operations simply assert the minimum requirements // before delegating to the usual algorithm. This library does not dispatch // based on iterator type. template<typename Iter> inline void std_advance(Iter& i, Distance_type<Iter> n = 1) { static_assert(Weakly_incrementable<Iter>(), ""); std::advance(i, n); } template<typename Iter> inline Iter std_next(Iter i, Distance_type<Iter> n = 1) { static_assert(Weakly_incrementable<Iter>(), ""); return std::next(i, n); } template<typename Iter> inline Iter std_prev(Iter i, Distance_type<Iter> n = 1) { static_assert(Bidirectional_iterator<Iter>(), ""); return std::prev(i, n); } template<typename Iter> inline Distance_type<Iter> std_distance(Iter i, Iter j) { static_assert(Weakly_incrementable<Iter>(), ""); return std::distance(i, j); } } // namespace origin #endif <|endoftext|>
<commit_before>#include <iostream> #include <QtConcurrent> #include <QCoreApplication> #include <stdint.h> #include <pulse/simple.h> #include "DBMeter.hpp" using namespace std; DBMeter::DBMeter() { settings.setCodec("audio/PCM"); settings.setChannelCount(1); settings.setSampleRate(16000); recorder = new QAudioRecorder(this); recorder->setAudioInput("pulseaudio:"); recorder->setAudioSettings(settings); QUrl url = QString("/dev/null"); recorder->setOutputLocation(url); probe = new QAudioProbe(this); connect(probe, SIGNAL(audioBufferProbed(QAudioBuffer)), this, SLOT(AudioCb(QAudioBuffer))); probe->setSource(recorder); } DBMeter::~DBMeter() { delete recorder; } void DBMeter::Start() { recorder->record(); } void DBMeter::Stop() { recorder->stop(); } void DBMeter::AudioCb(const QAudioBuffer &buffer) { const int16_t *ptr = buffer.constData<int16_t>(); uint16_t maxVal = 0, val; int nbFrame = buffer.sampleCount(); while (nbFrame--) { val = abs(*ptr++); if (val > maxVal) maxVal = val; } cerr << " maxVal " << maxVal << endl; } <commit_msg>Remove an include not needed<commit_after>#include <iostream> #include <QtConcurrent> #include <QCoreApplication> #include <stdint.h> #include "DBMeter.hpp" using namespace std; DBMeter::DBMeter() { settings.setCodec("audio/PCM"); settings.setChannelCount(1); settings.setSampleRate(16000); recorder = new QAudioRecorder(this); recorder->setAudioInput("pulseaudio:"); recorder->setAudioSettings(settings); QUrl url = QString("/dev/null"); recorder->setOutputLocation(url); probe = new QAudioProbe(this); connect(probe, SIGNAL(audioBufferProbed(QAudioBuffer)), this, SLOT(AudioCb(QAudioBuffer))); probe->setSource(recorder); } DBMeter::~DBMeter() { delete recorder; } void DBMeter::Start() { recorder->record(); } void DBMeter::Stop() { recorder->stop(); } void DBMeter::AudioCb(const QAudioBuffer &buffer) { const int16_t *ptr = buffer.constData<int16_t>(); uint16_t maxVal = 0, val; int nbFrame = buffer.sampleCount(); while (nbFrame--) { val = abs(*ptr++); if (val > maxVal) maxVal = val; } cerr << " maxVal " << maxVal << endl; } <|endoftext|>
<commit_before> #include <planet/common.hpp> #include <planet/utils.hpp> #include <syslog.h> namespace planet { int core_file_system::getattr(path_type const& path, struct stat& stbuf) const { if (auto fs_ent = get_entry_of(path)) { stbuf.st_nlink = fs_ent.use_count(); stbuf.st_atime = st_inode::to_time_t(fs_ent->inode().atime); stbuf.st_mtime = st_inode::to_time_t(fs_ent->inode().mtime); stbuf.st_ctime = st_inode::to_time_t(fs_ent->inode().ctime); stbuf.st_mode = fs_ent->inode().mode; stbuf.st_size = fs_ent->size(); } else throw exception_errno(ENOENT); return 0; } int core_file_system::mknod(path_type const& path, mode_t mode, dev_t device) { return mknod(path, mode, device, path_mgr_[path]); } int core_file_system::mknod(path_type const& path, mode_t mode, dev_t device, op_type_code op_code) { if (auto parent_dir = directory_cast(get_entry_of(path.parent_path()))) { st_inode new_inode; new_inode.dev = device; new_inode.mode = mode | S_IFREG; parent_dir->add_entry<file_entry>(path.filename().string(), op_code, new_inode); try { auto fentry = file_cast(get_entry_of(path)); ops_mgr_[fentry->get_op()]->mknod(fentry, path, mode, device); } catch (...) { parent_dir->remove_entry(path.filename().string()); throw; } } else throw exception_errno(ENOENT); return 0; } int core_file_system::unlink(path_type const& path) { int ret = 0; if (auto parent_dir = directory_cast(get_entry_of(path.parent_path()))) { auto fentry = file_cast(get_entry_of(path)); ret = ops_mgr_[fentry->get_op()]->rmnod(fentry, path); if (ret < 0) return ret; parent_dir->remove_entry(path.filename().string()); } else throw exception_errno(ENOENT); return ret; } int core_file_system::mkdir(path_type const& path, mode_t mode) { if (auto parent_dir = directory_cast(get_entry_of(path.parent_path()))) { st_inode new_inode; new_inode.mode = mode | S_IFDIR; parent_dir->add_entry<dentry>(path.filename().string(), new_inode); } else throw exception_errno(ENOENT); return 0; } int core_file_system::rmdir(path_type const& path) { if (auto parent_dir = directory_cast(get_entry_of(path.parent_path()))) parent_dir->remove_entry(path.filename().string()); else throw exception_errno(ENOENT); return 0; } std::vector<std::string> core_file_system::readdir(path_type const& path) const { std::vector<std::string> store; if (auto dir_ent = directory_cast(get_entry_of(path))) { for (auto entry : dir_ent->entries()) store.push_back(entry->name()); } else throw exception_errno(ENOENT); return store; } handle_t core_file_system::open(path_type const& path) { handle_t new_handle; if (auto entry = get_entry_of(path)) { if (entry->type() != file_type::regular_file) throw exception_errno(EISDIR); auto fentry = file_cast(entry); new_handle = handle_mgr.register_op(fentry, ops_mgr_[fentry->get_op()]->new_instance()); try { auto& op_tuple = handle_mgr.get_operation_entry(new_handle); std::get<1>(op_tuple)->open(std::get<0>(op_tuple), path); } catch (...) { handle_mgr.unregister_op(new_handle); throw; } } else throw exception_errno(ENOENT); return new_handle; } shared_ptr<fs_entry> core_file_system::get_entry_of(path_type const& path) const { return (path == "/" ? root : get_entry_of__(root, path)); } shared_ptr<fs_entry> core_file_system::get_entry_of__(shared_ptr<dentry> root, path_type const& path) const { if (path.empty() || path.is_relative() || !root) throw std::runtime_error{"empty string or invalid root passed"}; string_type p = path.string(); auto pos = p.find_first_of('/', 1); if (pos == std::string::npos) return root->search_entries(p.substr(1)); // Get parent directory from filename auto dir_entry = root->search_entries(p.substr(1, pos - 1)); if (!dir_entry || dir_entry->type() != file_type::directory) return detail::shared_null_ptr; return get_entry_of__(directory_cast(dir_entry), "/" + p.substr(pos + 1)); } } // namespace planet <commit_msg>fs_core.cpp: find file_entry from its parent dir<commit_after> #include <planet/common.hpp> #include <planet/utils.hpp> #include <syslog.h> namespace planet { int core_file_system::getattr(path_type const& path, struct stat& stbuf) const { if (auto fs_ent = get_entry_of(path)) { stbuf.st_nlink = fs_ent.use_count(); stbuf.st_atime = st_inode::to_time_t(fs_ent->inode().atime); stbuf.st_mtime = st_inode::to_time_t(fs_ent->inode().mtime); stbuf.st_ctime = st_inode::to_time_t(fs_ent->inode().ctime); stbuf.st_mode = fs_ent->inode().mode; stbuf.st_size = fs_ent->size(); } else throw exception_errno(ENOENT); return 0; } int core_file_system::mknod(path_type const& path, mode_t mode, dev_t device) { return mknod(path, mode, device, path_mgr_[path]); } int core_file_system::mknod(path_type const& path, mode_t mode, dev_t device, op_type_code op_code) { if (auto parent_dir = directory_cast(get_entry_of(path.parent_path()))) { st_inode new_inode; new_inode.dev = device; new_inode.mode = mode | S_IFREG; parent_dir->add_entry<file_entry>(path.filename().string(), op_code, new_inode); try { auto fentry = file_cast(get_entry_of(path)); ops_mgr_[fentry->get_op()]->mknod(fentry, path, mode, device); } catch (...) { parent_dir->remove_entry(path.filename().string()); throw; } } else throw exception_errno(ENOENT); return 0; } int core_file_system::unlink(path_type const& path) { int ret = 0; if (auto parent_dir = directory_cast(get_entry_of(path.parent_path()))) { auto fentry = file_cast(parent_dir->search_entries(path.filename().string())); ret = ops_mgr_[fentry->get_op()]->rmnod(fentry, path); if (ret < 0) return ret; parent_dir->remove_entry(path.filename().string()); } else throw exception_errno(ENOENT); return ret; } int core_file_system::mkdir(path_type const& path, mode_t mode) { if (auto parent_dir = directory_cast(get_entry_of(path.parent_path()))) { st_inode new_inode; new_inode.mode = mode | S_IFDIR; parent_dir->add_entry<dentry>(path.filename().string(), new_inode); } else throw exception_errno(ENOENT); return 0; } int core_file_system::rmdir(path_type const& path) { if (auto parent_dir = directory_cast(get_entry_of(path.parent_path()))) parent_dir->remove_entry(path.filename().string()); else throw exception_errno(ENOENT); return 0; } std::vector<std::string> core_file_system::readdir(path_type const& path) const { std::vector<std::string> store; if (auto dir_ent = directory_cast(get_entry_of(path))) { for (auto entry : dir_ent->entries()) store.push_back(entry->name()); } else throw exception_errno(ENOENT); return store; } handle_t core_file_system::open(path_type const& path) { handle_t new_handle; if (auto entry = get_entry_of(path)) { if (entry->type() != file_type::regular_file) throw exception_errno(EISDIR); auto fentry = file_cast(entry); new_handle = handle_mgr.register_op(fentry, ops_mgr_[fentry->get_op()]->new_instance()); try { auto& op_tuple = handle_mgr.get_operation_entry(new_handle); std::get<1>(op_tuple)->open(std::get<0>(op_tuple), path); } catch (...) { handle_mgr.unregister_op(new_handle); throw; } } else throw exception_errno(ENOENT); return new_handle; } shared_ptr<fs_entry> core_file_system::get_entry_of(path_type const& path) const { return (path == "/" ? root : get_entry_of__(root, path)); } shared_ptr<fs_entry> core_file_system::get_entry_of__(shared_ptr<dentry> root, path_type const& path) const { if (path.empty() || path.is_relative() || !root) throw std::runtime_error{"empty string or invalid root passed"}; string_type p = path.string(); auto pos = p.find_first_of('/', 1); if (pos == std::string::npos) return root->search_entries(p.substr(1)); // Get parent directory from filename auto dir_entry = root->search_entries(p.substr(1, pos - 1)); if (!dir_entry || dir_entry->type() != file_type::directory) return detail::shared_null_ptr; return get_entry_of__(directory_cast(dir_entry), "/" + p.substr(pos + 1)); } } // namespace planet <|endoftext|>
<commit_before> /* Display.cpp * * Copyright (C) 2013 Michael Imamura * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ #include "StdAfx.h" #include "Exception.h" #include "Display.h" namespace AISDL { Display::Display() : window(nullptr), renderer(nullptr) { windowPtr = std::shared_ptr<SDL_Window>( SDL_CreateWindow("Adventures in SDL2", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE | SDL_WINDOW_OPENGL), SDL_DestroyWindow); if (!windowPtr) { throw Exception(SDL_GetError()); } window = windowPtr.get(); rendererPtr = std::shared_ptr<SDL_Renderer>( SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC), SDL_DestroyRenderer); if (!rendererPtr) { throw Exception(SDL_GetError()); } renderer = rendererPtr.get(); } /** * Create a new 32-bit OpenGL-compatible surface with an alpha channel. * @param w The width of the surface. * @param h The height of the surface. * @return The created surface. * @throws Exception The surface could not be created. */ SDL_Surface *Display::NewAlphaSurface(int w, int h) { // Adapted from http://wiki.libsdl.org/SDL_CreateRGBSurface Uint32 rmask, gmask, bmask, amask; # if SDL_BYTEORDER == SDL_BIG_ENDIAN rmask = 0xff000000; gmask = 0x00ff0000; bmask = 0x0000ff00; amask = 0x000000ff; # else rmask = 0x000000ff; gmask = 0x0000ff00; bmask = 0x00ff0000; amask = 0xff000000; # endif SDL_Surface *surface = SDL_CreateRGBSurface(0, w, h, 32, rmask, gmask, bmask, amask); if (!surface) { throw Exception(SDL_GetError()); } return surface; } /** * Simply render a texture to the screen. * * This handles the simple case where the whole texture is to be * rendered to a specific position. * * @param texture The texture to render (may not be @c nullptr); * @param x The destination */ void Display::RenderTexture(SDL_Texture *texture, int x, int y) { int w, h; SDL_QueryTexture(texture, nullptr, nullptr, &w, &h); SDL_Rect destRect = { x, y, w, h }; SDL_RenderCopy(renderer, texture, nullptr, &destRect); } } // namespace AISDL <commit_msg>Use virtual 640x480 viewport.<commit_after> /* Display.cpp * * Copyright (C) 2013 Michael Imamura * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ #include "StdAfx.h" #include "Exception.h" #include "Display.h" namespace AISDL { Display::Display() : window(nullptr), renderer(nullptr) { windowPtr = std::shared_ptr<SDL_Window>( SDL_CreateWindow("Adventures in SDL2", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE | SDL_WINDOW_OPENGL), SDL_DestroyWindow); if (!windowPtr) { throw Exception(SDL_GetError()); } window = windowPtr.get(); rendererPtr = std::shared_ptr<SDL_Renderer>( SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC), SDL_DestroyRenderer); if (!rendererPtr) { throw Exception(SDL_GetError()); } renderer = rendererPtr.get(); // Act as if we're using a 640x480 framebuffer, even if the window is // larger or smaller. SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "best"); SDL_RenderSetLogicalSize(renderer, 640, 480); } /** * Create a new 32-bit OpenGL-compatible surface with an alpha channel. * @param w The width of the surface. * @param h The height of the surface. * @return The created surface. * @throws Exception The surface could not be created. */ SDL_Surface *Display::NewAlphaSurface(int w, int h) { // Adapted from http://wiki.libsdl.org/SDL_CreateRGBSurface Uint32 rmask, gmask, bmask, amask; # if SDL_BYTEORDER == SDL_BIG_ENDIAN rmask = 0xff000000; gmask = 0x00ff0000; bmask = 0x0000ff00; amask = 0x000000ff; # else rmask = 0x000000ff; gmask = 0x0000ff00; bmask = 0x00ff0000; amask = 0xff000000; # endif SDL_Surface *surface = SDL_CreateRGBSurface(0, w, h, 32, rmask, gmask, bmask, amask); if (!surface) { throw Exception(SDL_GetError()); } return surface; } /** * Simply render a texture to the screen. * * This handles the simple case where the whole texture is to be * rendered to a specific position. * * @param texture The texture to render (may not be @c nullptr); * @param x The destination */ void Display::RenderTexture(SDL_Texture *texture, int x, int y) { int w, h; SDL_QueryTexture(texture, nullptr, nullptr, &w, &h); SDL_Rect destRect = { x, y, w, h }; SDL_RenderCopy(renderer, texture, nullptr, &destRect); } } // namespace AISDL <|endoftext|>
<commit_before>/////////////////////////////////////////////////////////////////////////////// // BOSSA // // Copyright (c) 2011-2012, ShumaTech // 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 <organization> 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 <COPYRIGHT HOLDER> BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /////////////////////////////////////////////////////////////////////////////// #include <string> #include <exception> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include "Flasher.h" using namespace std; void Flasher::progressBar(int num, int div) { int ticks; int bars = 30; printf("\r["); ticks = num * bars / div; while (ticks-- > 0) { putchar('='); bars--; } while (bars-- > 0) { putchar(' '); } printf("] %d%% (%d/%d pages)", num * 100 / div, num, div); fflush(stdout); } void Flasher::erase() { printf("Erase flash\n"); _flash->eraseAll(); _flash->eraseAuto(false); } void Flasher::write(const char* filename) { FILE* infile; uint32_t pageSize = _flash->pageSize(); uint32_t pageNum = 0; uint32_t numPages; long fsize; size_t fbytes; infile = fopen(filename, "rb"); if (!infile) throw FileOpenError(errno); try { if (fseek(infile, 0, SEEK_END) != 0 || (fsize = ftell(infile)) < 0) throw FileIoError(errno); rewind(infile); numPages = (fsize + pageSize - 1) / pageSize; if (numPages > _flash->numPages()) throw FileSizeError(); printf("Write %ld bytes to flash (%u pages)\n", fsize, numPages); if (_flash->isWriteBufferAvailable()) { // If multi-page write is available.... const uint32_t BLK_SIZE = 4096; uint32_t offset = 0; uint8_t buffer[BLK_SIZE]; memset(buffer, 0, BLK_SIZE); while ((fbytes = fread(buffer, 1, BLK_SIZE, infile)) > 0) { if (fbytes < BLK_SIZE) { // Ceil to nearest pagesize fbytes = (fbytes + pageSize - 1) / pageSize * pageSize; } _flash->loadBuffer(buffer, fbytes); _flash->writeBuffer(offset, fbytes); offset += fbytes; progressBar(offset/pageSize, numPages); memset(buffer, 0, BLK_SIZE); } } else { // ...otherwise go with the legacy slow method uint8_t buffer[pageSize]; while ((fbytes = fread(buffer, 1, pageSize, infile)) > 0) { // updated from one print per 10 pages to one per 10 percent if (pageNum % (numPages/10) == 0) progressBar(pageNum, numPages); _flash->loadBuffer(buffer, fbytes); _flash->writePage(pageNum); pageNum++; if (pageNum == numPages || fbytes != pageSize) break; } progressBar(pageNum, numPages); } printf("\n"); } catch(...) { fclose(infile); throw; } fclose(infile); } bool Flasher::verify(const char* filename) { FILE* infile; uint32_t pageSize = _flash->pageSize(); uint8_t bufferA[pageSize]; uint8_t bufferB[pageSize]; uint32_t pageNum = 0; uint32_t numPages; uint32_t byteErrors = 0; uint32_t pageErrors = 0; uint32_t totalErrors = 0; long fsize; size_t fbytes; infile = fopen(filename, "rb"); if (!infile) throw FileOpenError(errno); if (fseek(infile, 0, SEEK_END) != 0 || (fsize = ftell(infile)) < 0) throw FileIoError(errno); rewind(infile); // If checksum buffer is available, use it... if (_flash->isChecksumBufferAvailable()) { bool failed = false; try { printf("Verify %ld bytes of flash with checksum.\n", fsize); // Perform checksum every 4096 bytes uint32_t BLK_SIZE = 4096; uint8_t buffer[BLK_SIZE]; uint32_t offset = 0; while ((fbytes = fread(buffer, 1, BLK_SIZE, infile)) > 0) { uint32_t i; uint16_t crc = 0; for (i=0; i<fbytes; i++) crc = _flash->crc16AddByte(buffer[i], crc); uint16_t flashCrc = _flash->checksumBuffer(offset, fbytes); offset += fbytes; if (crc != flashCrc) { failed = true; break; } } } catch(...) { fclose(infile); throw; } fclose(infile); if (failed) { printf("Verify failed\n"); return false; } printf("Verify successful\n"); return true; } // ...otherwise go with the slow legacy method... try { numPages = (fsize + pageSize - 1) / pageSize; if (numPages > _flash->numPages()) throw FileSizeError(); printf("Verify %ld bytes of flash\n", fsize); while ((fbytes = fread(bufferA, 1, pageSize, infile)) > 0) { // updated from one print per 10 pages to one per 10 percent if (pageNum % (numPages/10) == 0) progressBar(pageNum, numPages); _flash->readPage(pageNum, bufferB); byteErrors = 0; for (uint32_t i = 0; i < fbytes; i++) { if (bufferA[i] != bufferB[i]) byteErrors++; } if (byteErrors != 0) { pageErrors++; totalErrors += byteErrors; } pageNum++; if (pageNum == numPages || fbytes != pageSize) break; } progressBar(pageNum, numPages); printf("\n"); } catch(...) { fclose(infile); throw; } fclose(infile); if (byteErrors != 0) { printf("Verify failed\n"); printf("Page errors: %d\n", pageErrors); printf("Byte errors: %d\n", totalErrors); return false; } printf("Verify successful\n"); return true; } void Flasher::read(const char* filename, long fsize) { FILE* outfile; uint32_t pageSize = _flash->pageSize(); uint8_t buffer[pageSize]; uint32_t pageNum = 0; uint32_t numPages; size_t fbytes; if (fsize == 0) fsize = pageSize * _flash->numPages(); outfile = fopen(filename, "wb"); if (!outfile) throw FileOpenError(errno); try { numPages = (fsize + pageSize - 1) / pageSize; if (numPages > _flash->numPages()) throw FileSizeError(); printf("Read %ld bytes from flash\n", fsize); for (pageNum = 0; pageNum < numPages; pageNum++) { // updated from one print per 10 pages to one per 10 percent if (pageNum % (numPages/10) == 0) progressBar(pageNum, numPages); _flash->readPage(pageNum, buffer); if (pageNum == numPages - 1 && fsize % pageSize > 0) pageSize = fsize % pageSize; fbytes = fwrite(buffer, 1, pageSize, outfile); if (fbytes != pageSize) throw FileShortError(); } progressBar(pageNum, numPages); printf("\n"); } catch(...) { fclose(outfile); throw; } fclose(outfile); } void Flasher::lock(string& regionArg, bool enable) { if (regionArg.empty()) { printf("%s all regions\n", enable ? "Lock" : "Unlock"); if (enable) _flash->lockAll(); else _flash->unlockAll(); } else { size_t pos = 0; size_t delim; uint32_t region; string sub; do { delim = regionArg.find(',', pos); sub = regionArg.substr(pos, delim - pos); region = strtol(sub.c_str(), NULL, 0); printf("%s region %d\n", enable ? "Lock" : "Unlock", region); _flash->setLockRegion(region, enable); pos = delim + 1; } while (delim != string::npos); } } void Flasher::info(Samba& samba) { bool first; printf("Device : %s\n", _flash->name().c_str()); printf("Chip ID : %08x\n", samba.chipId()); printf("Version : %s\n", samba.version().c_str()); printf("Address : %d\n", _flash->address()); printf("Pages : %d\n", _flash->numPages()); printf("Page Size : %d bytes\n", _flash->pageSize()); printf("Total Size : %dKB\n", _flash->numPages() * _flash->pageSize() / 1024); printf("Planes : %d\n", _flash->numPlanes()); printf("Lock Regions : %d\n", _flash->lockRegions()); printf("Locked : "); first = true; for (uint32_t region = 0; region < _flash->lockRegions(); region++) { if (_flash->getLockRegion(region)) { printf("%s%d", first ? "" : ",", region); first = false; } } printf("%s\n", first ? "none" : ""); printf("Security : %s\n", _flash->getSecurity() ? "true" : "false"); if (_flash->canBootFlash()) printf("Boot Flash : %s\n", _flash->getBootFlash() ? "true" : "false"); if (_flash->canBod()) printf("BOD : %s\n", _flash->getBod() ? "true" : "false"); if (_flash->canBor()) printf("BOR : %s\n", _flash->getBor() ? "true" : "false"); if (samba.isChipEraseAvailable()) printf("Arduino : FAST_CHIP_ERASE\n"); if (samba.isWriteBufferAvailable()) printf("Arduino : FAST_MULTI_PAGE_WRITE\n"); if (samba.isChecksumBufferAvailable()) printf("Arduino : CAN_CHECKSUM_MEMORY_BUFFER\n"); } <commit_msg>Don't divide by zero on small transfers<commit_after>/////////////////////////////////////////////////////////////////////////////// // BOSSA // // Copyright (c) 2011-2012, ShumaTech // 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 <organization> 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 <COPYRIGHT HOLDER> BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /////////////////////////////////////////////////////////////////////////////// #include <string> #include <exception> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include "Flasher.h" using namespace std; void Flasher::progressBar(int num, int div) { int ticks; int bars = 30; printf("\r["); ticks = num * bars / div; while (ticks-- > 0) { putchar('='); bars--; } while (bars-- > 0) { putchar(' '); } printf("] %d%% (%d/%d pages)", num * 100 / div, num, div); fflush(stdout); } void Flasher::erase() { printf("Erase flash\n"); _flash->eraseAll(); _flash->eraseAuto(false); } void Flasher::write(const char* filename) { FILE* infile; uint32_t pageSize = _flash->pageSize(); uint32_t pageNum = 0; uint32_t numPages; long fsize; size_t fbytes; infile = fopen(filename, "rb"); if (!infile) throw FileOpenError(errno); try { if (fseek(infile, 0, SEEK_END) != 0 || (fsize = ftell(infile)) < 0) throw FileIoError(errno); rewind(infile); numPages = (fsize + pageSize - 1) / pageSize; if (numPages > _flash->numPages()) throw FileSizeError(); printf("Write %ld bytes to flash (%u pages)\n", fsize, numPages); if (_flash->isWriteBufferAvailable()) { // If multi-page write is available.... const uint32_t BLK_SIZE = 4096; uint32_t offset = 0; uint8_t buffer[BLK_SIZE]; memset(buffer, 0, BLK_SIZE); while ((fbytes = fread(buffer, 1, BLK_SIZE, infile)) > 0) { if (fbytes < BLK_SIZE) { // Ceil to nearest pagesize fbytes = (fbytes + pageSize - 1) / pageSize * pageSize; } _flash->loadBuffer(buffer, fbytes); _flash->writeBuffer(offset, fbytes); offset += fbytes; progressBar(offset/pageSize, numPages); memset(buffer, 0, BLK_SIZE); } } else { // ...otherwise go with the legacy slow method uint8_t buffer[pageSize]; while ((fbytes = fread(buffer, 1, pageSize, infile)) > 0) { // updated from one print per 10 pages to one per 10 percent if ((pageNum < 10) || (pageNum % (numPages/10) == 0)) progressBar(pageNum, numPages); _flash->loadBuffer(buffer, fbytes); _flash->writePage(pageNum); pageNum++; if (pageNum == numPages || fbytes != pageSize) break; } progressBar(pageNum, numPages); } printf("\n"); } catch(...) { fclose(infile); throw; } fclose(infile); } bool Flasher::verify(const char* filename) { FILE* infile; uint32_t pageSize = _flash->pageSize(); uint8_t bufferA[pageSize]; uint8_t bufferB[pageSize]; uint32_t pageNum = 0; uint32_t numPages; uint32_t byteErrors = 0; uint32_t pageErrors = 0; uint32_t totalErrors = 0; long fsize; size_t fbytes; infile = fopen(filename, "rb"); if (!infile) throw FileOpenError(errno); if (fseek(infile, 0, SEEK_END) != 0 || (fsize = ftell(infile)) < 0) throw FileIoError(errno); rewind(infile); // If checksum buffer is available, use it... if (_flash->isChecksumBufferAvailable()) { bool failed = false; try { printf("Verify %ld bytes of flash with checksum.\n", fsize); // Perform checksum every 4096 bytes uint32_t BLK_SIZE = 4096; uint8_t buffer[BLK_SIZE]; uint32_t offset = 0; while ((fbytes = fread(buffer, 1, BLK_SIZE, infile)) > 0) { uint32_t i; uint16_t crc = 0; for (i=0; i<fbytes; i++) crc = _flash->crc16AddByte(buffer[i], crc); uint16_t flashCrc = _flash->checksumBuffer(offset, fbytes); offset += fbytes; if (crc != flashCrc) { failed = true; break; } } } catch(...) { fclose(infile); throw; } fclose(infile); if (failed) { printf("Verify failed\n"); return false; } printf("Verify successful\n"); return true; } // ...otherwise go with the slow legacy method... try { numPages = (fsize + pageSize - 1) / pageSize; if (numPages > _flash->numPages()) throw FileSizeError(); printf("Verify %ld bytes of flash\n", fsize); while ((fbytes = fread(bufferA, 1, pageSize, infile)) > 0) { // updated from one print per 10 pages to one per 10 percent if ((pageNum < 10) || (pageNum % (numPages/10) == 0)) progressBar(pageNum, numPages); _flash->readPage(pageNum, bufferB); byteErrors = 0; for (uint32_t i = 0; i < fbytes; i++) { if (bufferA[i] != bufferB[i]) byteErrors++; } if (byteErrors != 0) { pageErrors++; totalErrors += byteErrors; } pageNum++; if (pageNum == numPages || fbytes != pageSize) break; } progressBar(pageNum, numPages); printf("\n"); } catch(...) { fclose(infile); throw; } fclose(infile); if (byteErrors != 0) { printf("Verify failed\n"); printf("Page errors: %d\n", pageErrors); printf("Byte errors: %d\n", totalErrors); return false; } printf("Verify successful\n"); return true; } void Flasher::read(const char* filename, long fsize) { FILE* outfile; uint32_t pageSize = _flash->pageSize(); uint8_t buffer[pageSize]; uint32_t pageNum = 0; uint32_t numPages; size_t fbytes; if (fsize == 0) fsize = pageSize * _flash->numPages(); outfile = fopen(filename, "wb"); if (!outfile) throw FileOpenError(errno); try { numPages = (fsize + pageSize - 1) / pageSize; if (numPages > _flash->numPages()) throw FileSizeError(); printf("Read %ld bytes from flash\n", fsize); for (pageNum = 0; pageNum < numPages; pageNum++) { // updated from one print per 10 pages to one per 10 percent if ((pageNum < 10) || (pageNum % (numPages/10) == 0)) progressBar(pageNum, numPages); _flash->readPage(pageNum, buffer); if (pageNum == numPages - 1 && fsize % pageSize > 0) pageSize = fsize % pageSize; fbytes = fwrite(buffer, 1, pageSize, outfile); if (fbytes != pageSize) throw FileShortError(); } progressBar(pageNum, numPages); printf("\n"); } catch(...) { fclose(outfile); throw; } fclose(outfile); } void Flasher::lock(string& regionArg, bool enable) { if (regionArg.empty()) { printf("%s all regions\n", enable ? "Lock" : "Unlock"); if (enable) _flash->lockAll(); else _flash->unlockAll(); } else { size_t pos = 0; size_t delim; uint32_t region; string sub; do { delim = regionArg.find(',', pos); sub = regionArg.substr(pos, delim - pos); region = strtol(sub.c_str(), NULL, 0); printf("%s region %d\n", enable ? "Lock" : "Unlock", region); _flash->setLockRegion(region, enable); pos = delim + 1; } while (delim != string::npos); } } void Flasher::info(Samba& samba) { bool first; printf("Device : %s\n", _flash->name().c_str()); printf("Chip ID : %08x\n", samba.chipId()); printf("Version : %s\n", samba.version().c_str()); printf("Address : %d\n", _flash->address()); printf("Pages : %d\n", _flash->numPages()); printf("Page Size : %d bytes\n", _flash->pageSize()); printf("Total Size : %dKB\n", _flash->numPages() * _flash->pageSize() / 1024); printf("Planes : %d\n", _flash->numPlanes()); printf("Lock Regions : %d\n", _flash->lockRegions()); printf("Locked : "); first = true; for (uint32_t region = 0; region < _flash->lockRegions(); region++) { if (_flash->getLockRegion(region)) { printf("%s%d", first ? "" : ",", region); first = false; } } printf("%s\n", first ? "none" : ""); printf("Security : %s\n", _flash->getSecurity() ? "true" : "false"); if (_flash->canBootFlash()) printf("Boot Flash : %s\n", _flash->getBootFlash() ? "true" : "false"); if (_flash->canBod()) printf("BOD : %s\n", _flash->getBod() ? "true" : "false"); if (_flash->canBor()) printf("BOR : %s\n", _flash->getBor() ? "true" : "false"); if (samba.isChipEraseAvailable()) printf("Arduino : FAST_CHIP_ERASE\n"); if (samba.isWriteBufferAvailable()) printf("Arduino : FAST_MULTI_PAGE_WRITE\n"); if (samba.isChecksumBufferAvailable()) printf("Arduino : CAN_CHECKSUM_MEMORY_BUFFER\n"); } <|endoftext|>
<commit_before>#ifndef LEAP_SERVER_HPP #define LEAP_SERVER_HPP #include "Leap.h" enum Direction { FORWARD, BACKWARD, RIGHT, LEFT, UNDEFINED }; using namespace Leap; class LeapServer : public Listener { private: Direction direction; Controller controller; public: LeapServer() { direction = UNDEFINED; }; ~LeapServer() { controller.removeListener(*this); }; virtual void onConnect(const Controller &) { fprintf(stdout, "Leap connected : %d!\n", controller.isConnected()); }; virtual void onFrame(const Controller &) { const Frame frame = controller.frame(); FingerList fingers = frame.fingers().extended(); Hand hand = frame.hands()[0]; // Si la main est valide + 5 doigts if (hand.isValid() && fingers.count() == 5) { Direction tempDirection = findDirection(hand.palmPosition()); if (tempDirection != direction) { fprintf(stdout, "tempDirection : %d\n", tempDirection); // MAJ de la direction direction = tempDirection; } } }; // Retourne la direction du vecteur de la main Direction findDirection(const Vector & vector) { if (vector.x > 90) { // Droite return LEFT; } else if (vector.x < -90) { // Gauche return RIGHT; } else if (vector.z < -90) { // Haut return FORWARD; } else if (vector.z > 90) { // Bas return BACKWARD; } else { return UNDEFINED; } }; }; #endif // LEAP_SERVER_HPP <commit_msg>delete src/Leap.cpp<commit_after><|endoftext|>
<commit_before>/* * Copyright (c) 2015-present, 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 <fb/fbjni/CoreClasses.h> #include <fb/assert.h> #include <fb/log.h> #include <alloca.h> #include <cstdlib> #include <ios> #include <stdexcept> #include <stdio.h> #include <string> #include <system_error> #include <jni.h> namespace facebook { namespace jni { namespace { class JRuntimeException : public JavaClass<JRuntimeException, JThrowable> { public: static auto constexpr kJavaDescriptor = "Ljava/lang/RuntimeException;"; static local_ref<JRuntimeException> create(const char* str) { return newInstance(make_jstring(str)); } static local_ref<JRuntimeException> create() { return newInstance(); } }; class JIOException : public JavaClass<JIOException, JThrowable> { public: static auto constexpr kJavaDescriptor = "Ljava/io/IOException;"; static local_ref<JIOException> create(const char* str) { return newInstance(make_jstring(str)); } }; class JOutOfMemoryError : public JavaClass<JOutOfMemoryError, JThrowable> { public: static auto constexpr kJavaDescriptor = "Ljava/lang/OutOfMemoryError;"; static local_ref<JOutOfMemoryError> create(const char* str) { return newInstance(make_jstring(str)); } }; class JArrayIndexOutOfBoundsException : public JavaClass<JArrayIndexOutOfBoundsException, JThrowable> { public: static auto constexpr kJavaDescriptor = "Ljava/lang/ArrayIndexOutOfBoundsException;"; static local_ref<JArrayIndexOutOfBoundsException> create(const char* str) { return newInstance(make_jstring(str)); } }; class JUnknownCppException : public JavaClass<JUnknownCppException, JThrowable> { public: static auto constexpr kJavaDescriptor = "Lcom/facebook/jni/UnknownCppException;"; static local_ref<JUnknownCppException> create() { return newInstance(); } static local_ref<JUnknownCppException> create(const char* str) { return newInstance(make_jstring(str)); } }; class JCppSystemErrorException : public JavaClass<JCppSystemErrorException, JThrowable> { public: static auto constexpr kJavaDescriptor = "Lcom/facebook/jni/CppSystemErrorException;"; static local_ref<JCppSystemErrorException> create(const std::system_error& e) { return newInstance(make_jstring(e.what()), e.code().value()); } }; // Exception throwing & translating functions ////////////////////////////////////////////////////// // Functions that throw Java exceptions <commit_msg>Lines authored by mhorowitz<commit_after>/* * Copyright (c) 2015-present, 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 <fb/fbjni/CoreClasses.h> #include <fb/assert.h> #include <fb/log.h> #include <alloca.h> #include <cstdlib> #include <ios> #include <stdexcept> #include <stdio.h> #include <string> #include <system_error> #include <jni.h> namespace facebook { namespace jni { namespace { class JRuntimeException : public JavaClass<JRuntimeException, JThrowable> { public: static auto constexpr kJavaDescriptor = "Ljava/lang/RuntimeException;"; static local_ref<JRuntimeException> create(const char* str) { return newInstance(make_jstring(str)); } static local_ref<JRuntimeException> create() { return newInstance(); } }; class JIOException : public JavaClass<JIOException, JThrowable> { public: static auto constexpr kJavaDescriptor = "Ljava/io/IOException;"; static local_ref<JIOException> create(const char* str) { return newInstance(make_jstring(str)); } }; class JOutOfMemoryError : public JavaClass<JOutOfMemoryError, JThrowable> { public: static auto constexpr kJavaDescriptor = "Ljava/lang/OutOfMemoryError;"; static local_ref<JOutOfMemoryError> create(const char* str) { return newInstance(make_jstring(str)); } }; class JArrayIndexOutOfBoundsException : public JavaClass<JArrayIndexOutOfBoundsException, JThrowable> { public: static auto constexpr kJavaDescriptor = "Ljava/lang/ArrayIndexOutOfBoundsException;"; static local_ref<JArrayIndexOutOfBoundsException> create(const char* str) { return newInstance(make_jstring(str)); } }; class JUnknownCppException : public JavaClass<JUnknownCppException, JThrowable> { public: static auto constexpr kJavaDescriptor = "Lcom/facebook/jni/UnknownCppException;"; static local_ref<JUnknownCppException> create() { return newInstance(); } static local_ref<JUnknownCppException> create(const char* str) { return newInstance(make_jstring(str)); } }; class JCppSystemErrorException : public JavaClass<JCppSystemErrorException, JThrowable> { public: static auto constexpr kJavaDescriptor = "Lcom/facebook/jni/CppSystemErrorException;"; static local_ref<JCppSystemErrorException> create(const std::system_error& e) { return newInstance(make_jstring(e.what()), e.code().value()); } }; // Exception throwing & translating functions ////////////////////////////////////////////////////// // Functions that throw Java exceptions void setJavaExceptionAndAbortOnFailure(alias_ref<JThrowable> throwable) { auto env = Environment::current(); <|endoftext|>
<commit_before> // // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2015 Francois Beaune, The appleseedhq Organization // // 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. // // Interface header. #include "projectbuilder.h" // appleseed-max headers. #include "maxsceneentities.h" #include "utilities.h" // appleseed.renderer headers. #include "renderer/api/camera.h" #include "renderer/api/environment.h" #include "renderer/api/frame.h" #include "renderer/api/object.h" #include "renderer/api/project.h" #include "renderer/api/scene.h" #include "renderer/api/utility.h" // appleseed.foundation headers. #include "foundation/math/scalar.h" #include "foundation/math/transform.h" #include "foundation/platform/compiler.h" #include "foundation/utility/containers/dictionary.h" // 3ds Max headers. #include <bitmap.h> #include <object.h> #include <render.h> #include <triobj.h> // Standard headers. #include <cassert> #include <cstddef> #include <limits> #include <string> #include <vector> namespace asf = foundation; namespace asr = renderer; namespace { asf::auto_release_ptr<asr::Camera> build_camera( INode* view_node, const ViewParams& view_params, Bitmap* bitmap, const TimeValue time) { asr::ParamArray params; if (view_params.projType == PROJ_PERSPECTIVE) { params.insert("film_dimensions", make_vec_string(bitmap->Width(), bitmap->Height())); params.insert("horizontal_fov", asf::rad_to_deg(view_params.fov)); } else { assert(view_params.projType == PROJ_PARALLEL); const float ViewDefaultWidth = 400.0f; const float a = bitmap->Aspect(); const float aspect = static_cast<float>(bitmap->Height()) / bitmap->Width(); const float hscale = bitmap->Width() / (ViewDefaultWidth * view_params.zoom); const float vscale = hscale * aspect; const float film_width = ViewDefaultWidth * view_params.zoom; const float film_height = aspect * film_width; params.insert("film_dimensions", make_vec_string(film_width, film_height)); } asf::Matrix4d camera_matrix = max_to_as(Inverse(view_params.affineTM)); if (view_node) { const ObjectState& os = view_node->EvalWorldState(time); switch (os.obj->SuperClassID()) { case CAMERA_CLASS_ID: { CameraObject* cam = static_cast<CameraObject*>(os.obj); Interval validity_interval; validity_interval.SetInfinite(); Matrix3 cam_to_world = view_node->GetObjTMAfterWSM(time, &validity_interval); cam_to_world.NoScale(); camera_matrix = max_to_as(cam_to_world); CameraState cam_state; cam->EvalCameraState(time, validity_interval, &cam_state); if (cam_state.manualClip) params.insert("near_z", cam_state.hither); } break; case LIGHT_CLASS_ID: { // todo: implement. } break; default: assert(!"Unexpected super class ID for camera."); } } asf::auto_release_ptr<renderer::Camera> camera = view_params.projType == PROJ_PERSPECTIVE ? asr::PinholeCameraFactory().create("camera", params) : asr::OrthographicCameraFactory().create("camera", params); camera->transform_sequence().set_transform( 0.0, asf::Transformd::from_local_to_parent(camera_matrix)); return camera; } TriObject* get_tri_object_from_node( const ObjectState& object_state, const TimeValue time, bool& must_delete) { assert(object_state.obj); must_delete = false; const Class_ID TriObjectClassID(TRIOBJ_CLASS_ID, 0); if (!object_state.obj->CanConvertToType(TriObjectClassID)) return 0; TriObject* tri_object = static_cast<TriObject*>(object_state.obj->ConvertToType(time, TriObjectClassID)); must_delete = tri_object != object_state.obj; return tri_object; } void add_object( asr::Assembly& assembly, INode* node, const TimeValue time) { // Retrieve the name of the referenced object. Object* max_object = node->GetObjectRef(); const std::string object_name = utf8_encode(max_object->GetObjectName()); // Create the object if it doesn't already exist in the appleseed scene. if (assembly.objects().get_by_name(object_name.c_str()) == 0) { // Retrieve the ObjectState at the desired time. const ObjectState object_state = node->EvalWorldState(time); // Convert the object to a TriObject. bool must_delete_tri_object; TriObject* tri_object = get_tri_object_from_node(object_state, time, must_delete_tri_object); if (tri_object == 0) { // todo: emit a message? return; } // Create a new mesh object. asf::auto_release_ptr<asr::MeshObject> object( asr::MeshObjectFactory::create(object_name.c_str(), asr::ParamArray())); { Mesh& mesh = tri_object->GetMesh(); // Copy vertices to the mesh object. object->reserve_vertices(mesh.getNumVerts()); for (int i = 0, e = mesh.getNumVerts(); i < e; ++i) { const Point3& v = mesh.getVert(i); //object->push_vertex(max_to_as(v)); object->push_vertex(asf::Vector3d(v.x, v.y, v.z)); } // Copy triangles to mesh object. object->reserve_triangles(mesh.getNumFaces()); for (int i = 0, e = mesh.getNumFaces(); i < e; ++i) { Face& face = mesh.faces[i]; const asr::Triangle triangle( face.getVert(0), face.getVert(1), face.getVert(2)); object->push_triangle(triangle); } // Delete the TriObject if necessary. if (must_delete_tri_object) tri_object->DeleteMe(); } // Insert the object into the assembly. assembly.objects().insert(asf::auto_release_ptr<asr::Object>(object)); } // Figure out a unique name for this instance. std::string instance_name = utf8_encode(node->GetName()); if (assembly.object_instances().get_by_name(instance_name.c_str()) != 0) instance_name = asr::make_unique_name(instance_name, assembly.object_instances()); // Create an instance of the object and insert it into the assembly. assembly.object_instances().insert( asr::ObjectInstanceFactory::create( instance_name.c_str(), asr::ParamArray(), object_name.c_str(), asf::Transformd::from_local_to_parent( max_to_as(node->GetObjTMAfterWSM(time))), asf::StringDictionary())); } void populate_assembly( asr::Assembly& assembly, const MaxSceneEntities& entities, const TimeValue time) { for (size_t i = 0, e = entities.m_instances.size(); i < e; ++i) add_object(assembly, entities.m_instances[i], time); } } asf::auto_release_ptr<asr::Project> build_project( const MaxSceneEntities& entities, INode* view_node, const ViewParams& view_params, Bitmap* bitmap, const TimeValue time) { // Create an empty project. asf::auto_release_ptr<asr::Project> project( asr::ProjectFactory::create("project")); // Add default configurations to the project. project->add_default_configurations(); // Set the number of samples. project->configurations() .get_by_name("final")->get_parameters() .insert_path("uniform_pixel_renderer.samples", "1"); // Create a scene. asf::auto_release_ptr<asr::Scene> scene(asr::SceneFactory::create()); // Create an assembly. asf::auto_release_ptr<asr::Assembly> assembly( asr::AssemblyFactory().create("assembly", asr::ParamArray())); // Populate the assembly with entities from the 3ds Max scene. populate_assembly(assembly.ref(), entities, time); // Create an instance of the assembly and insert it into the scene. asf::auto_release_ptr<asr::AssemblyInstance> assembly_instance( asr::AssemblyInstanceFactory::create( "assembly_inst", asr::ParamArray(), "assembly")); assembly_instance ->transform_sequence() .set_transform(0.0, asf::Transformd::identity()); scene->assembly_instances().insert(assembly_instance); // Insert the assembly into the scene. scene->assemblies().insert(assembly); // Create a default environment and bind it to the scene. scene->set_environment( asr::EnvironmentFactory::create("environment", asr::ParamArray())); // Create a camera. scene->set_camera( build_camera( view_node, view_params, bitmap, time)); // Create a frame and bind it to the project. project->set_frame( asr::FrameFactory::create( "beauty", asr::ParamArray() .insert("camera", scene->get_camera()->get_name()) .insert("resolution", make_vec_string(bitmap->Width(), bitmap->Height())) .insert("color_space", "linear_rgb"))); // Bind the scene to the project. project->set_scene(scene); return project; } <commit_msg>Remove unused variables<commit_after> // // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2015 Francois Beaune, The appleseedhq Organization // // 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. // // Interface header. #include "projectbuilder.h" // appleseed-max headers. #include "maxsceneentities.h" #include "utilities.h" // appleseed.renderer headers. #include "renderer/api/camera.h" #include "renderer/api/environment.h" #include "renderer/api/frame.h" #include "renderer/api/object.h" #include "renderer/api/project.h" #include "renderer/api/scene.h" #include "renderer/api/utility.h" // appleseed.foundation headers. #include "foundation/math/scalar.h" #include "foundation/math/transform.h" #include "foundation/platform/compiler.h" #include "foundation/utility/containers/dictionary.h" // 3ds Max headers. #include <bitmap.h> #include <object.h> #include <render.h> #include <triobj.h> // Standard headers. #include <cassert> #include <cstddef> #include <limits> #include <string> #include <vector> namespace asf = foundation; namespace asr = renderer; namespace { asf::auto_release_ptr<asr::Camera> build_camera( INode* view_node, const ViewParams& view_params, Bitmap* bitmap, const TimeValue time) { asr::ParamArray params; if (view_params.projType == PROJ_PERSPECTIVE) { params.insert("film_dimensions", make_vec_string(bitmap->Width(), bitmap->Height())); params.insert("horizontal_fov", asf::rad_to_deg(view_params.fov)); } else { assert(view_params.projType == PROJ_PARALLEL); const float ViewDefaultWidth = 400.0f; const float aspect = static_cast<float>(bitmap->Height()) / bitmap->Width(); const float film_width = ViewDefaultWidth * view_params.zoom; const float film_height = film_width * aspect; params.insert("film_dimensions", make_vec_string(film_width, film_height)); } asf::Matrix4d camera_matrix = max_to_as(Inverse(view_params.affineTM)); if (view_node) { const ObjectState& os = view_node->EvalWorldState(time); switch (os.obj->SuperClassID()) { case CAMERA_CLASS_ID: { CameraObject* cam = static_cast<CameraObject*>(os.obj); Interval validity_interval; validity_interval.SetInfinite(); Matrix3 cam_to_world = view_node->GetObjTMAfterWSM(time, &validity_interval); cam_to_world.NoScale(); camera_matrix = max_to_as(cam_to_world); CameraState cam_state; cam->EvalCameraState(time, validity_interval, &cam_state); if (cam_state.manualClip) params.insert("near_z", cam_state.hither); } break; case LIGHT_CLASS_ID: { // todo: implement. } break; default: assert(!"Unexpected super class ID for camera."); } } asf::auto_release_ptr<renderer::Camera> camera = view_params.projType == PROJ_PERSPECTIVE ? asr::PinholeCameraFactory().create("camera", params) : asr::OrthographicCameraFactory().create("camera", params); camera->transform_sequence().set_transform( 0.0, asf::Transformd::from_local_to_parent(camera_matrix)); return camera; } TriObject* get_tri_object_from_node( const ObjectState& object_state, const TimeValue time, bool& must_delete) { assert(object_state.obj); must_delete = false; const Class_ID TriObjectClassID(TRIOBJ_CLASS_ID, 0); if (!object_state.obj->CanConvertToType(TriObjectClassID)) return 0; TriObject* tri_object = static_cast<TriObject*>(object_state.obj->ConvertToType(time, TriObjectClassID)); must_delete = tri_object != object_state.obj; return tri_object; } void add_object( asr::Assembly& assembly, INode* node, const TimeValue time) { // Retrieve the name of the referenced object. Object* max_object = node->GetObjectRef(); const std::string object_name = utf8_encode(max_object->GetObjectName()); // Create the object if it doesn't already exist in the appleseed scene. if (assembly.objects().get_by_name(object_name.c_str()) == 0) { // Retrieve the ObjectState at the desired time. const ObjectState object_state = node->EvalWorldState(time); // Convert the object to a TriObject. bool must_delete_tri_object; TriObject* tri_object = get_tri_object_from_node(object_state, time, must_delete_tri_object); if (tri_object == 0) { // todo: emit a message? return; } // Create a new mesh object. asf::auto_release_ptr<asr::MeshObject> object( asr::MeshObjectFactory::create(object_name.c_str(), asr::ParamArray())); { Mesh& mesh = tri_object->GetMesh(); // Copy vertices to the mesh object. object->reserve_vertices(mesh.getNumVerts()); for (int i = 0, e = mesh.getNumVerts(); i < e; ++i) { const Point3& v = mesh.getVert(i); //object->push_vertex(max_to_as(v)); object->push_vertex(asf::Vector3d(v.x, v.y, v.z)); } // Copy triangles to mesh object. object->reserve_triangles(mesh.getNumFaces()); for (int i = 0, e = mesh.getNumFaces(); i < e; ++i) { Face& face = mesh.faces[i]; const asr::Triangle triangle( face.getVert(0), face.getVert(1), face.getVert(2)); object->push_triangle(triangle); } // Delete the TriObject if necessary. if (must_delete_tri_object) tri_object->DeleteMe(); } // Insert the object into the assembly. assembly.objects().insert(asf::auto_release_ptr<asr::Object>(object)); } // Figure out a unique name for this instance. std::string instance_name = utf8_encode(node->GetName()); if (assembly.object_instances().get_by_name(instance_name.c_str()) != 0) instance_name = asr::make_unique_name(instance_name, assembly.object_instances()); // Create an instance of the object and insert it into the assembly. assembly.object_instances().insert( asr::ObjectInstanceFactory::create( instance_name.c_str(), asr::ParamArray(), object_name.c_str(), asf::Transformd::from_local_to_parent( max_to_as(node->GetObjTMAfterWSM(time))), asf::StringDictionary())); } void populate_assembly( asr::Assembly& assembly, const MaxSceneEntities& entities, const TimeValue time) { for (size_t i = 0, e = entities.m_instances.size(); i < e; ++i) add_object(assembly, entities.m_instances[i], time); } } asf::auto_release_ptr<asr::Project> build_project( const MaxSceneEntities& entities, INode* view_node, const ViewParams& view_params, Bitmap* bitmap, const TimeValue time) { // Create an empty project. asf::auto_release_ptr<asr::Project> project( asr::ProjectFactory::create("project")); // Add default configurations to the project. project->add_default_configurations(); // Set the number of samples. project->configurations() .get_by_name("final")->get_parameters() .insert_path("uniform_pixel_renderer.samples", "1"); // Create a scene. asf::auto_release_ptr<asr::Scene> scene(asr::SceneFactory::create()); // Create an assembly. asf::auto_release_ptr<asr::Assembly> assembly( asr::AssemblyFactory().create("assembly", asr::ParamArray())); // Populate the assembly with entities from the 3ds Max scene. populate_assembly(assembly.ref(), entities, time); // Create an instance of the assembly and insert it into the scene. asf::auto_release_ptr<asr::AssemblyInstance> assembly_instance( asr::AssemblyInstanceFactory::create( "assembly_inst", asr::ParamArray(), "assembly")); assembly_instance ->transform_sequence() .set_transform(0.0, asf::Transformd::identity()); scene->assembly_instances().insert(assembly_instance); // Insert the assembly into the scene. scene->assemblies().insert(assembly); // Create a default environment and bind it to the scene. scene->set_environment( asr::EnvironmentFactory::create("environment", asr::ParamArray())); // Create a camera. scene->set_camera( build_camera( view_node, view_params, bitmap, time)); // Create a frame and bind it to the project. project->set_frame( asr::FrameFactory::create( "beauty", asr::ParamArray() .insert("camera", scene->get_camera()->get_name()) .insert("resolution", make_vec_string(bitmap->Width(), bitmap->Height())) .insert("color_space", "linear_rgb"))); // Bind the scene to the project. project->set_scene(scene); return project; } <|endoftext|>
<commit_before>#include "Message.hpp" #include "User.hpp" #include "Channel.hpp" #include "Role.hpp" #include "Network.hpp" #include "PawnDispatcher.hpp" #include "Callback.hpp" #include "Logger.hpp" #include "utils.hpp" Message::Message(MessageId_t pawn_id, json const &data) : m_PawnId(pawn_id) { std::string author_id, channel_id; _valid = utils::TryGetJsonValue(data, m_Id, "id") && utils::TryGetJsonValue(data, author_id, "author", "id") && utils::TryGetJsonValue(data, channel_id, "channel_id") && utils::TryGetJsonValue(data, m_Content, "content") && utils::TryGetJsonValue(data, m_IsTts, "tts") && utils::TryGetJsonValue(data, m_MentionsEveryone, "mention_everyone"); if (!_valid) { Logger::Get()->Log(LogLevel::ERROR, "can't construct message object: invalid JSON: \"{}\"", data.dump()); return; } Channel_t const &channel = ChannelManager::Get()->FindChannelById(channel_id); m_Channel = channel ? channel->GetPawnId() : INVALID_CHANNEL_ID; User_t const &user = UserManager::Get()->FindUserById(author_id); m_Author = user ? user->GetPawnId() : INVALID_USER_ID; if (utils::IsValidJson(data, "mentions", json::value_t::array)) { for (auto &c : data["mentions"]) { std::string mu_id; if (!utils::TryGetJsonValue(c, mu_id, "id")) continue; User_t const &mu = UserManager::Get()->FindUserById(mu_id); if (mu) m_UserMentions.push_back(mu->GetPawnId()); } } if (utils::IsValidJson(data, "mention_roles", json::value_t::array)) { for (auto &c : data["mention_roles"]) { std::string mr_id; if (!utils::TryGetJsonValue(c, mr_id, "id")) continue; Role_t const &mr = RoleManager::Get()->FindRoleById(mr_id); if (mr) m_RoleMentions.push_back(mr->GetPawnId()); } } } void Message::DeleteMessage() { Channel_t const &channel = ChannelManager::Get()->FindChannel(GetChannel()); if (!channel) return; Network::Get()->Http().Delete(fmt::format( "/channels/{:s}/messages/{:s}", channel->GetId(), GetId())); } void MessageManager::Initialize() { // PAWN callbacks Network::Get()->WebSocket().RegisterEvent(WebSocket::Event::MESSAGE_CREATE, [](json const &data) { PawnDispatcher::Get()->Dispatch([data]() mutable { MessageId_t msg = MessageManager::Get()->Create(data); if (msg != INVALID_MESSAGE_ID) { // forward DCC_OnMessageCreate(DCC_Message:message); pawn_cb::Error error; pawn_cb::Callback::CallFirst(error, "DCC_OnMessageCreate", msg); MessageManager::Get()->Delete(msg); } }); }); Network::Get()->WebSocket().RegisterEvent(WebSocket::Event::MESSAGE_DELETE, [](json const &data) { Snowflake_t sfid; if (!utils::TryGetJsonValue(data, sfid, "id")) return; PawnDispatcher::Get()->Dispatch([sfid]() mutable { auto const &msg = MessageManager::Get()->FindById(sfid); if (msg) { // forward DCC_OnMessageDelete(DCC_Message:message); pawn_cb::Error error; pawn_cb::Callback::CallFirst(error, "DCC_OnMessageDelete", msg->GetPawnId()); MessageManager::Get()->Delete(msg->GetPawnId()); } }); }); } MessageId_t MessageManager::Create(json const &data) { MessageId_t id = 1; while (m_Messages.find(id) != m_Messages.end()) ++id; if (!m_Messages.emplace(id, Message_t(new Message(id, data))).first->second) { Logger::Get()->Log(LogLevel::ERROR, "can't create message: duplicate key '{}'", id); return INVALID_USER_ID; } Logger::Get()->Log(LogLevel::INFO, "successfully created message with id '{}'", id); return id; } bool MessageManager::Delete(MessageId_t id) { auto it = m_Messages.find(id); if (it == m_Messages.end()) return false; m_Messages.erase(it); Logger::Get()->Log(LogLevel::DEBUG, "deleted message with id '{}'", id); return true; } Message_t const &MessageManager::Find(MessageId_t id) { static Message_t invalid_msg; auto it = m_Messages.find(id); if (it == m_Messages.end()) return invalid_msg; return it->second; } Message_t const &MessageManager::FindById(Snowflake_t const &sfid) { static Message_t invalid_msg; for (auto const &u : m_Messages) { auto const &msg = u.second; if (msg->GetId().compare(sfid) == 0) return msg; } return invalid_msg; } <commit_msg>make log message debug<commit_after>#include "Message.hpp" #include "User.hpp" #include "Channel.hpp" #include "Role.hpp" #include "Network.hpp" #include "PawnDispatcher.hpp" #include "Callback.hpp" #include "Logger.hpp" #include "utils.hpp" Message::Message(MessageId_t pawn_id, json const &data) : m_PawnId(pawn_id) { std::string author_id, channel_id; _valid = utils::TryGetJsonValue(data, m_Id, "id") && utils::TryGetJsonValue(data, author_id, "author", "id") && utils::TryGetJsonValue(data, channel_id, "channel_id") && utils::TryGetJsonValue(data, m_Content, "content") && utils::TryGetJsonValue(data, m_IsTts, "tts") && utils::TryGetJsonValue(data, m_MentionsEveryone, "mention_everyone"); if (!_valid) { Logger::Get()->Log(LogLevel::ERROR, "can't construct message object: invalid JSON: \"{}\"", data.dump()); return; } Channel_t const &channel = ChannelManager::Get()->FindChannelById(channel_id); m_Channel = channel ? channel->GetPawnId() : INVALID_CHANNEL_ID; User_t const &user = UserManager::Get()->FindUserById(author_id); m_Author = user ? user->GetPawnId() : INVALID_USER_ID; if (utils::IsValidJson(data, "mentions", json::value_t::array)) { for (auto &c : data["mentions"]) { std::string mu_id; if (!utils::TryGetJsonValue(c, mu_id, "id")) continue; User_t const &mu = UserManager::Get()->FindUserById(mu_id); if (mu) m_UserMentions.push_back(mu->GetPawnId()); } } if (utils::IsValidJson(data, "mention_roles", json::value_t::array)) { for (auto &c : data["mention_roles"]) { std::string mr_id; if (!utils::TryGetJsonValue(c, mr_id, "id")) continue; Role_t const &mr = RoleManager::Get()->FindRoleById(mr_id); if (mr) m_RoleMentions.push_back(mr->GetPawnId()); } } } void Message::DeleteMessage() { Channel_t const &channel = ChannelManager::Get()->FindChannel(GetChannel()); if (!channel) return; Network::Get()->Http().Delete(fmt::format( "/channels/{:s}/messages/{:s}", channel->GetId(), GetId())); } void MessageManager::Initialize() { // PAWN callbacks Network::Get()->WebSocket().RegisterEvent(WebSocket::Event::MESSAGE_CREATE, [](json const &data) { PawnDispatcher::Get()->Dispatch([data]() mutable { MessageId_t msg = MessageManager::Get()->Create(data); if (msg != INVALID_MESSAGE_ID) { // forward DCC_OnMessageCreate(DCC_Message:message); pawn_cb::Error error; pawn_cb::Callback::CallFirst(error, "DCC_OnMessageCreate", msg); MessageManager::Get()->Delete(msg); } }); }); Network::Get()->WebSocket().RegisterEvent(WebSocket::Event::MESSAGE_DELETE, [](json const &data) { Snowflake_t sfid; if (!utils::TryGetJsonValue(data, sfid, "id")) return; PawnDispatcher::Get()->Dispatch([sfid]() mutable { auto const &msg = MessageManager::Get()->FindById(sfid); if (msg) { // forward DCC_OnMessageDelete(DCC_Message:message); pawn_cb::Error error; pawn_cb::Callback::CallFirst(error, "DCC_OnMessageDelete", msg->GetPawnId()); MessageManager::Get()->Delete(msg->GetPawnId()); } }); }); } MessageId_t MessageManager::Create(json const &data) { MessageId_t id = 1; while (m_Messages.find(id) != m_Messages.end()) ++id; if (!m_Messages.emplace(id, Message_t(new Message(id, data))).first->second) { Logger::Get()->Log(LogLevel::ERROR, "can't create message: duplicate key '{}'", id); return INVALID_USER_ID; } Logger::Get()->Log(LogLevel::DEBUG, "created message with id '{}'", id); return id; } bool MessageManager::Delete(MessageId_t id) { auto it = m_Messages.find(id); if (it == m_Messages.end()) return false; m_Messages.erase(it); Logger::Get()->Log(LogLevel::DEBUG, "deleted message with id '{}'", id); return true; } Message_t const &MessageManager::Find(MessageId_t id) { static Message_t invalid_msg; auto it = m_Messages.find(id); if (it == m_Messages.end()) return invalid_msg; return it->second; } Message_t const &MessageManager::FindById(Snowflake_t const &sfid) { static Message_t invalid_msg; for (auto const &u : m_Messages) { auto const &msg = u.second; if (msg->GetId().compare(sfid) == 0) return msg; } return invalid_msg; } <|endoftext|>
<commit_before>#include <ctype.h> #ifndef wcslen /* for cygwin */ #include <wchar.h> #endif #undef _WIN32_WINNT #define _WIN32_WINNT 0x0501 // For AddVectoredExceptionHandler #ifndef UNICODE #define UNICODE #endif #include <windows.h> #include <shellapi.h> #ifdef _MSC_VER #undef min #undef max #endif /* Difference between Jan 1 00:00:00 1601 and Jan 1 00:00:00 1970 */ #define EPOCH_OFFSET 0x019db1ded53e8000LL namespace factor { typedef wchar_t vm_char; typedef char symbol_char; typedef HANDLE THREADHANDLE; #define STRING_LITERAL(string) L##string #define MAX_UNICODE_PATH 32768 #define VM_C_API extern "C" __declspec(dllexport) #define SSCANF swscanf #define STRCMP wcscmp #define STRNCMP wcsncmp #define STRDUP _wcsdup #ifdef _MSC_VER #define FTELL ftell #define FSEEK fseek #define SNPRINTF _snprintf #else #define FTELL ftello64 #define FSEEK fseeko64 #define SNPRINTF snprintf #endif #define FACTOR_OS_STRING "windows" #define FACTOR_DLL NULL // SSE traps raise these exception codes, which are defined in internal NT headers // but not winbase.h #ifndef STATUS_FLOAT_MULTIPLE_FAULTS #define STATUS_FLOAT_MULTIPLE_FAULTS 0xC00002B4 #endif #ifndef STATUS_FLOAT_MULTIPLE_TRAPS #define STATUS_FLOAT_MULTIPLE_TRAPS 0xC00002B5 #endif #define OPEN_READ(path) _wfopen((path),L"rb") #define OPEN_WRITE(path) _wfopen((path),L"wb") inline static void early_init() {} u64 nano_count(); void sleep_nanos(u64 nsec); long getpagesize(); void move_file(const vm_char *path1, const vm_char *path2); VM_C_API LONG exception_handler(PEXCEPTION_RECORD e, void *frame, PCONTEXT c, void *dispatch); THREADHANDLE start_thread(void *(*start_routine)(void *),void *args); inline static THREADHANDLE thread_id() { return GetCurrentThread(); } #define CODE_TO_FUNCTION_POINTER(code) (void)0 #define CODE_TO_FUNCTION_POINTER_CALLBACK(vm, code) (void)0 #define FUNCTION_CODE_POINTER(ptr) ptr #define FUNCTION_TOC_POINTER(ptr) ptr } <commit_msg>vm: win32 GetCurrentThread is a fake thread handle Open a real thread handle with the necessary permissions to dispatch a handler from the the Ctrl-C handler thread.<commit_after>#include <ctype.h> #ifndef wcslen /* for cygwin */ #include <wchar.h> #endif #undef _WIN32_WINNT #define _WIN32_WINNT 0x0501 // For AddVectoredExceptionHandler #ifndef UNICODE #define UNICODE #endif #include <windows.h> #include <shellapi.h> #ifdef _MSC_VER #undef min #undef max #endif /* Difference between Jan 1 00:00:00 1601 and Jan 1 00:00:00 1970 */ #define EPOCH_OFFSET 0x019db1ded53e8000LL namespace factor { typedef wchar_t vm_char; typedef char symbol_char; typedef HANDLE THREADHANDLE; #define STRING_LITERAL(string) L##string #define MAX_UNICODE_PATH 32768 #define VM_C_API extern "C" __declspec(dllexport) #define SSCANF swscanf #define STRCMP wcscmp #define STRNCMP wcsncmp #define STRDUP _wcsdup #ifdef _MSC_VER #define FTELL ftell #define FSEEK fseek #define SNPRINTF _snprintf #else #define FTELL ftello64 #define FSEEK fseeko64 #define SNPRINTF snprintf #endif #define FACTOR_OS_STRING "windows" #define FACTOR_DLL NULL // SSE traps raise these exception codes, which are defined in internal NT headers // but not winbase.h #ifndef STATUS_FLOAT_MULTIPLE_FAULTS #define STATUS_FLOAT_MULTIPLE_FAULTS 0xC00002B4 #endif #ifndef STATUS_FLOAT_MULTIPLE_TRAPS #define STATUS_FLOAT_MULTIPLE_TRAPS 0xC00002B5 #endif #define OPEN_READ(path) _wfopen((path),L"rb") #define OPEN_WRITE(path) _wfopen((path),L"wb") inline static void early_init() {} u64 nano_count(); void sleep_nanos(u64 nsec); long getpagesize(); void move_file(const vm_char *path1, const vm_char *path2); VM_C_API LONG exception_handler(PEXCEPTION_RECORD e, void *frame, PCONTEXT c, void *dispatch); THREADHANDLE start_thread(void *(*start_routine)(void *),void *args); inline static THREADHANDLE thread_id() { DWORD id = GetCurrentThreadId(); HANDLE threadHandle = OpenThread( THREAD_GET_CONTEXT | THREAD_SET_CONTEXT | THREAD_SUSPEND_RESUME, FALSE, id ); assert(threadHandle != NULL); return threadHandle; } #define CODE_TO_FUNCTION_POINTER(code) (void)0 #define CODE_TO_FUNCTION_POINTER_CALLBACK(vm, code) (void)0 #define FUNCTION_CODE_POINTER(ptr) ptr #define FUNCTION_TOC_POINTER(ptr) ptr } <|endoftext|>
<commit_before>/// /// @file PhiTiny.cpp /// @brief phi_tiny(x, a) counts the numbers <= x that are not /// divisible by any of the first a primes. phi_tiny(x, a) /// computes phi(x, a) in constant time for a <= 8 using /// lookup tables and the formula below. /// /// phi(x, a) = (x / pp) * φ(pp) + phi(x % pp, a) /// with pp = 2 * 3 * ... * prime[a] /// φ(pp) = \prod_{i=1}^{a} (prime[i] - 1) /// /// Copyright (C) 2021 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <PhiTiny.hpp> #include <popcnt.hpp> #include <imath.hpp> #include <stdint.h> #include <array> #include <limits> #include <vector> namespace primecount { const std::array<uint32_t, 8> PhiTiny::primes = { 0, 2, 3, 5, 7, 11, 13, 17 }; // prime_products[n] = \prod_{i=1}^{n} primes[i] const std::array<uint32_t, 8> PhiTiny::prime_products = { 1, 2, 6, 30, 210, 2310, 30030, 510510 }; // totients[n] = \prod_{i=1}^{n} (primes[i] - 1) const std::array<uint32_t, 8> PhiTiny::totients = { 1, 1, 2, 8, 48, 480, 5760, 92160 }; // Number of primes <= primes.back() const std::array<uint8_t, 20> PhiTiny::pi = { 0, 0, 1, 2, 2, 3, 3, 4, 4, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 8 }; // Singleton const PhiTiny phiTiny; PhiTiny::PhiTiny() { // The pi[x] lookup table should contain the // number of primes <= primes.back(). assert(pi.back() == primes.size() - 1); assert(primes.back() == pi.size() - 1); assert(phi_.size() == pi[5] + 1); assert(sieve_.size() == primes.size()); static_assert(prime_products.size() == primes.size(), "Invalid prime_products size!"); static_assert(totients.size() == primes.size(), "Invalid totients size!"); for (uint64_t a = 0; a < sieve_.size(); a++) { // For prime[a] <= 5 our phi(x % pp, a) lookup table // is a simple two dimensional array. if (a < phi_.size()) { uint64_t pp = prime_products[a]; phi_[a].resize(pp); phi_[a][0] = 0; for (uint64_t x = 1; x < pp; x++) { uint64_t phi_xa = phi(x, a - 1) - phi(x / primes[a], a - 1); assert(phi_xa <= std::numeric_limits<uint8_t>::max()); phi_[a][x] = (uint8_t) phi_xa; } } else { // For prime[a] > 5 we use a compressed phi(x % pp, a) // lookup table. Each bit of the sieve array corresponds // to an integer that is not divisible by 2, 3 and 5. // Hence the 8 bits of each byte correspond to the offsets // [ 1, 7, 11, 13, 17, 19, 23, 29 ]. uint64_t pp = prime_products[a]; uint64_t size = ceil_div(pp, 240); sieve_[a].resize(size); for (uint64_t i = pi[7]; i <= a; i++) for (uint64_t n = primes[i]; n < pp; n += primes[i] * 2) sieve_[a][n / 240].bits &= unset_bit_[n % 240]; // Fill an array with the cumulative 1 bit counts. // sieve[i][j] contains the count of numbers < j * 240 that // are not divisible by any of the first i primes. uint64_t count = 0; for (auto& sieve : sieve_[a]) { sieve.count = (uint32_t) count; count += popcnt64(sieve.bits); } } } } } // namespace <commit_msg>Fix -Wsign-compare<commit_after>/// /// @file PhiTiny.cpp /// @brief phi_tiny(x, a) counts the numbers <= x that are not /// divisible by any of the first a primes. phi_tiny(x, a) /// computes phi(x, a) in constant time for a <= 8 using /// lookup tables and the formula below. /// /// phi(x, a) = (x / pp) * φ(pp) + phi(x % pp, a) /// with pp = 2 * 3 * ... * prime[a] /// φ(pp) = \prod_{i=1}^{a} (prime[i] - 1) /// /// Copyright (C) 2021 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <PhiTiny.hpp> #include <popcnt.hpp> #include <imath.hpp> #include <stdint.h> #include <array> #include <limits> #include <vector> namespace primecount { const std::array<uint32_t, 8> PhiTiny::primes = { 0, 2, 3, 5, 7, 11, 13, 17 }; // prime_products[n] = \prod_{i=1}^{n} primes[i] const std::array<uint32_t, 8> PhiTiny::prime_products = { 1, 2, 6, 30, 210, 2310, 30030, 510510 }; // totients[n] = \prod_{i=1}^{n} (primes[i] - 1) const std::array<uint32_t, 8> PhiTiny::totients = { 1, 1, 2, 8, 48, 480, 5760, 92160 }; // Number of primes <= primes.back() const std::array<uint8_t, 20> PhiTiny::pi = { 0, 0, 1, 2, 2, 3, 3, 4, 4, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 8 }; // Singleton const PhiTiny phiTiny; PhiTiny::PhiTiny() { // The pi[x] lookup table should contain the // number of primes <= primes.back(). assert(pi.back() == primes.size() - 1); assert(primes.back() == pi.size() - 1); assert(phi_.size() - 1 == (uint64_t) pi[5]); assert(sieve_.size() == primes.size()); static_assert(prime_products.size() == primes.size(), "Invalid prime_products size!"); static_assert(totients.size() == primes.size(), "Invalid totients size!"); for (uint64_t a = 0; a < sieve_.size(); a++) { // For prime[a] <= 5 our phi(x % pp, a) lookup table // is a simple two dimensional array. if (a < phi_.size()) { uint64_t pp = prime_products[a]; phi_[a].resize(pp); phi_[a][0] = 0; for (uint64_t x = 1; x < pp; x++) { uint64_t phi_xa = phi(x, a - 1) - phi(x / primes[a], a - 1); assert(phi_xa <= std::numeric_limits<uint8_t>::max()); phi_[a][x] = (uint8_t) phi_xa; } } else { // For prime[a] > 5 we use a compressed phi(x % pp, a) // lookup table. Each bit of the sieve array corresponds // to an integer that is not divisible by 2, 3 and 5. // Hence the 8 bits of each byte correspond to the offsets // [ 1, 7, 11, 13, 17, 19, 23, 29 ]. uint64_t pp = prime_products[a]; uint64_t size = ceil_div(pp, 240); sieve_[a].resize(size); for (uint64_t i = pi[7]; i <= a; i++) for (uint64_t n = primes[i]; n < pp; n += primes[i] * 2) sieve_[a][n / 240].bits &= unset_bit_[n % 240]; // Fill an array with the cumulative 1 bit counts. // sieve[i][j] contains the count of numbers < j * 240 that // are not divisible by any of the first i primes. uint64_t count = 0; for (auto& sieve : sieve_[a]) { sieve.count = (uint32_t) count; count += popcnt64(sieve.bits); } } } } } // namespace <|endoftext|>
<commit_before>// This file is part of Tasks. // // Tasks is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Tasks 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 Tasks. If not, see <http://www.gnu.org/licenses/>. // associated header #include "QPTasks.h" // includes // std #include <cmath> #include <iostream> // Eigen #include <Eigen/Geometry> // RBDyn #include <RBDyn/MultiBody.h> #include <RBDyn/MultiBodyConfig.h> namespace tasks { namespace qp { /** * SetPointTask */ SetPointTask::SetPointTask(const rbd::MultiBody& mb, HighLevelTask* hlTask, double stiffness, double weight): Task(weight), hlTask_(hlTask), stiffness_(stiffness), stiffnessSqrt_(2.*std::sqrt(stiffness)), Q_(mb.nrDof(), mb.nrDof()), C_(mb.nrDof()), alphaVec_(mb.nrDof()) {} void SetPointTask::stiffness(double stiffness) { stiffness_ = stiffness; stiffnessSqrt_ = 2.*std::sqrt(stiffness); } void SetPointTask::update(const rbd::MultiBody& mb, const rbd::MultiBodyConfig& mbc) { hlTask_->update(mb, mbc); const Eigen::MatrixXd& J = hlTask_->jac(); const Eigen::MatrixXd& JD = hlTask_->jacDot(); const Eigen::VectorXd& err = hlTask_->eval(); rbd::paramToVector(mbc.alpha, alphaVec_); Q_ = J.transpose()*J; C_ = -J.transpose()*(stiffness_*err - stiffnessSqrt_*J*alphaVec_ - JD*alphaVec_); } const Eigen::MatrixXd& SetPointTask::Q() const { return Q_; } const Eigen::VectorXd& SetPointTask::C() const { return C_; } /** * QuadraticTask */ QuadraticTask::QuadraticTask(const rbd::MultiBody& mb, HighLevelTask* hlTask, double weight): Task(weight), hlTask_(hlTask), Q_(mb.nrDof(), mb.nrDof()), C_(mb.nrDof()), alphaVec_(mb.nrDof()) {} void QuadraticTask::update(const rbd::MultiBody& mb, const rbd::MultiBodyConfig& mbc) { hlTask_->update(mb, mbc); const Eigen::MatrixXd& J = hlTask_->jac(); const Eigen::MatrixXd& JD = hlTask_->jacDot(); const Eigen::VectorXd& err = hlTask_->eval(); rbd::paramToVector(mbc.alpha, alphaVec_); Q_ = J.transpose()*J; C_ = -J.transpose()*(err - JD*alphaVec_); } const Eigen::MatrixXd& QuadraticTask::Q() const { return Q_; } const Eigen::VectorXd& QuadraticTask::C() const { return C_; } /** * LinWeightTask */ LinWeightTask::LinWeightTask(Task* t, double step, double objWeight): Task(0.), task_(t), step_(step), objWeight_(objWeight) { } void LinWeightTask::weight(double w) { objWeight_ = w; } std::pair<int, int> LinWeightTask::begin() const { return task_->begin(); } void LinWeightTask::updateNrVars(const rbd::MultiBody& mb, const SolverData& data) { task_->updateNrVars(mb, data); } void LinWeightTask::update(const rbd::MultiBody& mb, const rbd::MultiBodyConfig& mbc) { double curW = Task::weight(); if(objWeight_ > curW) { curW = std::min(objWeight_, curW + step_); } else { curW = std::max(objWeight_, curW - step_); } Task::weight(curW); task_->update(mb, mbc); } const Eigen::MatrixXd& LinWeightTask::Q() const { return task_->Q(); } const Eigen::VectorXd& LinWeightTask::C() const { return task_->C(); } /** * PostureTask */ PostureTask::PostureTask(const rbd::MultiBody& mb, std::vector<std::vector<double>> q, double stiffness, double weight): Task(weight), pt_(mb, q), stiffness_(stiffness), stiffnessSqrt_(2.*std::sqrt(stiffness)), Q_(mb.nrDof(), mb.nrDof()), C_(mb.nrDof()), alphaVec_(mb.nrDof()) {} void PostureTask::stiffness(double stiffness) { stiffness_ = stiffness; stiffnessSqrt_ = 2.*std::sqrt(stiffness); } void PostureTask::update(const rbd::MultiBody& mb, const rbd::MultiBodyConfig& mbc) { pt_.update(mb, mbc); rbd::paramToVector(mbc.alpha, alphaVec_); Q_ = pt_.jac(); C_.setZero(); int deb = mb.jointPosInDof(1); int end = mb.nrDof() - deb; // joint C_.segment(deb, end) = -stiffness_*pt_.eval().segment(deb, end) + stiffnessSqrt_*alphaVec_.segment(deb, end); } const Eigen::MatrixXd& PostureTask::Q() const { return Q_; } const Eigen::VectorXd& PostureTask::C() const { return C_; } const Eigen::VectorXd& PostureTask::eval() const { return pt_.eval(); } /** * PositionTask */ PositionTask::PositionTask(const rbd::MultiBody& mb, int bodyId, const Eigen::Vector3d& pos, const Eigen::Vector3d& bodyPoint): pt_(mb, bodyId, pos, bodyPoint) { } int PositionTask::dim() { return 3; } void PositionTask::update(const rbd::MultiBody& mb, const rbd::MultiBodyConfig& mbc) { pt_.update(mb, mbc); pt_.updateDot(mb, mbc); } const Eigen::MatrixXd& PositionTask::jac() { return pt_.jac(); } const Eigen::MatrixXd& PositionTask::jacDot() { return pt_.jacDot(); } const Eigen::VectorXd& PositionTask::eval() { return pt_.eval(); } /** * OrientationTask */ OrientationTask::OrientationTask(const rbd::MultiBody& mb, int bodyId, const Eigen::Quaterniond& ori): ot_(mb, bodyId, ori) {} OrientationTask::OrientationTask(const rbd::MultiBody& mb, int bodyId, const Eigen::Matrix3d& ori): ot_(mb, bodyId, ori) {} int OrientationTask::dim() { return 3; } void OrientationTask::update(const rbd::MultiBody& mb, const rbd::MultiBodyConfig& mbc) { ot_.update(mb, mbc); ot_.updateDot(mb, mbc); } const Eigen::MatrixXd& OrientationTask::jac() { return ot_.jac(); } const Eigen::MatrixXd& OrientationTask::jacDot() { return ot_.jacDot(); } const Eigen::VectorXd& OrientationTask::eval() { return ot_.eval(); } /** * CoMTask */ CoMTask::CoMTask(const rbd::MultiBody& mb, const Eigen::Vector3d& com): ct_(mb, com) {} int CoMTask::dim() { return 3; } void CoMTask::update(const rbd::MultiBody& mb, const rbd::MultiBodyConfig& mbc) { ct_.update(mb, mbc); ct_.updateDot(mb, mbc); } const Eigen::MatrixXd& CoMTask::jac() { return ct_.jac(); } const Eigen::MatrixXd& CoMTask::jacDot() { return ct_.jacDot(); } const Eigen::VectorXd& CoMTask::eval() { return ct_.eval(); } /** * ContactTask */ void ContactTask::updateNrVars(const rbd::MultiBody& /* mb */, const SolverData& data) { int nrLambda = 0; begin_ = data.lambdaBegin(); for(const UnilateralContact& uc: data.unilateralContacts()) { if(uc.bodyId == bodyId_) { for(std::size_t i = 0; i < uc.points.size(); ++i) { nrLambda += uc.nrLambda(static_cast<int>(i)); } break; } begin_ += static_cast<int>(uc.cone.generators.size()); } Q_ = dir_*Eigen::MatrixXd::Identity(nrLambda, nrLambda); C_.setZero(nrLambda); } void ContactTask::update(const rbd::MultiBody& /* mb */, const rbd::MultiBodyConfig& /* mbc */) { } const Eigen::MatrixXd& ContactTask::Q() const { return Q_; } const Eigen::VectorXd& ContactTask::C() const { return C_; } /** * LinVelocityTask */ LinVelocityTask::LinVelocityTask(const rbd::MultiBody& mb, int bodyId, const Eigen::Vector3d& speed, const Eigen::Vector3d& bodyPoint): pt_(mb, bodyId, speed, bodyPoint) { } int LinVelocityTask::dim() { return 3; } void LinVelocityTask::update(const rbd::MultiBody& mb, const rbd::MultiBodyConfig& mbc) { pt_.update(mb, mbc); pt_.updateDot(mb, mbc); } const Eigen::MatrixXd& LinVelocityTask::jac() { return pt_.jac(); } const Eigen::MatrixXd& LinVelocityTask::jacDot() { return pt_.jacDot(); } const Eigen::VectorXd& LinVelocityTask::eval() { return pt_.eval(); } } // namespace qp } // namespace tasks <commit_msg>Fix ContactTask and add Bilateral contact support.<commit_after>// This file is part of Tasks. // // Tasks is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Tasks 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 Tasks. If not, see <http://www.gnu.org/licenses/>. // associated header #include "QPTasks.h" // includes // std #include <cmath> #include <iostream> // Eigen #include <Eigen/Geometry> // RBDyn #include <RBDyn/MultiBody.h> #include <RBDyn/MultiBodyConfig.h> namespace tasks { namespace qp { /** * SetPointTask */ SetPointTask::SetPointTask(const rbd::MultiBody& mb, HighLevelTask* hlTask, double stiffness, double weight): Task(weight), hlTask_(hlTask), stiffness_(stiffness), stiffnessSqrt_(2.*std::sqrt(stiffness)), Q_(mb.nrDof(), mb.nrDof()), C_(mb.nrDof()), alphaVec_(mb.nrDof()) {} void SetPointTask::stiffness(double stiffness) { stiffness_ = stiffness; stiffnessSqrt_ = 2.*std::sqrt(stiffness); } void SetPointTask::update(const rbd::MultiBody& mb, const rbd::MultiBodyConfig& mbc) { hlTask_->update(mb, mbc); const Eigen::MatrixXd& J = hlTask_->jac(); const Eigen::MatrixXd& JD = hlTask_->jacDot(); const Eigen::VectorXd& err = hlTask_->eval(); rbd::paramToVector(mbc.alpha, alphaVec_); Q_ = J.transpose()*J; C_ = -J.transpose()*(stiffness_*err - stiffnessSqrt_*J*alphaVec_ - JD*alphaVec_); } const Eigen::MatrixXd& SetPointTask::Q() const { return Q_; } const Eigen::VectorXd& SetPointTask::C() const { return C_; } /** * QuadraticTask */ QuadraticTask::QuadraticTask(const rbd::MultiBody& mb, HighLevelTask* hlTask, double weight): Task(weight), hlTask_(hlTask), Q_(mb.nrDof(), mb.nrDof()), C_(mb.nrDof()), alphaVec_(mb.nrDof()) {} void QuadraticTask::update(const rbd::MultiBody& mb, const rbd::MultiBodyConfig& mbc) { hlTask_->update(mb, mbc); const Eigen::MatrixXd& J = hlTask_->jac(); const Eigen::MatrixXd& JD = hlTask_->jacDot(); const Eigen::VectorXd& err = hlTask_->eval(); rbd::paramToVector(mbc.alpha, alphaVec_); Q_ = J.transpose()*J; C_ = -J.transpose()*(err - JD*alphaVec_); } const Eigen::MatrixXd& QuadraticTask::Q() const { return Q_; } const Eigen::VectorXd& QuadraticTask::C() const { return C_; } /** * LinWeightTask */ LinWeightTask::LinWeightTask(Task* t, double step, double objWeight): Task(0.), task_(t), step_(step), objWeight_(objWeight) { } void LinWeightTask::weight(double w) { objWeight_ = w; } std::pair<int, int> LinWeightTask::begin() const { return task_->begin(); } void LinWeightTask::updateNrVars(const rbd::MultiBody& mb, const SolverData& data) { task_->updateNrVars(mb, data); } void LinWeightTask::update(const rbd::MultiBody& mb, const rbd::MultiBodyConfig& mbc) { double curW = Task::weight(); if(objWeight_ > curW) { curW = std::min(objWeight_, curW + step_); } else { curW = std::max(objWeight_, curW - step_); } Task::weight(curW); task_->update(mb, mbc); } const Eigen::MatrixXd& LinWeightTask::Q() const { return task_->Q(); } const Eigen::VectorXd& LinWeightTask::C() const { return task_->C(); } /** * PostureTask */ PostureTask::PostureTask(const rbd::MultiBody& mb, std::vector<std::vector<double>> q, double stiffness, double weight): Task(weight), pt_(mb, q), stiffness_(stiffness), stiffnessSqrt_(2.*std::sqrt(stiffness)), Q_(mb.nrDof(), mb.nrDof()), C_(mb.nrDof()), alphaVec_(mb.nrDof()) {} void PostureTask::stiffness(double stiffness) { stiffness_ = stiffness; stiffnessSqrt_ = 2.*std::sqrt(stiffness); } void PostureTask::update(const rbd::MultiBody& mb, const rbd::MultiBodyConfig& mbc) { pt_.update(mb, mbc); rbd::paramToVector(mbc.alpha, alphaVec_); Q_ = pt_.jac(); C_.setZero(); int deb = mb.jointPosInDof(1); int end = mb.nrDof() - deb; // joint C_.segment(deb, end) = -stiffness_*pt_.eval().segment(deb, end) + stiffnessSqrt_*alphaVec_.segment(deb, end); } const Eigen::MatrixXd& PostureTask::Q() const { return Q_; } const Eigen::VectorXd& PostureTask::C() const { return C_; } const Eigen::VectorXd& PostureTask::eval() const { return pt_.eval(); } /** * PositionTask */ PositionTask::PositionTask(const rbd::MultiBody& mb, int bodyId, const Eigen::Vector3d& pos, const Eigen::Vector3d& bodyPoint): pt_(mb, bodyId, pos, bodyPoint) { } int PositionTask::dim() { return 3; } void PositionTask::update(const rbd::MultiBody& mb, const rbd::MultiBodyConfig& mbc) { pt_.update(mb, mbc); pt_.updateDot(mb, mbc); } const Eigen::MatrixXd& PositionTask::jac() { return pt_.jac(); } const Eigen::MatrixXd& PositionTask::jacDot() { return pt_.jacDot(); } const Eigen::VectorXd& PositionTask::eval() { return pt_.eval(); } /** * OrientationTask */ OrientationTask::OrientationTask(const rbd::MultiBody& mb, int bodyId, const Eigen::Quaterniond& ori): ot_(mb, bodyId, ori) {} OrientationTask::OrientationTask(const rbd::MultiBody& mb, int bodyId, const Eigen::Matrix3d& ori): ot_(mb, bodyId, ori) {} int OrientationTask::dim() { return 3; } void OrientationTask::update(const rbd::MultiBody& mb, const rbd::MultiBodyConfig& mbc) { ot_.update(mb, mbc); ot_.updateDot(mb, mbc); } const Eigen::MatrixXd& OrientationTask::jac() { return ot_.jac(); } const Eigen::MatrixXd& OrientationTask::jacDot() { return ot_.jacDot(); } const Eigen::VectorXd& OrientationTask::eval() { return ot_.eval(); } /** * CoMTask */ CoMTask::CoMTask(const rbd::MultiBody& mb, const Eigen::Vector3d& com): ct_(mb, com) {} int CoMTask::dim() { return 3; } void CoMTask::update(const rbd::MultiBody& mb, const rbd::MultiBodyConfig& mbc) { ct_.update(mb, mbc); ct_.updateDot(mb, mbc); } const Eigen::MatrixXd& CoMTask::jac() { return ct_.jac(); } const Eigen::MatrixXd& CoMTask::jacDot() { return ct_.jacDot(); } const Eigen::VectorXd& CoMTask::eval() { return ct_.eval(); } /** * ContactTask */ void ContactTask::updateNrVars(const rbd::MultiBody& /* mb */, const SolverData& data) { int nrLambda = 0; begin_ = data.lambdaBegin(); for(const UnilateralContact& uc: data.unilateralContacts()) { int curLambda = 0; for(std::size_t i = 0; i < uc.points.size(); ++i) { curLambda += uc.nrLambda(static_cast<int>(i)); } if(uc.bodyId == bodyId_) { nrLambda = curLambda; break; } begin_ += curLambda; } // if body Id is not unilateral we search in bilateral if(nrLambda == 0) { for(const BilateralContact& uc: data.bilateralContacts()) { int curLambda = 0; for(std::size_t i = 0; i < uc.points.size(); ++i) { curLambda += uc.nrLambda(static_cast<int>(i)); } if(uc.bodyId == bodyId_) { nrLambda = curLambda; break; } begin_ += curLambda; } } Q_ = dir_*Eigen::MatrixXd::Identity(nrLambda, nrLambda); C_.setZero(nrLambda); } void ContactTask::update(const rbd::MultiBody& /* mb */, const rbd::MultiBodyConfig& /* mbc */) { } const Eigen::MatrixXd& ContactTask::Q() const { return Q_; } const Eigen::VectorXd& ContactTask::C() const { return C_; } /** * LinVelocityTask */ LinVelocityTask::LinVelocityTask(const rbd::MultiBody& mb, int bodyId, const Eigen::Vector3d& speed, const Eigen::Vector3d& bodyPoint): pt_(mb, bodyId, speed, bodyPoint) { } int LinVelocityTask::dim() { return 3; } void LinVelocityTask::update(const rbd::MultiBody& mb, const rbd::MultiBodyConfig& mbc) { pt_.update(mb, mbc); pt_.updateDot(mb, mbc); } const Eigen::MatrixXd& LinVelocityTask::jac() { return pt_.jac(); } const Eigen::MatrixXd& LinVelocityTask::jacDot() { return pt_.jacDot(); } const Eigen::VectorXd& LinVelocityTask::eval() { return pt_.eval(); } } // namespace qp } // namespace tasks <|endoftext|>
<commit_before>#ifndef SAPLIST_HPP #define SAPLIST_HPP 1 #include <functional> #include <map> #include <typeinfo> #include "CollisionManager.hpp" struct AABB { /** min/max * - first is x axis * - second is y axis */ struct EndPoint * min[2]; struct EndPoint * max[2]; size_t typeId; /* Need to use std::type_info::hash_code() */ void * owner; }; /** * TODO: * - Optimize merging isMin boolean into another member * (as a flag) * - Using doubly-linked list could waste memory but is easier to implement * than arrays. * - Implement pair manager */ struct EndPoint { struct AABB * owner; int value; bool isMin; struct EndPoint * prev; struct EndPoint * next; }; /** * Action manager stores actions to perform on collision or separation * of two objects depending on their type * It also stores default actions to execute if no specific action is * defined for two types. */ struct ActionManager { std::map < std::pair < size_t,size_t >, std::pair < std::function < void (void *, void *) >, std::function < void (void *, void *) > > > actions; std::function < void (void *, void *) > onCollision(size_t t1, size_t t2) { return this ->actions[std::pair<size_t, size_t>(t1,t2)].first; } std::function < void (void *, void *) > onSeparation(size_t t1, size_t t2) { return this ->actions[std::pair<size_t, size_t>(t1,t2)].second; } }; class SAP : public CollisionManager<struct AABB> { private: /** FIXME: use sentinels */ struct EndPoint * xAxis; struct EndPoint * yAxis; struct ActionManager actions; void swap(struct EndPoint * p1, struct EndPoint * p2) { p2->next->prev = p1; p1->next = p2->next; p1->prev->next = p2; p1->prev = p2; p2->next = p1; } /* check on one axis */ inline bool partialCollisionCheck(const struct AABB & b1, const struct AABB & b2, char dim) { return (b1.max[dim] <= b2.max[dim] && b1.max[dim] >= b2.min[dim]) || (b1.min[dim] >= b2.min[dim] && b1.max[dim] <= b2.max[dim]); } bool collisionCheck(const struct AABB & b1, const struct AABB & b2) { return partialCollisionCheck (b1, b2, 0) && partialCollisionCheck (b1, b2, 1); } void updateEndPoint(struct EndPoint * pt) { auto aux = [&pt, this] (std::function<struct EndPoint*(struct EndPoint*)>succ, std::function<bool(int,int)>loop_cond, std::function<bool(struct EndPoint*,struct EndPoint*)>mustAdd, std::function<bool(struct EndPoint*,struct EndPoint*)>mustRm) { EndPoint * tmp = succ(pt); while (loop_cond(tmp->value, pt->value)) { this->swap(tmp, pt); if (mustAdd(pt, tmp)) { if (this->collisionCheck(*(pt->owner), *(tmp->owner))) { this->actions.onCollision (pt->owner->typeId, tmp->owner->typeId) (pt->owner->owner, tmp->owner->owner); } } else if (mustRm(pt, tmp)) { this->actions.onSeparation (pt->owner->typeId,tmp->owner->typeId) (pt->owner->owner, tmp->owner->owner); } } }; /** TODO: use aux to update on x and y axis */ } public: void addObject(const struct AABB &) {} void updateObject(const struct AABB &) {} void removeObject(const struct AABB &) {} int main () {}; }; #endif <commit_msg>Removed main method, converted table index in int instead of char, renammed SAP class to SAPList class.<commit_after>#ifndef SAPLIST_HPP #define SAPLIST_HPP 1 #include <functional> #include <map> #include <typeinfo> #include "CollisionManager.hpp" struct AABB { /** min/max * - first is x axis * - second is y axis */ struct EndPoint * min[2]; struct EndPoint * max[2]; size_t typeId; /* Need to use std::type_info::hash_code() */ void * owner; }; /** * TODO: * - Optimize merging isMin boolean into another member * (as a flag) * - Using doubly-linked list could waste memory but is easier to implement * than arrays. * - Implement pair manager */ struct EndPoint { struct AABB * owner; int value; bool isMin; struct EndPoint * prev; struct EndPoint * next; }; /** * Action manager stores actions to perform on collision or separation * of two objects depending on their type * It also stores default actions to execute if no specific action is * defined for two types. */ struct ActionManager { std::map < std::pair < size_t,size_t >, std::pair < std::function < void (void *, void *) >, std::function < void (void *, void *) > > > actions; std::function < void (void *, void *) > onCollision(size_t t1, size_t t2) { return this ->actions[std::pair<size_t, size_t>(t1,t2)].first; } std::function < void (void *, void *) > onSeparation(size_t t1, size_t t2) { return this ->actions[std::pair<size_t, size_t>(t1,t2)].second; } }; class SAPList : public CollisionManager<struct AABB> { private: /** FIXME: use sentinels */ struct EndPoint * xAxis; struct EndPoint * yAxis; struct ActionManager actions; void swap(struct EndPoint * p1, struct EndPoint * p2) { p2->next->prev = p1; p1->next = p2->next; p1->prev->next = p2; p1->prev = p2; p2->next = p1; } /* check on one axis */ inline bool partialCollisionCheck(const struct AABB & b1, const struct AABB & b2, int dim) { return (b1.max[dim] <= b2.max[dim] && b1.max[dim] >= b2.min[dim]) || (b1.min[dim] >= b2.min[dim] && b1.max[dim] <= b2.max[dim]); } bool collisionCheck(const struct AABB & b1, const struct AABB & b2) { return partialCollisionCheck (b1, b2, 0) && partialCollisionCheck (b1, b2, 1); } void updateEndPoint(struct EndPoint * pt) { auto aux = [&pt, this] (std::function<struct EndPoint*(struct EndPoint*)>succ, std::function<bool(int,int)>loop_cond, std::function<bool(struct EndPoint*,struct EndPoint*)>mustAdd, std::function<bool(struct EndPoint*,struct EndPoint*)>mustRm) { EndPoint * tmp = succ(pt); while (loop_cond(tmp->value, pt->value)) { this->swap(tmp, pt); if (mustAdd(pt, tmp)) { if (this->collisionCheck(*(pt->owner), *(tmp->owner))) { this->actions.onCollision (pt->owner->typeId, tmp->owner->typeId) (pt->owner->owner, tmp->owner->owner); } } else if (mustRm(pt, tmp)) { this->actions.onSeparation (pt->owner->typeId,tmp->owner->typeId) (pt->owner->owner, tmp->owner->owner); } } }; /** TODO: use aux to update on x and y axis */ } public: void addObject(const struct AABB &) {} void updateObject(const struct AABB &) {} void removeObject(const struct AABB &) {} }; #endif <|endoftext|>
<commit_before>// Copyright 2017 Netherlands Institute for Radio Astronomy (ASTRON) // Copyright 2017 Netherlands eScience Center // // 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 <Trigger.hpp> void trigger(const unsigned int firstSynthesizedBeam, const Options &options, const unsigned int padding, const unsigned int integration, const AstroData::Observation &observation, const HostMemory &hostMemory, TriggeredEvents &triggeredEvents) { unsigned int nrDMs = 0; if (options.subbandDedispersion) { nrDMs = observation.getNrDMs(true) * observation.getNrDMs(); } else { nrDMs = observation.getNrDMs(); } for (unsigned int beam = 0; beam < options.nrSynthesizedBeamsPerChunk; beam++) { for (unsigned int dm = 0; dm < nrDMs; dm++) { unsigned int maxIndex = 0; outputDataType maxSNR = 0; // outputDataType maxSNR_mad = 0; if (options.snrMode == SNRMode::Standard) { maxSNR = hostMemory.snrData.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm); maxIndex = hostMemory.snrSamples.at((beam * isa::utils::pad(nrDMs, padding / sizeof(unsigned int))) + dm); } else if (options.snrMode == SNRMode::Momad) { maxSNR = (hostMemory.maxValues.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm) - hostMemory.medianOfMedians.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm)) / (hostMemory.medianOfMediansAbsoluteDeviation.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm) * 1.48); maxIndex = hostMemory.maxIndices.at((beam * isa::utils::pad(nrDMs, padding / sizeof(unsigned int))) + dm); } else if ( options.snrMode == SNRMode::MomSigmaCut ) { maxSNR = (hostMemory.maxValues.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm) - hostMemory.medianOfMedians.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm)) / (options.sigmaCorrectionFactor * hostMemory.stdevs.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm)); maxIndex = hostMemory.maxIndices.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm); } if ( (std::isnormal(maxSNR)) && (maxSNR >= options.threshold) ) { TriggeredEvent event; event.beam = firstSynthesizedBeam + beam; event.sample = maxIndex; event.integration = integration; event.DM = dm; event.SNR = maxSNR; try { // Add event to its existing list triggeredEvents.at(firstSynthesizedBeam + beam).at(dm).push_back(event); } catch (std::out_of_range &err) { // Add event to new list std::vector<TriggeredEvent> events; events.push_back(event); triggeredEvents.at(firstSynthesizedBeam + beam).insert(std::pair<unsigned int, std::vector<TriggeredEvent>>(dm, events)); } } } } } void compact(const AstroData::Observation &observation, const TriggeredEvents &triggeredEvents, CompactedEvents &compactedEvents) { CompactedEvents temporaryEvents(observation.getNrSynthesizedBeams()); // Compact integration for (auto beamEvents = triggeredEvents.begin(); beamEvents != triggeredEvents.end(); ++beamEvents) { for (auto dmEvents = beamEvents->begin(); dmEvents != beamEvents->end(); ++dmEvents) { CompactedEvent event; for (auto dmEvent = dmEvents->second.begin(); dmEvent != dmEvents->second.end(); ++dmEvent) { if (dmEvent->SNR > event.SNR) { event.beam = dmEvent->beam; event.sample = dmEvent->sample; event.integration = dmEvent->integration; event.DM = dmEvent->DM; event.SNR = dmEvent->SNR; } } event.compactedIntegration = dmEvents->second.size(); temporaryEvents.at(event.beam).push_back(event); } } // Compact DM for (auto beamEvents = temporaryEvents.begin(); beamEvents != temporaryEvents.end(); ++beamEvents) { for (auto event = beamEvents->begin(); event != beamEvents->end(); ++event) { CompactedEvent finalEvent; unsigned int window = 0; while ( (event->DM + window) == (event + window)->DM && ((event + window) != beamEvents->end()) ) { if ((event + window)->SNR > finalEvent.SNR) { finalEvent.beam = (event + window)->beam; finalEvent.sample = (event + window)->sample; finalEvent.integration = (event + window)->integration; finalEvent.compactedIntegration = (event + window)->compactedIntegration; finalEvent.DM = (event + window)->DM; finalEvent.SNR = (event + window)->SNR; } window++; } finalEvent.compactedDMs = window; compactedEvents.at(finalEvent.beam).push_back(finalEvent); // Move the iterator forward event += (window - 1); } } } <commit_msg>Fix for synthesized beams.<commit_after>// Copyright 2017 Netherlands Institute for Radio Astronomy (ASTRON) // Copyright 2017 Netherlands eScience Center // // 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 <Trigger.hpp> void trigger(const unsigned int firstSynthesizedBeam, const Options &options, const unsigned int padding, const unsigned int integration, const AstroData::Observation &observation, const HostMemory &hostMemory, TriggeredEvents &triggeredEvents) { unsigned int nrDMs = 0; if (options.subbandDedispersion) { nrDMs = observation.getNrDMs(true) * observation.getNrDMs(); } else { nrDMs = observation.getNrDMs(); } for (unsigned int beam = 0; beam < options.nrSynthesizedBeamsPerChunk; beam++) { // If there are remaining synthesized beams in the last chunk, skip if ( firstSynthesizedBeam + beam >= observation.getNrSynthesizedBeams() ) { break; } for (unsigned int dm = 0; dm < nrDMs; dm++) { unsigned int maxIndex = 0; outputDataType maxSNR = 0; // outputDataType maxSNR_mad = 0; if (options.snrMode == SNRMode::Standard) { maxSNR = hostMemory.snrData.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm); maxIndex = hostMemory.snrSamples.at((beam * isa::utils::pad(nrDMs, padding / sizeof(unsigned int))) + dm); } else if (options.snrMode == SNRMode::Momad) { maxSNR = (hostMemory.maxValues.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm) - hostMemory.medianOfMedians.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm)) / (hostMemory.medianOfMediansAbsoluteDeviation.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm) * 1.48); maxIndex = hostMemory.maxIndices.at((beam * isa::utils::pad(nrDMs, padding / sizeof(unsigned int))) + dm); } else if ( options.snrMode == SNRMode::MomSigmaCut ) { maxSNR = (hostMemory.maxValues.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm) - hostMemory.medianOfMedians.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm)) / (options.sigmaCorrectionFactor * hostMemory.stdevs.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm)); maxIndex = hostMemory.maxIndices.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm); } if ( (std::isnormal(maxSNR)) && (maxSNR >= options.threshold) ) { TriggeredEvent event; event.beam = firstSynthesizedBeam + beam; event.sample = maxIndex; event.integration = integration; event.DM = dm; event.SNR = maxSNR; try { // Add event to its existing list triggeredEvents.at(firstSynthesizedBeam + beam).at(dm).push_back(event); } catch (std::out_of_range &err) { // Add event to new list std::vector<TriggeredEvent> events; events.push_back(event); triggeredEvents.at(firstSynthesizedBeam + beam).insert(std::pair<unsigned int, std::vector<TriggeredEvent>>(dm, events)); } } } } } void compact(const AstroData::Observation &observation, const TriggeredEvents &triggeredEvents, CompactedEvents &compactedEvents) { CompactedEvents temporaryEvents(observation.getNrSynthesizedBeams()); // Compact integration for (auto beamEvents = triggeredEvents.begin(); beamEvents != triggeredEvents.end(); ++beamEvents) { for (auto dmEvents = beamEvents->begin(); dmEvents != beamEvents->end(); ++dmEvents) { CompactedEvent event; for (auto dmEvent = dmEvents->second.begin(); dmEvent != dmEvents->second.end(); ++dmEvent) { if (dmEvent->SNR > event.SNR) { event.beam = dmEvent->beam; event.sample = dmEvent->sample; event.integration = dmEvent->integration; event.DM = dmEvent->DM; event.SNR = dmEvent->SNR; } } event.compactedIntegration = dmEvents->second.size(); temporaryEvents.at(event.beam).push_back(event); } } // Compact DM for (auto beamEvents = temporaryEvents.begin(); beamEvents != temporaryEvents.end(); ++beamEvents) { for (auto event = beamEvents->begin(); event != beamEvents->end(); ++event) { CompactedEvent finalEvent; unsigned int window = 0; while ( (event->DM + window) == (event + window)->DM && ((event + window) != beamEvents->end()) ) { if ((event + window)->SNR > finalEvent.SNR) { finalEvent.beam = (event + window)->beam; finalEvent.sample = (event + window)->sample; finalEvent.integration = (event + window)->integration; finalEvent.compactedIntegration = (event + window)->compactedIntegration; finalEvent.DM = (event + window)->DM; finalEvent.SNR = (event + window)->SNR; } window++; } finalEvent.compactedDMs = window; compactedEvents.at(finalEvent.beam).push_back(finalEvent); // Move the iterator forward event += (window - 1); } } } <|endoftext|>
<commit_before>#include "Utility.h" #include <vector> #include <random> #include <chrono> #include <fstream> #include <algorithm> #include <string> #include <cctype> #include <iostream> #include <cmath> namespace String { namespace { const auto whitespace = " \t\n"; } } std::vector<std::string> String::split(const std::string& s, const std::string& delim, size_t count) { std::vector<std::string> result; size_t start_index = 0; size_t end_index = 0; size_t split_count = 0; while(end_index < s.size() && split_count < count) { end_index = (delim.empty() ? s.find_first_of(" \t\n", start_index) : s.find(delim, start_index)); result.push_back(s.substr(start_index, end_index-start_index)); if(end_index == std::string::npos) { start_index = std::string::npos; } else { start_index = end_index + (delim.empty() ? 1 : delim.size()); } ++split_count; } if(start_index < s.size()) { result.push_back(s.substr(start_index)); } if(delim.empty()) { auto it = result.begin(); while(it != result.end()) { if((*it).empty()) { it = result.erase(it); } else { (*it) = String::trim_outer_whitespace(*it); ++it; } } } return result; } bool String::starts_with(const std::string& s, const std::string& beginning) { if(beginning.size() > s.size()) { return false; } return std::equal(beginning.begin(), beginning.end(), s.begin()); } bool String::starts_with(const std::string& s, char beginning) { return s[0] == beginning; } std::string String::consolidate_inner_whitespace(const std::string& s) { size_t start = s.find_first_not_of(whitespace); auto initial_whitespace = s.substr(0, start); size_t last_non_whitespace = s.find_last_not_of(whitespace); std::string final_whitespace; if(last_non_whitespace != std::string::npos) { final_whitespace = s.substr(last_non_whitespace + 1); } std::string result; while(true) { auto end = s.find_first_of(whitespace, start); // [start, end) is all non-whitespace if( ! result.empty()) { result += " "; } result += s.substr(start, end - start); start = s.find_first_not_of(whitespace, end); if(start == std::string::npos) { start = end; // only whitespace left break; } } return initial_whitespace + result + final_whitespace; } std::string String::trim_outer_whitespace(const std::string& s) { auto text_start = s.find_first_not_of(whitespace); if(text_start == std::string::npos) { return std::string{}; } auto text_end = s.find_last_not_of(whitespace); if(text_end == std::string::npos) { return s.substr(text_start); } return s.substr(text_start, text_end - text_start + 1); } std::string String::remove_extra_whitespace(const std::string& s) { return trim_outer_whitespace(consolidate_inner_whitespace(s)); } std::string String::strip_comments(const std::string& str, char comment) { return trim_outer_whitespace(str.substr(0, str.find(comment))); } std::string String::strip_block_comment(const std::string& str, char start, char end) { auto start_comment_index = str.find(start); auto end_comment_index = str.find(end); if(start_comment_index == std::string::npos || end_comment_index == std::string::npos) { return consolidate_inner_whitespace(trim_outer_whitespace(str)); } auto first_part = str.substr(0, start_comment_index); auto last_part = str.substr(end_comment_index + 1); return strip_block_comment(first_part + " " + last_part, start, end); } std::string String::lowercase(std::string s) { std::transform(s.begin(), s.end(), s.begin(), [](char c) -> char { return std::tolower(c); }); return s; } int Random::random_integer(int min, int max) { thread_local static std::mt19937_64 generator(std::random_device{}()); using uid = std::uniform_int_distribution<int>; thread_local static auto dist = uid{}; return dist(generator, uid::param_type{min, max}); } double Random::random_normal(double standard_deviation) { thread_local static std::mt19937_64 generator(std::random_device{}()); using nd = std::normal_distribution<double>; thread_local static auto dist = nd{}; return dist(generator, nd::param_type{0.0, standard_deviation}); } double Random::random_real(double min, double max) { thread_local static std::mt19937_64 generator(std::random_device{}()); using urd = std::uniform_real_distribution<double>; thread_local static auto dist = urd{}; return dist(generator, urd::param_type{min, max}); } bool Random::coin_flip() { return success_probability(0.5); } bool Random::success_probability(double probability) { return random_real(0.0, 1.0) < probability; } // Mean moves left in game given that a number of moves have been made already. double Math::average_moves_left(double mean_moves, double width, size_t moves_so_far) { // Assumes the number of moves in a game has a log-normal distribution. // // A = Sum(x = moves_so_far + 1 to infinity) P(x)*x = average number of moves // given game has already progressed // moves_so_far // // B = Sum(x = moves_so_far + 1 to infinity) P(x) = renormalization of P(x) for a // truncated range // // The calculations below for A and B use integrals on continuous functions as a // faster approximation. auto M = std::log(mean_moves); auto S = width; auto S2 = std::pow(S, 2); auto Sr2 = S*std::sqrt(2); auto ln_x = std::log(moves_so_far); auto A = std::exp(M + S2/2)*(1 + std::erf((M + S2 - ln_x)/Sr2)); auto B = 1 + std::erf((M-ln_x)/Sr2); auto expected_mean = A/B; // If moves_so_far is much greater than mean_moves with a small // width in the log-normal distribution, A and B can end up // being zero, resulting in an undefined answer (NaN most likely). // This represents an extremely long game, so expect the game to end // soon. if( ! std::isfinite(expected_mean)) { return 1.0; } return expected_mean - moves_so_far; } Configuration_File::Configuration_File(const std::string& file_name) { std::ifstream ifs(file_name); std::string line; while(std::getline(ifs, line)) { line = String::strip_comments(line, '#'); if(line.empty()) { continue; } if( ! String::contains(line, '=')) { throw std::runtime_error("Configuration file lines must be of form \"Name = Value\"\n" + line); } auto line_split = String::split(line, "=", 1); auto parameter = String::lowercase(String::remove_extra_whitespace(line_split[0])); parameters[parameter] = String::trim_outer_whitespace(line_split[1]); } } std::string Configuration_File::get_text(const std::string& parameter) const { try { return parameters.at(parameter); } catch(const std::out_of_range&) { for(const auto& key_value : parameters) { std::cerr << "\"" << key_value.first << "\" --> \"" << key_value.second << "\"" << std::endl; } throw std::runtime_error("Configuration parameter not found: " + parameter); } } double Configuration_File::get_number(const std::string& parameter) const { try { return std::stod(get_text(parameter)); } catch(const std::invalid_argument&) { throw std::runtime_error("Invalid number for \"" + parameter + "\" : " + get_text(parameter)); } } std::ofstream Scoped_Stopwatch::out_file; std::mutex Scoped_Stopwatch::write_lock; Scoped_Stopwatch::Scoped_Stopwatch(const std::string& name) : place_name(name), start_time(std::chrono::steady_clock::now()), stopped(false) { } Scoped_Stopwatch::~Scoped_Stopwatch() { stop(); } void Scoped_Stopwatch::stop() { auto end_time = std::chrono::steady_clock::now(); if(stopped) { return; } std::lock_guard<std::mutex> write_lock_guard(write_lock); if( ! out_file.is_open()) { out_file.open("timings.txt"); } out_file << place_name << "|" << std::chrono::duration_cast<std::chrono::duration<double>> (end_time - start_time).count() << '\n'; stopped = true; } void Scoped_Stopwatch::add_info(const std::string& info) { place_name += info; } <commit_msg>Use whitespace constant in String utilities<commit_after>#include "Utility.h" #include <vector> #include <random> #include <chrono> #include <fstream> #include <algorithm> #include <string> #include <cctype> #include <iostream> #include <cmath> namespace String { namespace { const auto whitespace = " \t\n"; } } std::vector<std::string> String::split(const std::string& s, const std::string& delim, size_t count) { std::vector<std::string> result; size_t start_index = 0; size_t end_index = 0; size_t split_count = 0; while(end_index < s.size() && split_count < count) { end_index = (delim.empty() ? s.find_first_of(whitespace, start_index) : s.find(delim, start_index)); result.push_back(s.substr(start_index, end_index-start_index)); if(end_index == std::string::npos) { start_index = std::string::npos; } else { start_index = end_index + (delim.empty() ? 1 : delim.size()); } ++split_count; } if(start_index < s.size()) { result.push_back(s.substr(start_index)); } if(delim.empty()) { auto it = result.begin(); while(it != result.end()) { if((*it).empty()) { it = result.erase(it); } else { (*it) = String::trim_outer_whitespace(*it); ++it; } } } return result; } bool String::starts_with(const std::string& s, const std::string& beginning) { if(beginning.size() > s.size()) { return false; } return std::equal(beginning.begin(), beginning.end(), s.begin()); } bool String::starts_with(const std::string& s, char beginning) { return s[0] == beginning; } std::string String::consolidate_inner_whitespace(const std::string& s) { size_t start = s.find_first_not_of(whitespace); auto initial_whitespace = s.substr(0, start); size_t last_non_whitespace = s.find_last_not_of(whitespace); std::string final_whitespace; if(last_non_whitespace != std::string::npos) { final_whitespace = s.substr(last_non_whitespace + 1); } std::string result; while(true) { auto end = s.find_first_of(whitespace, start); // [start, end) is all non-whitespace if( ! result.empty()) { result += " "; } result += s.substr(start, end - start); start = s.find_first_not_of(whitespace, end); if(start == std::string::npos) { start = end; // only whitespace left break; } } return initial_whitespace + result + final_whitespace; } std::string String::trim_outer_whitespace(const std::string& s) { auto text_start = s.find_first_not_of(whitespace); if(text_start == std::string::npos) { return std::string{}; } auto text_end = s.find_last_not_of(whitespace); if(text_end == std::string::npos) { return s.substr(text_start); } return s.substr(text_start, text_end - text_start + 1); } std::string String::remove_extra_whitespace(const std::string& s) { return trim_outer_whitespace(consolidate_inner_whitespace(s)); } std::string String::strip_comments(const std::string& str, char comment) { return trim_outer_whitespace(str.substr(0, str.find(comment))); } std::string String::strip_block_comment(const std::string& str, char start, char end) { auto start_comment_index = str.find(start); auto end_comment_index = str.find(end); if(start_comment_index == std::string::npos || end_comment_index == std::string::npos) { return consolidate_inner_whitespace(trim_outer_whitespace(str)); } auto first_part = str.substr(0, start_comment_index); auto last_part = str.substr(end_comment_index + 1); return strip_block_comment(first_part + " " + last_part, start, end); } std::string String::lowercase(std::string s) { std::transform(s.begin(), s.end(), s.begin(), [](char c) -> char { return std::tolower(c); }); return s; } int Random::random_integer(int min, int max) { thread_local static std::mt19937_64 generator(std::random_device{}()); using uid = std::uniform_int_distribution<int>; thread_local static auto dist = uid{}; return dist(generator, uid::param_type{min, max}); } double Random::random_normal(double standard_deviation) { thread_local static std::mt19937_64 generator(std::random_device{}()); using nd = std::normal_distribution<double>; thread_local static auto dist = nd{}; return dist(generator, nd::param_type{0.0, standard_deviation}); } double Random::random_real(double min, double max) { thread_local static std::mt19937_64 generator(std::random_device{}()); using urd = std::uniform_real_distribution<double>; thread_local static auto dist = urd{}; return dist(generator, urd::param_type{min, max}); } bool Random::coin_flip() { return success_probability(0.5); } bool Random::success_probability(double probability) { return random_real(0.0, 1.0) < probability; } // Mean moves left in game given that a number of moves have been made already. double Math::average_moves_left(double mean_moves, double width, size_t moves_so_far) { // Assumes the number of moves in a game has a log-normal distribution. // // A = Sum(x = moves_so_far + 1 to infinity) P(x)*x = average number of moves // given game has already progressed // moves_so_far // // B = Sum(x = moves_so_far + 1 to infinity) P(x) = renormalization of P(x) for a // truncated range // // The calculations below for A and B use integrals on continuous functions as a // faster approximation. auto M = std::log(mean_moves); auto S = width; auto S2 = std::pow(S, 2); auto Sr2 = S*std::sqrt(2); auto ln_x = std::log(moves_so_far); auto A = std::exp(M + S2/2)*(1 + std::erf((M + S2 - ln_x)/Sr2)); auto B = 1 + std::erf((M-ln_x)/Sr2); auto expected_mean = A/B; // If moves_so_far is much greater than mean_moves with a small // width in the log-normal distribution, A and B can end up // being zero, resulting in an undefined answer (NaN most likely). // This represents an extremely long game, so expect the game to end // soon. if( ! std::isfinite(expected_mean)) { return 1.0; } return expected_mean - moves_so_far; } Configuration_File::Configuration_File(const std::string& file_name) { std::ifstream ifs(file_name); std::string line; while(std::getline(ifs, line)) { line = String::strip_comments(line, '#'); if(line.empty()) { continue; } if( ! String::contains(line, '=')) { throw std::runtime_error("Configuration file lines must be of form \"Name = Value\"\n" + line); } auto line_split = String::split(line, "=", 1); auto parameter = String::lowercase(String::remove_extra_whitespace(line_split[0])); parameters[parameter] = String::trim_outer_whitespace(line_split[1]); } } std::string Configuration_File::get_text(const std::string& parameter) const { try { return parameters.at(parameter); } catch(const std::out_of_range&) { for(const auto& key_value : parameters) { std::cerr << "\"" << key_value.first << "\" --> \"" << key_value.second << "\"" << std::endl; } throw std::runtime_error("Configuration parameter not found: " + parameter); } } double Configuration_File::get_number(const std::string& parameter) const { try { return std::stod(get_text(parameter)); } catch(const std::invalid_argument&) { throw std::runtime_error("Invalid number for \"" + parameter + "\" : " + get_text(parameter)); } } std::ofstream Scoped_Stopwatch::out_file; std::mutex Scoped_Stopwatch::write_lock; Scoped_Stopwatch::Scoped_Stopwatch(const std::string& name) : place_name(name), start_time(std::chrono::steady_clock::now()), stopped(false) { } Scoped_Stopwatch::~Scoped_Stopwatch() { stop(); } void Scoped_Stopwatch::stop() { auto end_time = std::chrono::steady_clock::now(); if(stopped) { return; } std::lock_guard<std::mutex> write_lock_guard(write_lock); if( ! out_file.is_open()) { out_file.open("timings.txt"); } out_file << place_name << "|" << std::chrono::duration_cast<std::chrono::duration<double>> (end_time - start_time).count() << '\n'; stopped = true; } void Scoped_Stopwatch::add_info(const std::string& info) { place_name += info; } <|endoftext|>
<commit_before>/* * fMBT, free Model Based Testing tool * Copyright (c) 2011, Intel Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License along with * this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ /* Implementations of Bounded Depth-First-Search for models and * coverages with push() and pop() */ #include "alg_bdfs.hh" #include "model.hh" #include "coverage.hh" #include <algorithm> #include <cstdlib> extern int _g_simulation_depth_hint; double AlgPathToBestCoverage::search(Model& model, Coverage& coverage, std::vector<int>& path) { m_coverage = &coverage; m_model = &model; return path_to_best_evaluation(model, path, m_search_depth); } double AlgPathToBestCoverage::evaluate() { return m_coverage->getCoverage(); } void AlgPathToBestCoverage::doExecute(int action) { if (!status) { return; } m_model->push(); m_coverage->push(); if (!m_model->execute(action)) { status=false; return;} m_coverage->execute(action); } void AlgPathToBestCoverage::undoExecute() { if (!status) { return; } m_model->pop(); m_coverage->pop(); } double AlgPathToAction::search(Model& model, int find_this_action, std::vector<int> &path) { m_model = &model; m_find_this_action = find_this_action; return path_to_best_evaluation(model, path, m_search_depth); } double AlgPathToAction::evaluate() { int *actions; int action_count; /* Is action m_find_this_action available in the current state? */ action_count = m_model->getActions(&actions); if (!status) { return 0.0; } for (int i = 0; i < action_count; i++) { if (actions[i] == m_find_this_action) return 1.0; } return 0.0; } void AlgPathToAction::doExecute(int action) { m_model->push(); m_model->execute(action); } void AlgPathToAction::undoExecute() { m_model->pop(); } double AlgBDFS::path_to_best_evaluation(Model& model, std::vector<int>& path, int depth) { volatile double current_score = evaluate(); volatile double best_score = 0; std::vector<int> hinted_path; if (!model.status || !status) { status=false; return 0.0; } _g_simulation_depth_hint = depth; model.push(); _g_simulation_depth_hint = 0; if (path.size() > 0) { // Path includes a hint to look at this path at first before // considering others. // // Evaluating the hinted options first has too effects: // // - If one path has been chosen earlier, it's preferred to // continue execution that way instead of switching it to // another path that seems to be as good as the // original. This prevents oscillation between equally good // paths. // // - If maximal growth rate is known, search starting with a // good "so far best score" is able to drop unnecessary // lookups. (Not implemented) int invalid_step = -1; for (unsigned int i = 0; i < path.size(); i++) { doExecute(path[i]); if (status == false) { invalid_step = i; status = true; } if (!model.status) { status = false; return 0.0; } } if (invalid_step > -1) { // Hinted path is no more valid, throw it away. path.resize(0); for (int i = invalid_step; i > -1; i--) undoExecute(); } else { std::vector<int> additional_path; best_score = _path_to_best_evaluation(model, additional_path, depth - path.size(), current_score); if (!model.status || !status) { status=false; return 0.0; } for (unsigned int i = 0; i < path.size(); i++) undoExecute(); if (!model.status || !status) { status=false; return 0.0; } if (best_score > current_score) { hinted_path = path; for (int i = additional_path.size() - 1; i >= 0; i--) hinted_path.push_back(additional_path[i]); current_score = best_score; } } } best_score = _path_to_best_evaluation(model, path, depth, current_score); model.pop(); if (!model.status || !status) { status=false; return 0.0; } if (best_score > current_score) { // The real algorithm constructs the best path in the opposite // direction to the path vector, this wrapper reverses it. std::reverse(path.begin(), path.end()); } else if (hinted_path.size() > 0) { path = hinted_path; } else { path.resize(0); } return best_score; } bool AlgBDFS::grows_first(std::vector<int>& first_path, int first_path_start, std::vector<int>& second_path, int second_path_start) { if (first_path.size() != second_path.size()) { status=false; return false; } volatile double current_score = evaluate(); first_path.push_back(first_path_start); second_path.push_back(second_path_start); int first_difference = first_path.size(); for (int i = first_path.size() - 1; i >= 0; i--) { doExecute(first_path[i]); volatile double score = evaluate(); if (!status) { return false; } if (score > current_score) { first_difference = i; break; } } if (first_difference == (int)first_path.size()) { status=false; return false; } for (int j = first_path.size() - 1; j >= first_difference; j--) undoExecute(); int second_difference = second_path.size(); for (int i = second_path.size() - 1; i >= 0; i--) { doExecute(second_path[i]); volatile double score = evaluate(); if (score > current_score) { second_difference = i; break; } } if (second_difference == (int)second_path.size()) { status=false; return false; } for (int j = second_path.size() - 1; j >= second_difference; j--) undoExecute(); first_path.pop_back(); second_path.pop_back(); if (first_difference > second_difference) return true; else return false; } double AlgBDFS::_path_to_best_evaluation(Model& model, std::vector<int>& path, int depth, double best_evaluation) { int *input_actions = NULL; int input_action_count = 0; if (!status) { return 0.0; } volatile double current_state_evaluation = evaluate(); if (current_state_evaluation > best_evaluation) best_evaluation = current_state_evaluation; /* Can we still continue the search? */ if (depth <= 0) return current_state_evaluation; /* Recursive search for the best path */ input_action_count = model.getIActions(&input_actions); if (!model.status) { status=false; return 0.0; } std::vector<int> action_candidates; for (int i = 0; i < input_action_count; i++) action_candidates.push_back(input_actions[i]); std::vector<int> best_path; unsigned int best_path_length = 0; int best_action = -1; for (int i = 0; i < input_action_count; i++) { std::vector<int> a_path; volatile double an_evaluation; doExecute(action_candidates[i]); a_path.resize(0); an_evaluation = _path_to_best_evaluation(model, a_path, depth - 1, best_evaluation); undoExecute(); if (!model.status || !status) { status=false; return 0.0; } if (an_evaluation > current_state_evaluation && (an_evaluation > best_evaluation || (an_evaluation == best_evaluation && (best_action == -1 || (best_action > -1 && (a_path.size() < best_path_length || (a_path.size() == best_path_length && grows_first(a_path, action_candidates[i], best_path, best_action)))))))) { best_path_length = a_path.size(); best_path = a_path; best_action = action_candidates[i]; best_evaluation = an_evaluation; } } if ((int)best_action > -1) { path = best_path; path.push_back(best_action); return best_evaluation; } return current_state_evaluation; } <commit_msg>Fix push/pop thing..<commit_after>/* * fMBT, free Model Based Testing tool * Copyright (c) 2011, Intel Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License along with * this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ /* Implementations of Bounded Depth-First-Search for models and * coverages with push() and pop() */ #include "alg_bdfs.hh" #include "model.hh" #include "coverage.hh" #include <algorithm> #include <cstdlib> #include "helper.hh" extern int _g_simulation_depth_hint; double AlgPathToBestCoverage::search(Model& model, Coverage& coverage, std::vector<int>& path) { m_coverage = &coverage; m_model = &model; return path_to_best_evaluation(model, path, m_search_depth); } double AlgPathToBestCoverage::evaluate() { return m_coverage->getCoverage(); } void AlgPathToBestCoverage::doExecute(int action) { if (!status) { return; } m_model->push(); m_coverage->push(); if (!m_model->execute(action)) { errormsg="Model execute error"; status=false; return;} m_coverage->execute(action); } void AlgPathToBestCoverage::undoExecute() { if (!status) { return; } m_model->pop(); m_coverage->pop(); } double AlgPathToAction::search(Model& model, int find_this_action, std::vector<int> &path) { m_model = &model; m_find_this_action = find_this_action; return path_to_best_evaluation(model, path, m_search_depth); } double AlgPathToAction::evaluate() { int *actions; int action_count; /* Is action m_find_this_action available in the current state? */ action_count = m_model->getActions(&actions); if (!status) { return 0.0; } for (int i = 0; i < action_count; i++) { if (actions[i] == m_find_this_action) return 1.0; } return 0.0; } void AlgPathToAction::doExecute(int action) { m_model->push(); m_model->execute(action); } void AlgPathToAction::undoExecute() { m_model->pop(); } double AlgBDFS::path_to_best_evaluation(Model& model, std::vector<int>& path, int depth) { volatile double current_score = evaluate(); volatile double best_score = 0; std::vector<int> hinted_path; if (!model.status || !status) { if (!model.status) errormsg = "Model error:"+model.errormsg; status=false; return 0.0; } _g_simulation_depth_hint = depth; model.push(); _g_simulation_depth_hint = 0; if (path.size() > 0) { // Path includes a hint to look at this path at first before // considering others. // // Evaluating the hinted options first has too effects: // // - If one path has been chosen earlier, it's preferred to // continue execution that way instead of switching it to // another path that seems to be as good as the // original. This prevents oscillation between equally good // paths. // // - If maximal growth rate is known, search starting with a // good "so far best score" is able to drop unnecessary // lookups. (Not implemented) int invalid_step = -1; for (unsigned int pos = 0; pos < path.size() && invalid_step == -1; pos++) { doExecute(path[pos]); if (status == false) { invalid_step = pos; status = true; } if (!model.status) { status = false; return 0.0; } } if (invalid_step > -1) { // Hinted path is no more valid, throw it away. path.resize(0); for (int current_step = invalid_step; current_step > -1; current_step--) undoExecute(); } else { std::vector<int> additional_path; best_score = _path_to_best_evaluation(model, additional_path, depth - path.size(), current_score); if (!model.status || !status) { if (!model.status) errormsg = "Model error:"+model.errormsg; status=false; return 0.0; } for (unsigned int i = 0; i < path.size(); i++) undoExecute(); if (!model.status || !status) { if (!model.status) errormsg = "Model error:"+model.errormsg; status=false; return 0.0; } if (best_score > current_score) { hinted_path = path; for (int i = additional_path.size() - 1; i >= 0; i--) hinted_path.push_back(additional_path[i]); current_score = best_score; } } } best_score = _path_to_best_evaluation(model, path, depth, current_score); model.pop(); if (!model.status || !status) { if (!model.status) errormsg = "Model error:"+model.errormsg; status=false; return 0.0; } if (best_score > current_score) { // The real algorithm constructs the best path in the opposite // direction to the path vector, this wrapper reverses it. std::reverse(path.begin(), path.end()); } else if (hinted_path.size() > 0) { path = hinted_path; } else { path.resize(0); } return best_score; } bool AlgBDFS::grows_first(std::vector<int>& first_path, int first_path_start, std::vector<int>& second_path, int second_path_start) { if (first_path.size() != second_path.size()) { errormsg="first_path.size() != second_path.size()"; status=false; return false; } volatile double current_score = evaluate(); first_path.push_back(first_path_start); second_path.push_back(second_path_start); int first_difference = first_path.size(); for (int i = first_path.size() - 1; i >= 0; i--) { doExecute(first_path[i]); volatile double score = evaluate(); if (!status) { return false; } if (score > current_score) { first_difference = i; break; } } if (first_difference == (int)first_path.size()) { errormsg = "first_difference == (int)first_path.size() "+to_string(first_difference); status=false; return false; } for (int j = first_path.size() - 1; j >= first_difference; j--) undoExecute(); int second_difference = second_path.size(); for (int i = second_path.size() - 1; i >= 0; i--) { doExecute(second_path[i]); volatile double score = evaluate(); if (score > current_score) { second_difference = i; break; } } if (second_difference == (int)second_path.size()) { errormsg = "second_difference == (int)second_path.size()"; status=false; return false; } for (int j = second_path.size() - 1; j >= second_difference; j--) undoExecute(); first_path.pop_back(); second_path.pop_back(); if (first_difference > second_difference) return true; else return false; } double AlgBDFS::_path_to_best_evaluation(Model& model, std::vector<int>& path, int depth, double best_evaluation) { int *input_actions = NULL; int input_action_count = 0; if (!status) { return 0.0; } volatile double current_state_evaluation = evaluate(); if (current_state_evaluation > best_evaluation) best_evaluation = current_state_evaluation; /* Can we still continue the search? */ if (depth <= 0) return current_state_evaluation; /* Recursive search for the best path */ input_action_count = model.getIActions(&input_actions); if (!model.status) { errormsg = "Model error:"+model.errormsg; status=false; return 0.0; } std::vector<int> action_candidates; for (int i = 0; i < input_action_count; i++) action_candidates.push_back(input_actions[i]); std::vector<int> best_path; unsigned int best_path_length = 0; int best_action = -1; for (int i = 0; i < input_action_count; i++) { std::vector<int> a_path; volatile double an_evaluation; doExecute(action_candidates[i]); a_path.resize(0); an_evaluation = _path_to_best_evaluation(model, a_path, depth - 1, best_evaluation); undoExecute(); if (!model.status || !status) { if (!model.status) errormsg = "Model error:"+model.errormsg; status=false; return 0.0; } if (an_evaluation > current_state_evaluation && (an_evaluation > best_evaluation || (an_evaluation == best_evaluation && (best_action == -1 || (best_action > -1 && (a_path.size() < best_path_length || (a_path.size() == best_path_length && grows_first(a_path, action_candidates[i], best_path, best_action)))))))) { best_path_length = a_path.size(); best_path = a_path; best_action = action_candidates[i]; best_evaluation = an_evaluation; } } if ((int)best_action > -1) { path = best_path; path.push_back(best_action); return best_evaluation; } return current_state_evaluation; } <|endoftext|>
<commit_before>/* Copyright (c) 2012 Carsten Burstedde, Donna Calhoun All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "amr_forestclaw.H" #include "amr_utils.H" #include "clawpack_fort.H" #include "fclaw2d_solvers.H" #include "ClawPatch.H" void cb_tag4refinement(fclaw2d_domain_t *domain, fclaw2d_patch_t *this_patch, int this_block_idx, int this_patch_idx, void *user); void cb_domain_adapt(fclaw2d_domain_t * old_domain, fclaw2d_patch_t * old_patch, fclaw2d_domain_t * new_domain, fclaw2d_patch_t * new_patch, fclaw2d_patch_relation_t newsize, int blockno, int old_patchno, int new_patchno, void *user); static void cb_initialize_base(fclaw2d_domain_t *domain, fclaw2d_patch_t *this_patch, int this_block_idx, int this_patch_idx, void *user) { const amr_options_t *gparms = get_domain_parms(domain); ClawPatch *cp = new ClawPatch(); int level = this_patch->level; cp->define(this_patch->xlower, this_patch->ylower, this_patch->xupper, this_patch->yupper, this_block_idx, level, gparms); set_patch_data(this_patch,cp); /* The user can now retrieve the ClawPatch from 'this_patch' and set up whatever they need to set up. */ fclaw2d_solver_functions_t *sf = get_solver_functions(domain); (sf->f_patch_setup)(domain,this_patch,this_block_idx,this_patch_idx); } static void set_base_level(fclaw2d_domain_t *domain, const int& level) { fclaw2d_domain_iterate_level(domain, level, cb_initialize_base,(void *) NULL); } /* ----------------------------------------------------------------- Initial grid ----------------------------------------------------------------- */ static void cb_amrinit(fclaw2d_domain_t *domain, fclaw2d_patch_t *this_patch, int this_block_idx, int this_patch_idx, void *user) { fclaw2d_solver_functions_t *sf = get_solver_functions(domain); (sf->f_patch_initialize)(domain,this_patch,this_block_idx,this_patch_idx); } // Initialize a base level of grids void amrinit(fclaw2d_domain_t **domain) { const amr_options_t *gparms = get_domain_parms(*domain); fclaw2d_domain_data_t* ddata = get_domain_data(*domain); (ddata->f_problem_setup)(*domain); double t = 0; set_domain_time(*domain,t); int minlevel = gparms->minlevel; int maxlevel = gparms->maxlevel; // Set problem dependent parameters for Riemann solvers, etc. // Values are typically stored in Fortran common blocks, and are not // available outside of Fortran. init_block_and_patch_data(*domain); /* Allocate block and patch data */ // This function is redundant, and should be made more general. cout << "Setting base level " << endl; set_base_level(*domain,minlevel); cout << "Done with amr_set_base_level " << endl; // Initialize base level grid - combine with 'amr_set_base_level' above? fclaw2d_domain_iterate_level(*domain, minlevel, cb_amrinit, (void *) NULL); cout << "Done with domain adaptation " << endl; int num = (*domain)->num_blocks; for (int i = 0; i < num; i++) { fclaw2d_block_t *block = &(*domain)->blocks[i]; set_block_data(block,gparms->mthbc); } set_phys_bc(*domain,minlevel,t); // Refine as needed. bool init_flag = true; for (int level = minlevel; level < maxlevel; level++) { cout << "amrinit : level = " << level << endl << endl; // TODO: don't use level_refined since it is not agreed upon in parallel // the fclaw2d_domain_adapt and _partition calls work fine in parallel fclaw2d_domain_iterate_level(*domain, level, cb_tag4refinement, (void *) &init_flag); // Rebuild domain if necessary cout << "amrinit : Building new domain " << endl; fclaw2d_domain_t *new_domain = fclaw2d_domain_adapt(*domain); cout << "amrinit : Done building new domain " << endl << endl; if (new_domain != NULL) { // This is just for fun; remove when it gets annoying. // fclaw2d_domain_list_adapted(*domain, new_domain, SC_LP_STATISTICS); // Allocate memory for user data types (but they don't get set) init_domain_data(new_domain); copy_domain_data(*domain,new_domain); // Initialize new grids. Assume that all ghost cells are filled //in by qinit. init_block_and_patch_data(new_domain); // Physical BCs are needed in boundary level exchange // Assume only one block, since we are assuming mthbc int num = new_domain->num_blocks; for (int i = 0; i < num; i++) { fclaw2d_block_t *block = &new_domain->blocks[i]; // This is kind of dumb for now, since block won't in general // have the same physical boundary conditions types. set_block_data(block,gparms->mthbc); } fclaw2d_domain_iterate_adapted(*domain, new_domain, cb_domain_adapt, (void *) &init_flag); // Set some of the user data types. Some of this is done // in 'amr_set_base_level', // I should probably come up with a more general way to do this. // Not needed, because of copy above. // set_domain_data(new_domain, gparms); // set_domain_time(new_domain,t); int new_level = level+1; // Upon initialization, we don't do any ghost cell exchanges, because we assume // that the initial conditions have set all internal ghost cells. set_phys_bc(new_domain,new_level,t); // free all memory associated with old domain amrreset(domain); *domain = new_domain; fclaw2d_domain_t *domain_partitioned = fclaw2d_domain_partition (*domain); if (domain_partitioned != NULL) { // TODO: allocate patch and block etc. memory for domain_partitioned // TODO: write a function to transfer values in parallel */ /* then the old domain is no longer necessary */ amrreset(domain); *domain = domain_partitioned; /* internal clean up */ fclaw2d_domain_complete(*domain); } } else { // exit loop; we are done refining break; } cout << "amrinit : done with level " << endl << endl;; } cout << "Done with building initial grid structure " << endl; } <commit_msg>All callbacks are now static - I defined special 'init' callbacks<commit_after>/* Copyright (c) 2012 Carsten Burstedde, Donna Calhoun All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "amr_forestclaw.H" #include "amr_utils.H" #include "clawpack_fort.H" #include "fclaw2d_solvers.H" // Put this here so that I don't have to include "ClawPatch.H" void set_clawpatch(fclaw2d_domain_t* domain, fclaw2d_patch_t *this_patch, int blockno, int patchno); // This is essentially the same function that is in amr_regrid.cpp static void cb_tag4refinement_init(fclaw2d_domain_t *domain, fclaw2d_patch_t *this_patch, int this_block_idx, int this_patch_idx, void *user) { const amr_options_t *gparms = get_domain_parms(domain); int maxlevel = gparms->maxlevel; int level = this_patch->level; int initflag = 1; if (level < maxlevel) { fclaw2d_regrid_functions_t* rf = get_regrid_functions(domain); fclaw_bool refine_patch = (rf->f_patch_tag4refinement)(domain,this_patch,this_block_idx, this_patch_idx,initflag); if (refine_patch) { fclaw2d_patch_mark_refine(domain, this_block_idx, this_patch_idx); } } } /* ----------------------------------------------------------------- Initial grid ----------------------------------------------------------------- */ static void cb_initialize (fclaw2d_domain_t *domain, fclaw2d_patch_t *this_patch, int this_block_idx, int this_patch_idx, void *user) { set_clawpatch(domain,this_patch,this_block_idx, this_patch_idx); fclaw2d_solver_functions_t *sf = get_solver_functions(domain); // One-time setup of patch (sf->f_patch_setup)(domain,this_patch,this_block_idx,this_patch_idx); // Set initial values on patch (sf->f_patch_initialize)(domain,this_patch,this_block_idx,this_patch_idx); } static void cb_domain_adapt_init (fclaw2d_domain_t * old_domain, fclaw2d_patch_t * old_patch, fclaw2d_domain_t * new_domain, fclaw2d_patch_t * new_patch, fclaw2d_patch_relation_t newsize, int blockno, int old_patchno, int new_patchno, void *user) { if (newsize == FCLAW2D_PATCH_SAMESIZE) { // Grid doesn't change set_clawpatch(new_domain,new_patch,blockno,new_patchno); // Setup new patch using solver specific routine fclaw2d_solver_functions_t *sf = get_solver_functions(old_domain); (sf->f_patch_setup)(new_domain,new_patch,blockno,new_patchno); // Need a copy function in regrid_functions fclaw2d_regrid_functions_t *rf = get_regrid_functions(old_domain); (rf->f_patch_copy2samesize)(new_domain,old_patch,new_patch,blockno,old_patchno, new_patchno); } else if (newsize == FCLAW2D_PATCH_HALFSIZE) { // Patch has been refined. fclaw2d_patch_t *fine_siblings = new_patch; // Loop over four siblings (z-ordering) and interpolate // data from coarser parent grid to each finer sibling grid. for (int igrid = 0; igrid < NumSiblings; igrid++) { fclaw2d_patch_t *fine_patch = &fine_siblings[igrid]; int fine_patchno = new_patchno + igrid; // Create new ClawPatch and assign patch pointer to it. set_clawpatch(new_domain, fine_patch, blockno, fine_patchno); // Do one-time setup on new patch fclaw2d_solver_functions_t *sf = get_solver_functions(old_domain); (sf->f_patch_setup)(new_domain,fine_patch,blockno,fine_patchno); // This is only used here, since only in the initial grid layout do we // create fine grids from coarser grids. (sf->f_patch_initialize)(new_domain,fine_patch,blockno,fine_patchno); } } else if (newsize == FCLAW2D_PATCH_DOUBLESIZE) { // We don't coarsen for the initial time step } else { printf("cb_adapt_domain : newsize not recognized\n"); exit(1); } } // Initialize a base level of grids void amrinit (fclaw2d_domain_t **domain) { const amr_options_t *gparms = get_domain_parms(*domain); fclaw2d_domain_data_t* ddata = get_domain_data(*domain); // Set problem dependent parameters for Riemann solvers, etc. // Values are typically stored in Fortran common blocks, and are not // available outside of Fortran. (ddata->f_problem_setup)(*domain); double t = 0; set_domain_time(*domain,t); int minlevel = gparms->minlevel; int maxlevel = gparms->maxlevel; init_block_and_patch_data(*domain); /* Allocate block and patch data */ // Initialize base level grid - combine with 'amr_set_base_level' above? fclaw2d_domain_iterate_level(*domain, minlevel, cb_initialize, (void *) NULL); int num = (*domain)->num_blocks; for (int i = 0; i < num; i++) { fclaw2d_block_t *block = &(*domain)->blocks[i]; set_block_data(block,gparms->mthbc); } set_phys_bc(*domain,minlevel,t); // Refine as needed. for (int level = minlevel; level < maxlevel; level++) { // TODO: don't use level_refined since it is not agreed upon in parallel // the fclaw2d_domain_adapt and _partition calls work fine in parallel fclaw2d_domain_iterate_level(*domain, level, cb_tag4refinement_init, (void *) NULL); // Rebuild domain if necessary fclaw2d_domain_t *new_domain = fclaw2d_domain_adapt(*domain); if (new_domain != NULL) { // This is just for fun; remove when it gets annoying. // fclaw2d_domain_list_adapted(*domain, new_domain, SC_LP_STATISTICS); // Allocate memory for user data types (but they don't get set) init_domain_data(new_domain); copy_domain_data(*domain,new_domain); // Initialize new grids. Assume that all ghost cells are filled //in by qinit. init_block_and_patch_data(new_domain); // Physical BCs are needed in boundary level exchange // Assume only one block, since we are assuming mthbc int num = new_domain->num_blocks; for (int i = 0; i < num; i++) { fclaw2d_block_t *block = &new_domain->blocks[i]; // This is kind of dumb for now, since block won't in general // have the same physical boundary conditions types. set_block_data(block,gparms->mthbc); } fclaw2d_domain_iterate_adapted(*domain, new_domain, cb_domain_adapt_init, (void *) NULL); int new_level = level+1; // Upon initialization, we don't do any ghost cell exchanges, because we assume // that the initial conditions have set all internal ghost cells. set_phys_bc(new_domain,new_level,t); // free all memory associated with old domain amrreset(domain); *domain = new_domain; fclaw2d_domain_t *domain_partitioned = fclaw2d_domain_partition (*domain); if (domain_partitioned != NULL) { // TODO: allocate patch and block etc. memory for domain_partitioned // TODO: write a function to transfer values in parallel */ /* then the old domain is no longer necessary */ amrreset(domain); *domain = domain_partitioned; /* internal clean up */ fclaw2d_domain_complete(*domain); } } else { // exit loop; we are done refining break; } } } <|endoftext|>
<commit_before>#include "OscillatorModule.h" #include <cmath> OscillatorModule::OscillatorModule(ModularSynth& synth) :SynthModule(synth, moduleId, 2, 1, 0), mAccumulator(0.0f), mPreviousSync(0.0f) { } void OscillatorModule::cycle() { if (getInput(1) > 0.0f && mPreviousSync <= 0.0f) mAccumulator = 0; mPreviousSync = getInput(1); mAccumulator = fmod(mAccumulator + getInput(0), 1.0f); setOutput(0, sin(mAccumulator * (3.14157 * 2))); } const char * OscillatorModule::getInputName(int input) const { static const char *names[] = {"Frequency", "Sync", "C"}; return names[input]; } const char * OscillatorModule::getOutputName(int output) const { return "Output"; } const char * OscillatorModule::getName() const { return moduleName; } SynthModule * OscillatorModule::createModule(ModularSynth& synth) { return new OscillatorModule(synth); } <commit_msg>Added a phase input for OscillatorModule<commit_after>#include "OscillatorModule.h" #include <cmath> OscillatorModule::OscillatorModule(ModularSynth& synth) :SynthModule(synth, moduleId, 3, 1, 0), mAccumulator(0.0f), mPreviousSync(0.0f) { } void OscillatorModule::cycle() { if (getInput(1) > 0.0f && mPreviousSync <= 0.0f) mAccumulator = 0; mPreviousSync = getInput(1); mAccumulator = fmod(mAccumulator + getInput(0), 1.0f); setOutput(0, sin((mAccumulator + getInput(2)) * (3.14157 * 2))); } const char * OscillatorModule::getInputName(int input) const { static const char *names[] = {"Frequency", "Sync", "Phase"}; return names[input]; } const char * OscillatorModule::getOutputName(int output) const { return "Output"; } const char * OscillatorModule::getName() const { return moduleName; } SynthModule * OscillatorModule::createModule(ModularSynth& synth) { return new OscillatorModule(synth); } <|endoftext|>
<commit_before>#pragma once #include <functional> #include <string> #include <system_error> #include <type_traits> #include <utility> /** @brief Wraps common c style error handling for exception throwing * This requires the callee to set errno on error. * @details We often have a pattern in our code for checking errors and * propagating up exceptions: * * int c_call(const char* path); * * int our_cpp_call(const char* path) * { * int r = c_call(path); * if (r < 0) * { * throw std::system_error(errno, std::generic_category(), * "our msg"); * } * return r; * } * * To make that more succinct, we can use CHECK_ERRNO: * * int our_cpp_call(const char* path) * { * return CHECK_ERRNO(c_call(path), "our msg"); * } * * @param[in] expr - The expression returning an errno value * @param[in] error_handler - Passed to the doError function * @throws std::system_error (depends on error_handler) for an error case * @return A successful return value based on the function type */ #define CHECK_ERRNO(expr, error_handler) \ [&](auto check_errno_ret) { \ if constexpr (::std::is_pointer_v<decltype(check_errno_ret)>) \ { \ if (check_errno_ret == nullptr) \ ::stdplus::util::doError(errno, (error_handler)); \ } \ else if constexpr (::std::is_signed_v<decltype(check_errno_ret)>) \ { \ if (check_errno_ret < 0) \ ::stdplus::util::doError(errno, (error_handler)); \ } \ else \ { \ static_assert(::std::is_same_v<decltype(check_errno_ret), int>, \ "Unimplemented check routine"); \ } \ return check_errno_ret; \ }((expr)) /** @brief Wraps common c style error handling for exception throwing * This requires the callee to provide error information in -r. * See CHECK_ERRNO() for details. * * @param[in] expr - The expression returning an negative error value * @param[in] error_handler - Passed to the doError function * @throws std::system_error (depends on error_handler) for an error case * @return A successful return value based on the function type */ #define CHECK_RET(expr, error_handler) \ [&](auto check_ret_ret) { \ if constexpr (::std::is_signed_v<decltype(check_ret_ret)>) \ { \ if (check_ret_ret < 0) \ ::stdplus::util::doError(-check_ret_ret, (error_handler)); \ } \ else \ { \ static_assert(::std::is_same_v<decltype(check_ret_ret), int>, \ "Unimplemented check routine"); \ } \ return check_ret_ret; \ }((expr)) namespace stdplus { namespace util { /** @brief Common pattern used by default for constructing a system exception * @details Most libc or system calls will want to return a generic * system_error when detecting an error in a call. This function * creates that error from the errno and message. * * @param[in] error - * @param[in] msg - * @return The exception passed to a `throw` call. */ inline auto makeSystemError(int error, const char* msg) { return std::system_error(error, std::generic_category(), msg); } /** @brief Turns errors into exceptions for the given error handler * * @param[in] error - The numeric system error code * @param[in] msg - The string used to describe the error * @throws A system exception with the given error and msg */ inline void doError(int error, const char* msg) { throw makeSystemError(error, msg); } inline void doError(int error, const std::string& msg) { throw makeSystemError(error, msg.c_str()); } /** @brief Turns errors into exceptions for the given error handler * * @param[in] error - The numeric system error code * @param[in] fun - the function used to throw the error */ template <typename Fun> inline std::enable_if_t<std::is_invocable_v<Fun, int>, void> doError(int error, Fun&& fun) { fun(error); } /** @brief Wraps common c style error handling for exception throwing * This requires the callee to set errno on error. * @details We often have a pattern in our code for checking errors and * propagating up exceptions: * * int c_call(const char* path); * * int our_cpp_call(const char* path) * { * int r = c_call(path); * if (r < 0) * { * throw std::system_error(errno, std::generic_category(), * "our msg"); * } * return r; * } * * To make that more succinct, we can use callCheckErrno: * * int our_cpp_call(const char* path) * { * return callCheckErrno("our msg", c_call, path); * } * * @param[in] msg - The error message displayed when errno is set. * @param[in] func - The wrapped function we invoke * @param[in] args... - The arguments passed to the function * @throws std::system_error for an error case. * @return A successful return value based on the function type */ template <auto (*makeError)(int, const char*) = makeSystemError, typename... Args> inline auto callCheckErrno(const char* msg, Args&&... args) { using Ret = typename std::invoke_result<Args...>::type; if constexpr (std::is_integral_v<Ret> && std::is_signed_v<Ret>) { Ret r = std::invoke(std::forward<Args>(args)...); if (r < 0) throw makeError(errno, msg); return r; } else if constexpr (std::is_pointer_v<Ret>) { Ret r = std::invoke(std::forward<Args>(args)...); if (r == nullptr) throw makeError(errno, msg); return r; } else { static_assert(std::is_same_v<Ret, int>, "Unimplemented check routine"); } } template <auto (*makeError)(int, const char*) = makeSystemError, typename... Args> inline auto callCheckErrno(const std::string& msg, Args&&... args) { return callCheckErrno(msg.c_str(), std::forward<Args>(args)...); } /** @brief Wraps common c style error handling for exception throwing * This requires the callee to provide error information in -r. * See callCheckErrno() for details. * * @param[in] msg - The error message displayed when errno is set. * @param[in] func - The wrapped function we invoke * @param[in] args... - The arguments passed to the function * @throws std::system_error for an error case. * @return A successful return value based on the function type */ template <auto (*makeError)(int, const char*) = makeSystemError, typename... Args> inline auto callCheckRet(const char* msg, Args&&... args) { using Ret = typename std::invoke_result<Args...>::type; if constexpr (std::is_integral_v<Ret> && std::is_signed_v<Ret>) { Ret r = std::invoke(std::forward<Args>(args)...); if (r < 0) throw makeError(-r, msg); return r; } else { static_assert(std::is_same_v<Ret, int>, "Unimplemented check routine"); } } template <auto (*makeError)(int, const char*) = makeSystemError, typename... Args> inline auto callCheckRet(const std::string& msg, Args&&... args) { return callCheckRet(msg.c_str(), std::forward<Args>(args)...); } } // namespace util } // namespace stdplus <commit_msg>treewide: Update for new code format<commit_after>#pragma once #include <functional> #include <string> #include <system_error> #include <type_traits> #include <utility> /** @brief Wraps common c style error handling for exception throwing * This requires the callee to set errno on error. * @details We often have a pattern in our code for checking errors and * propagating up exceptions: * * int c_call(const char* path); * * int our_cpp_call(const char* path) * { * int r = c_call(path); * if (r < 0) * { * throw std::system_error(errno, std::generic_category(), * "our msg"); * } * return r; * } * * To make that more succinct, we can use CHECK_ERRNO: * * int our_cpp_call(const char* path) * { * return CHECK_ERRNO(c_call(path), "our msg"); * } * * @param[in] expr - The expression returning an errno value * @param[in] error_handler - Passed to the doError function * @throws std::system_error (depends on error_handler) for an error case * @return A successful return value based on the function type */ #define CHECK_ERRNO(expr, error_handler) \ [&](auto check_errno_ret) { \ if constexpr (::std::is_pointer_v<decltype(check_errno_ret)>) \ { \ if (check_errno_ret == nullptr) \ ::stdplus::util::doError(errno, (error_handler)); \ } \ else if constexpr (::std::is_signed_v<decltype(check_errno_ret)>) \ { \ if (check_errno_ret < 0) \ ::stdplus::util::doError(errno, (error_handler)); \ } \ else \ { \ static_assert(::std::is_same_v<decltype(check_errno_ret), int>, \ "Unimplemented check routine"); \ } \ return check_errno_ret; \ }((expr)) /** @brief Wraps common c style error handling for exception throwing * This requires the callee to provide error information in -r. * See CHECK_ERRNO() for details. * * @param[in] expr - The expression returning an negative error value * @param[in] error_handler - Passed to the doError function * @throws std::system_error (depends on error_handler) for an error case * @return A successful return value based on the function type */ #define CHECK_RET(expr, error_handler) \ [&](auto check_ret_ret) { \ if constexpr (::std::is_signed_v<decltype(check_ret_ret)>) \ { \ if (check_ret_ret < 0) \ ::stdplus::util::doError(-check_ret_ret, (error_handler)); \ } \ else \ { \ static_assert(::std::is_same_v<decltype(check_ret_ret), int>, \ "Unimplemented check routine"); \ } \ return check_ret_ret; \ }((expr)) namespace stdplus { namespace util { /** @brief Common pattern used by default for constructing a system exception * @details Most libc or system calls will want to return a generic * system_error when detecting an error in a call. This function * creates that error from the errno and message. * * @param[in] error - * @param[in] msg - * @return The exception passed to a `throw` call. */ inline auto makeSystemError(int error, const char* msg) { return std::system_error(error, std::generic_category(), msg); } /** @brief Turns errors into exceptions for the given error handler * * @param[in] error - The numeric system error code * @param[in] msg - The string used to describe the error * @throws A system exception with the given error and msg */ inline void doError(int error, const char* msg) { throw makeSystemError(error, msg); } inline void doError(int error, const std::string& msg) { throw makeSystemError(error, msg.c_str()); } /** @brief Turns errors into exceptions for the given error handler * * @param[in] error - The numeric system error code * @param[in] fun - the function used to throw the error */ template <typename Fun> inline std::enable_if_t<std::is_invocable_v<Fun, int>, void> doError(int error, Fun&& fun) { fun(error); } /** @brief Wraps common c style error handling for exception throwing * This requires the callee to set errno on error. * @details We often have a pattern in our code for checking errors and * propagating up exceptions: * * int c_call(const char* path); * * int our_cpp_call(const char* path) * { * int r = c_call(path); * if (r < 0) * { * throw std::system_error(errno, std::generic_category(), * "our msg"); * } * return r; * } * * To make that more succinct, we can use callCheckErrno: * * int our_cpp_call(const char* path) * { * return callCheckErrno("our msg", c_call, path); * } * * @param[in] msg - The error message displayed when errno is set. * @param[in] func - The wrapped function we invoke * @param[in] args... - The arguments passed to the function * @throws std::system_error for an error case. * @return A successful return value based on the function type */ template <auto(*makeError)(int, const char*) = makeSystemError, typename... Args> inline auto callCheckErrno(const char* msg, Args&&... args) { using Ret = typename std::invoke_result<Args...>::type; if constexpr (std::is_integral_v<Ret> && std::is_signed_v<Ret>) { Ret r = std::invoke(std::forward<Args>(args)...); if (r < 0) throw makeError(errno, msg); return r; } else if constexpr (std::is_pointer_v<Ret>) { Ret r = std::invoke(std::forward<Args>(args)...); if (r == nullptr) throw makeError(errno, msg); return r; } else { static_assert(std::is_same_v<Ret, int>, "Unimplemented check routine"); } } template <auto(*makeError)(int, const char*) = makeSystemError, typename... Args> inline auto callCheckErrno(const std::string& msg, Args&&... args) { return callCheckErrno(msg.c_str(), std::forward<Args>(args)...); } /** @brief Wraps common c style error handling for exception throwing * This requires the callee to provide error information in -r. * See callCheckErrno() for details. * * @param[in] msg - The error message displayed when errno is set. * @param[in] func - The wrapped function we invoke * @param[in] args... - The arguments passed to the function * @throws std::system_error for an error case. * @return A successful return value based on the function type */ template <auto(*makeError)(int, const char*) = makeSystemError, typename... Args> inline auto callCheckRet(const char* msg, Args&&... args) { using Ret = typename std::invoke_result<Args...>::type; if constexpr (std::is_integral_v<Ret> && std::is_signed_v<Ret>) { Ret r = std::invoke(std::forward<Args>(args)...); if (r < 0) throw makeError(-r, msg); return r; } else { static_assert(std::is_same_v<Ret, int>, "Unimplemented check routine"); } } template <auto(*makeError)(int, const char*) = makeSystemError, typename... Args> inline auto callCheckRet(const std::string& msg, Args&&... args) { return callCheckRet(msg.c_str(), std::forward<Args>(args)...); } } // namespace util } // namespace stdplus <|endoftext|>
<commit_before>#define RAINY_RENDERER_EXPORT #include "Renderer.h" #include <fstream> #include <algorithm> #include "common.h" #include "Vector3.h" #include "material.h" #include "Scene.h" namespace rainy { const Color Renderer::backgroundColor = Color(); const int Renderer::maxDepth = 5; const int Renderer::depthLimit = 64; Renderer::Renderer(int width, int height, int samples, int supsamples) : _width(width) , _height(height) , _samplePerPixel(samples) , _supersamplePerAxis(supsamples) { } Renderer::Renderer(const Renderer& renderer) : _width(renderer._width) , _height(renderer._height) , _samplePerPixel(renderer._samplePerPixel) , _supersamplePerAxis(renderer._supersamplePerAxis) { } Renderer::~Renderer() { } Renderer& Renderer::operator=(const Renderer& renderer) { this->_width = renderer._width; this->_height = renderer._height; this->_samplePerPixel = renderer._samplePerPixel; this->_supersamplePerAxis = renderer._supersamplePerAxis; return *this; } void Renderer::setSize(int width, int height) { this->_width = width; this->_height = height; } void Renderer::setSamples(int samples, int supsamples) { this->_samplePerPixel = samples; this->_supersamplePerAxis = supsamples; } int Renderer::render() { // Camera position const Vector3 cameraPos(50.0, 52.0, 220.0); const Vector3 cameraDir = Vector3(0.0, -0.04, -1.0).normalize(); const Vector3 cameraUp(0.0, 1.0, 0.0); // Screen size in world space const double screenWidth = 30.0 * _width / _height; const double screenHeight = 30.0; // Distance to the screen const double distToScreen = 40.0; // Vectors spanning screen const Vector3 screenX = cameraDir.cross(cameraUp).normalize() * screenWidth; const Vector3 screenY = screenX.cross(cameraDir).normalize() * screenHeight; const Vector3 scrrenCenter = cameraPos + cameraDir * distToScreen; Color* image = new Color[_width * _height]; Random rng = Random::getRNG(); ompfor (int y = 0; y < _height; y++) { std::cout << "Row: " << y << " is processing..." << std::endl; for (int x = 0; x < _width; x++) { const int pixelIndex = (_height - y - 1) * _width + x; for (int sy = 0; sy < _supersamplePerAxis; sy++) { for (int sx = 0; sx < _supersamplePerAxis; sx++) { Color accum; for (int s = 0; s < _samplePerPixel; s++) { const double rate = (1.0 / _supersamplePerAxis); const double rx = sx * rate + rate / 2.0; const double ry = sy * rate + rate / 2.0; const Vector3 screenPos = scrrenCenter + screenX * ((rx + x) / _width - 0.5) + screenY * ((ry + y) / _height - 0.5); const Vector3 rayDirection = (screenPos - cameraPos).normalize(); accum += radiance(Ray(cameraPos, rayDirection), rng, 0) / (_samplePerPixel * _supersamplePerAxis * _supersamplePerAxis); } image[pixelIndex] += accum; } } } } savePPM("image.ppm", image, _width, _height); delete[] image; return 0; } Color Renderer::radiance(const Ray& ray, Random& rng, const int depth) { Intersection intersection; // NOT intersect the scene if (!intersectScene(ray, intersection)) { return backgroundColor; } const Sphere& currentObject = spheres[intersection.objectId()]; const HitPoint& hitpoint = intersection.hitPoint(); const Vector3 orientNormal = hitpoint.normal().dot(ray.direction()) < 0.0 ? hitpoint.normal() : (-1.0 * hitpoint.normal()); double rouletteProb =std::max(currentObject.color().x(), std::max(currentObject.color().y(), currentObject.color().z())); if (depth > depthLimit) { rouletteProb *= pow(0.5, depth - depthLimit); } if (depth > maxDepth) { if (rng.randReal() > rouletteProb) { return currentObject.emission(); } } else { rouletteProb = 1.0; } Color incomingRad; Color weight = Color(1.0, 0.0, 0.0); if (currentObject.reftype() == REFLECTION_DIFFUSE) { Vector3 u, v, w; w = orientNormal; if (abs(w.x()) > EPS) { u = Vector3(0.0, 1.0, 0.0).cross(w).normalize(); } else { u = Vector3(1.0, 0.0, 0.0).cross(w).normalize(); } v = w.cross(u); const double r1 = 2.0 * PI * rng.randReal(); const double r2 = rng.randReal(); const double r2s = sqrt(r2); Vector3 nextDir = (u * cos(r1) * r2s + v * sin(r1) * r2s + w * sqrt(1.0 - r2)).normalize(); incomingRad = radiance(Ray(hitpoint.position(), nextDir), rng, depth + 1); weight = currentObject.color() / rouletteProb; } else if (currentObject.reftype() == REFLECTION_SPECULAR) { Vector3 nextDir = ray.direction() - (2.0 * hitpoint.normal().dot(ray.direction())) * hitpoint.normal(); incomingRad = radiance(Ray(hitpoint.position(), nextDir), rng, depth + 1); weight = currentObject.color() / rouletteProb; } else if (currentObject.reftype() == REFLECTION_REFRACTION) { Vector3 reflectDir = ray.direction() - (2.0 * hitpoint.normal().dot(ray.direction())) * hitpoint.normal(); const Ray reflectRay = Ray(hitpoint.position(), reflectDir); // Incoming or outgoing const bool isIncoming = hitpoint.normal().dot(orientNormal) > 0.0; // Snell's rule const double nc = 1.0; const double nt = indexOfRef; const double nnt = isIncoming ? nc / nt : nt / nc; const double ddn = ray.direction().dot(orientNormal); const double cos2t = 1.0 - nnt * nnt * (1.0 - ddn * ddn); if (cos2t < 0.0) { // Total reflection incomingRad = radiance(reflectRay, rng, depth + 1); weight += currentObject.color() / rouletteProb; } else { Vector3 refractDir = (ray.direction() * nnt - hitpoint.normal() * (isIncoming ? 1.0 : -1.0) * (ddn * nnt + sqrt(cos2t))).normalize(); const Ray refractRay = Ray(hitpoint.position(), refractDir); // Schlick's approximation of Fresnel coefficient const double a = nt - nc; const double b = nt + nc; const double R0 = (a * a) / (b * b); const double c = 1.0 - (isIncoming ? -ddn : - refractDir.dot(orientNormal)); const double Re = R0 + (1.0 - R0) * pow(c, 5.0); const double nnt2 = pow(isIncoming ? nc / nt : nt / nc, 2.0); const double Tr = (1.0 - Re) * nnt2; const double prob = 0.25 + 0.5 * Re; if (depth > 2) { if (rng.randReal() < prob) { incomingRad = radiance(reflectRay, rng, depth + 1) * Re; weight = currentObject.color() / (prob * rouletteProb); } else { incomingRad = radiance(refractRay, rng, depth + 1) * Tr; weight = currentObject.color() / ((1.0 - prob) * rouletteProb); } } else { incomingRad = radiance(reflectRay, rng, depth + 1) * Re + radiance(refractRay, rng, depth + 1) * Tr; weight = currentObject.color() / rouletteProb; } } } return currentObject.emission() + weight.cwiseMultiply(incomingRad); } void Renderer::savePPM(std::string filename, Color* image, int width, int height) { std::ofstream ofs(filename, std::ios::out); ofs << "P3" << std::endl; ofs << width << " " << height << " 255" << std::endl; for (int i = 0; i < width * height; i++) { int r = std::max(0, std::min((int)image[i].x(), 255)); int g = std::max(0, std::min((int)image[i].y(), 255)); int b = std::max(0, std::min((int)image[i].z(), 255)); ofs << r << " " << g << " " << b << std::endl; } ofs.close(); } } <commit_msg>Add iostream to file-related processes.<commit_after>#define RAINY_RENDERER_EXPORT #include "Renderer.h" #include <iostream> #include <fstream> #include <algorithm> #include "common.h" #include "Vector3.h" #include "material.h" #include "Scene.h" namespace rainy { const Color Renderer::backgroundColor = Color(); const int Renderer::maxDepth = 5; const int Renderer::depthLimit = 64; Renderer::Renderer(int width, int height, int samples, int supsamples) : _width(width) , _height(height) , _samplePerPixel(samples) , _supersamplePerAxis(supsamples) { } Renderer::Renderer(const Renderer& renderer) : _width(renderer._width) , _height(renderer._height) , _samplePerPixel(renderer._samplePerPixel) , _supersamplePerAxis(renderer._supersamplePerAxis) { } Renderer::~Renderer() { } Renderer& Renderer::operator=(const Renderer& renderer) { this->_width = renderer._width; this->_height = renderer._height; this->_samplePerPixel = renderer._samplePerPixel; this->_supersamplePerAxis = renderer._supersamplePerAxis; return *this; } void Renderer::setSize(int width, int height) { this->_width = width; this->_height = height; } void Renderer::setSamples(int samples, int supsamples) { this->_samplePerPixel = samples; this->_supersamplePerAxis = supsamples; } int Renderer::render() { // Camera position const Vector3 cameraPos(50.0, 52.0, 220.0); const Vector3 cameraDir = Vector3(0.0, -0.04, -1.0).normalize(); const Vector3 cameraUp(0.0, 1.0, 0.0); // Screen size in world space const double screenWidth = 30.0 * _width / _height; const double screenHeight = 30.0; // Distance to the screen const double distToScreen = 40.0; // Vectors spanning screen const Vector3 screenX = cameraDir.cross(cameraUp).normalize() * screenWidth; const Vector3 screenY = screenX.cross(cameraDir).normalize() * screenHeight; const Vector3 scrrenCenter = cameraPos + cameraDir * distToScreen; Color* image = new Color[_width * _height]; Random rng = Random::getRNG(); ompfor (int y = 0; y < _height; y++) { std::cout << "Row: " << y << " is processing..." << std::endl; for (int x = 0; x < _width; x++) { const int pixelIndex = (_height - y - 1) * _width + x; for (int sy = 0; sy < _supersamplePerAxis; sy++) { for (int sx = 0; sx < _supersamplePerAxis; sx++) { Color accum; for (int s = 0; s < _samplePerPixel; s++) { const double rate = (1.0 / _supersamplePerAxis); const double rx = sx * rate + rate / 2.0; const double ry = sy * rate + rate / 2.0; const Vector3 screenPos = scrrenCenter + screenX * ((rx + x) / _width - 0.5) + screenY * ((ry + y) / _height - 0.5); const Vector3 rayDirection = (screenPos - cameraPos).normalize(); accum += radiance(Ray(cameraPos, rayDirection), rng, 0) / (_samplePerPixel * _supersamplePerAxis * _supersamplePerAxis); } image[pixelIndex] += accum; } } } } savePPM("image.ppm", image, _width, _height); delete[] image; return 0; } Color Renderer::radiance(const Ray& ray, Random& rng, const int depth) { Intersection intersection; // NOT intersect the scene if (!intersectScene(ray, intersection)) { return backgroundColor; } const Sphere& currentObject = spheres[intersection.objectId()]; const HitPoint& hitpoint = intersection.hitPoint(); const Vector3 orientNormal = hitpoint.normal().dot(ray.direction()) < 0.0 ? hitpoint.normal() : (-1.0 * hitpoint.normal()); double rouletteProb =std::max(currentObject.color().x(), std::max(currentObject.color().y(), currentObject.color().z())); if (depth > depthLimit) { rouletteProb *= pow(0.5, depth - depthLimit); } if (depth > maxDepth) { if (rng.randReal() > rouletteProb) { return currentObject.emission(); } } else { rouletteProb = 1.0; } Color incomingRad; Color weight = Color(1.0, 0.0, 0.0); if (currentObject.reftype() == REFLECTION_DIFFUSE) { Vector3 u, v, w; w = orientNormal; if (abs(w.x()) > EPS) { u = Vector3(0.0, 1.0, 0.0).cross(w).normalize(); } else { u = Vector3(1.0, 0.0, 0.0).cross(w).normalize(); } v = w.cross(u); const double r1 = 2.0 * PI * rng.randReal(); const double r2 = rng.randReal(); const double r2s = sqrt(r2); Vector3 nextDir = (u * cos(r1) * r2s + v * sin(r1) * r2s + w * sqrt(1.0 - r2)).normalize(); incomingRad = radiance(Ray(hitpoint.position(), nextDir), rng, depth + 1); weight = currentObject.color() / rouletteProb; } else if (currentObject.reftype() == REFLECTION_SPECULAR) { Vector3 nextDir = ray.direction() - (2.0 * hitpoint.normal().dot(ray.direction())) * hitpoint.normal(); incomingRad = radiance(Ray(hitpoint.position(), nextDir), rng, depth + 1); weight = currentObject.color() / rouletteProb; } else if (currentObject.reftype() == REFLECTION_REFRACTION) { Vector3 reflectDir = ray.direction() - (2.0 * hitpoint.normal().dot(ray.direction())) * hitpoint.normal(); const Ray reflectRay = Ray(hitpoint.position(), reflectDir); // Incoming or outgoing const bool isIncoming = hitpoint.normal().dot(orientNormal) > 0.0; // Snell's rule const double nc = 1.0; const double nt = indexOfRef; const double nnt = isIncoming ? nc / nt : nt / nc; const double ddn = ray.direction().dot(orientNormal); const double cos2t = 1.0 - nnt * nnt * (1.0 - ddn * ddn); if (cos2t < 0.0) { // Total reflection incomingRad = radiance(reflectRay, rng, depth + 1); weight += currentObject.color() / rouletteProb; } else { Vector3 refractDir = (ray.direction() * nnt - hitpoint.normal() * (isIncoming ? 1.0 : -1.0) * (ddn * nnt + sqrt(cos2t))).normalize(); const Ray refractRay = Ray(hitpoint.position(), refractDir); // Schlick's approximation of Fresnel coefficient const double a = nt - nc; const double b = nt + nc; const double R0 = (a * a) / (b * b); const double c = 1.0 - (isIncoming ? -ddn : - refractDir.dot(orientNormal)); const double Re = R0 + (1.0 - R0) * pow(c, 5.0); const double nnt2 = pow(isIncoming ? nc / nt : nt / nc, 2.0); const double Tr = (1.0 - Re) * nnt2; const double prob = 0.25 + 0.5 * Re; if (depth > 2) { if (rng.randReal() < prob) { incomingRad = radiance(reflectRay, rng, depth + 1) * Re; weight = currentObject.color() / (prob * rouletteProb); } else { incomingRad = radiance(refractRay, rng, depth + 1) * Tr; weight = currentObject.color() / ((1.0 - prob) * rouletteProb); } } else { incomingRad = radiance(reflectRay, rng, depth + 1) * Re + radiance(refractRay, rng, depth + 1) * Tr; weight = currentObject.color() / rouletteProb; } } } return currentObject.emission() + weight.cwiseMultiply(incomingRad); } void Renderer::savePPM(std::string filename, Color* image, int width, int height) { std::ofstream ofs(filename, std::ios::out); ofs << "P3" << std::endl; ofs << width << " " << height << " 255" << std::endl; for (int i = 0; i < width * height; i++) { int r = std::max(0, std::min((int)image[i].x(), 255)); int g = std::max(0, std::min((int)image[i].y(), 255)); int b = std::max(0, std::min((int)image[i].z(), 255)); ofs << r << " " << g << " " << b << std::endl; } ofs.close(); } } <|endoftext|>
<commit_before>/* Copyright (C) 2007-2008 Tanguy Krotoff <tkrotoff@gmail.com> Copyright (C) 2008 Lukas Durfina <lukas.durfina@gmail.com> Copyright (C) 2009 Fathi Boudra <fabo@kde.org> Copyright (C) 2009-2011 vlc-phonon AUTHORS Copyright (C) 2011 Harald Sitter <sitter@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 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, see <http://www.gnu.org/licenses/>. */ #include "backend.h" #include <QtCore/QLatin1Literal> #include <QtCore/QtPlugin> #include <QtCore/QVariant> #include <QtGui/QMessageBox> #include <phonon/GlobalDescriptionContainer> #ifdef PHONON_PULSESUPPORT #include <phonon/pulsesupport.h> #endif #include <vlc/libvlc_version.h> #include "audio/audiooutput.h" #include "audio/audiodataoutput.h" #include "devicemanager.h" #include "effect.h" #include "effectmanager.h" #include "mediaobject.h" #include "sinknode.h" #include "utils/debug.h" #include "utils/libvlc.h" //#include "video/videodataoutput.h" #include "video/videowidget.h" Q_EXPORT_PLUGIN2(phonon_vlc, Phonon::VLC::Backend) namespace Phonon { namespace VLC { Backend *Backend::self; Backend::Backend(QObject *parent, const QVariantList &) : QObject(parent) , m_deviceManager(0) , m_effectManager(0) { self = this; // Backend information properties setProperty("identifier", QLatin1String("phonon_vlc")); setProperty("backendName", QLatin1String("VLC")); setProperty("backendComment", QLatin1String("VLC backend for Phonon")); setProperty("backendVersion", QLatin1String(PHONON_VLC_VERSION)); setProperty("backendIcon", QLatin1String("vlc")); setProperty("backendWebsite", QLatin1String("https://projects.kde.org/projects/kdesupport/phonon/phonon-vlc")); // Check if we should enable debug output int debugLevel = qgetenv("PHONON_BACKEND_DEBUG").toInt(); if (debugLevel > 3) // 3 is maximum debugLevel = 3; Debug::setMinimumDebugLevel((Debug::DebugLevel)((int) Debug::DEBUG_NONE - 1 - debugLevel)); // Actual libVLC initialisation if (LibVLC::init()) { debug() << "Using VLC version %0" << libvlc_get_version(); } else { #ifdef __GNUC__ #warning TODO - this error message is about as useful as a cooling unit in the arctic #warning TODO - supposedly Phonon VLC should not make kabooom if libvlc fails to init, probably impossible though #endif QMessageBox msg; msg.setIcon(QMessageBox::Critical); msg.setWindowTitle(tr("LibVLC Failed to Initialize")); msg.setText(tr("Phonon's VLC backend failed to start." "\n\n" "This usually means a problem with your VLC installation," " please report a bug with your distributor.")); msg.setDetailedText(LibVLC::errorMessage()); msg.exec(); fatal() << "Phonon::VLC::vlcInit: Failed to initialize VLC"; } m_deviceManager = new DeviceManager(this); m_effectManager = new EffectManager(this); #ifdef PHONON_PULSESUPPORT // Initialise PulseAudio support PulseSupport *pulse = PulseSupport::getInstance(); pulse->enable(); connect(pulse, SIGNAL(objectDescriptionChanged(ObjectDescriptionType)), SIGNAL(objectDescriptionChanged(ObjectDescriptionType))); #endif } Backend::~Backend() { if (LibVLC::self) delete LibVLC::self; if (GlobalAudioChannels::self) delete GlobalAudioChannels::self; if (GlobalSubtitles::self) delete GlobalSubtitles::self; #ifdef PHONON_PULSESUPPORT PulseSupport::shutdown(); #endif } QObject *Backend::createObject(BackendInterface::Class c, QObject *parent, const QList<QVariant> &args) { if (!LibVLC::self || !libvlc) return 0; switch (c) { case MediaObjectClass: return new MediaObject(parent); case AudioOutputClass: return new AudioOutput(parent); #ifdef __GNUC__ #warning VLC 2.0 broke sout/transcode/smem -> ADO #endif #if (LIBVLC_VERSION_INT < LIBVLC_VERSION(2, 0, 0, 0)) || (LIBVLC_VERSION_INT >= LIBVLC_VERSION(2, 1, 0, 0)) case AudioDataOutputClass: return new AudioDataOutput(parent); #endif case EffectClass: return new Effect(m_effectManager, args[0].toInt(), parent); case VideoWidgetClass: return new VideoWidget(qobject_cast<QWidget *>(parent)); } warning() << "Backend class" << c << "is not supported by Phonon VLC :("; return 0; } QStringList Backend::availableMimeTypes() const { if (m_supportedMimeTypes.isEmpty()) { const_cast<Backend *>(this)->m_supportedMimeTypes << QLatin1String("application/ogg") << QLatin1String("application/x-ogg") << QLatin1String("application/vnd.rn-realmedia") << QLatin1String("application/x-annodex") << QLatin1String("application/x-flash-video") << QLatin1String("application/x-quicktimeplayer") << QLatin1String("application/x-extension-mp4") << QLatin1String("audio/168sv") << QLatin1String("audio/3gpp") << QLatin1String("audio/3gpp2") << QLatin1String("audio/8svx") << QLatin1String("audio/aiff") << QLatin1String("audio/amr") << QLatin1String("audio/amr-wb") << QLatin1String("audio/basic") << QLatin1String("audio/mp3") << QLatin1String("audio/mp4") << QLatin1String("audio/midi") << QLatin1String("audio/mpeg") << QLatin1String("audio/mpeg2") << QLatin1String("audio/mpeg3") << QLatin1String("audio/vnd.rn-realaudio") << QLatin1String("audio/vnd.rn-realmedia") << QLatin1String("audio/wav") << QLatin1String("audio/webm") << QLatin1String("audio/x-16sv") << QLatin1String("audio/x-8svx") << QLatin1String("audio/x-aiff") << QLatin1String("audio/x-basic") << QLatin1String("audio/x-it") << QLatin1String("audio/x-m4a") << QLatin1String("audio/x-matroska") << QLatin1String("audio/x-mp3") << QLatin1String("audio/x-mpeg") << QLatin1String("audio/x-mpeg2") << QLatin1String("audio/x-mpeg3") << QLatin1String("audio/x-mpegurl") << QLatin1String("audio/x-ms-wma") << QLatin1String("audio/x-ogg") << QLatin1String("audio/x-pn-aiff") << QLatin1String("audio/x-pn-au") << QLatin1String("audio/x-pn-realaudio-plugin") << QLatin1String("audio/x-pn-wav") << QLatin1String("audio/x-pn-windows-acm") << QLatin1String("audio/x-real-audio") << QLatin1String("audio/x-realaudio") << QLatin1String("audio/x-s3m") << QLatin1String("audio/x-speex+ogg") << QLatin1String("audio/x-vorbis+ogg") << QLatin1String("audio/x-wav") << QLatin1String("audio/x-xm") << QLatin1String("image/ilbm") << QLatin1String("image/png") << QLatin1String("image/x-ilbm") << QLatin1String("image/x-png") << QLatin1String("video/3gpp") << QLatin1String("video/3gpp2") << QLatin1String("video/anim") << QLatin1String("video/avi") << QLatin1String("video/divx") << QLatin1String("video/flv") << QLatin1String("video/mkv") << QLatin1String("video/mng") << QLatin1String("video/mp4") << QLatin1String("video/mpeg") << QLatin1String("video/mpeg-system") << QLatin1String("video/mpg") << QLatin1String("video/msvideo") << QLatin1String("video/ogg") << QLatin1String("video/quicktime") << QLatin1String("video/webm") << QLatin1String("video/x-anim") << QLatin1String("video/x-flic") << QLatin1String("video/x-flv") << QLatin1String("video/x-matroska") << QLatin1String("video/x-mng") << QLatin1String("video/x-m4v") << QLatin1String("video/x-mpeg") << QLatin1String("video/x-mpeg-system") << QLatin1String("video/x-ms-asf") << QLatin1String("video/x-ms-wma") << QLatin1String("video/x-ms-wmv") << QLatin1String("video/x-ms-wvx") << QLatin1String("video/x-msvideo") << QLatin1String("video/x-quicktime") << QLatin1String("audio/x-flac") << QLatin1String("audio/x-ape"); } return m_supportedMimeTypes; } QList<int> Backend::objectDescriptionIndexes(ObjectDescriptionType type) const { QList<int> list; switch (type) { case Phonon::AudioChannelType: { list << GlobalAudioChannels::instance()->globalIndexes(); } break; case Phonon::AudioOutputDeviceType: case Phonon::AudioCaptureDeviceType: case Phonon::VideoCaptureDeviceType: { return deviceManager()->deviceIds(type); } break; case Phonon::EffectType: { QList<EffectInfo *> effectList = effectManager()->effects(); for (int eff = 0; eff < effectList.size(); ++eff) { list.append(eff); } } break; case Phonon::SubtitleType: { list << GlobalSubtitles::instance()->globalIndexes(); } break; } return list; } QHash<QByteArray, QVariant> Backend::objectDescriptionProperties(ObjectDescriptionType type, int index) const { QHash<QByteArray, QVariant> ret; switch (type) { case Phonon::AudioChannelType: { const AudioChannelDescription description = GlobalAudioChannels::instance()->fromIndex(index); ret.insert("name", description.name()); ret.insert("description", description.description()); } break; case Phonon::AudioOutputDeviceType: case Phonon::AudioCaptureDeviceType: case Phonon::VideoCaptureDeviceType: { // Index should be unique, even for different categories return deviceManager()->deviceProperties(index); } break; case Phonon::EffectType: { QList<EffectInfo *> effectList = effectManager()->effects(); if (index >= 0 && index <= effectList.size()) { const EffectInfo *effect = effectList[ index ]; ret.insert("name", effect->name()); ret.insert("description", effect->description()); ret.insert("author", effect->author()); } else { Q_ASSERT(1); // Since we use list position as ID, this should not happen } } break; case Phonon::SubtitleType: { const SubtitleDescription description = GlobalSubtitles::instance()->fromIndex(index); ret.insert("name", description.name()); ret.insert("description", description.description()); ret.insert("type", description.property("type")); } break; } return ret; } bool Backend::startConnectionChange(QSet<QObject *> objects) { //FIXME foreach(QObject * object, objects) { debug() << "Object:" << object->metaObject()->className(); } // There is nothing we can do but hope the connection changes will not take too long // so that buffers would underrun // But we should be pretty safe the way xine works by not doing anything here. return true; } bool Backend::connectNodes(QObject *source, QObject *sink) { debug() << "Backend connected" << source->metaObject()->className() << "to" << sink->metaObject()->className(); SinkNode *sinkNode = dynamic_cast<SinkNode *>(sink); if (sinkNode) { MediaObject *mediaObject = qobject_cast<MediaObject *>(source); if (mediaObject) { // Connect the SinkNode to a MediaObject sinkNode->connectToMediaObject(mediaObject); return true; } /* Effect *effect = qobject_cast<Effect *>(source); if (effect) { // FIXME connect the effect return true; } */ } warning() << "Linking" << source->metaObject()->className() << "to" << sink->metaObject()->className() << "failed"; return false; } bool Backend::disconnectNodes(QObject *source, QObject *sink) { SinkNode *sinkNode = dynamic_cast<SinkNode *>(sink); if (sinkNode) { MediaObject *const mediaObject = qobject_cast<MediaObject *>(source); if (mediaObject) { // Disconnect the SinkNode from a MediaObject sinkNode->disconnectFromMediaObject(mediaObject); return true; } /* Effect *effect = qobject_cast<Effect *>(source); if (effect) { // FIXME disconnect the effect return true; } */ } return false; } bool Backend::endConnectionChange(QSet<QObject *> objects) { foreach(QObject *object, objects) { debug() << "Object:" << object->metaObject()->className(); } return true; } DeviceManager *Backend::deviceManager() const { return m_deviceManager; } EffectManager *Backend::effectManager() const { return m_effectManager; } } // namespace VLC } // namespace Phonon <commit_msg>AudioDataOutput also works with VLC 2.0.2<commit_after>/* Copyright (C) 2007-2008 Tanguy Krotoff <tkrotoff@gmail.com> Copyright (C) 2008 Lukas Durfina <lukas.durfina@gmail.com> Copyright (C) 2009 Fathi Boudra <fabo@kde.org> Copyright (C) 2009-2011 vlc-phonon AUTHORS Copyright (C) 2011 Harald Sitter <sitter@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 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, see <http://www.gnu.org/licenses/>. */ #include "backend.h" #include <QtCore/QLatin1Literal> #include <QtCore/QtPlugin> #include <QtCore/QVariant> #include <QtGui/QMessageBox> #include <phonon/GlobalDescriptionContainer> #ifdef PHONON_PULSESUPPORT #include <phonon/pulsesupport.h> #endif #include <vlc/libvlc_version.h> #include "audio/audiooutput.h" #include "audio/audiodataoutput.h" #include "devicemanager.h" #include "effect.h" #include "effectmanager.h" #include "mediaobject.h" #include "sinknode.h" #include "utils/debug.h" #include "utils/libvlc.h" //#include "video/videodataoutput.h" #include "video/videowidget.h" Q_EXPORT_PLUGIN2(phonon_vlc, Phonon::VLC::Backend) namespace Phonon { namespace VLC { Backend *Backend::self; Backend::Backend(QObject *parent, const QVariantList &) : QObject(parent) , m_deviceManager(0) , m_effectManager(0) { self = this; // Backend information properties setProperty("identifier", QLatin1String("phonon_vlc")); setProperty("backendName", QLatin1String("VLC")); setProperty("backendComment", QLatin1String("VLC backend for Phonon")); setProperty("backendVersion", QLatin1String(PHONON_VLC_VERSION)); setProperty("backendIcon", QLatin1String("vlc")); setProperty("backendWebsite", QLatin1String("https://projects.kde.org/projects/kdesupport/phonon/phonon-vlc")); // Check if we should enable debug output int debugLevel = qgetenv("PHONON_BACKEND_DEBUG").toInt(); if (debugLevel > 3) // 3 is maximum debugLevel = 3; Debug::setMinimumDebugLevel((Debug::DebugLevel)((int) Debug::DEBUG_NONE - 1 - debugLevel)); // Actual libVLC initialisation if (LibVLC::init()) { debug() << "Using VLC version %0" << libvlc_get_version(); } else { #ifdef __GNUC__ #warning TODO - this error message is about as useful as a cooling unit in the arctic #warning TODO - supposedly Phonon VLC should not make kabooom if libvlc fails to init, probably impossible though #endif QMessageBox msg; msg.setIcon(QMessageBox::Critical); msg.setWindowTitle(tr("LibVLC Failed to Initialize")); msg.setText(tr("Phonon's VLC backend failed to start." "\n\n" "This usually means a problem with your VLC installation," " please report a bug with your distributor.")); msg.setDetailedText(LibVLC::errorMessage()); msg.exec(); fatal() << "Phonon::VLC::vlcInit: Failed to initialize VLC"; } m_deviceManager = new DeviceManager(this); m_effectManager = new EffectManager(this); #ifdef PHONON_PULSESUPPORT // Initialise PulseAudio support PulseSupport *pulse = PulseSupport::getInstance(); pulse->enable(); connect(pulse, SIGNAL(objectDescriptionChanged(ObjectDescriptionType)), SIGNAL(objectDescriptionChanged(ObjectDescriptionType))); #endif } Backend::~Backend() { if (LibVLC::self) delete LibVLC::self; if (GlobalAudioChannels::self) delete GlobalAudioChannels::self; if (GlobalSubtitles::self) delete GlobalSubtitles::self; #ifdef PHONON_PULSESUPPORT PulseSupport::shutdown(); #endif } QObject *Backend::createObject(BackendInterface::Class c, QObject *parent, const QList<QVariant> &args) { if (!LibVLC::self || !libvlc) return 0; switch (c) { case MediaObjectClass: return new MediaObject(parent); case AudioOutputClass: return new AudioOutput(parent); #ifdef __GNUC__ #warning VLC 2.0 broke sout/transcode/smem -> ADO #endif #if (LIBVLC_VERSION_INT < LIBVLC_VERSION(2, 0, 0, 0)) || (LIBVLC_VERSION_INT >= LIBVLC_VERSION(2, 0, 2, 0)) case AudioDataOutputClass: return new AudioDataOutput(parent); #endif case EffectClass: return new Effect(m_effectManager, args[0].toInt(), parent); case VideoWidgetClass: return new VideoWidget(qobject_cast<QWidget *>(parent)); } warning() << "Backend class" << c << "is not supported by Phonon VLC :("; return 0; } QStringList Backend::availableMimeTypes() const { if (m_supportedMimeTypes.isEmpty()) { const_cast<Backend *>(this)->m_supportedMimeTypes << QLatin1String("application/ogg") << QLatin1String("application/x-ogg") << QLatin1String("application/vnd.rn-realmedia") << QLatin1String("application/x-annodex") << QLatin1String("application/x-flash-video") << QLatin1String("application/x-quicktimeplayer") << QLatin1String("application/x-extension-mp4") << QLatin1String("audio/168sv") << QLatin1String("audio/3gpp") << QLatin1String("audio/3gpp2") << QLatin1String("audio/8svx") << QLatin1String("audio/aiff") << QLatin1String("audio/amr") << QLatin1String("audio/amr-wb") << QLatin1String("audio/basic") << QLatin1String("audio/mp3") << QLatin1String("audio/mp4") << QLatin1String("audio/midi") << QLatin1String("audio/mpeg") << QLatin1String("audio/mpeg2") << QLatin1String("audio/mpeg3") << QLatin1String("audio/vnd.rn-realaudio") << QLatin1String("audio/vnd.rn-realmedia") << QLatin1String("audio/wav") << QLatin1String("audio/webm") << QLatin1String("audio/x-16sv") << QLatin1String("audio/x-8svx") << QLatin1String("audio/x-aiff") << QLatin1String("audio/x-basic") << QLatin1String("audio/x-it") << QLatin1String("audio/x-m4a") << QLatin1String("audio/x-matroska") << QLatin1String("audio/x-mp3") << QLatin1String("audio/x-mpeg") << QLatin1String("audio/x-mpeg2") << QLatin1String("audio/x-mpeg3") << QLatin1String("audio/x-mpegurl") << QLatin1String("audio/x-ms-wma") << QLatin1String("audio/x-ogg") << QLatin1String("audio/x-pn-aiff") << QLatin1String("audio/x-pn-au") << QLatin1String("audio/x-pn-realaudio-plugin") << QLatin1String("audio/x-pn-wav") << QLatin1String("audio/x-pn-windows-acm") << QLatin1String("audio/x-real-audio") << QLatin1String("audio/x-realaudio") << QLatin1String("audio/x-s3m") << QLatin1String("audio/x-speex+ogg") << QLatin1String("audio/x-vorbis+ogg") << QLatin1String("audio/x-wav") << QLatin1String("audio/x-xm") << QLatin1String("image/ilbm") << QLatin1String("image/png") << QLatin1String("image/x-ilbm") << QLatin1String("image/x-png") << QLatin1String("video/3gpp") << QLatin1String("video/3gpp2") << QLatin1String("video/anim") << QLatin1String("video/avi") << QLatin1String("video/divx") << QLatin1String("video/flv") << QLatin1String("video/mkv") << QLatin1String("video/mng") << QLatin1String("video/mp4") << QLatin1String("video/mpeg") << QLatin1String("video/mpeg-system") << QLatin1String("video/mpg") << QLatin1String("video/msvideo") << QLatin1String("video/ogg") << QLatin1String("video/quicktime") << QLatin1String("video/webm") << QLatin1String("video/x-anim") << QLatin1String("video/x-flic") << QLatin1String("video/x-flv") << QLatin1String("video/x-matroska") << QLatin1String("video/x-mng") << QLatin1String("video/x-m4v") << QLatin1String("video/x-mpeg") << QLatin1String("video/x-mpeg-system") << QLatin1String("video/x-ms-asf") << QLatin1String("video/x-ms-wma") << QLatin1String("video/x-ms-wmv") << QLatin1String("video/x-ms-wvx") << QLatin1String("video/x-msvideo") << QLatin1String("video/x-quicktime") << QLatin1String("audio/x-flac") << QLatin1String("audio/x-ape"); } return m_supportedMimeTypes; } QList<int> Backend::objectDescriptionIndexes(ObjectDescriptionType type) const { QList<int> list; switch (type) { case Phonon::AudioChannelType: { list << GlobalAudioChannels::instance()->globalIndexes(); } break; case Phonon::AudioOutputDeviceType: case Phonon::AudioCaptureDeviceType: case Phonon::VideoCaptureDeviceType: { return deviceManager()->deviceIds(type); } break; case Phonon::EffectType: { QList<EffectInfo *> effectList = effectManager()->effects(); for (int eff = 0; eff < effectList.size(); ++eff) { list.append(eff); } } break; case Phonon::SubtitleType: { list << GlobalSubtitles::instance()->globalIndexes(); } break; } return list; } QHash<QByteArray, QVariant> Backend::objectDescriptionProperties(ObjectDescriptionType type, int index) const { QHash<QByteArray, QVariant> ret; switch (type) { case Phonon::AudioChannelType: { const AudioChannelDescription description = GlobalAudioChannels::instance()->fromIndex(index); ret.insert("name", description.name()); ret.insert("description", description.description()); } break; case Phonon::AudioOutputDeviceType: case Phonon::AudioCaptureDeviceType: case Phonon::VideoCaptureDeviceType: { // Index should be unique, even for different categories return deviceManager()->deviceProperties(index); } break; case Phonon::EffectType: { QList<EffectInfo *> effectList = effectManager()->effects(); if (index >= 0 && index <= effectList.size()) { const EffectInfo *effect = effectList[ index ]; ret.insert("name", effect->name()); ret.insert("description", effect->description()); ret.insert("author", effect->author()); } else { Q_ASSERT(1); // Since we use list position as ID, this should not happen } } break; case Phonon::SubtitleType: { const SubtitleDescription description = GlobalSubtitles::instance()->fromIndex(index); ret.insert("name", description.name()); ret.insert("description", description.description()); ret.insert("type", description.property("type")); } break; } return ret; } bool Backend::startConnectionChange(QSet<QObject *> objects) { //FIXME foreach(QObject * object, objects) { debug() << "Object:" << object->metaObject()->className(); } // There is nothing we can do but hope the connection changes will not take too long // so that buffers would underrun // But we should be pretty safe the way xine works by not doing anything here. return true; } bool Backend::connectNodes(QObject *source, QObject *sink) { debug() << "Backend connected" << source->metaObject()->className() << "to" << sink->metaObject()->className(); SinkNode *sinkNode = dynamic_cast<SinkNode *>(sink); if (sinkNode) { MediaObject *mediaObject = qobject_cast<MediaObject *>(source); if (mediaObject) { // Connect the SinkNode to a MediaObject sinkNode->connectToMediaObject(mediaObject); return true; } /* Effect *effect = qobject_cast<Effect *>(source); if (effect) { // FIXME connect the effect return true; } */ } warning() << "Linking" << source->metaObject()->className() << "to" << sink->metaObject()->className() << "failed"; return false; } bool Backend::disconnectNodes(QObject *source, QObject *sink) { SinkNode *sinkNode = dynamic_cast<SinkNode *>(sink); if (sinkNode) { MediaObject *const mediaObject = qobject_cast<MediaObject *>(source); if (mediaObject) { // Disconnect the SinkNode from a MediaObject sinkNode->disconnectFromMediaObject(mediaObject); return true; } /* Effect *effect = qobject_cast<Effect *>(source); if (effect) { // FIXME disconnect the effect return true; } */ } return false; } bool Backend::endConnectionChange(QSet<QObject *> objects) { foreach(QObject *object, objects) { debug() << "Object:" << object->metaObject()->className(); } return true; } DeviceManager *Backend::deviceManager() const { return m_deviceManager; } EffectManager *Backend::effectManager() const { return m_effectManager; } } // namespace VLC } // namespace Phonon <|endoftext|>
<commit_before>/* * Copyright 2015 Aldebaran * * 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. * */ /* * LOCAL includes */ #include "moveto.hpp" /* * ROS includes */ //#include <tf/transform_datatypes.h> #include <tf2_geometry_msgs/tf2_geometry_msgs.h> #include "../helpers/transform_helpers.hpp" namespace naoqi { namespace subscriber { MovetoSubscriber::MovetoSubscriber( const std::string& name, const std::string& topic, const qi::SessionPtr& session, const boost::shared_ptr<tf2_ros::Buffer>& tf2_buffer): BaseSubscriber( name, topic, session ), p_motion_( session->service("ALMotion") ), tf2_buffer_( tf2_buffer ) {} void MovetoSubscriber::reset( ros::NodeHandle& nh ) { sub_moveto_ = nh.subscribe( topic_, 10, &MovetoSubscriber::callback, this ); is_initialized_ = true; } void MovetoSubscriber::callback( const geometry_msgs::PoseStampedConstPtr& pose_msg ) { if ( pose_msg->header.frame_id == "base_footprint" ) { double yaw = helpers::transform::getYaw(pose_msg->pose); std::cout << "going to move x: " << pose_msg->pose.position.x << " y: " << pose_msg->pose.position.y << " z: " << pose_msg->pose.position.z << " yaw: " << yaw << std::endl; p_motion_.async<void>("moveTo", pose_msg->pose.position.x, pose_msg->pose.position.y, yaw); } else{ geometry_msgs::PoseStamped pose_msg_bf; //geometry_msgs::TransformStamped tf_trans; //tf_listenerPtr_->waitForTransform( "/base_footprint", pose_msg->header.frame_id, ros::Time(0), ros::Duration(5) ); bool canTransform = tf2_buffer_->canTransform("base_footprint", pose_msg->header.frame_id, ros::Time(0), ros::Duration(2) ); if (!canTransform) { std::cout << "Cannot transform from " << pose_msg->header.frame_id << " to base_footprint" << std::endl; return; } try { //tf_listenerPtr_->lookupTransform( "/base_footprint", pose_msg->header.frame_id, ros::Time(0), tf_trans); //std::cout << "got a transform " << tf_trans.getOrigin().x() << std::endl; tf2_buffer_->transform( *pose_msg, pose_msg_bf, "base_footprint", ros::Time(0), pose_msg->header.frame_id ); double yaw = helpers::transform::getYaw(pose_msg_bf.pose); std::cout << "odom to move x: " << pose_msg_bf.pose.position.x << " y: " << pose_msg_bf.pose.position.y << " z: " << pose_msg_bf.pose.position.z << " yaw: " << yaw << std::endl; p_motion_.async<void>("moveTo", pose_msg_bf.pose.position.x, pose_msg_bf.pose.position.y, yaw ); } catch( const tf2::LookupException& e) { std::cout << e.what() << std::endl; std::cout << "moveto position in frame_id " << pose_msg->header.frame_id << "is not supported in any other base frame than basefootprint" << std::endl; } catch( const tf2::ExtrapolationException& e) { std::cout << "received an error on the time lookup" << std::endl; } } } } //publisher } // naoqi <commit_msg>Safer moveTo: only odom and base_footprint are accepted as references, and check if yaw is nan<commit_after>/* * Copyright 2015 Aldebaran * * 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. * */ /* * LOCAL includes */ #include "moveto.hpp" /* * ROS includes */ //#include <tf/transform_datatypes.h> #include <tf2_geometry_msgs/tf2_geometry_msgs.h> #include "../helpers/transform_helpers.hpp" namespace naoqi { namespace subscriber { MovetoSubscriber::MovetoSubscriber( const std::string& name, const std::string& topic, const qi::SessionPtr& session, const boost::shared_ptr<tf2_ros::Buffer>& tf2_buffer): BaseSubscriber( name, topic, session ), p_motion_( session->service("ALMotion") ), tf2_buffer_( tf2_buffer ) {} void MovetoSubscriber::reset( ros::NodeHandle& nh ) { sub_moveto_ = nh.subscribe( topic_, 10, &MovetoSubscriber::callback, this ); is_initialized_ = true; } void MovetoSubscriber::callback( const geometry_msgs::PoseStampedConstPtr& pose_msg ) { if (pose_msg->header.frame_id == "odom") { geometry_msgs::PoseStamped pose_msg_bf; bool canTransform = tf2_buffer_->canTransform( "base_footprint", "odom", ros::Time(0), ros::Duration(2)); if (!canTransform) { std::cout << "Cannot transform from " << "odom" << " to base_footprint" << std::endl; return; } try { tf2_buffer_->transform( *pose_msg, pose_msg_bf, "base_footprint", ros::Time(0), "odom"); double yaw = helpers::transform::getYaw(pose_msg_bf.pose); std::cout << "odom to move x: " << pose_msg_bf.pose.position.x << " y: " << pose_msg_bf.pose.position.y << " yaw: " << yaw << std::endl; if (std::isnan(yaw)) { yaw = 0.0; std::cout << "Yaw is nan, changed to 0.0" << std::endl; } p_motion_.async<void>( "moveTo", pose_msg_bf.pose.position.x, pose_msg_bf.pose.position.y, yaw); } catch( const tf2::LookupException& e) { std::cout << e.what() << std::endl; std::cout << "moveto position in frame_id " << pose_msg->header.frame_id << "is not supported in any other base frame than " "basefootprint" << std::endl; } catch( const tf2::ExtrapolationException& e) { std::cout << "received an error on the time lookup" << std::endl; } } else if (pose_msg->header.frame_id == "base_footprint"){ double yaw = helpers::transform::getYaw(pose_msg->pose); std::cout << "going to move x: " << pose_msg->pose.position.x << " y: " << pose_msg->pose.position.y << " yaw: " << yaw << std::endl; if (std::isnan(yaw)) { yaw = 0.0; std::cout << "Yaw is nan, changed to 0.0" << std::endl; } p_motion_.async<void>( "moveTo", pose_msg->pose.position.x, pose_msg->pose.position.y, yaw); } else std::cout << "Cannot reach position expressed in the " << pose_msg->header.frame_id << " frame, enter a valid frame id in the pose's header" " (base_footprint or odom)" << std::endl; } } //publisher } // naoqi <|endoftext|>
<commit_before>#pragma once #include <vector> #include <cssdom/dom.hpp> #include "elements/styleable.hpp" #include "elements/container.hpp" namespace svgdom{ class style_stack{ struct node{ const svgdom::styleable& s; const svgdom::container* c = nullptr; size_t index = 0; // index in its parent of the next item in the stack node(const svgdom::styleable& s) : s(s) {} }; std::vector<node> stack; std::vector<std::reference_wrapper<const cssdom::document>> css; class crawler : public cssdom::xml_dom_crawler{ const decltype(style_stack::stack)& stack; std::remove_reference<decltype(stack)>::type::const_reverse_iterator viter; decltype(container::children)::const_iterator hiter; public: crawler(decltype(stack) stack); const cssdom::styleable& get()override; bool move_up()override; bool move_left()override; void reset()override; }; const svgdom::style_value* get_css_style_property(svgdom::style_property p)const; public: const svgdom::style_value* get_style_property(svgdom::style_property p)const; void add_css(const cssdom::document& css_doc); class push{ style_stack& ss; public: push(style_stack& ss, const svgdom::styleable& s); push(style_stack& ss, const svgdom::styleable& s, const svgdom::container& c); ~push()noexcept; }; }; } <commit_msg>making public the stack field of the style_stack<commit_after>#pragma once #include <vector> #include <cssdom/dom.hpp> #include "elements/styleable.hpp" #include "elements/container.hpp" namespace svgdom{ class style_stack{ public: struct node{ const svgdom::styleable& s; const svgdom::container* c = nullptr; size_t index = 0; // index in its parent of the next item in the stack node(const svgdom::styleable& s) : s(s) {} }; std::vector<node> stack; private: std::vector<std::reference_wrapper<const cssdom::document>> css; class crawler : public cssdom::xml_dom_crawler{ const decltype(style_stack::stack)& stack; std::remove_reference<decltype(stack)>::type::const_reverse_iterator viter; decltype(container::children)::const_iterator hiter; public: crawler(decltype(stack) stack); const cssdom::styleable& get()override; bool move_up()override; bool move_left()override; void reset()override; }; const svgdom::style_value* get_css_style_property(svgdom::style_property p)const; public: const svgdom::style_value* get_style_property(svgdom::style_property p)const; void add_css(const cssdom::document& css_doc); class push{ style_stack& ss; public: push(style_stack& ss, const svgdom::styleable& s); push(style_stack& ss, const svgdom::styleable& s, const svgdom::container& c); ~push()noexcept; }; }; } <|endoftext|>
<commit_before>// Copyright (c) 2016, Joseph Mirabel // Authors: Joseph Mirabel (joseph.mirabel@laas.fr) // // This file is part of hpp-core. // hpp-core is free software: you can redistribute it // and/or modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation, either version // 3 of the License, or (at your option) any later version. // // hpp-core 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 Lesser Public License for more details. You should have // received a copy of the GNU Lesser General Public License along with // hpp-core. If not, see <http://www.gnu.org/licenses/>. #include <hpp/core/relative-motion.hh> #include <hpp/constraints/explicit/relative-pose.hh> #include <pinocchio/multibody/model.hpp> #include <hpp/pinocchio/device.hh> #include <hpp/pinocchio/joint.hh> #include <hpp/pinocchio/joint-collection.hh> #include <hpp/constraints/generic-transformation.hh> #include <hpp/constraints/implicit/relative-pose.hh> #include <hpp/constraints/explicit/relative-transformation.hh> #include <hpp/core/constraint-set.hh> #include <hpp/core/config-projector.hh> #include <hpp/constraints/implicit.hh> #include <hpp/constraints/locked-joint.hh> #include <hpp/constraints/explicit/implicit-function.hh> namespace hpp { namespace core { namespace { inline void symSet (RelativeMotion::matrix_type& m, size_type i0, size_type i1, RelativeMotion::RelativeMotionType t) { m(i0,i1) = m(i1,i0) = t; } /// Considering the order Constrained(0) < Parameterized(1) < Unconstrained(2) /// Change m(i0,i1) only if it decreases. inline void symSetNoDowngrade (RelativeMotion::matrix_type& m, size_type i0, size_type i1, RelativeMotion::RelativeMotionType t) { assert (RelativeMotion::Constrained < RelativeMotion::Parameterized && RelativeMotion::Parameterized < RelativeMotion::Unconstrained); assert (m(i0,i1) == m(i1,i0)); if (t < m(i0,i1)) m(i0,i1) = m(i1,i0) = t; } /// Check that a differentiable function defines a constraint of /// relative pose between two joints template <typename T > struct check { typedef boost::shared_ptr<T> Ptr_t; /// Check that function defines relative pose constraint /// \param f Differentiable function, /// \return whether f defines a relative pose constraint, /// \retval i1, i2 indices of joints that are constrained if so. static bool is (const DifferentiableFunctionPtr_t& f, size_type& i1, size_type& i2) { Ptr_t t = HPP_DYNAMIC_PTR_CAST(T, f); if (t) { i1 = RelativeMotion::idx(t->joint1()); i2 = RelativeMotion::idx(t->joint2()); hppDout (info, "function " << f->name () << " is a (relative) transformation. i1=" << i1 << ", i2=" << i2); return true; } return false; } }; } bool isRelativePoseConstraint (const constraints::ImplicitConstPtr_t& c, size_type& i1, size_type& i2) { constraints::implicit::RelativePoseConstPtr_t t (HPP_DYNAMIC_PTR_CAST(const constraints::implicit::RelativePose, c)); if (t) { i1 = RelativeMotion::idx(t->joint1()); i2 = RelativeMotion::idx(t->joint2()); hppDout (info, "constraint " << t->functionPtr ()->name () << " is a relative pose. i1=" << i1 << ", i2=" << i2); return true; } return false; } RelativeMotion::matrix_type RelativeMotion::matrix (const DevicePtr_t& dev) { assert (dev); const size_type N = dev->model().joints.size(); matrix_type matrix (N, N); matrix.setConstant (Unconstrained); matrix.diagonal().setConstant(Constrained); return matrix; } void RelativeMotion::fromConstraint (matrix_type& matrix, const DevicePtr_t& robot, const ConstraintSetPtr_t& c) { using constraints::Transformation; using constraints::RelativeTransformation; assert (robot); assert (c); const size_type N = robot->model().joints.size(); if (matrix.rows() != N || matrix.cols() != N) throw std::invalid_argument ("Wrong RelativeMotion::matrix_type size"); ConfigProjectorPtr_t proj = c->configProjector(); if (!proj) return; // Loop over the LockedJoint const pinocchio::Model& model = robot->model(); // Loop over the constraints const NumericalConstraints_t& ncs = proj->numericalConstraints (); for (NumericalConstraints_t::const_iterator _ncs = ncs.begin(); _ncs != ncs.end(); ++_ncs) { using hpp::constraints::implicit::RelativePose; constraints::ImplicitConstPtr_t nc = *_ncs; size_type i1, i2; // Detect locked joints LockedJointConstPtr_t lj (HPP_DYNAMIC_PTR_CAST (const LockedJoint, nc)); if (lj) { const std::string& jointName = lj->jointName(); if (!model.existJointName(jointName)) { // Extra dofs and partial locked joints have a name that won't be // recognized by Device::getJointByName. So they can be filtered // this way. hppDout (info, "Joint of locked joint not found: " << *lj); continue; } bool cstRHS (lj->parameterSize () == 0); i1 = model.getJointId(jointName); i2 = model.parents[i1]; recurseSetRelMotion (matrix, i1, i2, (cstRHS ? Constrained : Parameterized)); hppDout (info, "Locked joint found: " << lj->jointName ()); continue; } // Detect relative pose constraints if (nc->functionPtr()->outputSize() != 6) { hppDout (info, "Constraint " << nc->functionPtr()->name () << " is not of dimension 6."); continue; } if (!isRelativePoseConstraint (nc, i1, i2)) { hppDout (info, "Constraint " << nc->functionPtr()->name () << " is not of type RelativePose"); if (!check <Transformation>::is (nc->functionPtr (), i1, i2)) { hppDout (info, "Constraint function " << nc->functionPtr()->name () << " is not of type Transformation"); if (!check <RelativeTransformation>::is (nc->functionPtr (), i1, i2)) { hppDout (info, "Constraint function " << nc->functionPtr()->name () << " is not of type RelativeTransformation"); continue; } } } bool cstRHS (nc->parameterSize () == 0); recurseSetRelMotion (matrix, i1, i2, (cstRHS ? Constrained : Parameterized)); } } void RelativeMotion::recurseSetRelMotion(matrix_type& matrix, const size_type& i1, const size_type& i2, const RelativeMotion::RelativeMotionType& type) { assert (Constrained < Parameterized && Parameterized < Unconstrained); bool param = (type == Parameterized); RelativeMotionType t = Unconstrained; // Constrained(0) < Parameterized(1) < Unconstrained(2) // If the current value is more constraining, then do not change it. if (matrix(i1,i2) <= type) return; symSet(matrix, i1, i2, type); // i1 to i3 for (size_type i3 = 0; i3 < matrix.rows(); ++i3) { if (i3 == i1) continue; if (i3 == i2) continue; if (matrix(i2,i3) != Unconstrained) { t = (!param && matrix(i2,i3) == Constrained) ? Constrained : Parameterized; symSetNoDowngrade(matrix, i1, i3, t); } } for (size_type i0 = 0; i0 < matrix.rows(); ++i0) { if (i0 == i2) continue; if (i0 == i1) continue; // i0 to i2 if (matrix(i0,i1) != Unconstrained) { t = (!param && matrix(i0,i1) == Constrained) ? Constrained : Parameterized; symSetNoDowngrade (matrix, i0, i2 ,t); } // from i0 to i3 if (matrix(i0,i1) == Unconstrained) continue; for (size_type i3 = 0; i3 < matrix.rows(); ++i3) { if (i3 == i2) continue; if (i3 == i1) continue; if (i3 == i0) continue; if (matrix(i2,i3) == Unconstrained) continue; // If motion is already constrained, continue. t = (!param && matrix(i0,i1) == Constrained && matrix(i2,i3) == Constrained) ? Constrained : Parameterized; symSetNoDowngrade (matrix, i0, i3, t); } } } } // namespace core } // namespace hpp <commit_msg>Update to modifications in hpp-constraints<commit_after>// Copyright (c) 2016, Joseph Mirabel // Authors: Joseph Mirabel (joseph.mirabel@laas.fr) // // This file is part of hpp-core. // hpp-core is free software: you can redistribute it // and/or modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation, either version // 3 of the License, or (at your option) any later version. // // hpp-core 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 Lesser Public License for more details. You should have // received a copy of the GNU Lesser General Public License along with // hpp-core. If not, see <http://www.gnu.org/licenses/>. #include <hpp/core/relative-motion.hh> #include <hpp/constraints/explicit/relative-pose.hh> #include <pinocchio/multibody/model.hpp> #include <hpp/pinocchio/device.hh> #include <hpp/pinocchio/joint.hh> #include <hpp/pinocchio/joint-collection.hh> #include <hpp/constraints/generic-transformation.hh> #include <hpp/constraints/explicit/relative-transformation.hh> #include <hpp/core/constraint-set.hh> #include <hpp/core/config-projector.hh> #include <hpp/constraints/implicit.hh> #include <hpp/constraints/locked-joint.hh> #include <hpp/constraints/explicit/implicit-function.hh> namespace hpp { namespace core { namespace { inline void symSet (RelativeMotion::matrix_type& m, size_type i0, size_type i1, RelativeMotion::RelativeMotionType t) { m(i0,i1) = m(i1,i0) = t; } /// Considering the order Constrained(0) < Parameterized(1) < Unconstrained(2) /// Change m(i0,i1) only if it decreases. inline void symSetNoDowngrade (RelativeMotion::matrix_type& m, size_type i0, size_type i1, RelativeMotion::RelativeMotionType t) { assert (RelativeMotion::Constrained < RelativeMotion::Parameterized && RelativeMotion::Parameterized < RelativeMotion::Unconstrained); assert (m(i0,i1) == m(i1,i0)); if (t < m(i0,i1)) m(i0,i1) = m(i1,i0) = t; } /// Check that a differentiable function defines a constraint of /// relative pose between two joints template <typename T > struct check { typedef boost::shared_ptr<T> Ptr_t; /// Check that function defines relative pose constraint /// \param f Differentiable function, /// \return whether f defines a relative pose constraint, /// \retval i1, i2 indices of joints that are constrained if so. static bool is (const DifferentiableFunctionPtr_t& f, size_type& i1, size_type& i2) { Ptr_t t = HPP_DYNAMIC_PTR_CAST(T, f); if (t) { i1 = RelativeMotion::idx(t->joint1()); i2 = RelativeMotion::idx(t->joint2()); hppDout (info, "function " << f->name () << " is a (relative) transformation. i1=" << i1 << ", i2=" << i2); return true; } return false; } }; } RelativeMotion::matrix_type RelativeMotion::matrix (const DevicePtr_t& dev) { assert (dev); const size_type N = dev->model().joints.size(); matrix_type matrix (N, N); matrix.setConstant (Unconstrained); matrix.diagonal().setConstant(Constrained); return matrix; } void RelativeMotion::fromConstraint (matrix_type& matrix, const DevicePtr_t& robot, const ConstraintSetPtr_t& c) { using constraints::Transformation; using constraints::RelativeTransformation; assert (robot); assert (c); const size_type N = robot->model().joints.size(); if (matrix.rows() != N || matrix.cols() != N) throw std::invalid_argument ("Wrong RelativeMotion::matrix_type size"); ConfigProjectorPtr_t proj = c->configProjector(); if (!proj) return; // Loop over the LockedJoint const pinocchio::Model& model = robot->model(); // Loop over the constraints const NumericalConstraints_t& ncs = proj->numericalConstraints (); for (NumericalConstraints_t::const_iterator _ncs = ncs.begin(); _ncs != ncs.end(); ++_ncs) { constraints::ImplicitConstPtr_t nc = *_ncs; size_type i1, i2; // Detect locked joints LockedJointConstPtr_t lj (HPP_DYNAMIC_PTR_CAST (const LockedJoint, nc)); if (lj) { const std::string& jointName = lj->jointName(); if (!model.existJointName(jointName)) { // Extra dofs and partial locked joints have a name that won't be // recognized by Device::getJointByName. So they can be filtered // this way. hppDout (info, "Joint of locked joint not found: " << *lj); continue; } bool cstRHS (lj->parameterSize () == 0); i1 = model.getJointId(jointName); i2 = model.parents[i1]; recurseSetRelMotion (matrix, i1, i2, (cstRHS ? Constrained : Parameterized)); hppDout (info, "Locked joint found: " << lj->jointName ()); continue; } // Detect relative pose constraints if (nc->functionPtr()->outputSize() != 6) { hppDout (info, "Constraint " << nc->functionPtr()->name () << " is not of dimension 6."); continue; } if (!check <Transformation>::is (nc->functionPtr (), i1, i2)) { hppDout (info, "Constraint function " << nc->functionPtr()->name () << " is not of type Transformation"); if (!check <RelativeTransformation>::is (nc->functionPtr (), i1, i2)) { hppDout (info, "Constraint function " << nc->functionPtr()->name () << " is not of type RelativeTransformation"); continue; } } bool cstRHS (nc->parameterSize () == 0); recurseSetRelMotion (matrix, i1, i2, (cstRHS ? Constrained : Parameterized)); } } void RelativeMotion::recurseSetRelMotion(matrix_type& matrix, const size_type& i1, const size_type& i2, const RelativeMotion::RelativeMotionType& type) { assert (Constrained < Parameterized && Parameterized < Unconstrained); bool param = (type == Parameterized); RelativeMotionType t = Unconstrained; // Constrained(0) < Parameterized(1) < Unconstrained(2) // If the current value is more constraining, then do not change it. if (matrix(i1,i2) <= type) return; symSet(matrix, i1, i2, type); // i1 to i3 for (size_type i3 = 0; i3 < matrix.rows(); ++i3) { if (i3 == i1) continue; if (i3 == i2) continue; if (matrix(i2,i3) != Unconstrained) { t = (!param && matrix(i2,i3) == Constrained) ? Constrained : Parameterized; symSetNoDowngrade(matrix, i1, i3, t); } } for (size_type i0 = 0; i0 < matrix.rows(); ++i0) { if (i0 == i2) continue; if (i0 == i1) continue; // i0 to i2 if (matrix(i0,i1) != Unconstrained) { t = (!param && matrix(i0,i1) == Constrained) ? Constrained : Parameterized; symSetNoDowngrade (matrix, i0, i2 ,t); } // from i0 to i3 if (matrix(i0,i1) == Unconstrained) continue; for (size_type i3 = 0; i3 < matrix.rows(); ++i3) { if (i3 == i2) continue; if (i3 == i1) continue; if (i3 == i0) continue; if (matrix(i2,i3) == Unconstrained) continue; // If motion is already constrained, continue. t = (!param && matrix(i0,i1) == Constrained && matrix(i2,i3) == Constrained) ? Constrained : Parameterized; symSetNoDowngrade (matrix, i0, i3, t); } } } } // namespace core } // namespace hpp <|endoftext|>
<commit_before>/*========================================================================= * * Copyright UMC Utrecht and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ /** \file \brief Compare the advanced linear interpolator with the linear and 1st order B-spline. */ #include "itkLinearInterpolateImageFunction.h" #include "itkAdvancedLinearInterpolateImageFunction.h" #include "itkBSplineInterpolateImageFunction.h" #include "itkImage.h" #include "itkImageRegionIterator.h" #include "itkMersenneTwisterRandomVariateGenerator.h" #include "itkImageFileWriter.h" #include "vnl/vnl_math.h" #include "itkTimeProbe.h" //------------------------------------------------------------------------------------- // Test function templated over the dimension template< unsigned int Dimension > bool TestInterpolators( void ) { typedef itk::Image< short, Dimension > InputImageType; typedef typename InputImageType::SizeType SizeType; typedef typename InputImageType::SpacingType SpacingType; typedef typename InputImageType::PointType OriginType; typedef typename InputImageType::RegionType RegionType; //typedef typename RegionType::IndexType IndexType; typedef typename InputImageType::DirectionType DirectionType; typedef double CoordRepType; typedef double CoefficientType; typedef itk::LinearInterpolateImageFunction< InputImageType, CoordRepType > LinearInterpolatorType; typedef itk::AdvancedLinearInterpolateImageFunction< InputImageType, CoordRepType > AdvancedLinearInterpolatorType; typedef itk::BSplineInterpolateImageFunction< InputImageType, CoordRepType, CoefficientType > BSplineInterpolatorType; typedef typename LinearInterpolatorType::ContinuousIndexType ContinuousIndexType; typedef typename AdvancedLinearInterpolatorType::CovariantVectorType CovariantVectorType; typedef typename AdvancedLinearInterpolatorType::OutputType OutputType; // double scalar typedef itk::ImageRegionIterator< InputImageType > IteratorType; typedef itk::Statistics::MersenneTwisterRandomVariateGenerator RandomNumberGeneratorType; //typedef itk::ImageFileWriter< InputImageType > WriterType; RandomNumberGeneratorType::Pointer randomNum = RandomNumberGeneratorType::GetInstance(); /** Create random input image. */ SizeType size; SpacingType spacing; OriginType origin; for( unsigned int i = 0; i < Dimension; ++i ) { size[ i ] = 10; spacing[ i ] = randomNum->GetUniformVariate( 0.5, 2.0 ); origin[ i ] = randomNum->GetUniformVariate( -1, 0 ); } RegionType region; region.SetSize( size ); /** Make sure to test for non-identity direction cosines. */ DirectionType direction; direction.Fill( 0.0 ); if( Dimension == 2 ) { direction[ 0 ][ 1 ] = -1.0; direction[ 1 ][ 0 ] = 1.0; } else if( Dimension == 3 ) { direction[ 0 ][ 2 ] = -1.0; direction[ 1 ][ 1 ] = 1.0; direction[ 2 ][ 0 ] = 1.0; } typename InputImageType::Pointer image = InputImageType::New(); image->SetRegions( region ); image->SetOrigin( origin ); image->SetSpacing( spacing ); image->SetDirection( direction ); image->Allocate(); // loop over image and fill with random values IteratorType it( image, image->GetLargestPossibleRegion() ); it.GoToBegin(); while( !it.IsAtEnd() ) { it.Set( randomNum->GetUniformVariate( 0, 255 ) ); ++it; } /** Write the image. */ //WriterType::Pointer writer = WriterType::New(); //writer->SetInput( image ); //writer->SetFileName( "image.mhd" ); //writer->Update(); /** Create and setup interpolators. */ typename LinearInterpolatorType::Pointer linear = LinearInterpolatorType::New(); typename AdvancedLinearInterpolatorType::Pointer linearA = AdvancedLinearInterpolatorType::New(); typename BSplineInterpolatorType::Pointer bspline = BSplineInterpolatorType::New(); linear->SetInputImage( image ); linearA->SetInputImage( image ); bspline->SetSplineOrder( 1 ); // prior to SetInputImage() bspline->SetInputImage( image ); /** Test some points. */ const unsigned int count = 12; double darray1[ 12 ][ Dimension ]; if( Dimension == 2 ) { double darray2[ 12 ][ 2 ] = { { 0.1, 0.2 }, { 3.4, 5.8 }, { 4.0, 6.0 }, { 2.1, 8.0 }, { -0.1, -0.1 }, { 0.0, 0.0 }, { 1.3, 1.0 }, { 2.0, 5.7 }, { 9.5, 9.1 }, { 2.0, -0.1 }, { -0.1, 2.0 }, { 12.7, 15.3 } }; for( unsigned int i = 0; i < 12; i++ ) { for( unsigned int j = 0; j < Dimension; j++ ) { darray1[ i ][ j ] = darray2[ i ][ j ]; } } } else if( Dimension == 3 ) { //double darray2[count][3] = //{ { 0.0, 0.0, 0.0}, { 0.1, 0.0, 0.0}, { 0.2, 0.0, 0.0} }; // x, y=z=0, works //{ { 0.0, 0.5, 0.0}, { 0.1, 0.5, 0.0}, { 0.2, 0.5, 0.0} }; // x, z=0, works //{ { 0.0, 0.0, 0.5}, { 0.1, 0.0, 0.5}, { 0.2, 0.0, 0.5} }; // x, y=0, works //{ { 0.0, 0.2, 0.2}, { 0.0, 0.4, 0.4}, { 0.0, 0.5, 0.5} }; // x=0, y=z, works //{ { 0.0, 0.0, 0.0}, { 0.0, 0.1, 0.0}, { 0.0, 0.2, 0.0} }; // y, works //{ { 0.0, 0.0, 0.0}, { 0.0, 0.0, 0.1}, { 0.0, 0.0, 0.2} }; // z, works //{ { 0.0, 0.0, 0.0}, { 0.2, 0.1, 0.0}, { 0.5, 0.2, 0.0} }; // xy, works //{ { 0.0, 0.0, 0.0}, { 0.3, 0.0, 0.1}, { 0.5, 0.0, 0.2} }; // xz, works //{ { 0.0, 0.0, 0.0}, { 0.0, 0.1, 0.1}, { 0.0, 0.4, 0.2} }; // yz, works double darray2[ 12 ][ 3 ] = { { 0.1, 0.2, 0.1 }, { 3.4, 5.8, 4.7 }, { 4.0, 6.0, 5.0 }, { 2.1, 8.0, 3.4 }, { -0.1, -0.1, -0.1 }, { 0.0, 0.0, 0.0 }, { 1.3, 1.0, 1.4 }, { 2.0, 5.7, 7.5 }, { 9.5, 9.1, 9.3 }, { 2.0, -0.1, 5.3 }, { -0.1, 2.0, 4.0 }, { 12.7, 15.3, 14.1 } }; for( unsigned int i = 0; i < count; i++ ) { for( unsigned int j = 0; j < Dimension; j++ ) { darray1[ i ][ j ] = darray2[ i ][ j ]; } } } /** Compare results. */ OutputType valueLin, valueLinA, valueBSpline, valueBSpline2; CovariantVectorType derivLinA, derivBSpline, derivBSpline2; for( unsigned int i = 0; i < count; i++ ) { ContinuousIndexType cindex( &darray1[ i ][ 0 ] ); valueLin = linear->EvaluateAtContinuousIndex( cindex ); linearA->EvaluateValueAndDerivativeAtContinuousIndex( cindex, valueLinA, derivLinA ); valueBSpline = bspline->EvaluateAtContinuousIndex( cindex ); derivBSpline = bspline->EvaluateDerivativeAtContinuousIndex( cindex ); bspline->EvaluateValueAndDerivativeAtContinuousIndex( cindex, valueBSpline2, derivBSpline2 ); std::cout << "cindex: " << cindex << std::endl; std::cout << "linear: " << valueLin << " ---" << std::endl; std::cout << "linearA: " << valueLinA << " " << derivLinA << std::endl; std::cout << "B-spline: " << valueBSpline << " " << derivBSpline << std::endl; std::cout << "B-spline: " << valueBSpline2 << " " << derivBSpline2 << "\n" << std::endl; if( vnl_math_abs( valueLinA - valueBSpline ) > 1.0e-3 ) { std::cerr << "ERROR: there is a difference in the interpolated value, " << "between the linear and the 1st-order B-spline interpolator." << std::endl; return false; } if( vnl_math_abs( valueBSpline - valueBSpline2 ) > 1.0e-3 ) { std::cerr << "ERROR: there is a difference in the interpolated value, " << "within the 1st-order B-spline interpolator (inconsistency)." << std::endl; return false; } if( ( derivLinA - derivBSpline ).GetVnlVector().magnitude() > 1.0e-3 ) { std::cerr << "ERROR: there is a difference in the interpolated gradient, " << "between the linear and the 1st-order B-spline interpolator." << std::endl; return false; } if( ( derivBSpline - derivBSpline2 ).GetVnlVector().magnitude() > 1.0e-3 ) { std::cerr << "ERROR: there is a difference in the interpolated gradient, " << "within the 1st-order B-spline interpolator (inconsistency)." << std::endl; return false; } } /** Measure the run times, but only in release mode. */ #ifdef NDEBUG std::cout << std::endl; ContinuousIndexType cindex( &darray1[ 1 ][ 0 ] ); std::cout << "cindex: " << cindex << std::endl; OutputType value; CovariantVectorType deriv; const unsigned int runs = 1e5; itk::TimeProbe timer; timer.Start(); for( unsigned int i = 0; i < runs; ++i ) { value = linear->EvaluateAtContinuousIndex( cindex ); } timer.Stop(); std::cout << "linear (value) : " << 1.0e3 * timer.GetMean() / static_cast< double >( runs ) << " ms" << std::endl; timer.Reset(); timer.Start(); for( unsigned int i = 0; i < runs; ++i ) { linearA->EvaluateValueAndDerivativeAtContinuousIndex( cindex, value, deriv ); } timer.Stop(); std::cout << "linearA (v&d) : " << 1.0e3 * timer.GetMean() / static_cast< double >( runs ) << " ms" << std::endl; timer.Reset(); timer.Start(); for( unsigned int i = 0; i < runs; ++i ) { value = bspline->EvaluateAtContinuousIndex( cindex ); } timer.Stop(); std::cout << "B-spline (value): " << 1.0e3 * timer.GetMean() / static_cast< double >( runs ) << " ms" << std::endl; timer.Reset(); timer.Start(); for( unsigned int i = 0; i < runs; ++i ) { value = bspline->EvaluateAtContinuousIndex( cindex ); deriv = bspline->EvaluateDerivativeAtContinuousIndex( cindex ); } timer.Stop(); std::cout << "B-spline (v+d) : " << 1.0e3 * timer.GetMean() / static_cast< double >( runs ) << " ms" << std::endl; timer.Reset(); timer.Start(); for( unsigned int i = 0; i < runs; ++i ) { bspline->EvaluateValueAndDerivativeAtContinuousIndex( cindex, value, deriv ); } timer.Stop(); std::cout << "B-spline (v&d) : " << 1.0e3 * timer.GetMean() / static_cast< double >( runs ) << " ms" << std::endl; #endif return true; } // end TestInterpolator() int main( int argc, char ** argv ) { // 2D tests bool success = TestInterpolators< 2 >(); if( !success ) { return EXIT_FAILURE; } std::cerr << "\n\n\n-----------------------------------\n\n\n"; // 3D tests success = TestInterpolators< 3 >(); if( !success ) { return EXIT_FAILURE; } return EXIT_SUCCESS; } // end main <commit_msg>BUG: Avoid UMR: only call itk::LinearInterpolateImageFunction::EvaluateAtContinuousIndex() when point lies within image region.<commit_after>/*========================================================================= * * Copyright UMC Utrecht and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ /** \file \brief Compare the advanced linear interpolator with the linear and 1st order B-spline. */ #include "itkLinearInterpolateImageFunction.h" #include "itkAdvancedLinearInterpolateImageFunction.h" #include "itkBSplineInterpolateImageFunction.h" #include "itkImage.h" #include "itkImageRegionIterator.h" #include "itkMersenneTwisterRandomVariateGenerator.h" #include "itkImageFileWriter.h" #include "vnl/vnl_math.h" #include "itkTimeProbe.h" //------------------------------------------------------------------------------------- // Test function templated over the dimension template< unsigned int Dimension > bool TestInterpolators( void ) { typedef itk::Image< short, Dimension > InputImageType; typedef typename InputImageType::SizeType SizeType; typedef typename InputImageType::SpacingType SpacingType; typedef typename InputImageType::PointType OriginType; typedef typename InputImageType::RegionType RegionType; //typedef typename RegionType::IndexType IndexType; typedef typename InputImageType::DirectionType DirectionType; typedef double CoordRepType; typedef double CoefficientType; typedef itk::LinearInterpolateImageFunction< InputImageType, CoordRepType > LinearInterpolatorType; typedef itk::AdvancedLinearInterpolateImageFunction< InputImageType, CoordRepType > AdvancedLinearInterpolatorType; typedef itk::BSplineInterpolateImageFunction< InputImageType, CoordRepType, CoefficientType > BSplineInterpolatorType; typedef typename LinearInterpolatorType::ContinuousIndexType ContinuousIndexType; typedef typename AdvancedLinearInterpolatorType::CovariantVectorType CovariantVectorType; typedef typename AdvancedLinearInterpolatorType::OutputType OutputType; // double scalar typedef itk::ImageRegionIterator< InputImageType > IteratorType; typedef itk::Statistics::MersenneTwisterRandomVariateGenerator RandomNumberGeneratorType; //typedef itk::ImageFileWriter< InputImageType > WriterType; RandomNumberGeneratorType::Pointer randomNum = RandomNumberGeneratorType::GetInstance(); /** Create random input image. */ SizeType size; SpacingType spacing; OriginType origin; for( unsigned int i = 0; i < Dimension; ++i ) { size[ i ] = 10; spacing[ i ] = randomNum->GetUniformVariate( 0.5, 2.0 ); origin[ i ] = randomNum->GetUniformVariate( -1, 0 ); } RegionType region; region.SetSize( size ); /** Make sure to test for non-identity direction cosines. */ DirectionType direction; direction.Fill( 0.0 ); if( Dimension == 2 ) { direction[ 0 ][ 1 ] = -1.0; direction[ 1 ][ 0 ] = 1.0; } else if( Dimension == 3 ) { direction[ 0 ][ 2 ] = -1.0; direction[ 1 ][ 1 ] = 1.0; direction[ 2 ][ 0 ] = 1.0; } typename InputImageType::Pointer image = InputImageType::New(); image->SetRegions( region ); image->SetOrigin( origin ); image->SetSpacing( spacing ); image->SetDirection( direction ); image->Allocate(); // loop over image and fill with random values IteratorType it( image, image->GetLargestPossibleRegion() ); it.GoToBegin(); while( !it.IsAtEnd() ) { it.Set( randomNum->GetUniformVariate( 0, 255 ) ); ++it; } /** Write the image. */ //WriterType::Pointer writer = WriterType::New(); //writer->SetInput( image ); //writer->SetFileName( "image.mhd" ); //writer->Update(); /** Create and setup interpolators. */ typename LinearInterpolatorType::Pointer linear = LinearInterpolatorType::New(); typename AdvancedLinearInterpolatorType::Pointer linearA = AdvancedLinearInterpolatorType::New(); typename BSplineInterpolatorType::Pointer bspline = BSplineInterpolatorType::New(); linear->SetInputImage( image ); linearA->SetInputImage( image ); bspline->SetSplineOrder( 1 ); // prior to SetInputImage() bspline->SetInputImage( image ); /** Test some points. */ const unsigned int count = 12; double darray1[ 12 ][ Dimension ]; if( Dimension == 2 ) { double darray2[ 12 ][ 2 ] = { { 0.1, 0.2 }, { 3.4, 5.8 }, { 4.0, 6.0 }, { 2.1, 8.0 }, { -0.1, -0.1 }, { 0.0, 0.0 }, { 1.3, 1.0 }, { 2.0, 5.7 }, { 9.5, 9.1 }, { 2.0, -0.1 }, { -0.1, 2.0 }, { 12.7, 15.3 } }; for( unsigned int i = 0; i < 12; i++ ) { for( unsigned int j = 0; j < Dimension; j++ ) { darray1[ i ][ j ] = darray2[ i ][ j ]; } } } else if( Dimension == 3 ) { //double darray2[count][3] = //{ { 0.0, 0.0, 0.0}, { 0.1, 0.0, 0.0}, { 0.2, 0.0, 0.0} }; // x, y=z=0, works //{ { 0.0, 0.5, 0.0}, { 0.1, 0.5, 0.0}, { 0.2, 0.5, 0.0} }; // x, z=0, works //{ { 0.0, 0.0, 0.5}, { 0.1, 0.0, 0.5}, { 0.2, 0.0, 0.5} }; // x, y=0, works //{ { 0.0, 0.2, 0.2}, { 0.0, 0.4, 0.4}, { 0.0, 0.5, 0.5} }; // x=0, y=z, works //{ { 0.0, 0.0, 0.0}, { 0.0, 0.1, 0.0}, { 0.0, 0.2, 0.0} }; // y, works //{ { 0.0, 0.0, 0.0}, { 0.0, 0.0, 0.1}, { 0.0, 0.0, 0.2} }; // z, works //{ { 0.0, 0.0, 0.0}, { 0.2, 0.1, 0.0}, { 0.5, 0.2, 0.0} }; // xy, works //{ { 0.0, 0.0, 0.0}, { 0.3, 0.0, 0.1}, { 0.5, 0.0, 0.2} }; // xz, works //{ { 0.0, 0.0, 0.0}, { 0.0, 0.1, 0.1}, { 0.0, 0.4, 0.2} }; // yz, works double darray2[ 12 ][ 3 ] = { { 0.1, 0.2, 0.1 }, { 3.4, 5.8, 4.7 }, { 4.0, 6.0, 5.0 }, { 2.1, 8.0, 3.4 }, { -0.1, -0.1, -0.1 }, { 0.0, 0.0, 0.0 }, { 1.3, 1.0, 1.4 }, { 2.0, 5.7, 7.5 }, { 9.5, 9.1, 9.3 }, { 2.0, -0.1, 5.3 }, { -0.1, 2.0, 4.0 }, { 12.7, 15.3, 14.1 } }; for( unsigned int i = 0; i < count; i++ ) { for( unsigned int j = 0; j < Dimension; j++ ) { darray1[ i ][ j ] = darray2[ i ][ j ]; } } } /** Compare results. */ OutputType valueLinA, valueBSpline, valueBSpline2; CovariantVectorType derivLinA, derivBSpline, derivBSpline2; for( unsigned int i = 0; i < count; i++ ) { ContinuousIndexType cindex( &darray1[ i ][ 0 ] ); linearA->EvaluateValueAndDerivativeAtContinuousIndex( cindex, valueLinA, derivLinA ); valueBSpline = bspline->EvaluateAtContinuousIndex( cindex ); derivBSpline = bspline->EvaluateDerivativeAtContinuousIndex( cindex ); bspline->EvaluateValueAndDerivativeAtContinuousIndex( cindex, valueBSpline2, derivBSpline2 ); std::cout << "cindex: " << cindex << std::endl; if (image->GetBufferedRegion().IsInside(cindex)) { std::cout << "linear: " << linear->EvaluateAtContinuousIndex(cindex) << " ---" << std::endl; } else { std::cout << "linear: --- ---" << std::endl; } std::cout << "linearA: " << valueLinA << " " << derivLinA << std::endl; std::cout << "B-spline: " << valueBSpline << " " << derivBSpline << std::endl; std::cout << "B-spline: " << valueBSpline2 << " " << derivBSpline2 << "\n" << std::endl; if( vnl_math_abs( valueLinA - valueBSpline ) > 1.0e-3 ) { std::cerr << "ERROR: there is a difference in the interpolated value, " << "between the linear and the 1st-order B-spline interpolator." << std::endl; return false; } if( vnl_math_abs( valueBSpline - valueBSpline2 ) > 1.0e-3 ) { std::cerr << "ERROR: there is a difference in the interpolated value, " << "within the 1st-order B-spline interpolator (inconsistency)." << std::endl; return false; } if( ( derivLinA - derivBSpline ).GetVnlVector().magnitude() > 1.0e-3 ) { std::cerr << "ERROR: there is a difference in the interpolated gradient, " << "between the linear and the 1st-order B-spline interpolator." << std::endl; return false; } if( ( derivBSpline - derivBSpline2 ).GetVnlVector().magnitude() > 1.0e-3 ) { std::cerr << "ERROR: there is a difference in the interpolated gradient, " << "within the 1st-order B-spline interpolator (inconsistency)." << std::endl; return false; } } /** Measure the run times, but only in release mode. */ #ifdef NDEBUG std::cout << std::endl; ContinuousIndexType cindex( &darray1[ 1 ][ 0 ] ); std::cout << "cindex: " << cindex << std::endl; OutputType value; CovariantVectorType deriv; const unsigned int runs = 1e5; itk::TimeProbe timer; timer.Start(); for( unsigned int i = 0; i < runs; ++i ) { value = linear->EvaluateAtContinuousIndex( cindex ); } timer.Stop(); std::cout << "linear (value) : " << 1.0e3 * timer.GetMean() / static_cast< double >( runs ) << " ms" << std::endl; timer.Reset(); timer.Start(); for( unsigned int i = 0; i < runs; ++i ) { linearA->EvaluateValueAndDerivativeAtContinuousIndex( cindex, value, deriv ); } timer.Stop(); std::cout << "linearA (v&d) : " << 1.0e3 * timer.GetMean() / static_cast< double >( runs ) << " ms" << std::endl; timer.Reset(); timer.Start(); for( unsigned int i = 0; i < runs; ++i ) { value = bspline->EvaluateAtContinuousIndex( cindex ); } timer.Stop(); std::cout << "B-spline (value): " << 1.0e3 * timer.GetMean() / static_cast< double >( runs ) << " ms" << std::endl; timer.Reset(); timer.Start(); for( unsigned int i = 0; i < runs; ++i ) { value = bspline->EvaluateAtContinuousIndex( cindex ); deriv = bspline->EvaluateDerivativeAtContinuousIndex( cindex ); } timer.Stop(); std::cout << "B-spline (v+d) : " << 1.0e3 * timer.GetMean() / static_cast< double >( runs ) << " ms" << std::endl; timer.Reset(); timer.Start(); for( unsigned int i = 0; i < runs; ++i ) { bspline->EvaluateValueAndDerivativeAtContinuousIndex( cindex, value, deriv ); } timer.Stop(); std::cout << "B-spline (v&d) : " << 1.0e3 * timer.GetMean() / static_cast< double >( runs ) << " ms" << std::endl; #endif return true; } // end TestInterpolator() int main( int argc, char ** argv ) { // 2D tests bool success = TestInterpolators< 2 >(); if( !success ) { return EXIT_FAILURE; } std::cerr << "\n\n\n-----------------------------------\n\n\n"; // 3D tests success = TestInterpolators< 3 >(); if( !success ) { return EXIT_FAILURE; } return EXIT_SUCCESS; } // end main <|endoftext|>
<commit_before>#include "polylineStyle.h" #include "tangram.h" #include "platform.h" #include "material.h" #include "gl/shaderProgram.h" #include "gl/typedMesh.h" #include "scene/stops.h" #include "scene/drawRule.h" #include "tile/tile.h" #include "util/mapProjection.h" #include "glm/vec3.hpp" namespace Tangram { struct PolylineVertex { glm::vec3 pos; glm::vec2 texcoord; glm::vec4 extrude; GLuint abgr; GLfloat layer; }; using Mesh = TypedMesh<PolylineVertex>; PolylineStyle::PolylineStyle(std::string _name, Blending _blendMode, GLenum _drawMode) : Style(_name, _blendMode, _drawMode) { } void PolylineStyle::constructVertexLayout() { // TODO: Ideally this would be in the same location as the struct that it basically describes m_vertexLayout = std::shared_ptr<VertexLayout>(new VertexLayout({ {"a_position", 3, GL_FLOAT, false, 0}, {"a_texcoord", 2, GL_FLOAT, false, 0}, {"a_extrude", 4, GL_FLOAT, false, 0}, {"a_color", 4, GL_UNSIGNED_BYTE, true, 0}, {"a_layer", 1, GL_FLOAT, false, 0} })); } void PolylineStyle::constructShaderProgram() { std::string vertShaderSrcStr = stringFromFile("shaders/polyline.vs", PathType::internal); std::string fragShaderSrcStr = stringFromFile("shaders/polyline.fs", PathType::internal); m_shaderProgram->setSourceStrings(fragShaderSrcStr, vertShaderSrcStr); } VboMesh* PolylineStyle::newMesh() const { return new Mesh(m_vertexLayout, m_drawMode); } PolylineStyle::Parameters PolylineStyle::parseRule(const DrawRule& _rule) const { Parameters p; uint32_t cap = 0, join = 0; _rule.get(StyleParamKey::extrude, p.extrude); _rule.get(StyleParamKey::color, p.color); _rule.get(StyleParamKey::cap, cap); _rule.get(StyleParamKey::join, join); if (!_rule.get(StyleParamKey::order, p.order)) { LOGW("No 'order' specified for feature, ordering cannot be guaranteed :("); } p.cap = static_cast<CapTypes>(cap); p.join = static_cast<JoinTypes>(join); p.outlineOrder = p.order; // will offset from fill later if (_rule.get(StyleParamKey::outline_color, p.outlineColor) | _rule.get(StyleParamKey::outline_order, p.outlineOrder) | _rule.contains(StyleParamKey::outline_width) | _rule.get(StyleParamKey::outline_cap, cap) | _rule.get(StyleParamKey::outline_join, join)) { p.outlineOn = true; p.outlineCap = static_cast<CapTypes>(cap); p.outlineJoin = static_cast<JoinTypes>(join); } return p; } void PolylineStyle::buildPolygon(const Polygon& _poly, const DrawRule& _rule, const Properties& _props, VboMesh& _mesh, Tile& _tile) const { for (const auto& line : _poly) { buildLine(line, _rule, _props, _mesh, _tile); } } double widthMeterToPixel(int _zoom, double _tileSize, double _width) { // pixel per meter at z == 0 double meterRes = _tileSize / (2.0 * MapProjection::HALF_CIRCUMFERENCE); // pixel per meter at zoom meterRes *= exp2(_zoom); return _width * meterRes; } bool evalStyleParamWidth(StyleParamKey _key, const DrawRule& _rule, const Tile& _tile, float& width, float& dWdZ){ int zoom = _tile.getID().z; double tileSize = _tile.getProjection()->TileSize(); // NB: 0.5 because 'width' will be extruded in both directions double tileRes = 0.5 / tileSize; auto& styleParam = _rule.findParameter(_key); if (styleParam.stops) { width = styleParam.stops->evalWidth(zoom); width *= tileRes; dWdZ = styleParam.stops->evalWidth(zoom + 1); dWdZ *= tileRes; // NB: Multiply by 2 for the outline to get the expected stroke pixel width. if (_key == StyleParamKey::outline_width) { width *= 2; dWdZ *= 2; } dWdZ -= width; return true; } if (styleParam.value.is<StyleParam::Width>()) { auto& widthParam = styleParam.value.get<StyleParam::Width>(); width = widthParam.value; if (widthParam.isMeter()) { width = widthMeterToPixel(zoom, tileSize, width); width *= tileRes; dWdZ = width * 2; } else { width *= tileRes; dWdZ = width; } if (_key == StyleParamKey::outline_width) { width *= 2; dWdZ *= 2; } dWdZ -= width; return true; } logMsg("Error: Invalid type for Width '%d'\n", styleParam.value.which()); return false; } void PolylineStyle::buildLine(const Line& _line, const DrawRule& _rule, const Properties& _props, VboMesh& _mesh, Tile& _tile) const { if (!_rule.contains(StyleParamKey::color)) { const auto& blocks = m_shaderProgram->getSourceBlocks(); if (blocks.find("color") == blocks.end() && blocks.find("filter") == blocks.end()) { return; // No color parameter or color block? NO SOUP FOR YOU } } std::vector<PolylineVertex> vertices; Parameters params = parseRule(_rule); GLuint abgr = params.color; float dWdZ = 0.f; float width = 0.f; if (!evalStyleParamWidth(StyleParamKey::width, _rule, _tile, width, dWdZ)) { return; } if (Tangram::getDebugFlag(Tangram::DebugFlags::proxy_colors)) { abgr = abgr << (_tile.getID().z % 6); } float height = 0.0f; auto& extrude = params.extrude; if (extrude[0] != 0.0f || extrude[1] != 0.0f) { const static std::string key_height("height"); height = _props.getNumeric(key_height) * _tile.getInverseScale(); if (std::isnan(extrude[1])) { if (!std::isnan(extrude[0])) { height = extrude[0]; } } else { height = extrude[1]; } } PolyLineBuilder builder { [&](const glm::vec3& coord, const glm::vec2& normal, const glm::vec2& uv) { glm::vec4 extrude = { normal.x, normal.y, width, dWdZ }; vertices.push_back({ {coord.x, coord.y, height}, uv, extrude, abgr, (float)params.order }); }, [&](size_t sizeHint){ vertices.reserve(sizeHint); }, params.cap, params.join }; Builders::buildPolyLine(_line, builder); if (params.outlineOn) { GLuint abgrOutline = params.outlineColor; float outlineOrder = std::min(params.outlineOrder, params.order) - .5f; float widthOutline = 0.f; float dWdZOutline = 0.f; if (!evalStyleParamWidth(StyleParamKey::outline_width, _rule, _tile, widthOutline, dWdZOutline)) { return; } widthOutline += width; dWdZOutline += dWdZ; if (params.outlineCap != params.cap || params.outlineJoin != params.join) { // need to re-triangulate with different cap and/or join builder.cap = params.outlineCap; builder.join = params.outlineJoin; Builders::buildPolyLine(_line, builder); } else { // re-use indices from original line size_t oldSize = builder.indices.size(); size_t offset = vertices.size(); builder.indices.reserve(2 * oldSize); for(size_t i = 0; i < oldSize; i++) { builder.indices.push_back(offset + builder.indices[i]); } for (size_t i = 0; i < offset; i++) { const auto& v = vertices[i]; glm::vec4 extrudeOutline = { v.extrude.x, v.extrude.y, widthOutline, dWdZOutline }; vertices.push_back({ v.pos, v.texcoord, extrudeOutline, abgrOutline, outlineOrder }); } } } auto& mesh = static_cast<Mesh&>(_mesh); mesh.addVertices(std::move(vertices), std::move(builder.indices)); } } <commit_msg>log--<commit_after>#include "polylineStyle.h" #include "tangram.h" #include "platform.h" #include "material.h" #include "gl/shaderProgram.h" #include "gl/typedMesh.h" #include "scene/stops.h" #include "scene/drawRule.h" #include "tile/tile.h" #include "util/mapProjection.h" #include "glm/vec3.hpp" namespace Tangram { struct PolylineVertex { glm::vec3 pos; glm::vec2 texcoord; glm::vec4 extrude; GLuint abgr; GLfloat layer; }; using Mesh = TypedMesh<PolylineVertex>; PolylineStyle::PolylineStyle(std::string _name, Blending _blendMode, GLenum _drawMode) : Style(_name, _blendMode, _drawMode) { } void PolylineStyle::constructVertexLayout() { // TODO: Ideally this would be in the same location as the struct that it basically describes m_vertexLayout = std::shared_ptr<VertexLayout>(new VertexLayout({ {"a_position", 3, GL_FLOAT, false, 0}, {"a_texcoord", 2, GL_FLOAT, false, 0}, {"a_extrude", 4, GL_FLOAT, false, 0}, {"a_color", 4, GL_UNSIGNED_BYTE, true, 0}, {"a_layer", 1, GL_FLOAT, false, 0} })); } void PolylineStyle::constructShaderProgram() { std::string vertShaderSrcStr = stringFromFile("shaders/polyline.vs", PathType::internal); std::string fragShaderSrcStr = stringFromFile("shaders/polyline.fs", PathType::internal); m_shaderProgram->setSourceStrings(fragShaderSrcStr, vertShaderSrcStr); } VboMesh* PolylineStyle::newMesh() const { return new Mesh(m_vertexLayout, m_drawMode); } PolylineStyle::Parameters PolylineStyle::parseRule(const DrawRule& _rule) const { Parameters p; uint32_t cap = 0, join = 0; _rule.get(StyleParamKey::extrude, p.extrude); _rule.get(StyleParamKey::color, p.color); _rule.get(StyleParamKey::cap, cap); _rule.get(StyleParamKey::join, join); if (!_rule.get(StyleParamKey::order, p.order)) { LOGW("No 'order' specified for feature, ordering cannot be guaranteed :("); } p.cap = static_cast<CapTypes>(cap); p.join = static_cast<JoinTypes>(join); p.outlineOrder = p.order; // will offset from fill later if (_rule.get(StyleParamKey::outline_color, p.outlineColor) | _rule.get(StyleParamKey::outline_order, p.outlineOrder) | _rule.contains(StyleParamKey::outline_width) | _rule.get(StyleParamKey::outline_cap, cap) | _rule.get(StyleParamKey::outline_join, join)) { p.outlineOn = true; p.outlineCap = static_cast<CapTypes>(cap); p.outlineJoin = static_cast<JoinTypes>(join); } return p; } void PolylineStyle::buildPolygon(const Polygon& _poly, const DrawRule& _rule, const Properties& _props, VboMesh& _mesh, Tile& _tile) const { for (const auto& line : _poly) { buildLine(line, _rule, _props, _mesh, _tile); } } double widthMeterToPixel(int _zoom, double _tileSize, double _width) { // pixel per meter at z == 0 double meterRes = _tileSize / (2.0 * MapProjection::HALF_CIRCUMFERENCE); // pixel per meter at zoom meterRes *= exp2(_zoom); return _width * meterRes; } bool evalStyleParamWidth(StyleParamKey _key, const DrawRule& _rule, const Tile& _tile, float& width, float& dWdZ){ int zoom = _tile.getID().z; double tileSize = _tile.getProjection()->TileSize(); // NB: 0.5 because 'width' will be extruded in both directions double tileRes = 0.5 / tileSize; auto& styleParam = _rule.findParameter(_key); if (styleParam.stops) { width = styleParam.stops->evalWidth(zoom); width *= tileRes; dWdZ = styleParam.stops->evalWidth(zoom + 1); dWdZ *= tileRes; // NB: Multiply by 2 for the outline to get the expected stroke pixel width. if (_key == StyleParamKey::outline_width) { width *= 2; dWdZ *= 2; } dWdZ -= width; return true; } if (styleParam.value.is<StyleParam::Width>()) { auto& widthParam = styleParam.value.get<StyleParam::Width>(); width = widthParam.value; if (widthParam.isMeter()) { width = widthMeterToPixel(zoom, tileSize, width); width *= tileRes; dWdZ = width * 2; } else { width *= tileRes; dWdZ = width; } if (_key == StyleParamKey::outline_width) { width *= 2; dWdZ *= 2; } dWdZ -= width; return true; } LOGD("Invalid type for Width '%d'\n", styleParam.value.which()); return false; } void PolylineStyle::buildLine(const Line& _line, const DrawRule& _rule, const Properties& _props, VboMesh& _mesh, Tile& _tile) const { if (!_rule.contains(StyleParamKey::color)) { const auto& blocks = m_shaderProgram->getSourceBlocks(); if (blocks.find("color") == blocks.end() && blocks.find("filter") == blocks.end()) { return; // No color parameter or color block? NO SOUP FOR YOU } } std::vector<PolylineVertex> vertices; Parameters params = parseRule(_rule); GLuint abgr = params.color; float dWdZ = 0.f; float width = 0.f; if (!evalStyleParamWidth(StyleParamKey::width, _rule, _tile, width, dWdZ)) { return; } if (Tangram::getDebugFlag(Tangram::DebugFlags::proxy_colors)) { abgr = abgr << (_tile.getID().z % 6); } float height = 0.0f; auto& extrude = params.extrude; if (extrude[0] != 0.0f || extrude[1] != 0.0f) { const static std::string key_height("height"); height = _props.getNumeric(key_height) * _tile.getInverseScale(); if (std::isnan(extrude[1])) { if (!std::isnan(extrude[0])) { height = extrude[0]; } } else { height = extrude[1]; } } PolyLineBuilder builder { [&](const glm::vec3& coord, const glm::vec2& normal, const glm::vec2& uv) { glm::vec4 extrude = { normal.x, normal.y, width, dWdZ }; vertices.push_back({ {coord.x, coord.y, height}, uv, extrude, abgr, (float)params.order }); }, [&](size_t sizeHint){ vertices.reserve(sizeHint); }, params.cap, params.join }; Builders::buildPolyLine(_line, builder); if (params.outlineOn) { GLuint abgrOutline = params.outlineColor; float outlineOrder = std::min(params.outlineOrder, params.order) - .5f; float widthOutline = 0.f; float dWdZOutline = 0.f; if (!evalStyleParamWidth(StyleParamKey::outline_width, _rule, _tile, widthOutline, dWdZOutline)) { return; } widthOutline += width; dWdZOutline += dWdZ; if (params.outlineCap != params.cap || params.outlineJoin != params.join) { // need to re-triangulate with different cap and/or join builder.cap = params.outlineCap; builder.join = params.outlineJoin; Builders::buildPolyLine(_line, builder); } else { // re-use indices from original line size_t oldSize = builder.indices.size(); size_t offset = vertices.size(); builder.indices.reserve(2 * oldSize); for(size_t i = 0; i < oldSize; i++) { builder.indices.push_back(offset + builder.indices[i]); } for (size_t i = 0; i < offset; i++) { const auto& v = vertices[i]; glm::vec4 extrudeOutline = { v.extrude.x, v.extrude.y, widthOutline, dWdZOutline }; vertices.push_back({ v.pos, v.texcoord, extrudeOutline, abgrOutline, outlineOrder }); } } } auto& mesh = static_cast<Mesh&>(_mesh); mesh.addVertices(std::move(vertices), std::move(builder.indices)); } } <|endoftext|>
<commit_before>#include "FitsObject.h" #include <stdexcept> using namespace std; Fits::Fits(const string &filename) : m_status(0), m_filename(filename) { fits_open_file(&*this->fptr(), this->m_filename.c_str(), READWRITE, &this->status()); this->check(); } Fits::Fits() {} Fits::~Fits() { fits_close_file(*this->fptr(), &this->status()); this->check(); } void Fits::check() { if (this->status()) { char buf[FLEN_STATUS]; fits_get_errstatus(this->status(), buf); //Have to set the status back to 0 otherwise //when the destructor is called and the file is closed //then another exception will be thrown this->status() = 0; // Ensure the marks are not visible fits_clear_errmsg(); throw runtime_error(buf); } } void Fits::moveHDU(const string &hduname) { fits_movnam_hdu(*this->fptr(), ANY_HDU, const_cast<char*>(hduname.c_str()), 0, &this->status()); this->check(); } void Fits::moveHDU(int hdunum) { int hdutype; fits_movabs_hdu(*this->fptr(), hdunum, &hdutype, &this->status()); this->check(); } void Fits::checkForTable() { /* Checks for a table extension */ int hdutype; fits_get_hdu_type(*this->fptr(), &hdutype, &this->status()); this->check(); if ((hdutype != ASCII_TBL) && (hdutype != BINARY_TBL)) { throw runtime_error("Non-table hdu found"); } } int Fits::columnNumber(const std::string &colname) { this->checkForTable(); int colnum; fits_get_colnum(*this->fptr(), CASEINSEN, const_cast<char*>(colname.c_str()), &colnum, &this->status()); this->check(); return colnum; } long Fits::nrows() { // Ensure the current hdu is a (binary) table this->checkForTable(); int hdutype; fits_get_hdu_type(*this->fptr(), &hdutype, &this->status()); this->check(); if ((hdutype != ASCII_TBL) && (hdutype != BINARY_TBL)) { throw runtime_error("Non-table hdu found"); } long nrows; fits_get_num_rows(*this->fptr(), &nrows, &this->status()); this->check(); return nrows; } fitsfile **Fits::fptr() { return &this->m_fptr; } int &Fits::status() { return this->m_status; } void Fits::check(int status) { if (status) { char buf[FLEN_STATUS]; fits_get_errstatus(status, buf); throw runtime_error(buf); } } const string Fits::hduname() { char buf[FLEN_VALUE]; fits_read_key(*this->fptr(), TSTRING, "EXTNAME", buf, NULL, &this->status()); this->check(); return string(buf); } NewFits::NewFits(const string &filename) { this->m_filename = filename; this->status() = 0; fits_create_file(&*this->fptr(), filename.c_str(), &this->status()); this->check(); /* Ensure the basic keywords are there */ long naxes[] = {0, 0}; fits_create_img(*this->fptr(), BYTE_IMG, 0, naxes, &this->status()); this->check(); } vector<string> Fits::stringColumn(const string &columnname) { int colno = this->columnNumber(columnname); long nrows = this->nrows(); int dispwidth; fits_get_col_display_width(*this->fptr(), colno, &dispwidth, &this->status()); vector<string> Objects; for (int i=0; i<nrows; ++i) { char Name[dispwidth+1], *nptr=(char*)Name; fits_read_col_str(*this->fptr(), colno, i+1, 1, 1, "", &nptr, NULL, &this->status()); this->check(); Objects.push_back(Name); } this->check(); return Objects; } <commit_msg>added definitions<commit_after>#include "FitsObject.h" #include <stdexcept> using namespace std; Fits::Fits(const string &filename) : m_status(0), m_filename(filename) { fits_open_file(&*this->fptr(), this->m_filename.c_str(), READWRITE, &this->status()); this->check(); } Fits::Fits() {} Fits::~Fits() { fits_close_file(*this->fptr(), &this->status()); this->check(); } void Fits::check() { if (this->status()) { char buf[FLEN_STATUS]; fits_get_errstatus(this->status(), buf); //Have to set the status back to 0 otherwise //when the destructor is called and the file is closed //then another exception will be thrown this->status() = 0; // Ensure the marks are not visible fits_clear_errmsg(); throw runtime_error(buf); } } void Fits::moveHDU(const string &hduname) { fits_movnam_hdu(*this->fptr(), ANY_HDU, const_cast<char*>(hduname.c_str()), 0, &this->status()); this->check(); } void Fits::moveHDU(int hdunum) { int hdutype; fits_movabs_hdu(*this->fptr(), hdunum, &hdutype, &this->status()); this->check(); } void Fits::checkForTable() { /* Checks for a table extension */ int hdutype; fits_get_hdu_type(*this->fptr(), &hdutype, &this->status()); this->check(); if ((hdutype != ASCII_TBL) && (hdutype != BINARY_TBL)) { throw runtime_error("Non-table hdu found"); } } int Fits::columnNumber(const std::string &colname) { this->checkForTable(); int colnum; fits_get_colnum(*this->fptr(), CASEINSEN, const_cast<char*>(colname.c_str()), &colnum, &this->status()); this->check(); return colnum; } long Fits::nrows() { // Ensure the current hdu is a (binary) table this->checkForTable(); int hdutype; fits_get_hdu_type(*this->fptr(), &hdutype, &this->status()); this->check(); if ((hdutype != ASCII_TBL) && (hdutype != BINARY_TBL)) { throw runtime_error("Non-table hdu found"); } long nrows; fits_get_num_rows(*this->fptr(), &nrows, &this->status()); this->check(); return nrows; } fitsfile **Fits::fptr() { return &this->m_fptr; } int &Fits::status() { return this->m_status; } void Fits::check(int status) { if (status) { char buf[FLEN_STATUS]; fits_get_errstatus(status, buf); throw runtime_error(buf); } } const string Fits::hduname() { char buf[FLEN_VALUE]; fits_read_key(*this->fptr(), TSTRING, "EXTNAME", buf, NULL, &this->status()); this->check(); return string(buf); } NewFits::NewFits(const string &filename) { this->m_filename = filename; this->status() = 0; fits_create_file(&*this->fptr(), filename.c_str(), &this->status()); this->check(); /* Ensure the basic keywords are there */ long naxes[] = {0, 0}; fits_create_img(*this->fptr(), BYTE_IMG, 0, naxes, &this->status()); this->check(); } vector<string> Fits::stringColumn(const string &columnname) { int colno = this->columnNumber(columnname); long nrows = this->nrows(); int dispwidth; fits_get_col_display_width(*this->fptr(), colno, &dispwidth, &this->status()); vector<string> Objects; for (int i=0; i<nrows; ++i) { char Name[dispwidth+1], *nptr=(char*)Name; fits_read_col_str(*this->fptr(), colno, i+1, 1, 1, "", &nptr, NULL, &this->status()); this->check(); Objects.push_back(Name); } this->check(); return Objects; } template<> vector<double> Fits::columnData(const string &columnname) { int colno = this->columnNumber(columnname); long nrows = this->nrows(); std::vector<double> data(nrows); fits_read_col(*this->fptr(), TDOUBLE, colno, 1, 1, nrows, NULL, &data[0], NULL, &this->status()); this->check(); return data; } template<> vector<long> Fits::columnData(const string &columnname) { int colno = this->columnNumber(columnname); long nrows = this->nrows(); std::vector<long> data(nrows); fits_read_col(*this->fptr(), TINT, colno, 1, 1, nrows, NULL, &data[0], NULL, &this->status()); this->check(); return data; } template<> vector<int> Fits::columnData(const string &columnname) { int colno = this->columnNumber(columnname); long nrows = this->nrows(); std::vector<int> data(nrows); fits_read_col(*this->fptr(), TINT, colno, 1, 1, nrows, NULL, &data[0], NULL, &this->status()); this->check(); return data; } template<> vector<float> Fits::columnData(const string &columnname) { int colno = this->columnNumber(columnname); long nrows = this->nrows(); std::vector<float> data(nrows); fits_read_col(*this->fptr(), TFLOAT, colno, 1, 1, nrows, NULL, &data[0], NULL, &this->status()); this->check(); return data; } template<> vector<string> Fits::columnData(const string &columnname) { int colno = this->columnNumber(columnname); long nrows = this->nrows(); int dispwidth; fits_get_col_display_width(*this->fptr(), colno, &dispwidth, &this->status()); vector<string> Objects; for (int i=0; i<nrows; ++i) { char Name[dispwidth+1], *nptr=(char*)Name; fits_read_col_str(*this->fptr(), colno, i+1, 1, 1, "", &nptr, NULL, &this->status()); this->check(); Objects.push_back(Name); } this->check(); return Objects; } <|endoftext|>
<commit_before>/* open source routing machine Copyright (C) Dennis Luxen, others 2010 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 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 Affero General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA or see http://www.gnu.org/licenses/agpl.txt. */ #include "QueryObjectsStorage.h" QueryObjectsStorage::QueryObjectsStorage( const std::string & hsgrPath, const std::string & ramIndexPath, const std::string & fileIndexPath, const std::string & nodesPath, const std::string & edgesPath, const std::string & namesPath, const std::string & timestampPath ) { if("" == hsgrPath) { throw OSRMException("no hsgr file given in ini file"); } if("" == ramIndexPath) { throw OSRMException("no ram index file given in ini file"); } if("" == fileIndexPath) { throw OSRMException("no mem index file given in ini file"); } if("" == nodesPath) { throw OSRMException("no nodes file given in ini file"); } if("" == edgesPath) { throw OSRMException("no edges file given in ini file"); } if("" == namesPath) { throw OSRMException("no names file given in ini file"); } SimpleLogger().Write() << "loading graph data"; //Deserialize road network graph std::vector< QueryGraph::_StrNode> nodeList; std::vector< QueryGraph::_StrEdge> edgeList; const int n = readHSGRFromStream( hsgrPath, nodeList, edgeList, &checkSum ); SimpleLogger().Write() << "Data checksum is " << checkSum; graph = new QueryGraph(nodeList, edgeList); assert(0 == nodeList.size()); assert(0 == edgeList.size()); if(timestampPath.length()) { SimpleLogger().Write() << "Loading Timestamp"; std::ifstream timestampInStream(timestampPath.c_str()); if(!timestampInStream) { SimpleLogger().Write(logWARNING) << timestampPath << " not found"; } getline(timestampInStream, timestamp); timestampInStream.close(); } if(!timestamp.length()) { timestamp = "n/a"; } if(25 < timestamp.length()) { timestamp.resize(25); } SimpleLogger().Write() << "Loading auxiliary information"; //Init nearest neighbor data structure nodeHelpDesk = new NodeInformationHelpDesk( ramIndexPath, fileIndexPath, nodesPath, edgesPath, n, checkSum ); //deserialize street name list SimpleLogger().Write() << "Loading names index"; boost::filesystem::path names_file(namesPath); if ( !boost::filesystem::exists( names_file ) ) { throw OSRMException("names file does not exist"); } if ( 0 == boost::filesystem::file_size( names_file ) ) { throw OSRMException("names file is empty"); } boost::filesystem::ifstream name_stream(names_file, std::ios::binary); unsigned size = 0; name_stream.read((char *)&size, sizeof(unsigned)); BOOST_ASSERT_MSG(0 != size, "name file empty"); char buf[1024]; for( unsigned i = 0; i < size; ++i ) { unsigned size_of_string = 0; name_stream.read((char *)&size_of_string, sizeof(unsigned)); buf[size_of_string] = '\0'; // instead of memset name_stream.read(buf, size_of_string); names.push_back(buf); } std::vector<std::string>(names).swap(names); BOOST_ASSERT_MSG(0 != names.size(), "could not load any names"); name_stream.close(); SimpleLogger().Write() << "All query data structures loaded"; } QueryObjectsStorage::~QueryObjectsStorage() { // delete names; delete graph; delete nodeHelpDesk; } <commit_msg>use proper check for empty string<commit_after>/* open source routing machine Copyright (C) Dennis Luxen, others 2010 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 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 Affero General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA or see http://www.gnu.org/licenses/agpl.txt. */ #include "QueryObjectsStorage.h" QueryObjectsStorage::QueryObjectsStorage( const std::string & hsgrPath, const std::string & ramIndexPath, const std::string & fileIndexPath, const std::string & nodesPath, const std::string & edgesPath, const std::string & namesPath, const std::string & timestampPath ) { if( hsgrPath.empty() ) { throw OSRMException("no hsgr file given in ini file"); } if( ramIndexPath.empty() ) { throw OSRMException("no ram index file given in ini file"); } if( fileIndexPath.empty() ) { throw OSRMException("no mem index file given in ini file"); } if( nodesPath.empty() ) { throw OSRMException("no nodes file given in ini file"); } if( edgesPath.empty() ) { throw OSRMException("no edges file given in ini file"); } if( namesPath.empty() ) { throw OSRMException("no names file given in ini file"); } SimpleLogger().Write() << "loading graph data"; //Deserialize road network graph std::vector< QueryGraph::_StrNode> nodeList; std::vector< QueryGraph::_StrEdge> edgeList; const int n = readHSGRFromStream( hsgrPath, nodeList, edgeList, &checkSum ); SimpleLogger().Write() << "Data checksum is " << checkSum; graph = new QueryGraph(nodeList, edgeList); assert(0 == nodeList.size()); assert(0 == edgeList.size()); if(timestampPath.length()) { SimpleLogger().Write() << "Loading Timestamp"; std::ifstream timestampInStream(timestampPath.c_str()); if(!timestampInStream) { SimpleLogger().Write(logWARNING) << timestampPath << " not found"; } getline(timestampInStream, timestamp); timestampInStream.close(); } if(!timestamp.length()) { timestamp = "n/a"; } if(25 < timestamp.length()) { timestamp.resize(25); } SimpleLogger().Write() << "Loading auxiliary information"; //Init nearest neighbor data structure nodeHelpDesk = new NodeInformationHelpDesk( ramIndexPath, fileIndexPath, nodesPath, edgesPath, n, checkSum ); //deserialize street name list SimpleLogger().Write() << "Loading names index"; boost::filesystem::path names_file(namesPath); if ( !boost::filesystem::exists( names_file ) ) { throw OSRMException("names file does not exist"); } if ( 0 == boost::filesystem::file_size( names_file ) ) { throw OSRMException("names file is empty"); } boost::filesystem::ifstream name_stream(names_file, std::ios::binary); unsigned size = 0; name_stream.read((char *)&size, sizeof(unsigned)); BOOST_ASSERT_MSG(0 != size, "name file empty"); char buf[1024]; for( unsigned i = 0; i < size; ++i ) { unsigned size_of_string = 0; name_stream.read((char *)&size_of_string, sizeof(unsigned)); buf[size_of_string] = '\0'; // instead of memset name_stream.read(buf, size_of_string); names.push_back(buf); } std::vector<std::string>(names).swap(names); BOOST_ASSERT_MSG(0 != names.size(), "could not load any names"); name_stream.close(); SimpleLogger().Write() << "All query data structures loaded"; } QueryObjectsStorage::~QueryObjectsStorage() { // delete names; delete graph; delete nodeHelpDesk; } <|endoftext|>
<commit_before><commit_msg>Fix PickleTest.GetReadPointerAndAdvance not to produce wild addresses while checking for overflows.<commit_after><|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * 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 "mysql/YTable.hxx" #include "mysql/YTables.hxx" #include <com/sun/star/sdbc/XRow.hpp> #include <com/sun/star/sdbc/XResultSet.hpp> #include <com/sun/star/sdbcx/KeyType.hpp> #include <com/sun/star/sdbc/KeyRule.hpp> #include <cppuhelper/typeprovider.hxx> #include <com/sun/star/lang/DisposedException.hpp> #include <com/sun/star/sdbc/ColumnValue.hpp> #include <com/sun/star/sdbcx/Privilege.hpp> #include <comphelper/property.hxx> #include <comphelper/extract.hxx> #include <comphelper/types.hxx> #include "connectivity/dbtools.hxx" #include "connectivity/sdbcx/VColumn.hxx" #include "connectivity/TKeys.hxx" #include "connectivity/TIndexes.hxx" #include "connectivity/TColumnsHelper.hxx" #include "mysql/YCatalog.hxx" #include "mysql/YColumns.hxx" #include "TConnection.hxx" using namespace ::comphelper; using namespace connectivity::mysql; using namespace connectivity::sdbcx; using namespace connectivity; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::sdbcx; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::container; using namespace ::com::sun::star::lang; namespace connectivity { namespace mysql { class OMySQLKeysHelper : public OKeysHelper { protected: // ----------------------------------------------------------------------------- virtual ::rtl::OUString getDropForeignKey() const { return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(" DROP FOREIGN KEY ")); } public: OMySQLKeysHelper( OTableHelper* _pTable, ::osl::Mutex& _rMutex, const TStringVector& _rVector ) : OKeysHelper(_pTable,_rMutex,_rVector){} }; } } OMySQLTable::OMySQLTable( sdbcx::OCollection* _pTables, const Reference< XConnection >& _xConnection) :OTableHelper(_pTables,_xConnection,sal_True) { // we create a new table here, so we should have all the rights or ;-) m_nPrivileges = Privilege::DROP | Privilege::REFERENCE | Privilege::ALTER | Privilege::CREATE | Privilege::READ | Privilege::DELETE | Privilege::UPDATE | Privilege::INSERT | Privilege::SELECT; construct(); } // ------------------------------------------------------------------------- OMySQLTable::OMySQLTable( sdbcx::OCollection* _pTables, const Reference< XConnection >& _xConnection, const ::rtl::OUString& _Name, const ::rtl::OUString& _Type, const ::rtl::OUString& _Description , const ::rtl::OUString& _SchemaName, const ::rtl::OUString& _CatalogName, sal_Int32 _nPrivileges ) : OTableHelper( _pTables, _xConnection, sal_True, _Name, _Type, _Description, _SchemaName, _CatalogName) , m_nPrivileges(_nPrivileges) { construct(); } // ------------------------------------------------------------------------- void OMySQLTable::construct() { OTableHelper::construct(); if ( !isNew() ) registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_PRIVILEGES), PROPERTY_ID_PRIVILEGES,PropertyAttribute::READONLY,&m_nPrivileges, ::getCppuType(&m_nPrivileges)); } // ----------------------------------------------------------------------------- ::cppu::IPropertyArrayHelper* OMySQLTable::createArrayHelper( sal_Int32 /*_nId*/ ) const { return doCreateArrayHelper(); } // ------------------------------------------------------------------------- ::cppu::IPropertyArrayHelper & OMySQLTable::getInfoHelper() { return *static_cast<OMySQLTable_PROP*>(const_cast<OMySQLTable*>(this))->getArrayHelper(isNew() ? 1 : 0); } // ----------------------------------------------------------------------------- sdbcx::OCollection* OMySQLTable::createColumns(const TStringVector& _rNames) { OMySQLColumns* pColumns = new OMySQLColumns(*this,sal_True,m_aMutex,_rNames); pColumns->setParent(this); return pColumns; } // ----------------------------------------------------------------------------- sdbcx::OCollection* OMySQLTable::createKeys(const TStringVector& _rNames) { return new OMySQLKeysHelper(this,m_aMutex,_rNames); } // ----------------------------------------------------------------------------- sdbcx::OCollection* OMySQLTable::createIndexes(const TStringVector& _rNames) { return new OIndexesHelper(this,m_aMutex,_rNames); } //-------------------------------------------------------------------------- Sequence< sal_Int8 > OMySQLTable::getUnoTunnelImplementationId() { static ::cppu::OImplementationId * pId = 0; if (! pId) { ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() ); if (! pId) { static ::cppu::OImplementationId aId; pId = &aId; } } return pId->getImplementationId(); } // com::sun::star::lang::XUnoTunnel //------------------------------------------------------------------ sal_Int64 OMySQLTable::getSomething( const Sequence< sal_Int8 > & rId ) throw (RuntimeException) { return (rId.getLength() == 16 && 0 == rtl_compareMemory(getUnoTunnelImplementationId().getConstArray(), rId.getConstArray(), 16 ) ) ? reinterpret_cast< sal_Int64 >( this ) : OTable_TYPEDEF::getSomething(rId); } // ------------------------------------------------------------------------- // XAlterTable void SAL_CALL OMySQLTable::alterColumnByName( const ::rtl::OUString& colName, const Reference< XPropertySet >& descriptor ) throw(SQLException, NoSuchElementException, RuntimeException) { ::osl::MutexGuard aGuard(m_aMutex); checkDisposed( #ifdef GCC ::connectivity::sdbcx::OTableDescriptor_BASE::rBHelper.bDisposed #else rBHelper.bDisposed #endif ); if ( m_pColumns && !m_pColumns->hasByName(colName) ) throw NoSuchElementException(colName,*this); if ( !isNew() ) { // first we have to check what should be altered Reference<XPropertySet> xProp; m_pColumns->getByName(colName) >>= xProp; // first check the types sal_Int32 nOldType = 0,nNewType = 0,nOldPrec = 0,nNewPrec = 0,nOldScale = 0,nNewScale = 0; ::dbtools::OPropertyMap& rProp = OMetaConnection::getPropMap(); xProp->getPropertyValue(rProp.getNameByIndex(PROPERTY_ID_TYPE)) >>= nOldType; descriptor->getPropertyValue(rProp.getNameByIndex(PROPERTY_ID_TYPE)) >>= nNewType; // and precsions and scale xProp->getPropertyValue(rProp.getNameByIndex(PROPERTY_ID_PRECISION)) >>= nOldPrec; descriptor->getPropertyValue(rProp.getNameByIndex(PROPERTY_ID_PRECISION))>>= nNewPrec; xProp->getPropertyValue(rProp.getNameByIndex(PROPERTY_ID_SCALE)) >>= nOldScale; descriptor->getPropertyValue(rProp.getNameByIndex(PROPERTY_ID_SCALE)) >>= nNewScale; // second: check the "is nullable" value sal_Int32 nOldNullable = 0,nNewNullable = 0; xProp->getPropertyValue(rProp.getNameByIndex(PROPERTY_ID_ISNULLABLE)) >>= nOldNullable; descriptor->getPropertyValue(rProp.getNameByIndex(PROPERTY_ID_ISNULLABLE)) >>= nNewNullable; // check also the auto_increment sal_Bool bOldAutoIncrement = sal_False,bAutoIncrement = sal_False; xProp->getPropertyValue(rProp.getNameByIndex(PROPERTY_ID_ISAUTOINCREMENT)) >>= bOldAutoIncrement; descriptor->getPropertyValue(rProp.getNameByIndex(PROPERTY_ID_ISAUTOINCREMENT)) >>= bAutoIncrement; bool bColumnNameChanged = false; ::rtl::OUString sOldDesc,sNewDesc; xProp->getPropertyValue(rProp.getNameByIndex(PROPERTY_ID_DESCRIPTION)) >>= sOldDesc; descriptor->getPropertyValue(rProp.getNameByIndex(PROPERTY_ID_DESCRIPTION)) >>= sNewDesc; if ( nOldType != nNewType || nOldPrec != nNewPrec || nOldScale != nNewScale || nNewNullable != nOldNullable || bOldAutoIncrement != bAutoIncrement || sOldDesc != sNewDesc ) { // special handling because they change dthe type names to distinguish // if a column should be an auto_incmrement one if ( bOldAutoIncrement != bAutoIncrement ) { ::rtl::OUString sTypeName; descriptor->getPropertyValue(rProp.getNameByIndex(PROPERTY_ID_TYPENAME)) >>= sTypeName; static ::rtl::OUString s_sAutoIncrement(RTL_CONSTASCII_USTRINGPARAM("auto_increment")); if ( bAutoIncrement ) { if ( sTypeName.indexOf(s_sAutoIncrement) == -1 ) { sTypeName += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(" ")); sTypeName += s_sAutoIncrement; } } else { sal_Int32 nIndex = 0; if ( !sTypeName.isEmpty() && (nIndex = sTypeName.indexOf(s_sAutoIncrement)) != -1 ) { sTypeName = sTypeName.copy(0,nIndex); descriptor->setPropertyValue(rProp.getNameByIndex(PROPERTY_ID_TYPENAME),makeAny(sTypeName)); } } } alterColumnType(nNewType,colName,descriptor); bColumnNameChanged = true; } // third: check the default values ::rtl::OUString sNewDefault,sOldDefault; xProp->getPropertyValue(rProp.getNameByIndex(PROPERTY_ID_DEFAULTVALUE)) >>= sOldDefault; descriptor->getPropertyValue(rProp.getNameByIndex(PROPERTY_ID_DEFAULTVALUE)) >>= sNewDefault; if(!sOldDefault.isEmpty()) { dropDefaultValue(colName); if(!sNewDefault.isEmpty() && sOldDefault != sNewDefault) alterDefaultValue(sNewDefault,colName); } else if(sOldDefault.isEmpty() && !sNewDefault.isEmpty()) alterDefaultValue(sNewDefault,colName); // now we should look if the name of the column changed ::rtl::OUString sNewColumnName; descriptor->getPropertyValue(rProp.getNameByIndex(PROPERTY_ID_NAME)) >>= sNewColumnName; if ( !sNewColumnName.equalsIgnoreAsciiCase(colName) && !bColumnNameChanged ) { ::rtl::OUString sSql = getAlterTableColumnPart(); sSql += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(" CHANGE ")); const ::rtl::OUString sQuote = getMetaData()->getIdentifierQuoteString( ); sSql += ::dbtools::quoteName(sQuote,colName); sSql += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(" ")); sSql += OTables::adjustSQL(::dbtools::createStandardColumnPart(descriptor,getConnection(),static_cast<OTables*>(m_pTables),getTypeCreatePattern())); executeStatement(sSql); } m_pColumns->refresh(); } else { if(m_pColumns) { m_pColumns->dropByName(colName); m_pColumns->appendByDescriptor(descriptor); } } } // ----------------------------------------------------------------------------- void OMySQLTable::alterColumnType(sal_Int32 nNewType,const ::rtl::OUString& _rColName, const Reference<XPropertySet>& _xDescriptor) { ::rtl::OUString sSql = getAlterTableColumnPart(); sSql += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(" CHANGE ")); const ::rtl::OUString sQuote = getMetaData()->getIdentifierQuoteString( ); sSql += ::dbtools::quoteName(sQuote,_rColName); sSql += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(" ")); OColumn* pColumn = new OColumn(sal_True); Reference<XPropertySet> xProp = pColumn; ::comphelper::copyProperties(_xDescriptor,xProp); xProp->setPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPE),makeAny(nNewType)); sSql += OTables::adjustSQL(::dbtools::createStandardColumnPart(xProp,getConnection(),static_cast<OTables*>(m_pTables),getTypeCreatePattern())); executeStatement(sSql); } // ----------------------------------------------------------------------------- ::rtl::OUString OMySQLTable::getTypeCreatePattern() const { static const ::rtl::OUString s_sCreatePattern(RTL_CONSTASCII_USTRINGPARAM("(M,D)")); return s_sCreatePattern; } // ----------------------------------------------------------------------------- void OMySQLTable::alterDefaultValue(const ::rtl::OUString& _sNewDefault,const ::rtl::OUString& _rColName) { ::rtl::OUString sSql = getAlterTableColumnPart(); sSql += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(" ALTER ")); const ::rtl::OUString sQuote = getMetaData()->getIdentifierQuoteString( ); sSql += ::dbtools::quoteName(sQuote,_rColName); sSql += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(" SET DEFAULT '")) + _sNewDefault; sSql += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("'")); executeStatement(sSql); } // ----------------------------------------------------------------------------- void OMySQLTable::dropDefaultValue(const ::rtl::OUString& _rColName) { ::rtl::OUString sSql = getAlterTableColumnPart(); sSql += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(" ALTER ")); const ::rtl::OUString sQuote = getMetaData()->getIdentifierQuoteString( ); sSql += ::dbtools::quoteName(sQuote,_rColName); sSql += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(" DROP DEFAULT")); executeStatement(sSql); } // ----------------------------------------------------------------------------- ::rtl::OUString OMySQLTable::getAlterTableColumnPart() { ::rtl::OUString sSql( RTL_CONSTASCII_USTRINGPARAM( "ALTER TABLE " )); const ::rtl::OUString sQuote = getMetaData()->getIdentifierQuoteString( ); ::rtl::OUString sComposedName( ::dbtools::composeTableName( getMetaData(), m_CatalogName, m_SchemaName, m_Name, sal_True, ::dbtools::eInTableDefinitions ) ); sSql += sComposedName; return sSql; } // ----------------------------------------------------------------------------- void OMySQLTable::executeStatement(const ::rtl::OUString& _rStatement ) { ::rtl::OUString sSQL = _rStatement; if(sSQL.lastIndexOf(',') == (sSQL.getLength()-1)) sSQL = sSQL.replaceAt(sSQL.getLength()-1,1,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(")"))); Reference< XStatement > xStmt = getConnection()->createStatement( ); if ( xStmt.is() ) { xStmt->execute(sSQL); ::comphelper::disposeComponent(xStmt); } } // ----------------------------------------------------------------------------- ::rtl::OUString OMySQLTable::getRenameStart() const { return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("RENAME TABLE ")); } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>drop redundant always-true condition<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * 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 "mysql/YTable.hxx" #include "mysql/YTables.hxx" #include <com/sun/star/sdbc/XRow.hpp> #include <com/sun/star/sdbc/XResultSet.hpp> #include <com/sun/star/sdbcx/KeyType.hpp> #include <com/sun/star/sdbc/KeyRule.hpp> #include <cppuhelper/typeprovider.hxx> #include <com/sun/star/lang/DisposedException.hpp> #include <com/sun/star/sdbc/ColumnValue.hpp> #include <com/sun/star/sdbcx/Privilege.hpp> #include <comphelper/property.hxx> #include <comphelper/extract.hxx> #include <comphelper/types.hxx> #include "connectivity/dbtools.hxx" #include "connectivity/sdbcx/VColumn.hxx" #include "connectivity/TKeys.hxx" #include "connectivity/TIndexes.hxx" #include "connectivity/TColumnsHelper.hxx" #include "mysql/YCatalog.hxx" #include "mysql/YColumns.hxx" #include "TConnection.hxx" using namespace ::comphelper; using namespace connectivity::mysql; using namespace connectivity::sdbcx; using namespace connectivity; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::sdbcx; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::container; using namespace ::com::sun::star::lang; namespace connectivity { namespace mysql { class OMySQLKeysHelper : public OKeysHelper { protected: // ----------------------------------------------------------------------------- virtual ::rtl::OUString getDropForeignKey() const { return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(" DROP FOREIGN KEY ")); } public: OMySQLKeysHelper( OTableHelper* _pTable, ::osl::Mutex& _rMutex, const TStringVector& _rVector ) : OKeysHelper(_pTable,_rMutex,_rVector){} }; } } OMySQLTable::OMySQLTable( sdbcx::OCollection* _pTables, const Reference< XConnection >& _xConnection) :OTableHelper(_pTables,_xConnection,sal_True) { // we create a new table here, so we should have all the rights or ;-) m_nPrivileges = Privilege::DROP | Privilege::REFERENCE | Privilege::ALTER | Privilege::CREATE | Privilege::READ | Privilege::DELETE | Privilege::UPDATE | Privilege::INSERT | Privilege::SELECT; construct(); } // ------------------------------------------------------------------------- OMySQLTable::OMySQLTable( sdbcx::OCollection* _pTables, const Reference< XConnection >& _xConnection, const ::rtl::OUString& _Name, const ::rtl::OUString& _Type, const ::rtl::OUString& _Description , const ::rtl::OUString& _SchemaName, const ::rtl::OUString& _CatalogName, sal_Int32 _nPrivileges ) : OTableHelper( _pTables, _xConnection, sal_True, _Name, _Type, _Description, _SchemaName, _CatalogName) , m_nPrivileges(_nPrivileges) { construct(); } // ------------------------------------------------------------------------- void OMySQLTable::construct() { OTableHelper::construct(); if ( !isNew() ) registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_PRIVILEGES), PROPERTY_ID_PRIVILEGES,PropertyAttribute::READONLY,&m_nPrivileges, ::getCppuType(&m_nPrivileges)); } // ----------------------------------------------------------------------------- ::cppu::IPropertyArrayHelper* OMySQLTable::createArrayHelper( sal_Int32 /*_nId*/ ) const { return doCreateArrayHelper(); } // ------------------------------------------------------------------------- ::cppu::IPropertyArrayHelper & OMySQLTable::getInfoHelper() { return *static_cast<OMySQLTable_PROP*>(const_cast<OMySQLTable*>(this))->getArrayHelper(isNew() ? 1 : 0); } // ----------------------------------------------------------------------------- sdbcx::OCollection* OMySQLTable::createColumns(const TStringVector& _rNames) { OMySQLColumns* pColumns = new OMySQLColumns(*this,sal_True,m_aMutex,_rNames); pColumns->setParent(this); return pColumns; } // ----------------------------------------------------------------------------- sdbcx::OCollection* OMySQLTable::createKeys(const TStringVector& _rNames) { return new OMySQLKeysHelper(this,m_aMutex,_rNames); } // ----------------------------------------------------------------------------- sdbcx::OCollection* OMySQLTable::createIndexes(const TStringVector& _rNames) { return new OIndexesHelper(this,m_aMutex,_rNames); } //-------------------------------------------------------------------------- Sequence< sal_Int8 > OMySQLTable::getUnoTunnelImplementationId() { static ::cppu::OImplementationId * pId = 0; if (! pId) { ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() ); if (! pId) { static ::cppu::OImplementationId aId; pId = &aId; } } return pId->getImplementationId(); } // com::sun::star::lang::XUnoTunnel //------------------------------------------------------------------ sal_Int64 OMySQLTable::getSomething( const Sequence< sal_Int8 > & rId ) throw (RuntimeException) { return (rId.getLength() == 16 && 0 == rtl_compareMemory(getUnoTunnelImplementationId().getConstArray(), rId.getConstArray(), 16 ) ) ? reinterpret_cast< sal_Int64 >( this ) : OTable_TYPEDEF::getSomething(rId); } // ------------------------------------------------------------------------- // XAlterTable void SAL_CALL OMySQLTable::alterColumnByName( const ::rtl::OUString& colName, const Reference< XPropertySet >& descriptor ) throw(SQLException, NoSuchElementException, RuntimeException) { ::osl::MutexGuard aGuard(m_aMutex); checkDisposed( #ifdef GCC ::connectivity::sdbcx::OTableDescriptor_BASE::rBHelper.bDisposed #else rBHelper.bDisposed #endif ); if ( m_pColumns && !m_pColumns->hasByName(colName) ) throw NoSuchElementException(colName,*this); if ( !isNew() ) { // first we have to check what should be altered Reference<XPropertySet> xProp; m_pColumns->getByName(colName) >>= xProp; // first check the types sal_Int32 nOldType = 0,nNewType = 0,nOldPrec = 0,nNewPrec = 0,nOldScale = 0,nNewScale = 0; ::dbtools::OPropertyMap& rProp = OMetaConnection::getPropMap(); xProp->getPropertyValue(rProp.getNameByIndex(PROPERTY_ID_TYPE)) >>= nOldType; descriptor->getPropertyValue(rProp.getNameByIndex(PROPERTY_ID_TYPE)) >>= nNewType; // and precsions and scale xProp->getPropertyValue(rProp.getNameByIndex(PROPERTY_ID_PRECISION)) >>= nOldPrec; descriptor->getPropertyValue(rProp.getNameByIndex(PROPERTY_ID_PRECISION))>>= nNewPrec; xProp->getPropertyValue(rProp.getNameByIndex(PROPERTY_ID_SCALE)) >>= nOldScale; descriptor->getPropertyValue(rProp.getNameByIndex(PROPERTY_ID_SCALE)) >>= nNewScale; // second: check the "is nullable" value sal_Int32 nOldNullable = 0,nNewNullable = 0; xProp->getPropertyValue(rProp.getNameByIndex(PROPERTY_ID_ISNULLABLE)) >>= nOldNullable; descriptor->getPropertyValue(rProp.getNameByIndex(PROPERTY_ID_ISNULLABLE)) >>= nNewNullable; // check also the auto_increment sal_Bool bOldAutoIncrement = sal_False,bAutoIncrement = sal_False; xProp->getPropertyValue(rProp.getNameByIndex(PROPERTY_ID_ISAUTOINCREMENT)) >>= bOldAutoIncrement; descriptor->getPropertyValue(rProp.getNameByIndex(PROPERTY_ID_ISAUTOINCREMENT)) >>= bAutoIncrement; bool bColumnNameChanged = false; ::rtl::OUString sOldDesc,sNewDesc; xProp->getPropertyValue(rProp.getNameByIndex(PROPERTY_ID_DESCRIPTION)) >>= sOldDesc; descriptor->getPropertyValue(rProp.getNameByIndex(PROPERTY_ID_DESCRIPTION)) >>= sNewDesc; if ( nOldType != nNewType || nOldPrec != nNewPrec || nOldScale != nNewScale || nNewNullable != nOldNullable || bOldAutoIncrement != bAutoIncrement || sOldDesc != sNewDesc ) { // special handling because they change dthe type names to distinguish // if a column should be an auto_incmrement one if ( bOldAutoIncrement != bAutoIncrement ) { ::rtl::OUString sTypeName; descriptor->getPropertyValue(rProp.getNameByIndex(PROPERTY_ID_TYPENAME)) >>= sTypeName; static ::rtl::OUString s_sAutoIncrement(RTL_CONSTASCII_USTRINGPARAM("auto_increment")); if ( bAutoIncrement ) { if ( sTypeName.indexOf(s_sAutoIncrement) == -1 ) { sTypeName += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(" ")); sTypeName += s_sAutoIncrement; } } else { sal_Int32 nIndex = 0; if ( !sTypeName.isEmpty() && (nIndex = sTypeName.indexOf(s_sAutoIncrement)) != -1 ) { sTypeName = sTypeName.copy(0,nIndex); descriptor->setPropertyValue(rProp.getNameByIndex(PROPERTY_ID_TYPENAME),makeAny(sTypeName)); } } } alterColumnType(nNewType,colName,descriptor); bColumnNameChanged = true; } // third: check the default values ::rtl::OUString sNewDefault,sOldDefault; xProp->getPropertyValue(rProp.getNameByIndex(PROPERTY_ID_DEFAULTVALUE)) >>= sOldDefault; descriptor->getPropertyValue(rProp.getNameByIndex(PROPERTY_ID_DEFAULTVALUE)) >>= sNewDefault; if(!sOldDefault.isEmpty()) { dropDefaultValue(colName); if(!sNewDefault.isEmpty() && sOldDefault != sNewDefault) alterDefaultValue(sNewDefault,colName); } else if(!sNewDefault.isEmpty()) alterDefaultValue(sNewDefault,colName); // now we should look if the name of the column changed ::rtl::OUString sNewColumnName; descriptor->getPropertyValue(rProp.getNameByIndex(PROPERTY_ID_NAME)) >>= sNewColumnName; if ( !sNewColumnName.equalsIgnoreAsciiCase(colName) && !bColumnNameChanged ) { ::rtl::OUString sSql = getAlterTableColumnPart(); sSql += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(" CHANGE ")); const ::rtl::OUString sQuote = getMetaData()->getIdentifierQuoteString( ); sSql += ::dbtools::quoteName(sQuote,colName); sSql += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(" ")); sSql += OTables::adjustSQL(::dbtools::createStandardColumnPart(descriptor,getConnection(),static_cast<OTables*>(m_pTables),getTypeCreatePattern())); executeStatement(sSql); } m_pColumns->refresh(); } else { if(m_pColumns) { m_pColumns->dropByName(colName); m_pColumns->appendByDescriptor(descriptor); } } } // ----------------------------------------------------------------------------- void OMySQLTable::alterColumnType(sal_Int32 nNewType,const ::rtl::OUString& _rColName, const Reference<XPropertySet>& _xDescriptor) { ::rtl::OUString sSql = getAlterTableColumnPart(); sSql += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(" CHANGE ")); const ::rtl::OUString sQuote = getMetaData()->getIdentifierQuoteString( ); sSql += ::dbtools::quoteName(sQuote,_rColName); sSql += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(" ")); OColumn* pColumn = new OColumn(sal_True); Reference<XPropertySet> xProp = pColumn; ::comphelper::copyProperties(_xDescriptor,xProp); xProp->setPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPE),makeAny(nNewType)); sSql += OTables::adjustSQL(::dbtools::createStandardColumnPart(xProp,getConnection(),static_cast<OTables*>(m_pTables),getTypeCreatePattern())); executeStatement(sSql); } // ----------------------------------------------------------------------------- ::rtl::OUString OMySQLTable::getTypeCreatePattern() const { static const ::rtl::OUString s_sCreatePattern(RTL_CONSTASCII_USTRINGPARAM("(M,D)")); return s_sCreatePattern; } // ----------------------------------------------------------------------------- void OMySQLTable::alterDefaultValue(const ::rtl::OUString& _sNewDefault,const ::rtl::OUString& _rColName) { ::rtl::OUString sSql = getAlterTableColumnPart(); sSql += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(" ALTER ")); const ::rtl::OUString sQuote = getMetaData()->getIdentifierQuoteString( ); sSql += ::dbtools::quoteName(sQuote,_rColName); sSql += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(" SET DEFAULT '")) + _sNewDefault; sSql += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("'")); executeStatement(sSql); } // ----------------------------------------------------------------------------- void OMySQLTable::dropDefaultValue(const ::rtl::OUString& _rColName) { ::rtl::OUString sSql = getAlterTableColumnPart(); sSql += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(" ALTER ")); const ::rtl::OUString sQuote = getMetaData()->getIdentifierQuoteString( ); sSql += ::dbtools::quoteName(sQuote,_rColName); sSql += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(" DROP DEFAULT")); executeStatement(sSql); } // ----------------------------------------------------------------------------- ::rtl::OUString OMySQLTable::getAlterTableColumnPart() { ::rtl::OUString sSql( RTL_CONSTASCII_USTRINGPARAM( "ALTER TABLE " )); const ::rtl::OUString sQuote = getMetaData()->getIdentifierQuoteString( ); ::rtl::OUString sComposedName( ::dbtools::composeTableName( getMetaData(), m_CatalogName, m_SchemaName, m_Name, sal_True, ::dbtools::eInTableDefinitions ) ); sSql += sComposedName; return sSql; } // ----------------------------------------------------------------------------- void OMySQLTable::executeStatement(const ::rtl::OUString& _rStatement ) { ::rtl::OUString sSQL = _rStatement; if(sSQL.lastIndexOf(',') == (sSQL.getLength()-1)) sSQL = sSQL.replaceAt(sSQL.getLength()-1,1,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(")"))); Reference< XStatement > xStmt = getConnection()->createStatement( ); if ( xStmt.is() ) { xStmt->execute(sSQL); ::comphelper::disposeComponent(xStmt); } } // ----------------------------------------------------------------------------- ::rtl::OUString OMySQLTable::getRenameStart() const { return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("RENAME TABLE ")); } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/*********************************************************************** filename: CEGUIBasicImage.cpp created: Wed Feb 16 2011 author: Paul D Turner <paul@cegui.org.uk> *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team * * 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 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 "CEGUIBasicImage.h" #include "CEGUIGeometryBuffer.h" #include "CEGUITexture.h" #include "CEGUIVertex.h" #include "CEGUIColourRect.h" #include "CEGUISystem.h" // this being here is a bit nasty IMO // Start of CEGUI namespace section namespace CEGUI { //----------------------------------------------------------------------------// BasicImage::BasicImage(const String& name) : d_name(name), d_texture(0), d_area(0.0f, 0.0f, 0.0f, 0.0f), d_pixelSize(0, 0), d_pixelOffset(0.0f, 0.0f), d_autoscaled(false), d_nativeResolution(640, 480) { } //----------------------------------------------------------------------------// BasicImage::BasicImage(const String& name, Texture* texture, const Rect& pixel_area, const Vector2<>& pixel_offset, const bool autoscaled, const Size<>& native_res) : d_name(name), d_texture(texture), d_area(pixel_area), d_pixelSize(pixel_area.getSize()), d_pixelOffset(pixel_offset), d_autoscaled(autoscaled), d_nativeResolution(native_res) { // force initialisation of the autoscaling fields. notifyDisplaySizeChanged( System::getSingleton().getRenderer()->getDisplaySize()); } //----------------------------------------------------------------------------// void BasicImage::setTexture(Texture* texture) { d_texture = texture; } //----------------------------------------------------------------------------// void BasicImage::setArea(const Rect& pixel_area) { d_area = pixel_area; d_pixelSize = pixel_area.getSize(); if (d_autoscaled) notifyDisplaySizeChanged( System::getSingleton().getRenderer()->getDisplaySize()); } //----------------------------------------------------------------------------// void BasicImage::setOffset(const Vector2<>& pixel_offset) { d_pixelOffset = pixel_offset; if (d_autoscaled) notifyDisplaySizeChanged( System::getSingleton().getRenderer()->getDisplaySize()); } //----------------------------------------------------------------------------// void BasicImage::setAutoScaled(const bool autoscaled) { d_autoscaled = autoscaled; if (d_autoscaled) { notifyDisplaySizeChanged( System::getSingleton().getRenderer()->getDisplaySize()); } else { d_scaledSize = d_pixelSize; d_scaledOffset = d_pixelOffset; } } //----------------------------------------------------------------------------// void BasicImage::setNativeResolution(const Size<>& native_res) { d_nativeResolution = native_res; if (d_autoscaled) notifyDisplaySizeChanged( System::getSingleton().getRenderer()->getDisplaySize()); } //----------------------------------------------------------------------------// const String& BasicImage::getName() const { return d_name; } //----------------------------------------------------------------------------// const Size<>& BasicImage::getRenderedSize() const { return d_scaledSize; } //----------------------------------------------------------------------------// const Vector2<>& BasicImage::getRenderedOffset() const { return d_scaledOffset; } //----------------------------------------------------------------------------// void BasicImage::render(GeometryBuffer& buffer, const Rect& dest_area, const Rect* clip_area, const ColourRect& colours) const { const QuadSplitMode quad_split_mode(TopLeftToBottomRight); Rect dest(dest_area); // apply rendering offset to the destination Rect dest.offset(d_scaledOffset); // get the rect area that we will actually draw to (i.e. perform clipping) Rect final_rect(clip_area ? dest.getIntersection(*clip_area) : dest ); // check if rect was totally clipped if ((final_rect.getWidth() == 0) || (final_rect.getHeight() == 0)) return; // Obtain correct scale values from the texture const float x_scale = d_texture->getTexelScaling().d_x; const float y_scale = d_texture->getTexelScaling().d_y; const float tex_per_pix_x = d_area.getWidth() / dest.getWidth(); const float tex_per_pix_y = d_area.getHeight() / dest.getHeight(); // calculate final, clipped, texture co-ordinates const Rect tex_rect((d_area.d_left + ((final_rect.d_left - dest.d_left) * tex_per_pix_x)) * x_scale, (d_area.d_top + ((final_rect.d_top - dest.d_top) * tex_per_pix_y)) * y_scale, (d_area.d_right + ((final_rect.d_right - dest.d_right) * tex_per_pix_x)) * x_scale, (d_area.d_bottom + ((final_rect.d_bottom - dest.d_bottom) * tex_per_pix_y)) * y_scale); final_rect.d_left = PixelAligned(final_rect.d_left); final_rect.d_right = PixelAligned(final_rect.d_right); final_rect.d_top = PixelAligned(final_rect.d_top); final_rect.d_bottom = PixelAligned(final_rect.d_bottom); Vertex vbuffer[6]; // vertex 0 vbuffer[0].position = Vector3<>(final_rect.d_left, final_rect.d_top, 0.0f); vbuffer[0].colour_val = colours.d_top_left; vbuffer[0].tex_coords = Vector2<>(tex_rect.d_left, tex_rect.d_top); // vertex 1 vbuffer[1].position = Vector3<>(final_rect.d_left, final_rect.d_bottom, 0.0f); vbuffer[1].colour_val = colours.d_bottom_left; vbuffer[1].tex_coords = Vector2<>(tex_rect.d_left, tex_rect.d_bottom); // vertex 2 vbuffer[2].position.d_x = final_rect.d_right; vbuffer[2].position.d_z = 0.0f; vbuffer[2].colour_val = colours.d_bottom_right; vbuffer[2].tex_coords.d_x = tex_rect.d_right; // top-left to bottom-right diagonal if (quad_split_mode == TopLeftToBottomRight) { vbuffer[2].position.d_y = final_rect.d_bottom; vbuffer[2].tex_coords.d_y = tex_rect.d_bottom; } // bottom-left to top-right diagonal else { vbuffer[2].position.d_y = final_rect.d_top; vbuffer[2].tex_coords.d_y = tex_rect.d_top; } // vertex 3 vbuffer[3].position = Vector3<>(final_rect.d_right, final_rect.d_top, 0.0f); vbuffer[3].colour_val = colours.d_top_right; vbuffer[3].tex_coords = Vector2<>(tex_rect.d_right, tex_rect.d_top); // vertex 4 vbuffer[4].position.d_x = final_rect.d_left; vbuffer[4].position.d_z = 0.0f; vbuffer[4].colour_val = colours.d_top_left; vbuffer[4].tex_coords.d_x = tex_rect.d_left; // top-left to bottom-right diagonal if (quad_split_mode == TopLeftToBottomRight) { vbuffer[4].position.d_y = final_rect.d_top; vbuffer[4].tex_coords.d_y = tex_rect.d_top; } // bottom-left to top-right diagonal else { vbuffer[4].position.d_y = final_rect.d_bottom; vbuffer[4].tex_coords.d_y = tex_rect.d_bottom; } // vertex 5 vbuffer[5].position = Vector3<>(final_rect.d_right, final_rect.d_bottom, 0.0f); vbuffer[5].colour_val= colours.d_bottom_right; vbuffer[5].tex_coords = Vector2<>(tex_rect.d_right, tex_rect.d_bottom); buffer.setActiveTexture(d_texture); buffer.appendGeometry(vbuffer, 6); } //----------------------------------------------------------------------------// void BasicImage::notifyDisplaySizeChanged(const Size<>& size) { // TODO: This could be cleaned up by adding some more operators to // Size<> and Vector2<> const float x_scale = d_autoscaled ? size.d_width / d_nativeResolution.d_width : 1.0f; const float y_scale = d_autoscaled ? size.d_height / d_nativeResolution.d_height : 1.0f; d_scaledSize.d_width = d_pixelSize.d_width * x_scale; d_scaledSize.d_height = d_pixelSize.d_height * y_scale; d_scaledOffset.d_x = d_pixelOffset.d_x * x_scale; d_scaledOffset.d_y = d_pixelOffset.d_y * y_scale; } //----------------------------------------------------------------------------// Image& BasicImage::clone() const { return *new BasicImage(*this); } //----------------------------------------------------------------------------// } // End of CEGUI namespace section <commit_msg>FIX: A couple of initialisers missing in one of the constructors for BasicImage<commit_after>/*********************************************************************** filename: CEGUIBasicImage.cpp created: Wed Feb 16 2011 author: Paul D Turner <paul@cegui.org.uk> *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team * * 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 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 "CEGUIBasicImage.h" #include "CEGUIGeometryBuffer.h" #include "CEGUITexture.h" #include "CEGUIVertex.h" #include "CEGUIColourRect.h" #include "CEGUISystem.h" // this being here is a bit nasty IMO // Start of CEGUI namespace section namespace CEGUI { //----------------------------------------------------------------------------// BasicImage::BasicImage(const String& name) : d_name(name), d_texture(0), d_area(0.0f, 0.0f, 0.0f, 0.0f), d_pixelSize(0, 0), d_pixelOffset(0.0f, 0.0f), d_autoscaled(false), d_nativeResolution(640, 480), d_scaledSize(0, 0), d_scaledOffset(0, 0) { } //----------------------------------------------------------------------------// BasicImage::BasicImage(const String& name, Texture* texture, const Rect& pixel_area, const Vector2<>& pixel_offset, const bool autoscaled, const Size<>& native_res) : d_name(name), d_texture(texture), d_area(pixel_area), d_pixelSize(pixel_area.getSize()), d_pixelOffset(pixel_offset), d_autoscaled(autoscaled), d_nativeResolution(native_res) { // force initialisation of the autoscaling fields. notifyDisplaySizeChanged( System::getSingleton().getRenderer()->getDisplaySize()); } //----------------------------------------------------------------------------// void BasicImage::setTexture(Texture* texture) { d_texture = texture; } //----------------------------------------------------------------------------// void BasicImage::setArea(const Rect& pixel_area) { d_area = pixel_area; d_pixelSize = pixel_area.getSize(); if (d_autoscaled) notifyDisplaySizeChanged( System::getSingleton().getRenderer()->getDisplaySize()); } //----------------------------------------------------------------------------// void BasicImage::setOffset(const Vector2<>& pixel_offset) { d_pixelOffset = pixel_offset; if (d_autoscaled) notifyDisplaySizeChanged( System::getSingleton().getRenderer()->getDisplaySize()); } //----------------------------------------------------------------------------// void BasicImage::setAutoScaled(const bool autoscaled) { d_autoscaled = autoscaled; if (d_autoscaled) { notifyDisplaySizeChanged( System::getSingleton().getRenderer()->getDisplaySize()); } else { d_scaledSize = d_pixelSize; d_scaledOffset = d_pixelOffset; } } //----------------------------------------------------------------------------// void BasicImage::setNativeResolution(const Size<>& native_res) { d_nativeResolution = native_res; if (d_autoscaled) notifyDisplaySizeChanged( System::getSingleton().getRenderer()->getDisplaySize()); } //----------------------------------------------------------------------------// const String& BasicImage::getName() const { return d_name; } //----------------------------------------------------------------------------// const Size<>& BasicImage::getRenderedSize() const { return d_scaledSize; } //----------------------------------------------------------------------------// const Vector2<>& BasicImage::getRenderedOffset() const { return d_scaledOffset; } //----------------------------------------------------------------------------// void BasicImage::render(GeometryBuffer& buffer, const Rect& dest_area, const Rect* clip_area, const ColourRect& colours) const { const QuadSplitMode quad_split_mode(TopLeftToBottomRight); Rect dest(dest_area); // apply rendering offset to the destination Rect dest.offset(d_scaledOffset); // get the rect area that we will actually draw to (i.e. perform clipping) Rect final_rect(clip_area ? dest.getIntersection(*clip_area) : dest ); // check if rect was totally clipped if ((final_rect.getWidth() == 0) || (final_rect.getHeight() == 0)) return; // Obtain correct scale values from the texture const float x_scale = d_texture->getTexelScaling().d_x; const float y_scale = d_texture->getTexelScaling().d_y; const float tex_per_pix_x = d_area.getWidth() / dest.getWidth(); const float tex_per_pix_y = d_area.getHeight() / dest.getHeight(); // calculate final, clipped, texture co-ordinates const Rect tex_rect((d_area.d_left + ((final_rect.d_left - dest.d_left) * tex_per_pix_x)) * x_scale, (d_area.d_top + ((final_rect.d_top - dest.d_top) * tex_per_pix_y)) * y_scale, (d_area.d_right + ((final_rect.d_right - dest.d_right) * tex_per_pix_x)) * x_scale, (d_area.d_bottom + ((final_rect.d_bottom - dest.d_bottom) * tex_per_pix_y)) * y_scale); final_rect.d_left = PixelAligned(final_rect.d_left); final_rect.d_right = PixelAligned(final_rect.d_right); final_rect.d_top = PixelAligned(final_rect.d_top); final_rect.d_bottom = PixelAligned(final_rect.d_bottom); Vertex vbuffer[6]; // vertex 0 vbuffer[0].position = Vector3<>(final_rect.d_left, final_rect.d_top, 0.0f); vbuffer[0].colour_val = colours.d_top_left; vbuffer[0].tex_coords = Vector2<>(tex_rect.d_left, tex_rect.d_top); // vertex 1 vbuffer[1].position = Vector3<>(final_rect.d_left, final_rect.d_bottom, 0.0f); vbuffer[1].colour_val = colours.d_bottom_left; vbuffer[1].tex_coords = Vector2<>(tex_rect.d_left, tex_rect.d_bottom); // vertex 2 vbuffer[2].position.d_x = final_rect.d_right; vbuffer[2].position.d_z = 0.0f; vbuffer[2].colour_val = colours.d_bottom_right; vbuffer[2].tex_coords.d_x = tex_rect.d_right; // top-left to bottom-right diagonal if (quad_split_mode == TopLeftToBottomRight) { vbuffer[2].position.d_y = final_rect.d_bottom; vbuffer[2].tex_coords.d_y = tex_rect.d_bottom; } // bottom-left to top-right diagonal else { vbuffer[2].position.d_y = final_rect.d_top; vbuffer[2].tex_coords.d_y = tex_rect.d_top; } // vertex 3 vbuffer[3].position = Vector3<>(final_rect.d_right, final_rect.d_top, 0.0f); vbuffer[3].colour_val = colours.d_top_right; vbuffer[3].tex_coords = Vector2<>(tex_rect.d_right, tex_rect.d_top); // vertex 4 vbuffer[4].position.d_x = final_rect.d_left; vbuffer[4].position.d_z = 0.0f; vbuffer[4].colour_val = colours.d_top_left; vbuffer[4].tex_coords.d_x = tex_rect.d_left; // top-left to bottom-right diagonal if (quad_split_mode == TopLeftToBottomRight) { vbuffer[4].position.d_y = final_rect.d_top; vbuffer[4].tex_coords.d_y = tex_rect.d_top; } // bottom-left to top-right diagonal else { vbuffer[4].position.d_y = final_rect.d_bottom; vbuffer[4].tex_coords.d_y = tex_rect.d_bottom; } // vertex 5 vbuffer[5].position = Vector3<>(final_rect.d_right, final_rect.d_bottom, 0.0f); vbuffer[5].colour_val= colours.d_bottom_right; vbuffer[5].tex_coords = Vector2<>(tex_rect.d_right, tex_rect.d_bottom); buffer.setActiveTexture(d_texture); buffer.appendGeometry(vbuffer, 6); } //----------------------------------------------------------------------------// void BasicImage::notifyDisplaySizeChanged(const Size<>& size) { // TODO: This could be cleaned up by adding some more operators to // Size<> and Vector2<> const float x_scale = d_autoscaled ? size.d_width / d_nativeResolution.d_width : 1.0f; const float y_scale = d_autoscaled ? size.d_height / d_nativeResolution.d_height : 1.0f; d_scaledSize.d_width = d_pixelSize.d_width * x_scale; d_scaledSize.d_height = d_pixelSize.d_height * y_scale; d_scaledOffset.d_x = d_pixelOffset.d_x * x_scale; d_scaledOffset.d_y = d_pixelOffset.d_y * y_scale; } //----------------------------------------------------------------------------// Image& BasicImage::clone() const { return *new BasicImage(*this); } //----------------------------------------------------------------------------// } // End of CEGUI namespace section <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: YUsers.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: obo $ $Date: 2006-09-17 03:04:29 $ * * 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_connectivity.hxx" #ifndef _CONNECTIVITY_MYSQL_USERS_HXX_ #include "mysql/YUsers.hxx" #endif #ifndef _CONNECTIVITY_MYSQL_USER_HXX_ #include "mysql/YUser.hxx" #endif #ifndef CONNECTIVITY_MYSQL_TABLE_HXX #include "mysql/YTable.hxx" #endif #ifndef _COM_SUN_STAR_SDBC_XROW_HPP_ #include <com/sun/star/sdbc/XRow.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_ #include <com/sun/star/sdbc/XResultSet.hpp> #endif #ifndef _CONNECTIVITY_SDBCX_IREFRESHABLE_HXX_ #include "connectivity/sdbcx/IRefreshable.hxx" #endif #ifndef _COMPHELPER_TYPES_HXX_ #include <comphelper/types.hxx> #endif #ifndef _DBHELPER_DBEXCEPTION_HXX_ #include "connectivity/dbexception.hxx" #endif #ifndef _CONNECTIVITY_DBTOOLS_HXX_ #include "connectivity/dbtools.hxx" #endif #ifndef CONNECTIVITY_CONNECTION_HXX #include "TConnection.hxx" #endif using namespace ::comphelper; using namespace connectivity; using namespace connectivity::mysql; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::beans; // using namespace ::com::sun::star::sdbcx; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::container; using namespace ::com::sun::star::lang; typedef connectivity::sdbcx::OCollection OCollection_TYPE; OUsers::OUsers( ::cppu::OWeakObject& _rParent, ::osl::Mutex& _rMutex, const TStringVector &_rVector, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _xConnection, connectivity::sdbcx::IRefreshableUsers* _pParent) : sdbcx::OCollection(_rParent,sal_True,_rMutex,_rVector) ,m_xConnection(_xConnection) ,m_pParent(_pParent) { } // ----------------------------------------------------------------------------- sdbcx::ObjectType OUsers::createObject(const ::rtl::OUString& _rName) { return new OMySQLUser(m_xConnection,_rName); } // ------------------------------------------------------------------------- void OUsers::impl_refresh() throw(RuntimeException) { m_pParent->refreshUsers(); } // ------------------------------------------------------------------------- Reference< XPropertySet > OUsers::createDescriptor() { OUserExtend* pNew = new OUserExtend(m_xConnection); return pNew; } // ------------------------------------------------------------------------- // XAppend sdbcx::ObjectType OUsers::appendObject( const ::rtl::OUString& _rForName, const Reference< XPropertySet >& descriptor ) { ::rtl::OUString aSql = ::rtl::OUString::createFromAscii("GRANT USAGE ON * TO "); ::rtl::OUString aQuote = m_xConnection->getMetaData()->getIdentifierQuoteString( ); ::rtl::OUString sUserName( _rForName ); aSql += ::dbtools::quoteName(aQuote,sUserName) + ::rtl::OUString::createFromAscii(" @\"%\" "); ::rtl::OUString sPassword; descriptor->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_PASSWORD)) >>= sPassword; if ( sPassword.getLength() ) { aSql += ::rtl::OUString::createFromAscii(" IDENTIFIED BY '"); aSql += sPassword; aSql += ::rtl::OUString::createFromAscii("'"); } Reference< XStatement > xStmt = m_xConnection->createStatement( ); if(xStmt.is()) xStmt->execute(aSql); ::comphelper::disposeComponent(xStmt); return createObject( _rForName ); } // ------------------------------------------------------------------------- // XDrop void OUsers::dropObject(sal_Int32 /*_nPos*/,const ::rtl::OUString _sElementName) { ::rtl::OUString aSql = ::rtl::OUString::createFromAscii("REVOKE ALL ON * FROM "); ::rtl::OUString aQuote = m_xConnection->getMetaData()->getIdentifierQuoteString( ); aSql += ::dbtools::quoteName(aQuote,_sElementName); Reference< XStatement > xStmt = m_xConnection->createStatement( ); if(xStmt.is()) xStmt->execute(aSql); ::comphelper::disposeComponent(xStmt); } // ------------------------------------------------------------------------- <commit_msg>INTEGRATION: CWS changefileheader (1.8.216); FILE MERGED 2008/04/01 15:09:03 thb 1.8.216.3: #i85898# Stripping all external header guards 2008/04/01 10:53:15 thb 1.8.216.2: #i85898# Stripping all external header guards 2008/03/28 15:24:02 rt 1.8.216.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: YUsers.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. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_connectivity.hxx" #include "mysql/YUsers.hxx" #include "mysql/YUser.hxx" #include "mysql/YTable.hxx" #include <com/sun/star/sdbc/XRow.hpp> #include <com/sun/star/sdbc/XResultSet.hpp> #include "connectivity/sdbcx/IRefreshable.hxx" #include <comphelper/types.hxx> #include "connectivity/dbexception.hxx" #include "connectivity/dbtools.hxx" #include "TConnection.hxx" using namespace ::comphelper; using namespace connectivity; using namespace connectivity::mysql; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::beans; // using namespace ::com::sun::star::sdbcx; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::container; using namespace ::com::sun::star::lang; typedef connectivity::sdbcx::OCollection OCollection_TYPE; OUsers::OUsers( ::cppu::OWeakObject& _rParent, ::osl::Mutex& _rMutex, const TStringVector &_rVector, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _xConnection, connectivity::sdbcx::IRefreshableUsers* _pParent) : sdbcx::OCollection(_rParent,sal_True,_rMutex,_rVector) ,m_xConnection(_xConnection) ,m_pParent(_pParent) { } // ----------------------------------------------------------------------------- sdbcx::ObjectType OUsers::createObject(const ::rtl::OUString& _rName) { return new OMySQLUser(m_xConnection,_rName); } // ------------------------------------------------------------------------- void OUsers::impl_refresh() throw(RuntimeException) { m_pParent->refreshUsers(); } // ------------------------------------------------------------------------- Reference< XPropertySet > OUsers::createDescriptor() { OUserExtend* pNew = new OUserExtend(m_xConnection); return pNew; } // ------------------------------------------------------------------------- // XAppend sdbcx::ObjectType OUsers::appendObject( const ::rtl::OUString& _rForName, const Reference< XPropertySet >& descriptor ) { ::rtl::OUString aSql = ::rtl::OUString::createFromAscii("GRANT USAGE ON * TO "); ::rtl::OUString aQuote = m_xConnection->getMetaData()->getIdentifierQuoteString( ); ::rtl::OUString sUserName( _rForName ); aSql += ::dbtools::quoteName(aQuote,sUserName) + ::rtl::OUString::createFromAscii(" @\"%\" "); ::rtl::OUString sPassword; descriptor->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_PASSWORD)) >>= sPassword; if ( sPassword.getLength() ) { aSql += ::rtl::OUString::createFromAscii(" IDENTIFIED BY '"); aSql += sPassword; aSql += ::rtl::OUString::createFromAscii("'"); } Reference< XStatement > xStmt = m_xConnection->createStatement( ); if(xStmt.is()) xStmt->execute(aSql); ::comphelper::disposeComponent(xStmt); return createObject( _rForName ); } // ------------------------------------------------------------------------- // XDrop void OUsers::dropObject(sal_Int32 /*_nPos*/,const ::rtl::OUString _sElementName) { ::rtl::OUString aSql = ::rtl::OUString::createFromAscii("REVOKE ALL ON * FROM "); ::rtl::OUString aQuote = m_xConnection->getMetaData()->getIdentifierQuoteString( ); aSql += ::dbtools::quoteName(aQuote,_sElementName); Reference< XStatement > xStmt = m_xConnection->createStatement( ); if(xStmt.is()) xStmt->execute(aSql); ::comphelper::disposeComponent(xStmt); } // ------------------------------------------------------------------------- <|endoftext|>
<commit_before>/*********************************************************************** filename: CEGUISpinner.cpp created: 3/2/2005 author: Paul D Turner *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team * * 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 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 "CEGUI/widgets/Spinner.h" #include "CEGUI/widgets/PushButton.h" #include "CEGUI/widgets/Editbox.h" #include "CEGUI/Exceptions.h" #include "CEGUI/WindowManager.h" #include <stdio.h> #include <sstream> #include <iomanip> // Start of CEGUI namespace section namespace CEGUI { const String Spinner::WidgetTypeName("CEGUI/Spinner"); ////////////////////////////////////////////////////////////////////////// // event strings const String Spinner::EventNamespace("Spinner"); const String Spinner::EventValueChanged("ValueChanged"); const String Spinner::EventStepChanged("StepChanged"); const String Spinner::EventMaximumValueChanged("MaximumValueChanged"); const String Spinner::EventMinimumValueChanged("MinimumValueChanged"); const String Spinner::EventTextInputModeChanged("TextInputModeChanged"); // Validator strings const String Spinner::FloatValidator("-?\\d*\\.?\\d*"); const String Spinner::IntegerValidator("-?\\d*"); const String Spinner::HexValidator("[0-9a-fA-F]*"); const String Spinner::OctalValidator("[0-7]*"); // component widget name strings const String Spinner::EditboxName( "__auto_editbox__" ); const String Spinner::IncreaseButtonName( "__auto_incbtn__" ); const String Spinner::DecreaseButtonName( "__auto_decbtn__" ); ////////////////////////////////////////////////////////////////////////// Spinner::Spinner(const String& type, const String& name) : Window(type, name), d_stepSize(1.0f), d_currentValue(1.0f), d_maxValue(32767.0f), d_minValue(-32768.0f), d_inputMode((TextInputMode)-1) { addSpinnerProperties(); } Spinner::~Spinner(void) { // Nothing to do here. } void Spinner::initialiseComponents(void) { // get all the component widgets PushButton* increaseButton = getIncreaseButton(); PushButton* decreaseButton = getDecreaseButton(); Editbox* editbox = getEditbox(); // setup component controls increaseButton->setPointerAutoRepeatEnabled(true); decreaseButton->setPointerAutoRepeatEnabled(true); // perform event subscriptions. increaseButton->subscribeEvent(Window::EventPointerPressHold, Event::Subscriber(&Spinner::handleIncreaseButton, this)); decreaseButton->subscribeEvent(Window::EventPointerPressHold, Event::Subscriber(&Spinner::handleDecreaseButton, this)); editbox->subscribeEvent(Window::EventTextChanged, Event::Subscriber(&Spinner::handleEditTextChange, this)); // final initialisation setTextInputMode(Integer); setCurrentValue(0.0f); performChildWindowLayout(); } double Spinner::getCurrentValue(void) const { return d_currentValue; } double Spinner::getStepSize(void) const { return d_stepSize; } double Spinner::getMaximumValue(void) const { return d_maxValue; } double Spinner::getMinimumValue(void) const { return d_minValue; } Spinner::TextInputMode Spinner::getTextInputMode(void) const { return d_inputMode; } void Spinner::setCurrentValue(double value) { if (value != d_currentValue) { // limit input value to within valid range for spinner value = ceguimax(ceguimin(value, d_maxValue), d_minValue); d_currentValue = value; WindowEventArgs args(this); onValueChanged(args); } } void Spinner::setStepSize(double step) { if (step != d_stepSize) { d_stepSize = step; WindowEventArgs args(this); onStepChanged(args); } } void Spinner::setMaximumValue(double maxValue) { if (maxValue != d_maxValue) { d_maxValue = maxValue; WindowEventArgs args(this); onMaximumValueChanged(args); } } void Spinner::setMinimumValue(double minVaue) { if (minVaue != d_minValue) { d_minValue = minVaue; WindowEventArgs args(this); onMinimumValueChanged(args); } } void Spinner::setTextInputMode(TextInputMode mode) { if (mode != d_inputMode) { switch (mode) { case FloatingPoint: getEditbox()->setValidationString(FloatValidator); break; case Integer: getEditbox()->setValidationString(IntegerValidator); break; case Hexadecimal: getEditbox()->setValidationString(HexValidator); break; case Octal: getEditbox()->setValidationString(OctalValidator); break; default: CEGUI_THROW(InvalidRequestException( "An unknown TextInputMode was specified.")); } d_inputMode = mode; WindowEventArgs args(this); onTextInputModeChanged(args); } } void Spinner::addSpinnerProperties(void) { const String& propertyOrigin = WidgetTypeName; CEGUI_DEFINE_PROPERTY(Spinner, double, "CurrentValue", "Property to get/set the current value of the spinner. Value is a float.", &Spinner::setCurrentValue, &Spinner::getCurrentValue, 0.0f ); CEGUI_DEFINE_PROPERTY(Spinner, double, "StepSize", "Property to get/set the step size of the spinner. Value is a float.", &Spinner::setStepSize, &Spinner::getStepSize, 1.0f ); CEGUI_DEFINE_PROPERTY(Spinner, double, "MinimumValue", "Property to get/set the minimum value setting of the spinner. Value is a float.", &Spinner::setMinimumValue, &Spinner::getMinimumValue, -32768.000000f ); CEGUI_DEFINE_PROPERTY(Spinner, double, "MaximumValue", "Property to get/set the maximum value setting of the spinner. Value is a float.", &Spinner::setMaximumValue, &Spinner::getMaximumValue, 32767.000000f ); CEGUI_DEFINE_PROPERTY(Spinner, Spinner::TextInputMode, "TextInputMode", "Property to get/set the TextInputMode setting for the spinner. Value is \"FloatingPoint\", \"Integer\", \"Hexadecimal\", or \"Octal\".", &Spinner::setTextInputMode, &Spinner::getTextInputMode, Spinner::Integer ); } double Spinner::getValueFromText(void) const { String tmpTxt(getEditbox()->getText()); // handle empty and lone '-' or '.' cases if (tmpTxt.empty() || (tmpTxt == "-") || (tmpTxt == ".")) { return 0.0f; } int res, tmp; uint utmp; double val; switch (d_inputMode) { case FloatingPoint: res = sscanf(tmpTxt.c_str(), "%lf", &val); break; case Integer: res = sscanf(tmpTxt.c_str(), "%d", &tmp); val = static_cast<double>(tmp); break; case Hexadecimal: res = sscanf(tmpTxt.c_str(), "%x", &utmp); val = static_cast<double>(utmp); break; case Octal: res = sscanf(tmpTxt.c_str(), "%o", &utmp); val = static_cast<double>(utmp); break; default: CEGUI_THROW(InvalidRequestException( "An unknown TextInputMode was encountered.")); } if (res) { return val; } CEGUI_THROW(InvalidRequestException( "The string '" + getEditbox()->getText() + "' can not be converted to numerical representation.")); } String Spinner::getTextFromValue(void) const { std::stringstream tmp; switch (d_inputMode) { case FloatingPoint: return CEGUI::PropertyHelper<float>::toString( static_cast<float>(d_currentValue) ); break; case Integer: tmp << static_cast<int>(d_currentValue); break; case Hexadecimal: tmp << std::hex << std::uppercase << static_cast<int>(d_currentValue); break; case Octal: tmp << std::oct << static_cast<int>(d_currentValue); break; default: CEGUI_THROW(InvalidRequestException( "An unknown TextInputMode was encountered.")); } return String(tmp.str().c_str()); } void Spinner::onFontChanged(WindowEventArgs& e) { // Propagate to children getEditbox()->setFont(getFont()); // Call base class handler Window::onFontChanged(e); } void Spinner::onTextChanged(WindowEventArgs& e) { Editbox* editbox = getEditbox(); // update only if needed if (editbox->getText() != getText()) { // done before doing base class processing so event subscribers see // 'updated' version. editbox->setText(getText()); ++e.handled; Window::onTextChanged(e); } } void Spinner::onActivated(ActivationEventArgs& e) { if (!isActive()) { Window::onActivated(e); Editbox* editbox = getEditbox(); if (!editbox->isActive()) { editbox->activate(); } } } void Spinner::onValueChanged(WindowEventArgs& e) { Editbox* editbox = getEditbox(); // mute to save doing unnecessary events work. bool wasMuted = editbox->isMuted(); editbox->setMutedState(true); // Update text with new value. // (allow empty and '-' cases to equal 0 with no text change required) if (!(d_currentValue == 0 && (editbox->getText().empty() || editbox->getText() == "-"))) { editbox->setText(getTextFromValue()); } // restore previous mute state. editbox->setMutedState(wasMuted); fireEvent(EventValueChanged, e, EventNamespace); } void Spinner::onStepChanged(WindowEventArgs& e) { fireEvent(EventStepChanged, e, EventNamespace); } void Spinner::onMaximumValueChanged(WindowEventArgs& e) { fireEvent(EventMaximumValueChanged, e, EventNamespace); if (d_currentValue > d_maxValue) { setCurrentValue(d_maxValue); } } void Spinner::onMinimumValueChanged(WindowEventArgs& e) { fireEvent(EventMinimumValueChanged, e, EventNamespace); if (d_currentValue < d_minValue) { setCurrentValue(d_minValue); } } void Spinner::onTextInputModeChanged(WindowEventArgs& e) { Editbox* editbox = getEditbox(); // update edit box text to reflect new mode. // mute to save doing unnecessary events work. bool wasMuted = editbox->isMuted(); editbox->setMutedState(true); // Update text with new value. editbox->setText(getTextFromValue()); // restore previous mute state. editbox->setMutedState(wasMuted); fireEvent(EventTextInputModeChanged, e, EventNamespace); } bool Spinner::handleIncreaseButton(const EventArgs& e) { if (((const PointerEventArgs&)e).source == PS_Left) { setCurrentValue(d_currentValue + d_stepSize); return true; } return false; } bool Spinner::handleDecreaseButton(const EventArgs& e) { if (((const PointerEventArgs&)e).source == PS_Left) { setCurrentValue(d_currentValue - d_stepSize); return true; } return false; } bool Spinner::handleEditTextChange(const EventArgs&) { // set this windows text to match setText(getEditbox()->getText()); // update value setCurrentValue(getValueFromText()); return true; } PushButton* Spinner::getIncreaseButton() const { return static_cast<PushButton*>(getChild(IncreaseButtonName)); } PushButton* Spinner::getDecreaseButton() const { return static_cast<PushButton*>(getChild(DecreaseButtonName)); } Editbox* Spinner::getEditbox() const { return static_cast<Editbox*>(getChild(EditboxName)); } ////////////////////////////////////////////////////////////////////////// } // End of CEGUI namespace section <commit_msg>MOD: Fixing Spinner window text update on value change<commit_after>/*********************************************************************** filename: CEGUISpinner.cpp created: 3/2/2005 author: Paul D Turner *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team * * 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 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 "CEGUI/widgets/Spinner.h" #include "CEGUI/widgets/PushButton.h" #include "CEGUI/widgets/Editbox.h" #include "CEGUI/Exceptions.h" #include "CEGUI/WindowManager.h" #include <stdio.h> #include <sstream> #include <iomanip> // Start of CEGUI namespace section namespace CEGUI { const String Spinner::WidgetTypeName("CEGUI/Spinner"); ////////////////////////////////////////////////////////////////////////// // event strings const String Spinner::EventNamespace("Spinner"); const String Spinner::EventValueChanged("ValueChanged"); const String Spinner::EventStepChanged("StepChanged"); const String Spinner::EventMaximumValueChanged("MaximumValueChanged"); const String Spinner::EventMinimumValueChanged("MinimumValueChanged"); const String Spinner::EventTextInputModeChanged("TextInputModeChanged"); // Validator strings const String Spinner::FloatValidator("-?\\d*\\.?\\d*"); const String Spinner::IntegerValidator("-?\\d*"); const String Spinner::HexValidator("[0-9a-fA-F]*"); const String Spinner::OctalValidator("[0-7]*"); // component widget name strings const String Spinner::EditboxName( "__auto_editbox__" ); const String Spinner::IncreaseButtonName( "__auto_incbtn__" ); const String Spinner::DecreaseButtonName( "__auto_decbtn__" ); ////////////////////////////////////////////////////////////////////////// Spinner::Spinner(const String& type, const String& name) : Window(type, name), d_stepSize(1.0f), d_currentValue(1.0f), d_maxValue(32767.0f), d_minValue(-32768.0f), d_inputMode((TextInputMode)-1) { addSpinnerProperties(); } Spinner::~Spinner(void) { // Nothing to do here. } void Spinner::initialiseComponents(void) { // get all the component widgets PushButton* increaseButton = getIncreaseButton(); PushButton* decreaseButton = getDecreaseButton(); Editbox* editbox = getEditbox(); // setup component controls increaseButton->setPointerAutoRepeatEnabled(true); decreaseButton->setPointerAutoRepeatEnabled(true); // perform event subscriptions. increaseButton->subscribeEvent(Window::EventPointerPressHold, Event::Subscriber(&Spinner::handleIncreaseButton, this)); decreaseButton->subscribeEvent(Window::EventPointerPressHold, Event::Subscriber(&Spinner::handleDecreaseButton, this)); editbox->subscribeEvent(Window::EventTextChanged, Event::Subscriber(&Spinner::handleEditTextChange, this)); // final initialisation setTextInputMode(Integer); setCurrentValue(0.0f); performChildWindowLayout(); } double Spinner::getCurrentValue(void) const { return d_currentValue; } double Spinner::getStepSize(void) const { return d_stepSize; } double Spinner::getMaximumValue(void) const { return d_maxValue; } double Spinner::getMinimumValue(void) const { return d_minValue; } Spinner::TextInputMode Spinner::getTextInputMode(void) const { return d_inputMode; } void Spinner::setCurrentValue(double value) { if (value != d_currentValue) { // limit input value to within valid range for spinner value = ceguimax(ceguimin(value, d_maxValue), d_minValue); d_currentValue = value; WindowEventArgs args(this); onValueChanged(args); } } void Spinner::setStepSize(double step) { if (step != d_stepSize) { d_stepSize = step; WindowEventArgs args(this); onStepChanged(args); } } void Spinner::setMaximumValue(double maxValue) { if (maxValue != d_maxValue) { d_maxValue = maxValue; WindowEventArgs args(this); onMaximumValueChanged(args); } } void Spinner::setMinimumValue(double minVaue) { if (minVaue != d_minValue) { d_minValue = minVaue; WindowEventArgs args(this); onMinimumValueChanged(args); } } void Spinner::setTextInputMode(TextInputMode mode) { if (mode != d_inputMode) { switch (mode) { case FloatingPoint: getEditbox()->setValidationString(FloatValidator); break; case Integer: getEditbox()->setValidationString(IntegerValidator); break; case Hexadecimal: getEditbox()->setValidationString(HexValidator); break; case Octal: getEditbox()->setValidationString(OctalValidator); break; default: CEGUI_THROW(InvalidRequestException( "An unknown TextInputMode was specified.")); } d_inputMode = mode; WindowEventArgs args(this); onTextInputModeChanged(args); } } void Spinner::addSpinnerProperties(void) { const String& propertyOrigin = WidgetTypeName; CEGUI_DEFINE_PROPERTY(Spinner, double, "CurrentValue", "Property to get/set the current value of the spinner. Value is a float.", &Spinner::setCurrentValue, &Spinner::getCurrentValue, 0.0f ); CEGUI_DEFINE_PROPERTY(Spinner, double, "StepSize", "Property to get/set the step size of the spinner. Value is a float.", &Spinner::setStepSize, &Spinner::getStepSize, 1.0f ); CEGUI_DEFINE_PROPERTY(Spinner, double, "MinimumValue", "Property to get/set the minimum value setting of the spinner. Value is a float.", &Spinner::setMinimumValue, &Spinner::getMinimumValue, -32768.000000f ); CEGUI_DEFINE_PROPERTY(Spinner, double, "MaximumValue", "Property to get/set the maximum value setting of the spinner. Value is a float.", &Spinner::setMaximumValue, &Spinner::getMaximumValue, 32767.000000f ); CEGUI_DEFINE_PROPERTY(Spinner, Spinner::TextInputMode, "TextInputMode", "Property to get/set the TextInputMode setting for the spinner. Value is \"FloatingPoint\", \"Integer\", \"Hexadecimal\", or \"Octal\".", &Spinner::setTextInputMode, &Spinner::getTextInputMode, Spinner::Integer ); } double Spinner::getValueFromText(void) const { String tmpTxt(getEditbox()->getText()); // handle empty and lone '-' or '.' cases if (tmpTxt.empty() || (tmpTxt == "-") || (tmpTxt == ".")) { return 0.0f; } int res, tmp; uint utmp; double val; switch (d_inputMode) { case FloatingPoint: res = sscanf(tmpTxt.c_str(), "%lf", &val); break; case Integer: res = sscanf(tmpTxt.c_str(), "%d", &tmp); val = static_cast<double>(tmp); break; case Hexadecimal: res = sscanf(tmpTxt.c_str(), "%x", &utmp); val = static_cast<double>(utmp); break; case Octal: res = sscanf(tmpTxt.c_str(), "%o", &utmp); val = static_cast<double>(utmp); break; default: CEGUI_THROW(InvalidRequestException( "An unknown TextInputMode was encountered.")); } if (res) { return val; } CEGUI_THROW(InvalidRequestException( "The string '" + getEditbox()->getText() + "' can not be converted to numerical representation.")); } String Spinner::getTextFromValue(void) const { std::stringstream tmp; switch (d_inputMode) { case FloatingPoint: return CEGUI::PropertyHelper<float>::toString( static_cast<float>(d_currentValue) ); break; case Integer: tmp << static_cast<int>(d_currentValue); break; case Hexadecimal: tmp << std::hex << std::uppercase << static_cast<int>(d_currentValue); break; case Octal: tmp << std::oct << static_cast<int>(d_currentValue); break; default: CEGUI_THROW(InvalidRequestException( "An unknown TextInputMode was encountered.")); } return String(tmp.str().c_str()); } void Spinner::onFontChanged(WindowEventArgs& e) { // Propagate to children getEditbox()->setFont(getFont()); // Call base class handler Window::onFontChanged(e); } void Spinner::onTextChanged(WindowEventArgs& e) { Editbox* editbox = getEditbox(); // update only if needed if (editbox->getText() != getText()) { // done before doing base class processing so event subscribers see // 'updated' version. editbox->setText(getText()); ++e.handled; Window::onTextChanged(e); } } void Spinner::onActivated(ActivationEventArgs& e) { if (!isActive()) { Window::onActivated(e); Editbox* editbox = getEditbox(); if (!editbox->isActive()) { editbox->activate(); } } } void Spinner::onValueChanged(WindowEventArgs& e) { Editbox* editbox = getEditbox(); // mute to save doing unnecessary events work. bool wasMuted = editbox->isMuted(); editbox->setMutedState(true); // Update editbox and spinner text with new value. // (allow empty and '-' cases to equal 0 with no text change required) if (!(d_currentValue == 0 && (editbox->getText().empty() || editbox->getText() == "-"))) { const CEGUI::String& valueString = getTextFromValue(); editbox->setText(valueString); setText(valueString); } // restore previous mute state. editbox->setMutedState(wasMuted); fireEvent(EventValueChanged, e, EventNamespace); } void Spinner::onStepChanged(WindowEventArgs& e) { fireEvent(EventStepChanged, e, EventNamespace); } void Spinner::onMaximumValueChanged(WindowEventArgs& e) { fireEvent(EventMaximumValueChanged, e, EventNamespace); if (d_currentValue > d_maxValue) { setCurrentValue(d_maxValue); } } void Spinner::onMinimumValueChanged(WindowEventArgs& e) { fireEvent(EventMinimumValueChanged, e, EventNamespace); if (d_currentValue < d_minValue) { setCurrentValue(d_minValue); } } void Spinner::onTextInputModeChanged(WindowEventArgs& e) { Editbox* editbox = getEditbox(); // update edit box text to reflect new mode. // mute to save doing unnecessary events work. bool wasMuted = editbox->isMuted(); editbox->setMutedState(true); // Update text with new value. editbox->setText(getTextFromValue()); // restore previous mute state. editbox->setMutedState(wasMuted); fireEvent(EventTextInputModeChanged, e, EventNamespace); } bool Spinner::handleIncreaseButton(const EventArgs& e) { if (((const PointerEventArgs&)e).source == PS_Left) { setCurrentValue(d_currentValue + d_stepSize); return true; } return false; } bool Spinner::handleDecreaseButton(const EventArgs& e) { if (((const PointerEventArgs&)e).source == PS_Left) { setCurrentValue(d_currentValue - d_stepSize); return true; } return false; } bool Spinner::handleEditTextChange(const EventArgs&) { // set this windows text to match setText(getEditbox()->getText()); // update value setCurrentValue(getValueFromText()); return true; } PushButton* Spinner::getIncreaseButton() const { return static_cast<PushButton*>(getChild(IncreaseButtonName)); } PushButton* Spinner::getDecreaseButton() const { return static_cast<PushButton*>(getChild(DecreaseButtonName)); } Editbox* Spinner::getEditbox() const { return static_cast<Editbox*>(getChild(EditboxName)); } ////////////////////////////////////////////////////////////////////////// } // End of CEGUI namespace section <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/ppapi_plugin_process_host.h" #include <string> #include "base/base_switches.h" #include "base/command_line.h" #include "base/file_path.h" #include "base/process_util.h" #include "base/utf_string_conversions.h" #include "content/browser/browser_child_process_host_impl.h" #include "content/browser/plugin_service_impl.h" #include "content/browser/renderer_host/render_message_filter.h" #include "content/common/child_process_host_impl.h" #include "content/common/child_process_messages.h" #include "content/public/browser/content_browser_client.h" #include "content/public/common/content_switches.h" #include "content/public/common/pepper_plugin_info.h" #include "content/public/common/process_type.h" #include "ipc/ipc_switches.h" #include "net/base/network_change_notifier.h" #include "ppapi/proxy/ppapi_messages.h" #include "ui/base/ui_base_switches.h" #include "webkit/plugins/plugin_switches.h" namespace content { class PpapiPluginProcessHost::PluginNetworkObserver : public net::NetworkChangeNotifier::IPAddressObserver, public net::NetworkChangeNotifier::ConnectionTypeObserver { public: explicit PluginNetworkObserver(PpapiPluginProcessHost* process_host) : process_host_(process_host) { net::NetworkChangeNotifier::AddIPAddressObserver(this); net::NetworkChangeNotifier::AddConnectionTypeObserver(this); } ~PluginNetworkObserver() { net::NetworkChangeNotifier::RemoveConnectionTypeObserver(this); net::NetworkChangeNotifier::RemoveIPAddressObserver(this); } // IPAddressObserver implementation. virtual void OnIPAddressChanged() OVERRIDE { // TODO(brettw) bug 90246: This doesn't seem correct. The online/offline // notification seems like it should be sufficient, but I don't see that // when I unplug and replug my network cable. Sending this notification when // "something" changes seems to make Flash reasonably happy, but seems // wrong. We should really be able to provide the real online state in // OnConnectionTypeChanged(). process_host_->Send(new PpapiMsg_SetNetworkState(true)); } // ConnectionTypeObserver implementation. virtual void OnConnectionTypeChanged( net::NetworkChangeNotifier::ConnectionType type) { process_host_->Send(new PpapiMsg_SetNetworkState( type != net::NetworkChangeNotifier::CONNECTION_NONE)); } private: PpapiPluginProcessHost* const process_host_; }; PpapiPluginProcessHost::~PpapiPluginProcessHost() { DVLOG(1) << "PpapiPluginProcessHost" << (is_broker_ ? "[broker]" : "") << "~PpapiPluginProcessHost()"; CancelRequests(); } // static PpapiPluginProcessHost* PpapiPluginProcessHost::CreatePluginHost( const PepperPluginInfo& info, const FilePath& profile_data_directory, net::HostResolver* host_resolver) { PpapiPluginProcessHost* plugin_host = new PpapiPluginProcessHost( info, profile_data_directory, host_resolver); if (plugin_host->Init(info)) return plugin_host; NOTREACHED(); // Init is not expected to fail. return NULL; } // static PpapiPluginProcessHost* PpapiPluginProcessHost::CreateBrokerHost( const PepperPluginInfo& info) { PpapiPluginProcessHost* plugin_host = new PpapiPluginProcessHost(); if (plugin_host->Init(info)) return plugin_host; NOTREACHED(); // Init is not expected to fail. return NULL; } // static void PpapiPluginProcessHost::DidCreateOutOfProcessInstance( int plugin_process_id, int32 pp_instance, const PepperRendererInstanceData& instance_data) { for (PpapiPluginProcessHostIterator iter; !iter.Done(); ++iter) { if (iter->process_.get() && iter->process_->GetData().id == plugin_process_id) { // Found the plugin. iter->host_impl_->AddInstance(pp_instance, instance_data); return; } } // We'll see this passed with a 0 process ID for the browser tag stuff that // is currently in the process of being removed. // // TODO(brettw) When old browser tag impl is removed // (PepperPluginDelegateImpl::CreateBrowserPluginModule passes a 0 plugin // process ID) this should be converted to a NOTREACHED(). DCHECK(plugin_process_id == 0) << "Renderer sent a bad plugin process host ID"; } // static void PpapiPluginProcessHost::DidDeleteOutOfProcessInstance( int plugin_process_id, int32 pp_instance) { for (PpapiPluginProcessHostIterator iter; !iter.Done(); ++iter) { if (iter->process_.get() && iter->process_->GetData().id == plugin_process_id) { // Found the plugin. iter->host_impl_->DeleteInstance(pp_instance); return; } } // Note: It's possible that the plugin process has already been deleted by // the time this message is received. For example, it could have crashed. // That's OK, we can just ignore this message. } // static void PpapiPluginProcessHost::FindByName( const string16& name, std::vector<PpapiPluginProcessHost*>* hosts) { for (PpapiPluginProcessHostIterator iter; !iter.Done(); ++iter) { if (iter->process_.get() && iter->process_->GetData().name == name) hosts->push_back(*iter); } } bool PpapiPluginProcessHost::Send(IPC::Message* message) { return process_->Send(message); } void PpapiPluginProcessHost::OpenChannelToPlugin(Client* client) { if (process_->GetHost()->IsChannelOpening()) { // The channel is already in the process of being opened. Put // this "open channel" request into a queue of requests that will // be run once the channel is open. pending_requests_.push_back(client); return; } // We already have an open channel, send a request right away to plugin. RequestPluginChannel(client); } PpapiPluginProcessHost::PpapiPluginProcessHost( const PepperPluginInfo& info, const FilePath& profile_data_directory, net::HostResolver* host_resolver) : permissions_( ppapi::PpapiPermissions::GetForCommandLine(info.permissions)), profile_data_directory_(profile_data_directory), is_broker_(false) { process_.reset(new BrowserChildProcessHostImpl( PROCESS_TYPE_PPAPI_PLUGIN, this)); filter_ = new PepperMessageFilter(process_->GetData().type, permissions_, host_resolver); host_impl_.reset(new BrowserPpapiHostImpl(this, permissions_, info.name, profile_data_directory, process_->GetData().type)); process_->GetHost()->AddFilter(filter_.get()); process_->GetHost()->AddFilter(host_impl_->message_filter()); GetContentClient()->browser()->DidCreatePpapiPlugin(host_impl_.get()); // Only request network status updates if the plugin has dev permissions. if (permissions_.HasPermission(ppapi::PERMISSION_DEV)) network_observer_.reset(new PluginNetworkObserver(this)); } PpapiPluginProcessHost::PpapiPluginProcessHost() : is_broker_(true) { process_.reset(new BrowserChildProcessHostImpl( PROCESS_TYPE_PPAPI_BROKER, this)); ppapi::PpapiPermissions permissions; // No permissions. // The plugin name and profile data directory shouldn't be needed for the // broker. std::string plugin_name; FilePath profile_data_directory; host_impl_.reset(new BrowserPpapiHostImpl(this, permissions, plugin_name, profile_data_directory, process_->GetData().type)); } bool PpapiPluginProcessHost::Init(const PepperPluginInfo& info) { plugin_path_ = info.path; if (info.name.empty()) { process_->SetName(plugin_path_.BaseName().LossyDisplayName()); } else { process_->SetName(UTF8ToUTF16(info.name)); } std::string channel_id = process_->GetHost()->CreateChannel(); if (channel_id.empty()) return false; const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess(); CommandLine::StringType plugin_launcher = browser_command_line.GetSwitchValueNative(switches::kPpapiPluginLauncher); #if defined(OS_LINUX) int flags = plugin_launcher.empty() ? ChildProcessHost::CHILD_ALLOW_SELF : ChildProcessHost::CHILD_NORMAL; #else int flags = ChildProcessHost::CHILD_NORMAL; #endif FilePath exe_path = ChildProcessHost::GetChildPath(flags); if (exe_path.empty()) return false; CommandLine* cmd_line = new CommandLine(exe_path); cmd_line->AppendSwitchASCII(switches::kProcessType, is_broker_ ? switches::kPpapiBrokerProcess : switches::kPpapiPluginProcess); cmd_line->AppendSwitchASCII(switches::kProcessChannelID, channel_id); // These switches are forwarded to both plugin and broker pocesses. static const char* kCommonForwardSwitches[] = { switches::kVModule }; cmd_line->CopySwitchesFrom(browser_command_line, kCommonForwardSwitches, arraysize(kCommonForwardSwitches)); if (!is_broker_) { // TODO(vtl): Stop passing flash args in the command line, on windows is // going to explode. static const char* kPluginForwardSwitches[] = { switches::kDisablePepperThreading, switches::kDisableSeccompFilterSandbox, #if defined(OS_MACOSX) switches::kEnableSandboxLogging, #endif switches::kNoSandbox, switches::kPpapiFlashArgs, switches::kPpapiStartupDialog, }; cmd_line->CopySwitchesFrom(browser_command_line, kPluginForwardSwitches, arraysize(kPluginForwardSwitches)); } std::string locale = GetContentClient()->browser()->GetApplicationLocale(); if (!locale.empty()) { // Pass on the locale so the plugin will know what language we're using. cmd_line->AppendSwitchASCII(switches::kLang, locale); } if (!plugin_launcher.empty()) cmd_line->PrependWrapper(plugin_launcher); // On posix, never use the zygote for the broker. Also, only use the zygote if // the plugin is sandboxed, and we are not using a plugin launcher - having a // plugin launcher means we need to use another process instead of just // forking the zygote. #if defined(OS_POSIX) bool use_zygote = !is_broker_ && plugin_launcher.empty() && info.is_sandboxed; if (!info.is_sandboxed) cmd_line->AppendSwitchASCII(switches::kNoSandbox, ""); #endif // OS_POSIX process_->Launch( #if defined(OS_WIN) FilePath(), #elif defined(OS_POSIX) use_zygote, base::EnvironmentVector(), #endif cmd_line); return true; } void PpapiPluginProcessHost::RequestPluginChannel(Client* client) { base::ProcessHandle process_handle; int renderer_child_id; client->GetPpapiChannelInfo(&process_handle, &renderer_child_id); // We can't send any sync messages from the browser because it might lead to // a hang. See the similar code in PluginProcessHost for more description. PpapiMsg_CreateChannel* msg = new PpapiMsg_CreateChannel( base::GetProcId(process_handle), renderer_child_id, client->OffTheRecord()); msg->set_unblock(true); if (Send(msg)) { sent_requests_.push(client); } else { client->OnPpapiChannelOpened(IPC::ChannelHandle(), base::kNullProcessId, 0); } } void PpapiPluginProcessHost::OnProcessLaunched() { host_impl_->set_plugin_process_handle(process_->GetHandle()); } void PpapiPluginProcessHost::OnProcessCrashed(int exit_code) { PluginServiceImpl::GetInstance()->RegisterPluginCrash(plugin_path_); } bool PpapiPluginProcessHost::OnMessageReceived(const IPC::Message& msg) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(PpapiPluginProcessHost, msg) IPC_MESSAGE_HANDLER(PpapiHostMsg_ChannelCreated, OnRendererPluginChannelCreated) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() DCHECK(handled); return handled; } // Called when the browser <--> plugin channel has been established. void PpapiPluginProcessHost::OnChannelConnected(int32 peer_pid) { // This will actually load the plugin. Errors will actually not be reported // back at this point. Instead, the plugin will fail to establish the // connections when we request them on behalf of the renderer(s). Send(new PpapiMsg_LoadPlugin(plugin_path_, permissions_)); // Process all pending channel requests from the renderers. for (size_t i = 0; i < pending_requests_.size(); i++) RequestPluginChannel(pending_requests_[i]); pending_requests_.clear(); } // Called when the browser <--> plugin channel has an error. This normally // means the plugin has crashed. void PpapiPluginProcessHost::OnChannelError() { DVLOG(1) << "PpapiPluginProcessHost" << (is_broker_ ? "[broker]" : "") << "::OnChannelError()"; // We don't need to notify the renderers that were communicating with the // plugin since they have their own channels which will go into the error // state at the same time. Instead, we just need to notify any renderers // that have requested a connection but have not yet received one. CancelRequests(); } void PpapiPluginProcessHost::CancelRequests() { DVLOG(1) << "PpapiPluginProcessHost" << (is_broker_ ? "[broker]" : "") << "CancelRequests()"; for (size_t i = 0; i < pending_requests_.size(); i++) { pending_requests_[i]->OnPpapiChannelOpened(IPC::ChannelHandle(), base::kNullProcessId, 0); } pending_requests_.clear(); while (!sent_requests_.empty()) { sent_requests_.front()->OnPpapiChannelOpened(IPC::ChannelHandle(), base::kNullProcessId, 0); sent_requests_.pop(); } } // Called when a new plugin <--> renderer channel has been created. void PpapiPluginProcessHost::OnRendererPluginChannelCreated( const IPC::ChannelHandle& channel_handle) { if (sent_requests_.empty()) return; // All requests should be processed FIFO, so the next item in the // sent_requests_ queue should be the one that the plugin just created. Client* client = sent_requests_.front(); sent_requests_.pop(); const ChildProcessData& data = process_->GetData(); client->OnPpapiChannelOpened(channel_handle, base::GetProcId(data.handle), data.id); } } // namespace content <commit_msg>Prevent calling GetProcId with a null process handle in PpapiPluginProcessHost::RequestPluginChannel<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/ppapi_plugin_process_host.h" #include <string> #include "base/base_switches.h" #include "base/command_line.h" #include "base/file_path.h" #include "base/process_util.h" #include "base/utf_string_conversions.h" #include "content/browser/browser_child_process_host_impl.h" #include "content/browser/plugin_service_impl.h" #include "content/browser/renderer_host/render_message_filter.h" #include "content/common/child_process_host_impl.h" #include "content/common/child_process_messages.h" #include "content/public/browser/content_browser_client.h" #include "content/public/common/content_switches.h" #include "content/public/common/pepper_plugin_info.h" #include "content/public/common/process_type.h" #include "ipc/ipc_switches.h" #include "net/base/network_change_notifier.h" #include "ppapi/proxy/ppapi_messages.h" #include "ui/base/ui_base_switches.h" #include "webkit/plugins/plugin_switches.h" namespace content { class PpapiPluginProcessHost::PluginNetworkObserver : public net::NetworkChangeNotifier::IPAddressObserver, public net::NetworkChangeNotifier::ConnectionTypeObserver { public: explicit PluginNetworkObserver(PpapiPluginProcessHost* process_host) : process_host_(process_host) { net::NetworkChangeNotifier::AddIPAddressObserver(this); net::NetworkChangeNotifier::AddConnectionTypeObserver(this); } ~PluginNetworkObserver() { net::NetworkChangeNotifier::RemoveConnectionTypeObserver(this); net::NetworkChangeNotifier::RemoveIPAddressObserver(this); } // IPAddressObserver implementation. virtual void OnIPAddressChanged() OVERRIDE { // TODO(brettw) bug 90246: This doesn't seem correct. The online/offline // notification seems like it should be sufficient, but I don't see that // when I unplug and replug my network cable. Sending this notification when // "something" changes seems to make Flash reasonably happy, but seems // wrong. We should really be able to provide the real online state in // OnConnectionTypeChanged(). process_host_->Send(new PpapiMsg_SetNetworkState(true)); } // ConnectionTypeObserver implementation. virtual void OnConnectionTypeChanged( net::NetworkChangeNotifier::ConnectionType type) { process_host_->Send(new PpapiMsg_SetNetworkState( type != net::NetworkChangeNotifier::CONNECTION_NONE)); } private: PpapiPluginProcessHost* const process_host_; }; PpapiPluginProcessHost::~PpapiPluginProcessHost() { DVLOG(1) << "PpapiPluginProcessHost" << (is_broker_ ? "[broker]" : "") << "~PpapiPluginProcessHost()"; CancelRequests(); } // static PpapiPluginProcessHost* PpapiPluginProcessHost::CreatePluginHost( const PepperPluginInfo& info, const FilePath& profile_data_directory, net::HostResolver* host_resolver) { PpapiPluginProcessHost* plugin_host = new PpapiPluginProcessHost( info, profile_data_directory, host_resolver); if (plugin_host->Init(info)) return plugin_host; NOTREACHED(); // Init is not expected to fail. return NULL; } // static PpapiPluginProcessHost* PpapiPluginProcessHost::CreateBrokerHost( const PepperPluginInfo& info) { PpapiPluginProcessHost* plugin_host = new PpapiPluginProcessHost(); if (plugin_host->Init(info)) return plugin_host; NOTREACHED(); // Init is not expected to fail. return NULL; } // static void PpapiPluginProcessHost::DidCreateOutOfProcessInstance( int plugin_process_id, int32 pp_instance, const PepperRendererInstanceData& instance_data) { for (PpapiPluginProcessHostIterator iter; !iter.Done(); ++iter) { if (iter->process_.get() && iter->process_->GetData().id == plugin_process_id) { // Found the plugin. iter->host_impl_->AddInstance(pp_instance, instance_data); return; } } // We'll see this passed with a 0 process ID for the browser tag stuff that // is currently in the process of being removed. // // TODO(brettw) When old browser tag impl is removed // (PepperPluginDelegateImpl::CreateBrowserPluginModule passes a 0 plugin // process ID) this should be converted to a NOTREACHED(). DCHECK(plugin_process_id == 0) << "Renderer sent a bad plugin process host ID"; } // static void PpapiPluginProcessHost::DidDeleteOutOfProcessInstance( int plugin_process_id, int32 pp_instance) { for (PpapiPluginProcessHostIterator iter; !iter.Done(); ++iter) { if (iter->process_.get() && iter->process_->GetData().id == plugin_process_id) { // Found the plugin. iter->host_impl_->DeleteInstance(pp_instance); return; } } // Note: It's possible that the plugin process has already been deleted by // the time this message is received. For example, it could have crashed. // That's OK, we can just ignore this message. } // static void PpapiPluginProcessHost::FindByName( const string16& name, std::vector<PpapiPluginProcessHost*>* hosts) { for (PpapiPluginProcessHostIterator iter; !iter.Done(); ++iter) { if (iter->process_.get() && iter->process_->GetData().name == name) hosts->push_back(*iter); } } bool PpapiPluginProcessHost::Send(IPC::Message* message) { return process_->Send(message); } void PpapiPluginProcessHost::OpenChannelToPlugin(Client* client) { if (process_->GetHost()->IsChannelOpening()) { // The channel is already in the process of being opened. Put // this "open channel" request into a queue of requests that will // be run once the channel is open. pending_requests_.push_back(client); return; } // We already have an open channel, send a request right away to plugin. RequestPluginChannel(client); } PpapiPluginProcessHost::PpapiPluginProcessHost( const PepperPluginInfo& info, const FilePath& profile_data_directory, net::HostResolver* host_resolver) : permissions_( ppapi::PpapiPermissions::GetForCommandLine(info.permissions)), profile_data_directory_(profile_data_directory), is_broker_(false) { process_.reset(new BrowserChildProcessHostImpl( PROCESS_TYPE_PPAPI_PLUGIN, this)); filter_ = new PepperMessageFilter(process_->GetData().type, permissions_, host_resolver); host_impl_.reset(new BrowserPpapiHostImpl(this, permissions_, info.name, profile_data_directory, process_->GetData().type)); process_->GetHost()->AddFilter(filter_.get()); process_->GetHost()->AddFilter(host_impl_->message_filter()); GetContentClient()->browser()->DidCreatePpapiPlugin(host_impl_.get()); // Only request network status updates if the plugin has dev permissions. if (permissions_.HasPermission(ppapi::PERMISSION_DEV)) network_observer_.reset(new PluginNetworkObserver(this)); } PpapiPluginProcessHost::PpapiPluginProcessHost() : is_broker_(true) { process_.reset(new BrowserChildProcessHostImpl( PROCESS_TYPE_PPAPI_BROKER, this)); ppapi::PpapiPermissions permissions; // No permissions. // The plugin name and profile data directory shouldn't be needed for the // broker. std::string plugin_name; FilePath profile_data_directory; host_impl_.reset(new BrowserPpapiHostImpl(this, permissions, plugin_name, profile_data_directory, process_->GetData().type)); } bool PpapiPluginProcessHost::Init(const PepperPluginInfo& info) { plugin_path_ = info.path; if (info.name.empty()) { process_->SetName(plugin_path_.BaseName().LossyDisplayName()); } else { process_->SetName(UTF8ToUTF16(info.name)); } std::string channel_id = process_->GetHost()->CreateChannel(); if (channel_id.empty()) return false; const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess(); CommandLine::StringType plugin_launcher = browser_command_line.GetSwitchValueNative(switches::kPpapiPluginLauncher); #if defined(OS_LINUX) int flags = plugin_launcher.empty() ? ChildProcessHost::CHILD_ALLOW_SELF : ChildProcessHost::CHILD_NORMAL; #else int flags = ChildProcessHost::CHILD_NORMAL; #endif FilePath exe_path = ChildProcessHost::GetChildPath(flags); if (exe_path.empty()) return false; CommandLine* cmd_line = new CommandLine(exe_path); cmd_line->AppendSwitchASCII(switches::kProcessType, is_broker_ ? switches::kPpapiBrokerProcess : switches::kPpapiPluginProcess); cmd_line->AppendSwitchASCII(switches::kProcessChannelID, channel_id); // These switches are forwarded to both plugin and broker pocesses. static const char* kCommonForwardSwitches[] = { switches::kVModule }; cmd_line->CopySwitchesFrom(browser_command_line, kCommonForwardSwitches, arraysize(kCommonForwardSwitches)); if (!is_broker_) { // TODO(vtl): Stop passing flash args in the command line, on windows is // going to explode. static const char* kPluginForwardSwitches[] = { switches::kDisablePepperThreading, switches::kDisableSeccompFilterSandbox, #if defined(OS_MACOSX) switches::kEnableSandboxLogging, #endif switches::kNoSandbox, switches::kPpapiFlashArgs, switches::kPpapiStartupDialog, }; cmd_line->CopySwitchesFrom(browser_command_line, kPluginForwardSwitches, arraysize(kPluginForwardSwitches)); } std::string locale = GetContentClient()->browser()->GetApplicationLocale(); if (!locale.empty()) { // Pass on the locale so the plugin will know what language we're using. cmd_line->AppendSwitchASCII(switches::kLang, locale); } if (!plugin_launcher.empty()) cmd_line->PrependWrapper(plugin_launcher); // On posix, never use the zygote for the broker. Also, only use the zygote if // the plugin is sandboxed, and we are not using a plugin launcher - having a // plugin launcher means we need to use another process instead of just // forking the zygote. #if defined(OS_POSIX) bool use_zygote = !is_broker_ && plugin_launcher.empty() && info.is_sandboxed; if (!info.is_sandboxed) cmd_line->AppendSwitchASCII(switches::kNoSandbox, ""); #endif // OS_POSIX process_->Launch( #if defined(OS_WIN) FilePath(), #elif defined(OS_POSIX) use_zygote, base::EnvironmentVector(), #endif cmd_line); return true; } void PpapiPluginProcessHost::RequestPluginChannel(Client* client) { base::ProcessHandle process_handle; int renderer_child_id; client->GetPpapiChannelInfo(&process_handle, &renderer_child_id); base::ProcessId process_id = (process_handle == base::kNullProcessHandle) ? 0 : base::GetProcId(process_handle); // We can't send any sync messages from the browser because it might lead to // a hang. See the similar code in PluginProcessHost for more description. PpapiMsg_CreateChannel* msg = new PpapiMsg_CreateChannel( process_id, renderer_child_id, client->OffTheRecord()); msg->set_unblock(true); if (Send(msg)) { sent_requests_.push(client); } else { client->OnPpapiChannelOpened(IPC::ChannelHandle(), base::kNullProcessId, 0); } } void PpapiPluginProcessHost::OnProcessLaunched() { host_impl_->set_plugin_process_handle(process_->GetHandle()); } void PpapiPluginProcessHost::OnProcessCrashed(int exit_code) { PluginServiceImpl::GetInstance()->RegisterPluginCrash(plugin_path_); } bool PpapiPluginProcessHost::OnMessageReceived(const IPC::Message& msg) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(PpapiPluginProcessHost, msg) IPC_MESSAGE_HANDLER(PpapiHostMsg_ChannelCreated, OnRendererPluginChannelCreated) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() DCHECK(handled); return handled; } // Called when the browser <--> plugin channel has been established. void PpapiPluginProcessHost::OnChannelConnected(int32 peer_pid) { // This will actually load the plugin. Errors will actually not be reported // back at this point. Instead, the plugin will fail to establish the // connections when we request them on behalf of the renderer(s). Send(new PpapiMsg_LoadPlugin(plugin_path_, permissions_)); // Process all pending channel requests from the renderers. for (size_t i = 0; i < pending_requests_.size(); i++) RequestPluginChannel(pending_requests_[i]); pending_requests_.clear(); } // Called when the browser <--> plugin channel has an error. This normally // means the plugin has crashed. void PpapiPluginProcessHost::OnChannelError() { DVLOG(1) << "PpapiPluginProcessHost" << (is_broker_ ? "[broker]" : "") << "::OnChannelError()"; // We don't need to notify the renderers that were communicating with the // plugin since they have their own channels which will go into the error // state at the same time. Instead, we just need to notify any renderers // that have requested a connection but have not yet received one. CancelRequests(); } void PpapiPluginProcessHost::CancelRequests() { DVLOG(1) << "PpapiPluginProcessHost" << (is_broker_ ? "[broker]" : "") << "CancelRequests()"; for (size_t i = 0; i < pending_requests_.size(); i++) { pending_requests_[i]->OnPpapiChannelOpened(IPC::ChannelHandle(), base::kNullProcessId, 0); } pending_requests_.clear(); while (!sent_requests_.empty()) { sent_requests_.front()->OnPpapiChannelOpened(IPC::ChannelHandle(), base::kNullProcessId, 0); sent_requests_.pop(); } } // Called when a new plugin <--> renderer channel has been created. void PpapiPluginProcessHost::OnRendererPluginChannelCreated( const IPC::ChannelHandle& channel_handle) { if (sent_requests_.empty()) return; // All requests should be processed FIFO, so the next item in the // sent_requests_ queue should be the one that the plugin just created. Client* client = sent_requests_.front(); sent_requests_.pop(); const ChildProcessData& data = process_->GetData(); client->OnPpapiChannelOpened(channel_handle, base::GetProcId(data.handle), data.id); } } // namespace content <|endoftext|>
<commit_before>// $Id: mesh_refinement_smoothing.C,v 1.12 2006-04-17 21:18:09 roystgnr Exp $ // The libMesh Finite Element Library. // Copyright (C) 2002-2005 Benjamin S. Kirk, John W. Peterson // 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 // Local includes #include "libmesh_config.h" // only compile these functions if the user requests AMR support #ifdef ENABLE_AMR #include "mesh_refinement.h" #include "mesh_base.h" #include "elem.h" //----------------------------------------------------------------- // Mesh refinement methods bool MeshRefinement::limit_level_mismatch_at_node (const unsigned int max_mismatch) { bool flags_changed = false; // Vector holding the maximum element level that touches a node. std::vector<unsigned char> max_level_at_node (_mesh.n_nodes(), 0); // Loop over all the active elements & fill the vector { // const_active_elem_iterator elem_it (_mesh.const_elements_begin()); // const const_active_elem_iterator elem_end(_mesh.const_elements_end()); MeshBase::element_iterator elem_it = _mesh.active_elements_begin(); const MeshBase::element_iterator elem_end = _mesh.active_elements_end(); for (; elem_it != elem_end; ++elem_it) { const Elem* elem = *elem_it; const unsigned char elem_level = elem->level() + ((elem->refinement_flag() == Elem::REFINE) ? 1 : 0); // Set the max_level at each node for (unsigned int n=0; n<elem->n_nodes(); n++) { const unsigned int node_number = elem->node(n); assert (node_number < max_level_at_node.size()); max_level_at_node[node_number] = std::max (max_level_at_node[node_number], elem_level); } } } // Now loop over the active elements and flag the elements // who violate the requested level mismatch { // active_elem_iterator elem_it (_mesh.elements_begin()); // const active_elem_iterator elem_end(_mesh.elements_end()); MeshBase::element_iterator elem_it = _mesh.active_elements_begin(); const MeshBase::element_iterator elem_end = _mesh.active_elements_end(); for (; elem_it != elem_end; ++elem_it) { Elem* elem = *elem_it; const unsigned int elem_level = elem->level(); // Skip the element if it is already flagged if (elem->refinement_flag() == Elem::REFINE) continue; // Loop over the nodes, check for possible mismatch for (unsigned int n=0; n<elem->n_nodes(); n++) { const unsigned int node_number = elem->node(n); // Flag the element for refinement if it violates // the requested level mismatch if ( (elem_level + max_mismatch) < max_level_at_node[node_number]) { elem->set_refinement_flag (Elem::REFINE); flags_changed = true; } } } } return flags_changed; } bool MeshRefinement::eliminate_unrefined_patches () { bool flags_changed = false; // active_elem_iterator elem_it (_mesh.elements_begin()); // const active_elem_iterator elem_end(_mesh.elements_end()); MeshBase::element_iterator elem_it = _mesh.active_elements_begin(); const MeshBase::element_iterator elem_end = _mesh.active_elements_end(); for (; elem_it != elem_end; ++elem_it) { Elem* elem = *elem_it; const unsigned int my_level = elem->level(); bool flag_me = true; // Skip the element if it is already flagged for refinement if (elem->refinement_flag() == Elem::REFINE) continue; // Test the parent if that is already flagged for coarsening if (elem->refinement_flag() == Elem::COARSEN) { assert(elem->parent()); // FIXME: this is reasonable, but why don't we have a non-const // Elem::parent() to begin with? elem = const_cast<Elem *>(elem->parent()); if (elem->refinement_flag() != Elem::COARSEN_INACTIVE) continue; } // Check all the element neighbors for (unsigned int n=0; n<elem->n_neighbors(); n++) // Quit if the element is on the boundary, or // if the neighbor is active and will not be refined; // then we do not need to refine ourselves. if (elem->neighbor(n) == NULL || (elem->neighbor(n)->level() < my_level) || ((elem->neighbor(n)->active()) && (elem->neighbor(n)->refinement_flag() != Elem::REFINE)) || (elem->neighbor(n)->refinement_flag() == Elem::COARSEN_INACTIVE)) { flag_me = false; break; } if (flag_me) { // Parents that would create islands should no longer // coarsen if (elem->refinement_flag() == Elem::COARSEN_INACTIVE) { for (unsigned int c=0; c<elem->n_children(); c++) { assert(elem->child(c)->refinement_flag() == Elem::COARSEN); elem->child(c)->set_refinement_flag(Elem::DO_NOTHING); } elem->set_refinement_flag(Elem::INACTIVE); } else elem->set_refinement_flag(Elem::REFINE); flags_changed = true; } } return flags_changed; } #endif <commit_msg>Update smoothing code to handle hp meshes<commit_after>// $Id: mesh_refinement_smoothing.C,v 1.13 2006-04-18 03:44:23 roystgnr Exp $ // The libMesh Finite Element Library. // Copyright (C) 2002-2005 Benjamin S. Kirk, John W. Peterson // 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 // Local includes #include "libmesh_config.h" // only compile these functions if the user requests AMR support #ifdef ENABLE_AMR #include "mesh_refinement.h" #include "mesh_base.h" #include "elem.h" //----------------------------------------------------------------- // Mesh refinement methods bool MeshRefinement::limit_level_mismatch_at_node (const unsigned int max_mismatch) { bool flags_changed = false; // Vector holding the maximum element level that touches a node. std::vector<unsigned char> max_level_at_node (_mesh.n_nodes(), 0); std::vector<unsigned char> max_p_level_at_node (_mesh.n_nodes(), 0); // Loop over all the active elements & fill the vector { // const_active_elem_iterator elem_it (_mesh.const_elements_begin()); // const const_active_elem_iterator elem_end(_mesh.const_elements_end()); MeshBase::element_iterator elem_it = _mesh.active_elements_begin(); const MeshBase::element_iterator elem_end = _mesh.active_elements_end(); for (; elem_it != elem_end; ++elem_it) { const Elem* elem = *elem_it; const unsigned char elem_level = elem->level() + ((elem->refinement_flag() == Elem::REFINE) ? 1 : 0); const unsigned char elem_p_level = elem->p_level() + ((elem->p_refinement_flag() == Elem::REFINE) ? 1 : 0); // Set the max_level at each node for (unsigned int n=0; n<elem->n_nodes(); n++) { const unsigned int node_number = elem->node(n); assert (node_number < max_level_at_node.size()); max_level_at_node[node_number] = std::max (max_level_at_node[node_number], elem_level); max_p_level_at_node[node_number] = std::max (max_p_level_at_node[node_number], elem_p_level); } } } // Now loop over the active elements and flag the elements // who violate the requested level mismatch { // active_elem_iterator elem_it (_mesh.elements_begin()); // const active_elem_iterator elem_end(_mesh.elements_end()); MeshBase::element_iterator elem_it = _mesh.active_elements_begin(); const MeshBase::element_iterator elem_end = _mesh.active_elements_end(); for (; elem_it != elem_end; ++elem_it) { Elem* elem = *elem_it; const unsigned int elem_level = elem->level(); const unsigned int elem_p_level = elem->p_level(); // Skip the element if it is already fully flagged if (elem->refinement_flag() == Elem::REFINE && elem->p_refinement_flag() == Elem::REFINE) continue; // Loop over the nodes, check for possible mismatch for (unsigned int n=0; n<elem->n_nodes(); n++) { const unsigned int node_number = elem->node(n); // Flag the element for refinement if it violates // the requested level mismatch if ( (elem_level + max_mismatch) < max_level_at_node[node_number] && elem->refinement_flag() != Elem::REFINE) { elem->set_refinement_flag (Elem::REFINE); flags_changed = true; } if ( (elem_p_level + max_mismatch) < max_p_level_at_node[node_number] && elem->p_refinement_flag() != Elem::REFINE) { elem->set_p_refinement_flag (Elem::REFINE); flags_changed = true; } } } } return flags_changed; } bool MeshRefinement::eliminate_unrefined_patches () { bool flags_changed = false; // active_elem_iterator elem_it (_mesh.elements_begin()); // const active_elem_iterator elem_end(_mesh.elements_end()); MeshBase::element_iterator elem_it = _mesh.active_elements_begin(); const MeshBase::element_iterator elem_end = _mesh.active_elements_end(); for (; elem_it != elem_end; ++elem_it) { Elem* elem = *elem_it; bool h_flag_me = true, p_flag_me = true; // Skip the element if it is already fully flagged for refinement if (elem->p_refinement_flag() == Elem::REFINE) p_flag_me = false; if (elem->refinement_flag() == Elem::REFINE) { h_flag_me = false; if (!p_flag_me) continue; } // Test the parent if that is already flagged for coarsening else if (elem->refinement_flag() == Elem::COARSEN) { assert(elem->parent()); elem = elem->parent(); // FIXME - this doesn't seem right - RHS if (elem->refinement_flag() != Elem::COARSEN_INACTIVE) continue; p_flag_me = false; } const unsigned int my_level = elem->level(); int my_p_adjustment = 0; if (elem->p_refinement_flag() == Elem::REFINE) my_p_adjustment = 1; else if (elem->p_refinement_flag() == Elem::COARSEN) { assert(elem->p_level() > 0); my_p_adjustment = -1; } const unsigned int my_new_p_level = elem->p_level() + my_p_adjustment; // Check all the element neighbors for (unsigned int n=0; n<elem->n_neighbors(); n++) { const Elem *neighbor = elem->neighbor(n); // Quit if the element is on the boundary if (neighbor == NULL) { h_flag_me = false; p_flag_me = false; break; } // if the neighbor will be equally or less refined // than we are, then we do not need to h refine ourselves. if (h_flag_me && (neighbor->level() < my_level) || ((neighbor->active()) && (neighbor->refinement_flag() != Elem::REFINE)) || (neighbor->refinement_flag() == Elem::COARSEN_INACTIVE)) { h_flag_me = false; if (!p_flag_me) break; } if (p_flag_me) { // if active neighbors will have a p level // equal to or lower than ours, then we do not need to p refine // ourselves. if (neighbor->active()) { int p_adjustment = 0; if (neighbor->p_refinement_flag() == Elem::REFINE) p_adjustment = 1; else if (neighbor->p_refinement_flag() == Elem::COARSEN) { assert(neighbor->p_level() > 0); p_adjustment = -1; } if (my_new_p_level >= neighbor->p_level() + p_adjustment) { p_flag_me = false; if (!h_flag_me) break; } } // If we have inactive neighbors, we need to // test all their active descendants which neighbor us else { if (neighbor->min_new_p_level_by_neighbor(elem, my_new_p_level + 2) <= my_new_p_level) { p_flag_me = false; if (!h_flag_me) break; } } } } if (h_flag_me) { // Parents that would create islands should no longer // coarsen if (elem->refinement_flag() == Elem::COARSEN_INACTIVE) { for (unsigned int c=0; c<elem->n_children(); c++) { assert(elem->child(c)->refinement_flag() == Elem::COARSEN); elem->child(c)->set_refinement_flag(Elem::DO_NOTHING); } elem->set_refinement_flag(Elem::INACTIVE); } else elem->set_refinement_flag(Elem::REFINE); flags_changed = true; } if (p_flag_me) { elem->set_p_refinement_flag(Elem::REFINE); flags_changed = true; } } return flags_changed; } #endif <|endoftext|>
<commit_before>/***************************************************************************** * Media Library ***************************************************************************** * Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs * * Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "Common.hpp" #include "Media.h" #include "utils/Filename.h" namespace medialibrary { bool medialibrary::MetadataCommon::startPlayback( VLC::Media& media, VLC::MediaPlayer& mp ) { // Use a copy of the event manager to automatically unregister all events as soon // as we leave this method. bool hasVideoTrack = false; bool failedToStart = false; bool hasAnyTrack = false; bool success = false; auto em = mp.eventManager(); compat::Mutex mutex; compat::ConditionVariable cond; em.onESAdded([&mutex, &cond, &hasVideoTrack, &hasAnyTrack]( libvlc_track_type_t type, int ) { std::lock_guard<compat::Mutex> lock( mutex ); if ( type == libvlc_track_video ) hasVideoTrack = true; hasAnyTrack = true; cond.notify_all(); }); em.onEncounteredError([&mutex, &cond, &failedToStart]() { std::lock_guard<compat::Mutex> lock( mutex ); failedToStart = true; cond.notify_all(); }); bool metaArtworkChanged = false; bool watchForArtworkChange = false; auto mem = media.eventManager(); if ( utils::file::schemeIs( "attachment", media.meta( libvlc_meta_ArtworkURL ) ) == true ) { watchForArtworkChange = true; mem.onMetaChanged([&mutex, &cond, &metaArtworkChanged, &media]( libvlc_meta_t meta ) { if ( meta != libvlc_meta_ArtworkURL || metaArtworkChanged == true || utils::file::schemeIs( "attachment", media.meta( libvlc_meta_ArtworkURL ) ) == true ) return; std::lock_guard<compat::Mutex> lock( mutex ); metaArtworkChanged = true; cond.notify_all(); }); } { std::unique_lock<compat::Mutex> lock( mutex ); mp.play(); success = cond.wait_for( lock, std::chrono::seconds( 3 ), [&failedToStart, &hasAnyTrack]() { return failedToStart == true || hasAnyTrack == true; }); // In case the playback failed, we probably won't fetch anything interesting anyway. if ( failedToStart == true || success == false ) return false; // If we have any kind of track, but not a video track, we don't have to wait long, tracks are usually // being discovered together. if ( hasVideoTrack == false ) { if ( watchForArtworkChange == true ) { cond.wait_for( lock, std::chrono::milliseconds( 500 ), [&metaArtworkChanged]() { return metaArtworkChanged == true; }); } else { cond.wait_for( lock, std::chrono::seconds( 1 ), [&hasVideoTrack]() { return hasVideoTrack == true; }); } } } return true; } } <commit_msg>Metadata: Common: Remove useless scope<commit_after>/***************************************************************************** * Media Library ***************************************************************************** * Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs * * Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "Common.hpp" #include "Media.h" #include "utils/Filename.h" namespace medialibrary { bool medialibrary::MetadataCommon::startPlayback( VLC::Media& media, VLC::MediaPlayer& mp ) { // Use a copy of the event manager to automatically unregister all events as soon // as we leave this method. bool hasVideoTrack = false; bool failedToStart = false; bool hasAnyTrack = false; bool success = false; auto em = mp.eventManager(); compat::Mutex mutex; compat::ConditionVariable cond; em.onESAdded([&mutex, &cond, &hasVideoTrack, &hasAnyTrack]( libvlc_track_type_t type, int ) { std::lock_guard<compat::Mutex> lock( mutex ); if ( type == libvlc_track_video ) hasVideoTrack = true; hasAnyTrack = true; cond.notify_all(); }); em.onEncounteredError([&mutex, &cond, &failedToStart]() { std::lock_guard<compat::Mutex> lock( mutex ); failedToStart = true; cond.notify_all(); }); bool metaArtworkChanged = false; bool watchForArtworkChange = false; auto mem = media.eventManager(); if ( utils::file::schemeIs( "attachment", media.meta( libvlc_meta_ArtworkURL ) ) == true ) { watchForArtworkChange = true; mem.onMetaChanged([&mutex, &cond, &metaArtworkChanged, &media]( libvlc_meta_t meta ) { if ( meta != libvlc_meta_ArtworkURL || metaArtworkChanged == true || utils::file::schemeIs( "attachment", media.meta( libvlc_meta_ArtworkURL ) ) == true ) return; std::lock_guard<compat::Mutex> lock( mutex ); metaArtworkChanged = true; cond.notify_all(); }); } std::unique_lock<compat::Mutex> lock( mutex ); mp.play(); success = cond.wait_for( lock, std::chrono::seconds( 3 ), [&failedToStart, &hasAnyTrack]() { return failedToStart == true || hasAnyTrack == true; }); // In case the playback failed, we probably won't fetch anything interesting anyway. if ( failedToStart == true || success == false ) return false; // If we have any kind of track, but not a video track, we don't have to wait long, tracks are usually // being discovered together. if ( hasVideoTrack == false ) { if ( watchForArtworkChange == true ) { cond.wait_for( lock, std::chrono::milliseconds( 500 ), [&metaArtworkChanged]() { return metaArtworkChanged == true; }); } else { cond.wait_for( lock, std::chrono::seconds( 1 ), [&hasVideoTrack]() { return hasVideoTrack == true; }); } } return true; } } <|endoftext|>
<commit_before>// Copyright (c) 2016 Kasper Kronborg Isager and Radosław Niemczyk. #include <vector> #include <iostream> #include <fstream> #include <hayai/hayai.hpp> #include <hayai/hayai_posix_main.cpp> #include <hemingway/vector.hpp> #include <hemingway/table.hpp> using namespace lsh; std::vector<vector> parse(std::string path) { std::ifstream stream(path, std::ios::binary); std::vector<vector> vectors; std::vector<char> buffer(1 << 20); while (!stream.eof()) { stream.read(&buffer[0], 1 << 20); int read = stream.gcount(); for (int i = 0; i < read; i += 8) { unsigned long n; for (int j = 0; j < 8; j++) { ((char*) &n)[j] = buffer[i + j]; } std::vector<bool> c(64); for (int j = 0; j < 64; j++) { c[j] = (n >> (63 - j)) & 1; } vectors.push_back(vector(c)); } } return vectors; } std::vector<vector> vs = parse("bench/data/vectors.bin"); std::vector<vector> qs = parse("bench/data/queries.bin"); std::vector<vector> gt; table t_lin(table::brute({.dimensions = 64})); table t_cla({.dimensions = 64, .samples = 31, .partitions = 31}); table t_cov({.dimensions = 64, .radius = 4}); unsigned int vn = vs.size(); unsigned int qn = qs.size(); unsigned int vi; unsigned int qi; unsigned int runs = 50; BENCHMARK(table, insert_linear, runs, vn / runs) { t_lin.insert(vs[vi++ % vn]); } BENCHMARK(table, insert_classic, runs, vn / runs) { t_cla.insert(vs[vi++ % vn]); } BENCHMARK(table, insert_covering, runs, vn / runs) { t_cov.insert(vs[vi++ % vn]); } BENCHMARK(table, query_linear, runs, qn / runs) { vector q = qs[qi++ % qn]; vector r = t_lin.query(q); gt.push_back(r); } BENCHMARK(table, query_classic, runs, qn / runs) { unsigned int i = qi++ % qn; vector q = qs[i]; vector t = gt[i]; vector r = t_cla.query(q); if (vector::distance(q, t) <= 4) { if (r.size() == 0) { std::cout << " "; std::cout << "Incorrect result: Found nothing" << std::endl; } else if (vector::distance(q, r) > 4) { std::cout << " "; std::cout << "Incorrect result: False negative" << std::endl; } } } BENCHMARK(table, query_covering, runs, qn / runs) { unsigned int i = qi++ % qn; vector q = qs[i]; vector t = gt[i]; vector r = t_cov.query(q); if (vector::distance(q, t) <= 4) { if (r.size() == 0) { std::cout << " "; std::cout << "Incorrect result: Found nothing" << std::endl; } else if (vector::distance(q, r) > 4) { std::cout << " "; std::cout << "Incorrect result: False negative" << std::endl; } } } <commit_msg>Compute some variables automatically<commit_after>// Copyright (c) 2016 Kasper Kronborg Isager and Radosław Niemczyk. #include <vector> #include <iostream> #include <fstream> #include <hayai/hayai.hpp> #include <hayai/hayai_posix_main.cpp> #include <hemingway/vector.hpp> #include <hemingway/table.hpp> using namespace lsh; std::vector<vector> parse(std::string path) { std::ifstream stream(path, std::ios::binary); std::vector<vector> vectors; std::vector<char> buffer(1 << 20); while (!stream.eof()) { stream.read(&buffer[0], 1 << 20); int read = stream.gcount(); for (int i = 0; i < read; i += 8) { unsigned long n; for (int j = 0; j < 8; j++) { ((char*) &n)[j] = buffer[i + j]; } std::vector<bool> c(64); for (int j = 0; j < 64; j++) { c[j] = (n >> (63 - j)) & 1; } vectors.push_back(vector(c)); } } return vectors; } std::vector<vector> vs = parse("bench/data/vectors.bin"); std::vector<vector> qs = parse("bench/data/queries.bin"); std::vector<vector> gt; double delta = 0.01; unsigned short r = 4; unsigned short l = (1 << (r + 1)) - 1; unsigned short k = ceil(log2(1 - pow(delta, 1.0 / l)) / log2(1 - r / 64.0)); table t_lin(table::brute({.dimensions = 64})); table t_cla({.dimensions = 64, .samples = k, .partitions = l}); table t_cov({.dimensions = 64, .radius = r}); unsigned int vn = vs.size(); unsigned int qn = qs.size(); unsigned int vi; unsigned int qi; unsigned int runs = 50; BENCHMARK(table, insert_linear, runs, vn / runs) { t_lin.insert(vs[vi++ % vn]); } BENCHMARK(table, insert_classic, runs, vn / runs) { t_cla.insert(vs[vi++ % vn]); } BENCHMARK(table, insert_covering, runs, vn / runs) { t_cov.insert(vs[vi++ % vn]); } BENCHMARK(table, query_linear, runs, qn / runs) { vector q = qs[qi++ % qn]; vector r = t_lin.query(q); gt.push_back(r); } BENCHMARK(table, query_classic, runs, qn / runs) { unsigned int i = qi++ % qn; vector q = qs[i]; vector t = gt[i]; vector f = t_cla.query(q); if (vector::distance(q, t) <= r) { if (f.size() == 0) { std::cout << " "; std::cout << "Incorrect result: Found nothing" << std::endl; } else if (vector::distance(q, f) > r) { std::cout << " "; std::cout << "Incorrect result: False negative" << std::endl; } } } BENCHMARK(table, query_covering, runs, qn / runs) { unsigned int i = qi++ % qn; vector q = qs[i]; vector t = gt[i]; vector f = t_cov.query(q); if (vector::distance(q, t) <= r) { if (f.size() == 0) { std::cout << " "; std::cout << "Incorrect result: Found nothing" << std::endl; } else if (vector::distance(q, f) > r) { std::cout << " "; std::cout << "Incorrect result: False negative" << std::endl; } } } <|endoftext|>
<commit_before>#include "fight.h" #include "../drivers/MotorDriver.h" #include "../drivers/ProximitySensors.h" #include "../control/Movement.h" #define STANDARD_SPEED 170 enum { SEARCH_INITIAL, SEARCH_TURNING, SEARCH_FORWARD, FOUND_LEFT, FOUND_RIGHT, FOUND_STRAIGHT, STOP_MOVING } STATE = SEARCH_INITIAL; void MovePattern() { switch(STATE) { case SEARCH_INITIAL: if(isMovementComplete()) { initiateTurn(STANDARD_SPEED, 0, -90); STATE = SEARCH_TURNING; } break; case SEARCH_TURNING: if(isMovementComplete()) { initiateLinearMovement(STANDARD_SPEED, 200); STATE = SEARCH_FORWARD; } break; case SEARCH_FORWARD: if(isMovementComplete()) { initiateTurn(STANDARD_SPEED, 50, 270); STATE = SEARCH_TURNING; } break; case FOUND_LEFT: initiateTurn(STANDARD_SPEED, 0, -90); STATE = FOUND_STRAIGHT; break; case FOUND_RIGHT: initiateTurn(STANDARD_SPEED, 0, 90); STATE = FOUND_STRAIGHT; break; case FOUND_STRAIGHT: if(isMovementComplete()) { initiateLinearMovement(STANDARD_SPEED, 1000); STATE = FOUND_STRAIGHT; } break; default: if(isMovementComplete()) { setMotors(0, 0); } break; } } /* void RoundPattern() { switch(STATE) { case INITIAL_STATE: { Turn(200,360); STATE = STATE_TURNING; } break; case STATE_TURNING: if(isMovementComplete()) { // keep turning Turn(200,360); } break; default: setMotors(0, 0); break; } // if( digitalRead(LEFT_SENSOR_PIN) ^ 1 == 1 || digitalRead(RIGHT_SENSOR_PIN) ^ 1 == 1) // { // STATE = EXIT_STATE_ON_SIDE; // } // if(OutOfRing()) // { // STATE = EXIT_STATE_OUT_OF_RING; // } // if(Impact()) // { // STATE = EXIT_STATE_ON_IMPACT; // } } */ void initFight() { } void handleFight(void) { uint8_t left = readLeftSensor(); uint8_t right = readRightSensor(); if(left) STATE = FOUND_LEFT; else if(right) STATE = FOUND_RIGHT; MovePattern(); } <commit_msg>Update fight speed<commit_after>#include "fight.h" #include "../drivers/MotorDriver.h" #include "../drivers/ProximitySensors.h" #include "../control/Movement.h" #define STANDARD_SPEED 1000 enum { SEARCH_INITIAL, SEARCH_TURNING, SEARCH_FORWARD, FOUND_LEFT, FOUND_RIGHT, FOUND_STRAIGHT, STOP_MOVING } STATE = SEARCH_INITIAL; void MovePattern() { switch(STATE) { case SEARCH_INITIAL: if(isMovementComplete()) { initiateTurn(STANDARD_SPEED, 0, -90); STATE = SEARCH_TURNING; } break; case SEARCH_TURNING: if(isMovementComplete()) { initiateLinearMovement(STANDARD_SPEED, 200); STATE = SEARCH_FORWARD; } break; case SEARCH_FORWARD: if(isMovementComplete()) { initiateTurn(STANDARD_SPEED, 50, 270); STATE = SEARCH_TURNING; } break; case FOUND_LEFT: initiateTurn(STANDARD_SPEED, 0, -90); STATE = FOUND_STRAIGHT; break; case FOUND_RIGHT: initiateTurn(STANDARD_SPEED, 0, 90); STATE = FOUND_STRAIGHT; break; case FOUND_STRAIGHT: if(isMovementComplete()) { initiateLinearMovement(STANDARD_SPEED, 1000); STATE = FOUND_STRAIGHT; } break; default: if(isMovementComplete()) { setMotors(0, 0); } break; } } /* void RoundPattern() { switch(STATE) { case INITIAL_STATE: { Turn(200,360); STATE = STATE_TURNING; } break; case STATE_TURNING: if(isMovementComplete()) { // keep turning Turn(200,360); } break; default: setMotors(0, 0); break; } // if( digitalRead(LEFT_SENSOR_PIN) ^ 1 == 1 || digitalRead(RIGHT_SENSOR_PIN) ^ 1 == 1) // { // STATE = EXIT_STATE_ON_SIDE; // } // if(OutOfRing()) // { // STATE = EXIT_STATE_OUT_OF_RING; // } // if(Impact()) // { // STATE = EXIT_STATE_ON_IMPACT; // } } */ void initFight() { } void handleFight(void) { uint8_t left = readLeftSensor(); uint8_t right = readRightSensor(); if(left) STATE = FOUND_LEFT; else if(right) STATE = FOUND_RIGHT; MovePattern(); } <|endoftext|>
<commit_before>#include "include/rados/librados.h" #include "include/rados/librados.hpp" #include "test/rados-api/test.h" #include <sstream> #include <stdlib.h> #include <string> #include <time.h> #include <unistd.h> using namespace librados; std::string get_temp_pool_name() { char out[17]; memset(out, 0, sizeof(out)); for (size_t i = 0; i < sizeof(out) - 1; ++i) { out[i] = 'A' + (rand() % 26); } std::string prefix("test-rados-api-"); prefix += out; return prefix; } std::string create_one_pool(const std::string &pool_name, rados_t *cluster) { int ret; ret = rados_create(cluster, NULL); if (ret) { std::ostringstream oss; oss << "rados_create failed with error " << ret; return oss.str(); } ret = rados_conf_read_file(*cluster, NULL); if (ret) { rados_shutdown(*cluster); std::ostringstream oss; oss << "rados_conf_read_file failed with error " << ret; return oss.str(); } rados_conf_parse_env(*cluster, NULL); ret = rados_connect(*cluster); if (ret) { rados_shutdown(*cluster); std::ostringstream oss; oss << "rados_connect failed with error " << ret; return oss.str(); } ret = rados_pool_create(*cluster, pool_name.c_str()); if (ret) { rados_shutdown(*cluster); std::ostringstream oss; oss << "rados_pool_create(" << pool_name << ") failed with error " << ret; return oss.str(); } return ""; } std::string create_one_pool_pp(const std::string &pool_name, Rados &cluster) { char *id = getenv("CEPH_CLIENT_ID"); if (id) std::cerr << "Client id is: " << id << std::endl; int ret; ret = cluster.init(id); if (ret) { std::ostringstream oss; oss << "cluster.init failed with error " << ret; return oss.str(); } ret = cluster.conf_read_file(NULL); if (ret) { cluster.shutdown(); std::ostringstream oss; oss << "cluster.conf_read_file failed with error " << ret; return oss.str(); } cluster.conf_parse_env(NULL); ret = cluster.connect(); if (ret) { cluster.shutdown(); std::ostringstream oss; oss << "cluster.connect failed with error " << ret; return oss.str(); } ret = cluster.pool_create(pool_name.c_str()); if (ret) { cluster.shutdown(); std::ostringstream oss; oss << "cluster.pool_create(" << pool_name << ") failed with error " << ret; return oss.str(); } return ""; } int destroy_one_pool(const std::string &pool_name, rados_t *cluster) { int ret = rados_pool_delete(*cluster, pool_name.c_str()); if (ret) { rados_shutdown(*cluster); return ret; } rados_shutdown(*cluster); return 0; } int destroy_one_pool_pp(const std::string &pool_name, Rados &cluster) { int ret = cluster.pool_delete(pool_name.c_str()); if (ret) { cluster.shutdown(); return ret; } cluster.shutdown(); return 0; } <commit_msg>qa: rados-api: try harder to make these pool names unique<commit_after>#include "include/rados/librados.h" #include "include/rados/librados.hpp" #include "test/rados-api/test.h" #include <sstream> #include <stdlib.h> #include <string> #include <time.h> #include <unistd.h> using namespace librados; std::string get_temp_pool_name() { char hostname[80]; char out[80]; memset(hostname, 0, sizeof(hostname)); memset(out, 0, sizeof(out)); gethostname(hostname, sizeof(hostname)-1); static int num = 1; sprintf(out, "%s-%d-%d", hostname, getpid(), num); num++; std::string prefix("test-rados-api-"); prefix += out; return prefix; } std::string create_one_pool(const std::string &pool_name, rados_t *cluster) { int ret; ret = rados_create(cluster, NULL); if (ret) { std::ostringstream oss; oss << "rados_create failed with error " << ret; return oss.str(); } ret = rados_conf_read_file(*cluster, NULL); if (ret) { rados_shutdown(*cluster); std::ostringstream oss; oss << "rados_conf_read_file failed with error " << ret; return oss.str(); } rados_conf_parse_env(*cluster, NULL); ret = rados_connect(*cluster); if (ret) { rados_shutdown(*cluster); std::ostringstream oss; oss << "rados_connect failed with error " << ret; return oss.str(); } ret = rados_pool_create(*cluster, pool_name.c_str()); if (ret) { rados_shutdown(*cluster); std::ostringstream oss; oss << "rados_pool_create(" << pool_name << ") failed with error " << ret; return oss.str(); } return ""; } std::string create_one_pool_pp(const std::string &pool_name, Rados &cluster) { char *id = getenv("CEPH_CLIENT_ID"); if (id) std::cerr << "Client id is: " << id << std::endl; int ret; ret = cluster.init(id); if (ret) { std::ostringstream oss; oss << "cluster.init failed with error " << ret; return oss.str(); } ret = cluster.conf_read_file(NULL); if (ret) { cluster.shutdown(); std::ostringstream oss; oss << "cluster.conf_read_file failed with error " << ret; return oss.str(); } cluster.conf_parse_env(NULL); ret = cluster.connect(); if (ret) { cluster.shutdown(); std::ostringstream oss; oss << "cluster.connect failed with error " << ret; return oss.str(); } ret = cluster.pool_create(pool_name.c_str()); if (ret) { cluster.shutdown(); std::ostringstream oss; oss << "cluster.pool_create(" << pool_name << ") failed with error " << ret; return oss.str(); } return ""; } int destroy_one_pool(const std::string &pool_name, rados_t *cluster) { int ret = rados_pool_delete(*cluster, pool_name.c_str()); if (ret) { rados_shutdown(*cluster); return ret; } rados_shutdown(*cluster); return 0; } int destroy_one_pool_pp(const std::string &pool_name, Rados &cluster) { int ret = cluster.pool_delete(pool_name.c_str()); if (ret) { cluster.shutdown(); return ret; } cluster.shutdown(); return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2013 The Bitcoin Core developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <boost/test/unit_test.hpp> #include <iostream> #include "main.h" #include "util.h" #include "serialize.h" #include "version.h" #include "data/sighash.json.h" #include "json/json_spirit_reader_template.h" #include "json/json_spirit_utils.h" #include "json/json_spirit_writer_template.h" using namespace json_spirit; extern Array read_json(const std::string& jsondata); extern uint256 SignatureHash(const CScript &scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType); // Old script.cpp SignatureHash function uint256 static SignatureHashOld(CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType) { if (nIn >= txTo.vin.size()) { printf("ERROR: SignatureHash() : nIn=%d out of range\n", nIn); return 1; } CTransaction txTmp(txTo); // In case concatenating two scripts ends up with two codeseparators, // or an extra one at the end, this prevents all those possible incompatibilities. scriptCode.FindAndDelete(CScript(OP_CODESEPARATOR)); // Blank out other inputs' signatures for (unsigned int i = 0; i < txTmp.vin.size(); i++) txTmp.vin[i].scriptSig = CScript(); txTmp.vin[nIn].scriptSig = scriptCode; // Blank out some of the outputs if ((nHashType & 0x1f) == SIGHASH_NONE) { // Wildcard payee txTmp.vout.clear(); // Let the others update at will for (unsigned int i = 0; i < txTmp.vin.size(); i++) if (i != nIn) txTmp.vin[i].nSequence = 0; } else if ((nHashType & 0x1f) == SIGHASH_SINGLE) { // Only lock-in the txout payee at same index as txin unsigned int nOut = nIn; if (nOut >= txTmp.vout.size()) { printf("ERROR: SignatureHash() : nOut=%d out of range\n", nOut); return 1; } txTmp.vout.resize(nOut+1); for (unsigned int i = 0; i < nOut; i++) txTmp.vout[i].SetNull(); // Let the others update at will for (unsigned int i = 0; i < txTmp.vin.size(); i++) if (i != nIn) txTmp.vin[i].nSequence = 0; } // Blank out other inputs completely, not recommended for open transactions if (nHashType & SIGHASH_ANYONECANPAY) { txTmp.vin[0] = txTmp.vin[nIn]; txTmp.vin.resize(1); } // Serialize and hash CHashWriter ss(SER_GETHASH, 0); ss << txTmp << nHashType; return ss.GetHash(); } void static RandomScript(CScript &script) { static const opcodetype oplist[] = {OP_FALSE, OP_1, OP_2, OP_3, OP_CHECKSIG, OP_IF, OP_VERIF, OP_RETURN, OP_CODESEPARATOR}; script = CScript(); int ops = (insecure_rand() % 10); for (int i=0; i<ops; i++) script << oplist[insecure_rand() % (sizeof(oplist)/sizeof(oplist[0]))]; } void static RandomTransaction(CTransaction &tx, bool fSingle) { tx.nVersion = insecure_rand(); tx.vin.clear(); tx.vout.clear(); tx.nLockTime = (insecure_rand() % 2) ? insecure_rand() : 0; int ins = (insecure_rand() % 4) + 1; int outs = fSingle ? ins : (insecure_rand() % 4) + 1; for (int in = 0; in < ins; in++) { tx.vin.push_back(CTxIn()); CTxIn &txin = tx.vin.back(); txin.prevout.hash = GetRandHash(); txin.prevout.n = insecure_rand() % 4; RandomScript(txin.scriptSig); txin.nSequence = (insecure_rand() % 2) ? insecure_rand() : (unsigned int)-1; } for (int out = 0; out < outs; out++) { tx.vout.push_back(CTxOut()); CTxOut &txout = tx.vout.back(); txout.nValue = insecure_rand() % 100000000; RandomScript(txout.scriptPubKey); } } BOOST_AUTO_TEST_SUITE(sighash_tests) BOOST_AUTO_TEST_CASE(sighash_test) { seed_insecure_rand(false); for (int i=0; i<50000; i++) { int nHashType = insecure_rand(); CTransaction txTo; RandomTransaction(txTo, (nHashType & 0x1f) == SIGHASH_SINGLE); CScript scriptCode; RandomScript(scriptCode); int nIn = insecure_rand() % txTo.vin.size(); uint256 sh, sho; sho = SignatureHashOld(scriptCode, txTo, nIn, nHashType); sh = SignatureHash(scriptCode, txTo, nIn, nHashType); BOOST_CHECK(sh == sho); } } // Goal: check that SignatureHash generates correct hash BOOST_AUTO_TEST_CASE(sighash_from_data) { Array tests = read_json(std::string(json_tests::sighash, json_tests::sighash + sizeof(json_tests::sighash))); BOOST_FOREACH(Value& tv, tests) { Array test = tv.get_array(); std::string strTest = write_string(tv, false); if (test.size() < 1) // Allow for extra stuff (useful for comments) { BOOST_ERROR("Bad test: " << strTest); continue; } if (test.size() == 1) continue; // comment std::string raw_tx = test[0].get_str(); std::string raw_script = test[1].get_str(); int nIn = test[2].get_int(); int nHashType = test[3].get_int(); std::string sigHashHex = test[4].get_str(); uint256 sh; CDataStream stream(ParseHex(raw_tx), SER_NETWORK, PROTOCOL_VERSION); CTransaction tx; stream >> tx; CValidationState state; BOOST_CHECK_MESSAGE(CheckTransaction(tx, state), strTest); BOOST_CHECK(state.IsValid()); CScript scriptCode = CScript(); std::vector<unsigned char> raw = ParseHex(raw_script); scriptCode.insert(scriptCode.end(), raw.begin(), raw.end()); sh = SignatureHash(scriptCode, tx, nIn, nHashType); BOOST_CHECK_MESSAGE(sh.GetHex() == sigHashHex, strTest); } } BOOST_AUTO_TEST_SUITE_END() <commit_msg>Add code generating data/sighash.json test data<commit_after>// Copyright (c) 2013 The Bitcoin Core developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <boost/test/unit_test.hpp> #include <iostream> #include "main.h" #include "util.h" #include "serialize.h" #include "version.h" #include "data/sighash.json.h" #include "json/json_spirit_reader_template.h" #include "json/json_spirit_utils.h" #include "json/json_spirit_writer_template.h" using namespace json_spirit; extern Array read_json(const std::string& jsondata); extern uint256 SignatureHash(const CScript &scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType); // Old script.cpp SignatureHash function uint256 static SignatureHashOld(CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType) { if (nIn >= txTo.vin.size()) { printf("ERROR: SignatureHash() : nIn=%d out of range\n", nIn); return 1; } CTransaction txTmp(txTo); // In case concatenating two scripts ends up with two codeseparators, // or an extra one at the end, this prevents all those possible incompatibilities. scriptCode.FindAndDelete(CScript(OP_CODESEPARATOR)); // Blank out other inputs' signatures for (unsigned int i = 0; i < txTmp.vin.size(); i++) txTmp.vin[i].scriptSig = CScript(); txTmp.vin[nIn].scriptSig = scriptCode; // Blank out some of the outputs if ((nHashType & 0x1f) == SIGHASH_NONE) { // Wildcard payee txTmp.vout.clear(); // Let the others update at will for (unsigned int i = 0; i < txTmp.vin.size(); i++) if (i != nIn) txTmp.vin[i].nSequence = 0; } else if ((nHashType & 0x1f) == SIGHASH_SINGLE) { // Only lock-in the txout payee at same index as txin unsigned int nOut = nIn; if (nOut >= txTmp.vout.size()) { printf("ERROR: SignatureHash() : nOut=%d out of range\n", nOut); return 1; } txTmp.vout.resize(nOut+1); for (unsigned int i = 0; i < nOut; i++) txTmp.vout[i].SetNull(); // Let the others update at will for (unsigned int i = 0; i < txTmp.vin.size(); i++) if (i != nIn) txTmp.vin[i].nSequence = 0; } // Blank out other inputs completely, not recommended for open transactions if (nHashType & SIGHASH_ANYONECANPAY) { txTmp.vin[0] = txTmp.vin[nIn]; txTmp.vin.resize(1); } // Serialize and hash CHashWriter ss(SER_GETHASH, 0); ss << txTmp << nHashType; return ss.GetHash(); } void static RandomScript(CScript &script) { static const opcodetype oplist[] = {OP_FALSE, OP_1, OP_2, OP_3, OP_CHECKSIG, OP_IF, OP_VERIF, OP_RETURN, OP_CODESEPARATOR}; script = CScript(); int ops = (insecure_rand() % 10); for (int i=0; i<ops; i++) script << oplist[insecure_rand() % (sizeof(oplist)/sizeof(oplist[0]))]; } void static RandomTransaction(CTransaction &tx, bool fSingle) { tx.nVersion = insecure_rand(); tx.vin.clear(); tx.vout.clear(); tx.nLockTime = (insecure_rand() % 2) ? insecure_rand() : 0; int ins = (insecure_rand() % 4) + 1; int outs = fSingle ? ins : (insecure_rand() % 4) + 1; for (int in = 0; in < ins; in++) { tx.vin.push_back(CTxIn()); CTxIn &txin = tx.vin.back(); txin.prevout.hash = GetRandHash(); txin.prevout.n = insecure_rand() % 4; RandomScript(txin.scriptSig); txin.nSequence = (insecure_rand() % 2) ? insecure_rand() : (unsigned int)-1; } for (int out = 0; out < outs; out++) { tx.vout.push_back(CTxOut()); CTxOut &txout = tx.vout.back(); txout.nValue = insecure_rand() % 100000000; RandomScript(txout.scriptPubKey); } } BOOST_AUTO_TEST_SUITE(sighash_tests) BOOST_AUTO_TEST_CASE(sighash_test) { seed_insecure_rand(false); #if defined(PRINT_SIGHASH_JSON) std::cout << "[\n"; std::cout << "\t[\"raw_transaction, script, input_index, hashType, signature_hash (result)\"],\n"; #endif int nRandomTests = 50000; #if defined(PRINT_SIGHASH_JSON) nRandomTests = 500; #endif for (int i=0; i<nRandomTests; i++) { int nHashType = insecure_rand(); CTransaction txTo; RandomTransaction(txTo, (nHashType & 0x1f) == SIGHASH_SINGLE); CScript scriptCode; RandomScript(scriptCode); int nIn = insecure_rand() % txTo.vin.size(); uint256 sh, sho; sho = SignatureHashOld(scriptCode, txTo, nIn, nHashType); sh = SignatureHash(scriptCode, txTo, nIn, nHashType); #if defined(PRINT_SIGHASH_JSON) CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss << txTo; std::cout << "\t[\"" ; std::cout << HexStr(ss.begin(), ss.end()) << "\", \""; std::cout << HexStr(scriptCode) << "\", "; std::cout << nIn << ", "; std::cout << nHashType << ", \""; std::cout << sho.GetHex() << "\"]"; if (i+1 != nRandomTests) { std::cout << ","; } std::cout << "\n"; #endif BOOST_CHECK(sh == sho); } #if defined(PRINT_SIGHASH_JSON) std::cout << "]\n"; #endif } // Goal: check that SignatureHash generates correct hash BOOST_AUTO_TEST_CASE(sighash_from_data) { Array tests = read_json(std::string(json_tests::sighash, json_tests::sighash + sizeof(json_tests::sighash))); BOOST_FOREACH(Value& tv, tests) { Array test = tv.get_array(); std::string strTest = write_string(tv, false); if (test.size() < 1) // Allow for extra stuff (useful for comments) { BOOST_ERROR("Bad test: " << strTest); continue; } if (test.size() == 1) continue; // comment std::string raw_tx = test[0].get_str(); std::string raw_script = test[1].get_str(); int nIn = test[2].get_int(); int nHashType = test[3].get_int(); std::string sigHashHex = test[4].get_str(); uint256 sh; CDataStream stream(ParseHex(raw_tx), SER_NETWORK, PROTOCOL_VERSION); CTransaction tx; stream >> tx; CValidationState state; BOOST_CHECK_MESSAGE(CheckTransaction(tx, state), strTest); BOOST_CHECK(state.IsValid()); CScript scriptCode = CScript(); std::vector<unsigned char> raw = ParseHex(raw_script); scriptCode.insert(scriptCode.end(), raw.begin(), raw.end()); sh = SignatureHash(scriptCode, tx, nIn, nHashType); BOOST_CHECK_MESSAGE(sh.GetHex() == sigHashHex, strTest); } } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>#include <iostream> using namespace std; int main(int argc, char const *argv[]) { for (int i = 0; i < 100; ++i) { printf("%d\n",i*16 ); } return 0; }<commit_msg>Heure 6<commit_after>#include <iostream> using namespace std; int main(int argc, char const *argv[]) { for (int i = 0; i < 100; ++i) { cout<<i*16<<endl; } return 0; }<|endoftext|>
<commit_before>/* * (C) 2017 Jack Lloyd * * Botan is released under the Simplified BSD License (see license.txt) */ #include "tests.h" #if defined(BOTAN_HAS_CERTIFICATES) #include <botan/x509_dn.h> #include <botan/ber_dec.h> #endif namespace Botan_Tests { #if defined(BOTAN_HAS_CERTIFICATES) class X509_DN_Comparisons_Tests final : public Text_Based_Test { public: X509_DN_Comparisons_Tests() : Text_Based_Test("x509_dn.vec", "DN1,DN2") {} Test::Result run_one_test(const std::string& type, const VarMap& vars) override { const std::vector<uint8_t> dn_bits1 = get_req_bin(vars, "DN1"); const std::vector<uint8_t> dn_bits2 = get_req_bin(vars, "DN2"); const bool dn_same = (type == "Equal"); Test::Result result("X509_DN comparisons"); try { Botan::X509_DN dn1; Botan::BER_Decoder bd1(dn_bits1); dn1.decode_from(bd1); Botan::X509_DN dn2; Botan::BER_Decoder bd2(dn_bits2); dn2.decode_from(bd2); const bool compared_same = (dn1 == dn2); result.test_eq("Comparison matches expected", dn_same, compared_same); } catch(Botan::Exception& e) { result.test_failure(e.what()); } return result; } }; BOTAN_REGISTER_TEST("x509_dn_cmp", X509_DN_Comparisons_Tests); #endif } <commit_msg>Fix incorrect macro check<commit_after>/* * (C) 2017 Jack Lloyd * * Botan is released under the Simplified BSD License (see license.txt) */ #include "tests.h" #if defined(BOTAN_HAS_X509_CERTIFICATES) #include <botan/x509_dn.h> #include <botan/ber_dec.h> #endif namespace Botan_Tests { #if defined(BOTAN_HAS_X509_CERTIFICATES) class X509_DN_Comparisons_Tests final : public Text_Based_Test { public: X509_DN_Comparisons_Tests() : Text_Based_Test("x509_dn.vec", "DN1,DN2") {} Test::Result run_one_test(const std::string& type, const VarMap& vars) override { const std::vector<uint8_t> dn_bits1 = get_req_bin(vars, "DN1"); const std::vector<uint8_t> dn_bits2 = get_req_bin(vars, "DN2"); const bool dn_same = (type == "Equal"); Test::Result result("X509_DN comparisons"); try { Botan::X509_DN dn1; Botan::BER_Decoder bd1(dn_bits1); dn1.decode_from(bd1); Botan::X509_DN dn2; Botan::BER_Decoder bd2(dn_bits2); dn2.decode_from(bd2); const bool compared_same = (dn1 == dn2); result.test_eq("Comparison matches expected", dn_same, compared_same); } catch(Botan::Exception& e) { result.test_failure(e.what()); } return result; } }; BOTAN_REGISTER_TEST("x509_dn_cmp", X509_DN_Comparisons_Tests); #endif } <|endoftext|>
<commit_before>namespace RegularExpressionMatching { class Solution { public: bool checkIsMatch(const char *s, int posS, const char * p, int posP) { if (s[posS] == '\0' && p[posP] == '\0') { // sample case: s="", p="" return true; } if (s[posS] == '\0' && p[posP] != '\0') { if (p[posP + 1] == '*') { // sample case: s="", p="c*a*" return checkIsMatch(s, posS, p, posP + 2); } else { return false; // sample case: s="", p="a" } } if (s[posS] != '\0' && p[posP] == '\0') { return false; // sample case: s="abc", p="" } if (p[posP + 1] == '*') { bool res = checkIsMatch(s, posS, p, posP + 2); if (res) return res; int i = 1; if (p[posP] != '.' && p[posP] == s[posS]) { // sample case: s="aaaab", p="a*b" while (s[posS + i] == s[posS]) { bool res = checkIsMatch(s, posS + i, p, posP + 2); if (res) { return res; } i++; } } else if (p[posP] == '.') { // sample case: s="abcde", p=".*e" while (s[posS + i] != '\0') { bool res = checkIsMatch(s, posS + i, p, posP + 2); if (res) { return res; } i++; } } else { return false; // sample case: s="abcde", p="d*e" } return checkIsMatch(s, posS + i, p, posP + 2); } else { if (s[posS] == p[posP] || p[posP] == '.') { // sample case: s="abcde", p=".bcde" or s="abcde", p="abcde" return checkIsMatch(s, posS + 1, p, posP + 1); } else { return false; } } } bool isMatch(const char *s, const char *p) { if (s == NULL || p == NULL) { return false; } return checkIsMatch(s, 0, p, 0); } }; } <commit_msg>Add DP solution<commit_after>namespace RegularExpressionMatching { class Solution { public: bool checkIsMatch(const char *s, int posS, const char * p, int posP) { if (s[posS] == '\0' && p[posP] == '\0') { // sample case: s="", p="" return true; } if (s[posS] == '\0' && p[posP] != '\0') { if (p[posP + 1] == '*') { // sample case: s="", p="c*a*" return checkIsMatch(s, posS, p, posP + 2); } else { return false; // sample case: s="", p="a" } } if (s[posS] != '\0' && p[posP] == '\0') { return false; // sample case: s="abc", p="" } if (p[posP + 1] == '*') { bool res = checkIsMatch(s, posS, p, posP + 2); if (res) return res; int i = 1; if (p[posP] != '.' && p[posP] == s[posS]) { // sample case: s="aaaab", p="a*b" while (s[posS + i] == s[posS]) { bool res = checkIsMatch(s, posS + i, p, posP + 2); if (res) { return res; } i++; } } else if (p[posP] == '.') { // sample case: s="abcde", p=".*e" while (s[posS + i] != '\0') { bool res = checkIsMatch(s, posS + i, p, posP + 2); if (res) { return res; } i++; } } else { return false; // sample case: s="abcde", p="d*e" } return checkIsMatch(s, posS + i, p, posP + 2); } else { if (s[posS] == p[posP] || p[posP] == '.') { // sample case: s="abcde", p=".bcde" or s="abcde", p="abcde" return checkIsMatch(s, posS + 1, p, posP + 1); } else { return false; } } } bool isMatch(const char *s, const char *p) { if (s == NULL || p == NULL) { return false; } return checkIsMatch(s, 0, p, 0); } }; // ---------------------------------------------------------------- // add DP solution // ---------------------------------------------------------------- class Solution { public: bool isMatch(const char *s, const char *p) { int sLen = strlen(s); int pLen = strlen(p); vector<vector<bool> > dp(sLen + 1, vector<bool>(pLen + 1, false)); dp[0][0] = true; for (int i = 1; i <= pLen; i++) { if (p[i - 1] == '*') dp[0][i] = dp[0][i - 2]; // we assume that the invalid pattern with only a "*" won't appear } for (int i = 1; i <= sLen; i++) { for (int j = 1; j <= pLen; j++) { char cS = s[i - 1]; char cP = p[j - 1]; if (cS == cP || cP == '.') { dp[i][j] = dp[i - 1][j - 1]; } else if (cP == '*') { char cPPrev = p[j - 2]; if (cPPrev != cS && cPPrev != '.') { dp[i][j] = dp[i][j - 2]; } else { dp[i][j] = dp[i][j - 2] | dp[i - 1][j]; } } } } return dp[sLen][pLen]; } }; } <|endoftext|>
<commit_before>/** \file apply_differential_update.cc * \brief A tool for applying a differential update to a complete MARC dump. * \author Dr. Johannes Ruscheinski */ /* Copyright (C) 2018 Library of the University of Tübingen 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 <map> #include <stdexcept> #include <unordered_set> #include <cassert> #include <cstdlib> #include <cstring> #include "unistd.h" #include "Archive.h" #include "BSZUtil.h" #include "Compiler.h" #include "File.h" #include "FileUtil.h" #include "MARC.h" #include "RegexMatcher.h" #include "StringUtil.h" #include "util.h" namespace { [[noreturn]] void Usage() { std::cerr << "Usage: " << ::progname << " [--min-log-level=log_level] [--keep-intermediate-files] input_directory " << "difference_archive output_directory\n" << " Log levels are DEBUG, INFO, WARNING and ERROR with INFO being the default.\n\n"; std::exit(EXIT_FAILURE); } void CopyAndCollectPPNs(MARC::Reader * const reader, MARC::Writer * const writer, std::unordered_set<std::string> * const previously_seen_ppns) { while (auto record = reader->read()) { if (previously_seen_ppns->find(record.getControlNumber()) == previously_seen_ppns->end()) { previously_seen_ppns->emplace(record.getControlNumber()); if (record.getFirstField("ORI") == record.end()) record.appendField("ORI", MARC::Subfields(MARC::Subfield('a', FileUtil::GetLastPathComponent(reader->getPath())).toString())); writer->write(record); } } } void CopySelectedTypes(const std::vector<std::string> &archive_members, MARC::Writer * const writer, const std::set<BSZUtil::ArchiveType> &selected_types, std::unordered_set<std::string> * const previously_seen_ppns) { for (const auto &archive_member : archive_members) { if (selected_types.find(BSZUtil::GetArchiveType(archive_member)) != selected_types.cend()) { const auto reader(MARC::Reader::Factory(archive_member, MARC::FileType::BINARY)); CopyAndCollectPPNs(reader.get(), writer, previously_seen_ppns); } } } void PatchArchiveMembersAndCreateOutputArchive(const std::vector<std::string> &input_archive_members, const std::vector<std::string> &difference_archive_members, const std::string &output_directory) { if (input_archive_members.empty()) LOG_ERROR("no input archive members!"); if (difference_archive_members.empty()) LOG_WARNING("no difference archive members!"); // // We process title data first and combine all inferior and superior records. // const auto title_writer(MARC::Writer::Factory(output_directory + "/tit.mrc", MARC::FileType::BINARY)); std::unordered_set<std::string> previously_seen_title_ppns; CopySelectedTypes(difference_archive_members, title_writer.get(), { BSZUtil::TITLE_RECORDS, BSZUtil::SUPERIOR_TITLES }, &previously_seen_title_ppns); CopySelectedTypes(input_archive_members, title_writer.get(), { BSZUtil::TITLE_RECORDS, BSZUtil::SUPERIOR_TITLES }, &previously_seen_title_ppns); const auto authority_writer(MARC::Writer::Factory(output_directory + "/aut.mrc", MARC::FileType::BINARY)); std::unordered_set<std::string> previously_seen_authority_ppns; CopySelectedTypes(difference_archive_members, authority_writer.get(), { BSZUtil::AUTHORITY_RECORDS }, &previously_seen_authority_ppns); CopySelectedTypes(input_archive_members, authority_writer.get(), { BSZUtil::AUTHORITY_RECORDS }, &previously_seen_authority_ppns); } void GetDirectoryContentsWithRelativepath(const std::string &archive_name, std::vector<std::string> * const archive_members) { const std::string directory_name(archive_name); FileUtil::GetFileNameList(".(raw|mrc)$", archive_members, directory_name); for (auto &archive_member : *archive_members) archive_member = directory_name + "/" + archive_member; } std::string RemoveSuffix(const std::string &s, const std::string &suffix) { if (unlikely(not StringUtil::EndsWith(s, suffix))) LOG_ERROR("\"" + s + "\" does not end w/ \"" + suffix + "\"!"); return s.substr(0, s.length() - suffix.length()); } inline std::string StripTarGz(const std::string &archive_filename) { return RemoveSuffix(archive_filename, ".tar.gz"); } } // unnamed namespace int Main(int argc, char *argv[]) { if (argc < 4) Usage(); bool keep_intermediate_files(false); if (std::strcmp(argv[1], "--keep-intermediate-files") == 0) { keep_intermediate_files = true; --argc, ++argv; } if (argc != 4) Usage(); const std::string input_directory(FileUtil::MakeAbsolutePath(argv[1])); const std::string difference_archive(FileUtil::MakeAbsolutePath(argv[2])); const std::string output_directory(FileUtil::MakeAbsolutePath(argv[3])); if (input_directory == difference_archive or input_directory == output_directory or difference_archive == output_directory) LOG_ERROR("all archive names must be distinct!"); std::unique_ptr<FileUtil::AutoTempDirectory> working_directory; const std::string difference_directory(StripTarGz(difference_archive)); Archive::UnpackArchive(difference_archive, difference_directory); const auto directory_name(output_directory); if (not FileUtil::MakeDirectory(directory_name)) LOG_ERROR("failed to create directory: \"" + directory_name + "\"!"); std::vector<std::string> input_archive_members, difference_archive_members; GetDirectoryContentsWithRelativepath(input_directory, &input_archive_members); GetDirectoryContentsWithRelativepath(StripTarGz(difference_archive), &difference_archive_members); PatchArchiveMembersAndCreateOutputArchive(input_archive_members, difference_archive_members, output_directory); if (not keep_intermediate_files and not FileUtil::DeleteDirectory(difference_directory)) LOG_ERROR("failed to remove directory: \"" + difference_directory + "\"!"); return EXIT_SUCCESS; } <commit_msg>Fixed an incorrect function name.<commit_after>/** \file apply_differential_update.cc * \brief A tool for applying a differential update to a complete MARC dump. * \author Dr. Johannes Ruscheinski */ /* Copyright (C) 2018 Library of the University of Tübingen 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 <map> #include <stdexcept> #include <unordered_set> #include <cassert> #include <cstdlib> #include <cstring> #include "unistd.h" #include "Archive.h" #include "BSZUtil.h" #include "Compiler.h" #include "File.h" #include "FileUtil.h" #include "MARC.h" #include "RegexMatcher.h" #include "StringUtil.h" #include "util.h" namespace { [[noreturn]] void Usage() { std::cerr << "Usage: " << ::progname << " [--min-log-level=log_level] [--keep-intermediate-files] input_directory " << "difference_archive output_directory\n" << " Log levels are DEBUG, INFO, WARNING and ERROR with INFO being the default.\n\n"; std::exit(EXIT_FAILURE); } void CopyAndCollectPPNs(MARC::Reader * const reader, MARC::Writer * const writer, std::unordered_set<std::string> * const previously_seen_ppns) { while (auto record = reader->read()) { if (previously_seen_ppns->find(record.getControlNumber()) == previously_seen_ppns->end()) { previously_seen_ppns->emplace(record.getControlNumber()); if (record.getFirstField("ORI") == record.end()) record.appendField("ORI", MARC::Subfields(MARC::Subfield('a', FileUtil::GetLastPathComponent(reader->getPath())).toString())); writer->write(record); } } } void CopySelectedTypes(const std::vector<std::string> &archive_members, MARC::Writer * const writer, const std::set<BSZUtil::ArchiveType> &selected_types, std::unordered_set<std::string> * const previously_seen_ppns) { for (const auto &archive_member : archive_members) { if (selected_types.find(BSZUtil::GetArchiveType(archive_member)) != selected_types.cend()) { const auto reader(MARC::Reader::Factory(archive_member, MARC::FileType::BINARY)); CopyAndCollectPPNs(reader.get(), writer, previously_seen_ppns); } } } void PatchArchiveMembersAndCreateOutputArchive(const std::vector<std::string> &input_archive_members, const std::vector<std::string> &difference_archive_members, const std::string &output_directory) { if (input_archive_members.empty()) LOG_ERROR("no input archive members!"); if (difference_archive_members.empty()) LOG_WARNING("no difference archive members!"); // // We process title data first and combine all inferior and superior records. // const auto title_writer(MARC::Writer::Factory(output_directory + "/tit.mrc", MARC::FileType::BINARY)); std::unordered_set<std::string> previously_seen_title_ppns; CopySelectedTypes(difference_archive_members, title_writer.get(), { BSZUtil::TITLE_RECORDS, BSZUtil::SUPERIOR_TITLES }, &previously_seen_title_ppns); CopySelectedTypes(input_archive_members, title_writer.get(), { BSZUtil::TITLE_RECORDS, BSZUtil::SUPERIOR_TITLES }, &previously_seen_title_ppns); const auto authority_writer(MARC::Writer::Factory(output_directory + "/aut.mrc", MARC::FileType::BINARY)); std::unordered_set<std::string> previously_seen_authority_ppns; CopySelectedTypes(difference_archive_members, authority_writer.get(), { BSZUtil::AUTHORITY_RECORDS }, &previously_seen_authority_ppns); CopySelectedTypes(input_archive_members, authority_writer.get(), { BSZUtil::AUTHORITY_RECORDS }, &previously_seen_authority_ppns); } void GetDirectoryContentsWithRelativepath(const std::string &archive_name, std::vector<std::string> * const archive_members) { const std::string directory_name(archive_name); FileUtil::GetFileNameList(".(raw|mrc)$", archive_members, directory_name); for (auto &archive_member : *archive_members) archive_member = directory_name + "/" + archive_member; } std::string RemoveSuffix(const std::string &s, const std::string &suffix) { if (unlikely(not StringUtil::EndsWith(s, suffix))) LOG_ERROR("\"" + s + "\" does not end w/ \"" + suffix + "\"!"); return s.substr(0, s.length() - suffix.length()); } inline std::string StripTarGz(const std::string &archive_filename) { return RemoveSuffix(archive_filename, ".tar.gz"); } } // unnamed namespace int Main(int argc, char *argv[]) { if (argc < 4) Usage(); bool keep_intermediate_files(false); if (std::strcmp(argv[1], "--keep-intermediate-files") == 0) { keep_intermediate_files = true; --argc, ++argv; } if (argc != 4) Usage(); const std::string input_directory(FileUtil::MakeAbsolutePath(argv[1])); const std::string difference_archive(FileUtil::MakeAbsolutePath(argv[2])); const std::string output_directory(FileUtil::MakeAbsolutePath(argv[3])); if (input_directory == difference_archive or input_directory == output_directory or difference_archive == output_directory) LOG_ERROR("all archive names must be distinct!"); std::unique_ptr<FileUtil::AutoTempDirectory> working_directory; const std::string difference_directory(StripTarGz(difference_archive)); Archive::UnpackArchive(difference_archive, difference_directory); const auto directory_name(output_directory); if (not FileUtil::MakeDirectory(directory_name)) LOG_ERROR("failed to create directory: \"" + directory_name + "\"!"); std::vector<std::string> input_archive_members, difference_archive_members; GetDirectoryContentsWithRelativepath(input_directory, &input_archive_members); GetDirectoryContentsWithRelativepath(StripTarGz(difference_archive), &difference_archive_members); PatchArchiveMembersAndCreateOutputArchive(input_archive_members, difference_archive_members, output_directory); if (not keep_intermediate_files and not FileUtil::RemoveDirectory(difference_directory)) LOG_ERROR("failed to remove directory: \"" + difference_directory + "\"!"); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/** \file fix_article_biblio_levels.cc * \author Dr. Johannes Ruscheinski * * A tool for patching up the bibliographic level of article records. * Many, possibly all, article records that we get have an 'a' in leader position 7 instead of a 'b'. * If the referenced parent is no a monograph this tool changes the 'a' to a 'b'. */ /* Copyright (C) 2015-2018, Library of the University of Tübingen 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 <unordered_set> #include <vector> #include <cstdlib> #include "MARC.h" #include "RegexMatcher.h" #include "StringUtil.h" #include "util.h" namespace { [[noreturn]] void Usage() { std::cerr << "Usage: " << ::progname << " marc_input1 [marc_input2 ... marc_inputN] marc_output\n" << " Collects information about which superior/collective works are serials from the various\n" << " MARC inputs and then patches up records in \"marc_input1\" which have been marked as a book\n" << " component and changes them to be flagged as an article instead. The patched up version is\n" << " written to \"marc_output\".\n"; std::exit(EXIT_FAILURE); } void CollectMonographs(const std::vector<std::unique_ptr<MARC::Reader>> &marc_readers, std::unordered_set<std::string> * const monograph_control_numbers) { for (auto &marc_reader : marc_readers) { LOG_INFO("Extracting serial control numbers from \"" + marc_reader->getPath() + "\"."); while (const auto record = marc_reader->read()) { if (record.isMonograph()) monograph_control_numbers->insert(record.getControlNumber()); } } LOG_INFO("Found " + std::to_string(monograph_control_numbers->size()) + " serial records."); } bool HasMonographParent(const std::string &subfield, const MARC::Record &record, std::unordered_set<std::string> * const monograph_control_numbers) { const std::string tag(subfield.substr(0, 3)); const char subfield_code(subfield[3]); const auto field(record.findTag(tag)); if (field == record.end()) return false; const std::string &subfield_contents(field->getSubfields().getFirstSubfieldWithCode(subfield_code)); if (subfield_contents.empty()) return false; static RegexMatcher * const matcher(RegexMatcher::RegexMatcherFactory("\\(.+\\)(\\d{8}[\\dX])")); if (not matcher->matched(subfield_contents)) return false; const std::string parent_id((*matcher)[1]); return monograph_control_numbers->find(parent_id) != monograph_control_numbers->cend(); } bool HasAtLeastOneMonographParent(const std::string &subfield_list, const MARC::Record &record, std::unordered_set<std::string> * const monograph_control_numbers) { std::vector<std::string> subfields; StringUtil::Split(subfield_list, ':', &subfields); for (const auto &subfield : subfields) { if (HasMonographParent(subfield, record, monograph_control_numbers)) return true; } return false; } // Iterates over all records in a collection and retags all book component parts as articles // unless the object has a monograph as a parent. // Changes the bibliographic level of a record from 'a' to 'b' (= serial component part) if the parent is not a // monograph. Also writes all records to "output_ptr". void PatchUpBookComponentParts(MARC::Reader * const marc_reader, MARC::Writer * const marc_writer, std::unordered_set<std::string> * const monograph_control_numbers) { unsigned patch_count(0); while (auto record = marc_reader->read()) { if (record.isArticle() and not HasAtLeastOneMonographParent("800w:810w:830w:773w", record, monograph_control_numbers)) { record.setBibliographicLevel('b'); ++patch_count; } marc_writer->write(record); } LOG_INFO("Fixed the bibliographic level of " + std::to_string(patch_count) + " article records."); } } // unnamed namespace int Main(int argc, char **argv) { if (argc < 3) Usage(); std::vector<std::unique_ptr<MARC::Reader>> marc_readers; for (int arg_no(1); arg_no < (argc - 1) ; ++arg_no) marc_readers.emplace_back(MARC::Reader::Factory(argv[arg_no])); std::unique_ptr<MARC::Writer> marc_writer(MARC::Writer::Factory(argv[argc - 1])); std::unordered_set<std::string> monograph_control_numbers; CollectMonographs(marc_readers, &monograph_control_numbers); marc_readers[0]->rewind(); PatchUpBookComponentParts(marc_readers[0].get(), marc_writer.get(), &monograph_control_numbers); return EXIT_SUCCESS; } <commit_msg>Fixed a typo.<commit_after>/** \file fix_article_biblio_levels.cc * \author Dr. Johannes Ruscheinski * * A tool for patching up the bibliographic level of article records. * Many, possibly all, article records that we get have an 'a' in leader position 7 instead of a 'b'. * If the referenced parent is not a monograph this tool changes the 'a' to a 'b'. */ /* Copyright (C) 2015-2018, Library of the University of Tübingen 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 <unordered_set> #include <vector> #include <cstdlib> #include "MARC.h" #include "RegexMatcher.h" #include "StringUtil.h" #include "util.h" namespace { [[noreturn]] void Usage() { std::cerr << "Usage: " << ::progname << " marc_input1 [marc_input2 ... marc_inputN] marc_output\n" << " Collects information about which superior/collective works are serials from the various\n" << " MARC inputs and then patches up records in \"marc_input1\" which have been marked as a book\n" << " component and changes them to be flagged as an article instead. The patched up version is\n" << " written to \"marc_output\".\n"; std::exit(EXIT_FAILURE); } void CollectMonographs(const std::vector<std::unique_ptr<MARC::Reader>> &marc_readers, std::unordered_set<std::string> * const monograph_control_numbers) { for (auto &marc_reader : marc_readers) { LOG_INFO("Extracting serial control numbers from \"" + marc_reader->getPath() + "\"."); while (const auto record = marc_reader->read()) { if (record.isMonograph()) monograph_control_numbers->insert(record.getControlNumber()); } } LOG_INFO("Found " + std::to_string(monograph_control_numbers->size()) + " serial records."); } bool HasMonographParent(const std::string &subfield, const MARC::Record &record, std::unordered_set<std::string> * const monograph_control_numbers) { const std::string tag(subfield.substr(0, 3)); const char subfield_code(subfield[3]); const auto field(record.findTag(tag)); if (field == record.end()) return false; const std::string &subfield_contents(field->getSubfields().getFirstSubfieldWithCode(subfield_code)); if (subfield_contents.empty()) return false; static RegexMatcher * const matcher(RegexMatcher::RegexMatcherFactory("\\(.+\\)(\\d{8}[\\dX])")); if (not matcher->matched(subfield_contents)) return false; const std::string parent_id((*matcher)[1]); return monograph_control_numbers->find(parent_id) != monograph_control_numbers->cend(); } bool HasAtLeastOneMonographParent(const std::string &subfield_list, const MARC::Record &record, std::unordered_set<std::string> * const monograph_control_numbers) { std::vector<std::string> subfields; StringUtil::Split(subfield_list, ':', &subfields); for (const auto &subfield : subfields) { if (HasMonographParent(subfield, record, monograph_control_numbers)) return true; } return false; } // Iterates over all records in a collection and retags all book component parts as articles // unless the object has a monograph as a parent. // Changes the bibliographic level of a record from 'a' to 'b' (= serial component part) if the parent is not a // monograph. Also writes all records to "output_ptr". void PatchUpBookComponentParts(MARC::Reader * const marc_reader, MARC::Writer * const marc_writer, std::unordered_set<std::string> * const monograph_control_numbers) { unsigned patch_count(0); while (auto record = marc_reader->read()) { if (record.isArticle() and not HasAtLeastOneMonographParent("800w:810w:830w:773w", record, monograph_control_numbers)) { record.setBibliographicLevel('b'); ++patch_count; } marc_writer->write(record); } LOG_INFO("Fixed the bibliographic level of " + std::to_string(patch_count) + " article records."); } } // unnamed namespace int Main(int argc, char **argv) { if (argc < 3) Usage(); std::vector<std::unique_ptr<MARC::Reader>> marc_readers; for (int arg_no(1); arg_no < (argc - 1) ; ++arg_no) marc_readers.emplace_back(MARC::Reader::Factory(argv[arg_no])); std::unique_ptr<MARC::Writer> marc_writer(MARC::Writer::Factory(argv[argc - 1])); std::unordered_set<std::string> monograph_control_numbers; CollectMonographs(marc_readers, &monograph_control_numbers); marc_readers[0]->rewind(); PatchUpBookComponentParts(marc_readers[0].get(), marc_writer.get(), &monograph_control_numbers); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #include "gtest/gtest.h" #include <memory> #include <vector> #include "arrow/buffer.h" #include "arrow/csv/writer.h" #include "arrow/io/memory.h" #include "arrow/record_batch.h" #include "arrow/result_internal.h" #include "arrow/testing/gtest_util.h" #include "arrow/type.h" #include "arrow/type_fwd.h" namespace arrow { namespace csv { struct TestParams { std::shared_ptr<RecordBatch> record_batch; WriteOptions options; std::string expected_output; }; WriteOptions DefaultTestOptions(bool include_header) { WriteOptions options; options.batch_size = 5; options.include_header = include_header; return options; } std::vector<TestParams> GenerateTestCases() { auto abc_schema = schema({ {field("a", uint64())}, {field("b\"", utf8())}, {field("c ", int32())}, }); auto empty_batch = RecordBatch::Make(abc_schema, /*num_rows=*/0, { ArrayFromJSON(abc_schema->field(0)->type(), "[]"), ArrayFromJSON(abc_schema->field(1)->type(), "[]"), ArrayFromJSON(abc_schema->field(2)->type(), "[]"), }); auto populated_batch = RecordBatchFromJSON(abc_schema, R"([{"a": 1, "c ": -1}, { "a": 1, "b\"": "abc\"efg", "c ": 2324}, { "b\"": "abcd", "c ": 5467}, { }, { "a": 546, "b\"": "", "c ": 517 }, { "a": 124, "b\"": "a\"\"b\"" }])"); std::string expected_without_header = std::string("1,,-1") + "\n" + // line 1 +R"(1,"abc""efg",2324)" + "\n" + // line 2 R"(,"abcd",5467)" + "\n" + // line 3 R"(,,)" + "\n" + // line 4 R"(546,"",517)" + "\n" + // line 5 R"(124,"a""""b""",)" + "\n"; // line 6 std::string expected_header = std::string(R"("a","b""","c ")") + "\n"; return std::vector<TestParams>{ {empty_batch, DefaultTestOptions(/*header=*/false), ""}, {empty_batch, DefaultTestOptions(/*header=*/true), expected_header}, {populated_batch, DefaultTestOptions(/*header=*/false), expected_without_header}, {populated_batch, DefaultTestOptions(/*header=*/true), expected_header + expected_without_header}}; } class TestWriteCSV : public ::testing::TestWithParam<TestParams> { protected: template <typename Data> Result<std::string> ToCsvString(const Data& data, const WriteOptions& options) { std::shared_ptr<io::BufferOutputStream> out; ASSIGN_OR_RAISE(out, io::BufferOutputStream::Create()); RETURN_NOT_OK(WriteCSV(data, options, default_memory_pool(), out.get())); ASSIGN_OR_RAISE(std::shared_ptr<Buffer> buffer, out->Finish()); return std::string(reinterpret_cast<const char*>(buffer->data()), buffer->size()); } }; TEST_P(TestWriteCSV, TestWrite) { ASSERT_OK_AND_ASSIGN(std::shared_ptr<io::BufferOutputStream> out, io::BufferOutputStream::Create()); WriteOptions options = GetParam().options; std::string csv; ASSERT_OK_AND_ASSIGN(csv, ToCsvString(*GetParam().record_batch, options)); EXPECT_EQ(csv, GetParam().expected_output); // Batch size shouldn't matter. options.batch_size /= 2; ASSERT_OK_AND_ASSIGN(csv, ToCsvString(*GetParam().record_batch, options)); EXPECT_EQ(csv, GetParam().expected_output); // Table and Record batch should work identically. ASSERT_OK_AND_ASSIGN(std::shared_ptr<Table> table, Table::FromRecordBatches({GetParam().record_batch})); ASSERT_OK_AND_ASSIGN(csv, ToCsvString(*table, options)); EXPECT_EQ(csv, GetParam().expected_output); } INSTANTIATE_TEST_SUITE_P(MultiColumnWriteCSVTest, TestWriteCSV, ::testing::ValuesIn(GenerateTestCases())); INSTANTIATE_TEST_SUITE_P( SingleColumnWriteCSVTest, TestWriteCSV, ::testing::Values(TestParams{ RecordBatchFromJSON(schema({field("int64", int64())}), R"([{ "int64": 9999}, {}, { "int64": -15}])"), WriteOptions(), R"("int64")" "\n9999\n\n-15\n"})); } // namespace csv } // namespace arrow <commit_msg>ARROW-11904: [C++] Try to fix crash on test tear down<commit_after>// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #include "gtest/gtest.h" #include <memory> #include <vector> #include "arrow/buffer.h" #include "arrow/csv/writer.h" #include "arrow/io/memory.h" #include "arrow/record_batch.h" #include "arrow/result_internal.h" #include "arrow/testing/gtest_util.h" #include "arrow/type.h" #include "arrow/type_fwd.h" namespace arrow { namespace csv { struct TestParams { std::shared_ptr<Schema> schema; std::string batch_data; WriteOptions options; std::string expected_output; }; WriteOptions DefaultTestOptions(bool include_header) { WriteOptions options; options.batch_size = 5; options.include_header = include_header; return options; } std::vector<TestParams> GenerateTestCases() { auto abc_schema = schema({ {field("a", uint64())}, {field("b\"", utf8())}, {field("c ", int32())}, }); auto populated_batch = R"([{"a": 1, "c ": -1}, { "a": 1, "b\"": "abc\"efg", "c ": 2324}, { "b\"": "abcd", "c ": 5467}, { }, { "a": 546, "b\"": "", "c ": 517 }, { "a": 124, "b\"": "a\"\"b\"" }])"; std::string expected_without_header = std::string("1,,-1") + "\n" + // line 1 +R"(1,"abc""efg",2324)" + "\n" + // line 2 R"(,"abcd",5467)" + "\n" + // line 3 R"(,,)" + "\n" + // line 4 R"(546,"",517)" + "\n" + // line 5 R"(124,"a""""b""",)" + "\n"; // line 6 std::string expected_header = std::string(R"("a","b""","c ")") + "\n"; return std::vector<TestParams>{ {abc_schema, "[]", DefaultTestOptions(/*header=*/false), ""}, {abc_schema, "[]", DefaultTestOptions(/*header=*/true), expected_header}, {abc_schema, populated_batch, DefaultTestOptions(/*header=*/false), expected_without_header}, {abc_schema, populated_batch, DefaultTestOptions(/*header=*/true), expected_header + expected_without_header}}; } class TestWriteCSV : public ::testing::TestWithParam<TestParams> { protected: template <typename Data> Result<std::string> ToCsvString(const Data& data, const WriteOptions& options) { std::shared_ptr<io::BufferOutputStream> out; ASSIGN_OR_RAISE(out, io::BufferOutputStream::Create()); RETURN_NOT_OK(WriteCSV(data, options, default_memory_pool(), out.get())); ASSIGN_OR_RAISE(std::shared_ptr<Buffer> buffer, out->Finish()); return std::string(reinterpret_cast<const char*>(buffer->data()), buffer->size()); } }; TEST_P(TestWriteCSV, TestWrite) { ASSERT_OK_AND_ASSIGN(std::shared_ptr<io::BufferOutputStream> out, io::BufferOutputStream::Create()); WriteOptions options = GetParam().options; std::string csv; auto record_batch = RecordBatchFromJSON(GetParam().schema, GetParam().batch_data); ASSERT_OK_AND_ASSIGN(csv, ToCsvString(*record_batch, options)); EXPECT_EQ(csv, GetParam().expected_output); // Batch size shouldn't matter. options.batch_size /= 2; ASSERT_OK_AND_ASSIGN(csv, ToCsvString(*record_batch, options)); EXPECT_EQ(csv, GetParam().expected_output); // Table and Record batch should work identically. ASSERT_OK_AND_ASSIGN(std::shared_ptr<Table> table, Table::FromRecordBatches({record_batch})); ASSERT_OK_AND_ASSIGN(csv, ToCsvString(*table, options)); EXPECT_EQ(csv, GetParam().expected_output); } INSTANTIATE_TEST_SUITE_P(MultiColumnWriteCSVTest, TestWriteCSV, ::testing::ValuesIn(GenerateTestCases())); INSTANTIATE_TEST_SUITE_P(SingleColumnWriteCSVTest, TestWriteCSV, ::testing::Values(TestParams{ schema({field("int64", int64())}), R"([{ "int64": 9999}, {}, { "int64": -15}])", WriteOptions(), R"("int64")" "\n9999\n\n-15\n"})); } // namespace csv } // namespace arrow <|endoftext|>
<commit_before>// The MIT License (MIT) // // Copyright (c) 2016 Northeastern University // // 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 <stdio.h> #include <iostream> #include <memory> #include "Eigen/Dense" #include "gtest/gtest.h" #include "include/cpu_operations.h" #include "include/kdac.h" #include "include/util.h" #include "include/matrix.h" #include "include/vector.h" #include "include/kernel_types.h" template<typename T> class KDACTest : public ::testing::Test { protected: // Nice::Matrix<T> data_matrix_; std::shared_ptr<Nice::KDAC<T>> kdac_; int c_; std::string base_dir_; virtual void SetUp() { // data_matrix_ = Nice::util::FromFile<T>( // "../test/data_for_test/kdac/data_400.csv", ","); // c_ = 2; kdac_ = std::make_shared<Nice::KDAC<T>>(); kdac_->SetC(c_); base_dir_ = "../test/data_for_test/kdac"; } Nice::Matrix<T> ReadTestData( std::string matrix_name, std::string func_name, std::string test_data_type) { // test_data_type is either "ref" or "input" std::string dir = base_dir_ + "/" + func_name; std::string file_name = matrix_name + "_" + test_data_type + ".txt"; std::string file_path = dir + "/" + file_name; return Nice::util::FromFile<T>(file_path); } }; typedef ::testing::Types<float, int, long, double> AllTypes; typedef ::testing::Types<int, long> IntTypes; typedef ::testing::Types<float> FloatTypes; typedef ::testing::Types<float, double> BothTypes; TYPED_TEST_CASE(KDACTest, FloatTypes); #define EXPECT_MATRIX_EQ(a, ref)\ EXPECT_EQ(a.rows(), ref.rows());\ EXPECT_EQ(a.cols(), ref.cols());\ for (int i = 0; i < a.rows(); i++)\ for (int j = 0; j < a.cols(); j++)\ EXPECT_NEAR(double(a(i, j)), double(ref(i, j)), 0.0001);\ #define PRINTV(v, num_per_line)\ for (int i = 0; i < v.rows(); i++) {\ if (i % num_per_line == 0 && i != 0)\ std::cout << std::endl;\ std::cout << v(i) << ",";\ }\ std::cout << std::endl;\ #define EXPECT_MATRIX_ABS_EQ(a, ref, error)\ EXPECT_EQ(a.rows(), ref.rows());\ EXPECT_EQ(a.cols(), ref.cols());\ for (int i = 0; i < a.rows(); i++)\ for (int j = 0; j < a.cols(); j++)\ EXPECT_NEAR(std::abs(a(i, j)), std::abs(ref(i, j)), error);\ TYPED_TEST(KDACTest, PredGaussian) { int num_clusters = 3; int num_samples_per_cluster = 50; int num_samples = num_clusters * num_samples_per_cluster; int dim = 6; this->kdac_->SetQ(num_clusters); this->kdac_->SetC(num_clusters); std::string root_dir("../test/data_for_test/kdac/"); std::string file_name = "data_gaussian_" + std::to_string(num_samples) + "_" + std::to_string(dim) + "_" + std::to_string(num_clusters) + ".csv"; // Nice::Matrix<TypeParam> data_matrix = Nice::util::FromFile<TypeParam>( // "../test/data_for_test/kdac/data_gaussian_150_6_3.csv", ","); Nice::Matrix<TypeParam> data_matrix = Nice::util::FromFile<TypeParam>( root_dir + file_name, ","); Nice::Matrix<TypeParam> first_y = Nice::Matrix<TypeParam>::Zero(data_matrix.rows(), this->kdac_->GetC()); for (int center = 0; center < num_clusters; center++) { for (int sample = 0; sample < num_samples_per_cluster; sample ++) { first_y(center * num_samples_per_cluster + sample, center) = static_cast<TypeParam>(1); } } // for (int i = 0; i < 40; i++) // first_y(i, 0) = static_cast<TypeParam>(1); // for (int i = 40; i < 80; i++) // first_y(i, 1) = static_cast<TypeParam>(1); // for (int i = 80; i < 120; i++) // first_y(i, 2) = static_cast<TypeParam>(1); // this->kdac_->Print(first_y, "y_after"); // for (float sigma = 1; sigma < 20; sigma++) { this->kdac_->SetKernel(Nice::kGaussianKernel, 1.0); this->kdac_->Fit(data_matrix, first_y); PRINTV(this->kdac_->Predict(), num_samples_per_cluster); // } // // this->kdac_->Fit(data_matrix); // PRINTV(this->kdac_->Predict(), 40); // Nice::Matrix<TypeParam> // // Nice::Matrix<TypeParam> first_y = this->kdac_->GetY(); // this->kdac_->SetLambda(1.0); // this->kdac_->Fit(data_matrix, first_y); // PRINTV(this->kdac_->Predict(), 40); // // this->kdac_->SetLambda(2.0); // this->kdac_->Fit(data_matrix, first_y); // PRINTV(this->kdac_->Predict()); // // this->kdac_->SetLambda(3.0); // this->kdac_->Fit(data_matrix, first_y); // PRINTV(this->kdac_->Predict()); } TYPED_TEST(KDACTest, WlRef) { Nice::Matrix<TypeParam> w_matrix(3,3); for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) w_matrix(i, j) = i * 3 + j; std::cout << w_matrix << std::endl; Nice::Vector<TypeParam> w_l = w_matrix.col(0); w_l(0) = 88; std::cout << w_l << std::endl; std::cout << w_matrix << std::endl; } //TYPED_TEST(KDACTest, FitUMatrix) { // this->kdac_->Fit(this->data_matrix_); // Nice::Matrix<TypeParam> u_matrix = this->kdac_->GetU(); // Nice::Matrix<TypeParam> u_matrix_ref = // this->ReadTestData("u_matrix", "Fit", "ref"); // EXPECT_MATRIX_ABS_EQ(u_matrix, u_matrix_ref, 0.01); // //// std::cout << u_matrix.block(0, 0, 5, 2) << std::endl << std::endl; //// std::cout << u_matrix_ref.block(0, 0, 5, 2) << std::endl << std::endl; //} // //TYPED_TEST(KDACTest, FitLMatrix) { // this->kdac_->Fit(this->data_matrix_); // Nice::Matrix<TypeParam> l_matrix = this->kdac_->GetL(); // Nice::Matrix<TypeParam> l_matrix_ref = // this->ReadTestData("l_matrix", "Fit", "ref"); // EXPECT_MATRIX_EQ(l_matrix, l_matrix_ref); //} // //TYPED_TEST(KDACTest, FitKMatrix) { // this->kdac_->Fit(this->data_matrix_); // Nice::Matrix<TypeParam> k_matrix = this->kdac_->GetK(); // Nice::Matrix<TypeParam> k_matrix_ref = // this->ReadTestData("kernel_matrix", "Fit", "ref"); // EXPECT_MATRIX_EQ(k_matrix, k_matrix_ref); //// std::cout << k_matrix.block(0, 0, 5, 2) //// << std::endl << std::endl; //// std::cout << k_matrix_ref.block(0, 0, 5, 2) //// << std::endl << std::endl; //} // //TYPED_TEST(KDACTest, FitDMatrix) { // this->kdac_->Fit(this->data_matrix_); // Nice::Matrix<TypeParam> d_matrix = // this->kdac_->GetDToTheMinusHalf(); // Nice::Matrix<TypeParam> d_matrix_ref = // this->ReadTestData("d_matrix", "Fit", "ref"); // EXPECT_MATRIX_EQ(d_matrix, d_matrix_ref); //} // //TYPED_TEST(KDACTest, FitAMatrixList) { // this->kdac_->Fit(this->data_matrix_); // int n = this->data_matrix_.rows(); // std::vector<Nice::Matrix<TypeParam>> a_matrix_list = this->kdac_->GetAList(); // Nice::Matrix<TypeParam> a_matrix = a_matrix_list[2 * n + 3]; // Nice::Matrix<TypeParam> a_matrix_ref = // this->ReadTestData("a_matrix", "Fit", "ref"); // EXPECT_MATRIX_EQ(a_matrix, a_matrix_ref); //// std::cout << a_matrix_list[10] << std::endl << std::endl; //// for (int i = 0; i < n; i++) //// for (int j = 0; j < n; j++) //// std::cout << a_matrix_list[i * n + j] << std::endl << std::endl; //} //TYPED_TEST(KDACTest, FitWMatrix) { // this->kdac_->Fit(this->data_matrix_); // this->kdac_->Fit(); // Nice::Matrix<TypeParam> w_matrix = // this->kdac_->GetW(); // Nice::Matrix<TypeParam> w_matrix_ref = // this->ReadTestData("w_matrix", "Fit", "ref"); // EXPECT_MATRIX_EQ(w_matrix, w_matrix_ref); //} //TYPED_TEST(KDACTest, FitYMatrixTilde) { // this->kdac_->Fit(this->data_matrix_); // Nice::Matrix<TypeParam> y_matrix_tilde = this->kdac_->GetYTilde(); // Nice::Matrix<TypeParam> y_matrix_tilde_ref = // this->ReadTestData("y_matrix_tilde", "Fit", "ref"); // EXPECT_MATRIX_EQ(y_matrix_tilde, y_matrix_tilde_ref); //} // //TYPED_TEST(KDACTest, FitGammaMatrix) { // this->kdac_->Fit(this->data_matrix_); // Nice::Matrix<TypeParam> gamma_matrix = this->kdac_->GetGamma(); // Nice::Matrix<TypeParam> gamma_matrix_ref = // this->ReadTestData("gamma_matrix", "Fit", "ref"); //// std::cout << gamma_matrix << std::endl; // EXPECT_MATRIX_EQ(gamma_matrix.col(0), gamma_matrix_ref.col(0)); //} //TEST(KDACTest, ReferTest) { // Nice::Matrix<float> a(2,2); // a << 1,2, // 3,4; // std::cout << a << std::endl; // Nice::Matrix<float> &a_ref = a; // a_ref(0,0) = 88; // std::cout << a << std::endl; // Nice::Matrix<float> &b = a_ref; // b(0,0) = 99; // std::cout << a << std::endl; // std::cout << b << std::endl; //} //TYPED_TEST(KDACTest, Ortho) { // Nice::Matrix<TypeParam> m(3, 2); // m << 1.0,0.0, // 0.0,-1.0, // 0.0,0.0; // Nice::Vector<TypeParam> c(3); // c << 3,2,3; // Nice::Vector<TypeParam> vertical = this->kdac_->GenOrthogonal(m, c); // std::cout << vertical << std::endl; //}<commit_msg>Set verbose in kdac test<commit_after>// The MIT License (MIT) // // Copyright (c) 2016 Northeastern University // // 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 <stdio.h> #include <iostream> #include <memory> #include "Eigen/Dense" #include "gtest/gtest.h" #include "include/cpu_operations.h" #include "include/kdac.h" #include "include/util.h" #include "include/matrix.h" #include "include/vector.h" #include "include/kernel_types.h" template<typename T> class KDACTest : public ::testing::Test { protected: // Nice::Matrix<T> data_matrix_; std::shared_ptr<Nice::KDAC<T>> kdac_; int c_; std::string base_dir_; virtual void SetUp() { // data_matrix_ = Nice::util::FromFile<T>( // "../test/data_for_test/kdac/data_400.csv", ","); // c_ = 2; kdac_ = std::make_shared<Nice::KDAC<T>>(); kdac_->SetC(c_); base_dir_ = "../test/data_for_test/kdac"; } Nice::Matrix<T> ReadTestData( std::string matrix_name, std::string func_name, std::string test_data_type) { // test_data_type is either "ref" or "input" std::string dir = base_dir_ + "/" + func_name; std::string file_name = matrix_name + "_" + test_data_type + ".txt"; std::string file_path = dir + "/" + file_name; return Nice::util::FromFile<T>(file_path); } }; typedef ::testing::Types<float, int, long, double> AllTypes; typedef ::testing::Types<int, long> IntTypes; typedef ::testing::Types<float> FloatTypes; typedef ::testing::Types<float, double> BothTypes; TYPED_TEST_CASE(KDACTest, FloatTypes); #define EXPECT_MATRIX_EQ(a, ref)\ EXPECT_EQ(a.rows(), ref.rows());\ EXPECT_EQ(a.cols(), ref.cols());\ for (int i = 0; i < a.rows(); i++)\ for (int j = 0; j < a.cols(); j++)\ EXPECT_NEAR(double(a(i, j)), double(ref(i, j)), 0.0001);\ #define PRINTV(v, num_per_line)\ for (int i = 0; i < v.rows(); i++) {\ if (i % num_per_line == 0 && i != 0)\ std::cout << std::endl;\ std::cout << v(i) << ",";\ }\ std::cout << std::endl;\ #define EXPECT_MATRIX_ABS_EQ(a, ref, error)\ EXPECT_EQ(a.rows(), ref.rows());\ EXPECT_EQ(a.cols(), ref.cols());\ for (int i = 0; i < a.rows(); i++)\ for (int j = 0; j < a.cols(); j++)\ EXPECT_NEAR(std::abs(a(i, j)), std::abs(ref(i, j)), error);\ TYPED_TEST(KDACTest, PredGaussian) { int num_clusters = 3; int num_samples_per_cluster = 10; int num_samples = num_clusters * num_samples_per_cluster; int dim = 6; this->kdac_ ->SetQ(num_clusters); this->kdac_ ->SetC(num_clusters); this->kdac_ ->SetVerbose(true); std::string root_dir("../test/data_for_test/kdac/"); std::string file_name = "data_gaussian_" + std::to_string(num_samples) + "_" + std::to_string(dim) + "_" + std::to_string(num_clusters) + ".csv"; // Nice::Matrix<TypeParam> data_matrix = Nice::util::FromFile<TypeParam>( // "../test/data_for_test/kdac/data_gaussian_150_6_3.csv", ","); Nice::Matrix<TypeParam> data_matrix = Nice::util::FromFile<TypeParam>( root_dir + file_name, ","); Nice::Matrix<TypeParam> first_y = Nice::Matrix<TypeParam>::Zero(data_matrix.rows(), this->kdac_->GetC()); for (int center = 0; center < num_clusters; center++) { for (int sample = 0; sample < num_samples_per_cluster; sample ++) { first_y(center * num_samples_per_cluster + sample, center) = static_cast<TypeParam>(1); } } this->kdac_->SetKernel(Nice::kGaussianKernel, 1.0); this->kdac_->Fit(data_matrix, first_y); PRINTV(this->kdac_->Predict(), num_samples_per_cluster); } TYPED_TEST(KDACTest, WlRef) { Nice::Matrix<TypeParam> w_matrix(3,3); for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) w_matrix(i, j) = i * 3 + j; std::cout << w_matrix << std::endl; Nice::Vector<TypeParam> w_l = w_matrix.col(0); w_l(0) = 88; std::cout << w_l << std::endl; std::cout << w_matrix << std::endl; } //TYPED_TEST(KDACTest, FitUMatrix) { // this->kdac_->Fit(this->data_matrix_); // Nice::Matrix<TypeParam> u_matrix = this->kdac_->GetU(); // Nice::Matrix<TypeParam> u_matrix_ref = // this->ReadTestData("u_matrix", "Fit", "ref"); // EXPECT_MATRIX_ABS_EQ(u_matrix, u_matrix_ref, 0.01); // //// std::cout << u_matrix.block(0, 0, 5, 2) << std::endl << std::endl; //// std::cout << u_matrix_ref.block(0, 0, 5, 2) << std::endl << std::endl; //} // //TYPED_TEST(KDACTest, FitLMatrix) { // this->kdac_->Fit(this->data_matrix_); // Nice::Matrix<TypeParam> l_matrix = this->kdac_->GetL(); // Nice::Matrix<TypeParam> l_matrix_ref = // this->ReadTestData("l_matrix", "Fit", "ref"); // EXPECT_MATRIX_EQ(l_matrix, l_matrix_ref); //} // //TYPED_TEST(KDACTest, FitKMatrix) { // this->kdac_->Fit(this->data_matrix_); // Nice::Matrix<TypeParam> k_matrix = this->kdac_->GetK(); // Nice::Matrix<TypeParam> k_matrix_ref = // this->ReadTestData("kernel_matrix", "Fit", "ref"); // EXPECT_MATRIX_EQ(k_matrix, k_matrix_ref); //// std::cout << k_matrix.block(0, 0, 5, 2) //// << std::endl << std::endl; //// std::cout << k_matrix_ref.block(0, 0, 5, 2) //// << std::endl << std::endl; //} // //TYPED_TEST(KDACTest, FitDMatrix) { // this->kdac_->Fit(this->data_matrix_); // Nice::Matrix<TypeParam> d_matrix = // this->kdac_->GetDToTheMinusHalf(); // Nice::Matrix<TypeParam> d_matrix_ref = // this->ReadTestData("d_matrix", "Fit", "ref"); // EXPECT_MATRIX_EQ(d_matrix, d_matrix_ref); //} // //TYPED_TEST(KDACTest, FitAMatrixList) { // this->kdac_->Fit(this->data_matrix_); // int n = this->data_matrix_.rows(); // std::vector<Nice::Matrix<TypeParam>> a_matrix_list = this->kdac_->GetAList(); // Nice::Matrix<TypeParam> a_matrix = a_matrix_list[2 * n + 3]; // Nice::Matrix<TypeParam> a_matrix_ref = // this->ReadTestData("a_matrix", "Fit", "ref"); // EXPECT_MATRIX_EQ(a_matrix, a_matrix_ref); //// std::cout << a_matrix_list[10] << std::endl << std::endl; //// for (int i = 0; i < n; i++) //// for (int j = 0; j < n; j++) //// std::cout << a_matrix_list[i * n + j] << std::endl << std::endl; //} //TYPED_TEST(KDACTest, FitWMatrix) { // this->kdac_->Fit(this->data_matrix_); // this->kdac_->Fit(); // Nice::Matrix<TypeParam> w_matrix = // this->kdac_->GetW(); // Nice::Matrix<TypeParam> w_matrix_ref = // this->ReadTestData("w_matrix", "Fit", "ref"); // EXPECT_MATRIX_EQ(w_matrix, w_matrix_ref); //} //TYPED_TEST(KDACTest, FitYMatrixTilde) { // this->kdac_->Fit(this->data_matrix_); // Nice::Matrix<TypeParam> y_matrix_tilde = this->kdac_->GetYTilde(); // Nice::Matrix<TypeParam> y_matrix_tilde_ref = // this->ReadTestData("y_matrix_tilde", "Fit", "ref"); // EXPECT_MATRIX_EQ(y_matrix_tilde, y_matrix_tilde_ref); //} // //TYPED_TEST(KDACTest, FitGammaMatrix) { // this->kdac_->Fit(this->data_matrix_); // Nice::Matrix<TypeParam> gamma_matrix = this->kdac_->GetGamma(); // Nice::Matrix<TypeParam> gamma_matrix_ref = // this->ReadTestData("gamma_matrix", "Fit", "ref"); //// std::cout << gamma_matrix << std::endl; // EXPECT_MATRIX_EQ(gamma_matrix.col(0), gamma_matrix_ref.col(0)); //} //TEST(KDACTest, ReferTest) { // Nice::Matrix<float> a(2,2); // a << 1,2, // 3,4; // std::cout << a << std::endl; // Nice::Matrix<float> &a_ref = a; // a_ref(0,0) = 88; // std::cout << a << std::endl; // Nice::Matrix<float> &b = a_ref; // b(0,0) = 99; // std::cout << a << std::endl; // std::cout << b << std::endl; //} //TYPED_TEST(KDACTest, Ortho) { // Nice::Matrix<TypeParam> m(3, 2); // m << 1.0,0.0, // 0.0,-1.0, // 0.0,0.0; // Nice::Vector<TypeParam> c(3); // c << 3,2,3; // Nice::Vector<TypeParam> vertical = this->kdac_->GenOrthogonal(m, c); // std::cout << vertical << std::endl; //}<|endoftext|>
<commit_before>#ifndef GAMEOBJECT_HPP #define GAMEOBJECT_HPP #include "tools.hpp" class Game; class ContainerObject; class GameObject { //scenegraph nodes public: GameObject(); virtual ~GameObject(); virtual void update(float deltaTime); virtual void draw() const ; void addTo(GameObject* parent); void removeAndDelete(); void setName(std::string newName); std::string getName() const; int getDrawPriority() const; int getUpdatePriority() const; void setDrawPriority(int newPriority); void setUpdatePriority(int newPriority); template<class T> void getAllObjectsOfType(std::vector<T*> &v) { T* p = dynamic_cast<T*>(this); if(p) v.push_back(p); for(std::list<GameObject*>::const_iterator it = children.begin(); it != children.end(); ++it) (*it)->getAllObjectsOfType<T>(v); } template<class T> T* getFirstObjectOfType() const { const T* p = dynamic_cast<const T*>(this); if(p) return p; for(std::list<GameObject*>::const_iterator it = children.begin(); it != children.end(); ++it) { p = (*it)->getFirstObjectOfType<T>(); if(p) return p; } return nullptr; } const std::list<GameObject*>& getChildren() const; const int id; protected: Game* getGame() const; const GameObject* getParent() const; virtual void onObjectAdd(GameObject* object); //Model matrix mat4f transform; mutable mat4f fullTransform; private: void removeFromParent(); void propragateTransforms() const; void markForDelete(); virtual void addToContainer(GameObject* obj); virtual void removeFromContainer(GameObject* obj); GameObject* parent; std::list<GameObject*> children; int drawPriority; int updatePriority; std::string name; ContainerObject* container; bool isAlive; friend class ContainerObject; }; #endif // GAMEOBJECT_HPP <commit_msg>Yeah, const :/<commit_after>#ifndef GAMEOBJECT_HPP #define GAMEOBJECT_HPP #include "tools.hpp" class Game; class ContainerObject; class GameObject { //scenegraph nodes public: GameObject(); virtual ~GameObject(); virtual void update(float deltaTime); virtual void draw() const ; void addTo(GameObject* parent); void removeAndDelete(); void setName(std::string newName); std::string getName() const; int getDrawPriority() const; int getUpdatePriority() const; void setDrawPriority(int newPriority); void setUpdatePriority(int newPriority); template<class T> void getAllObjectsOfType(std::vector<T*> &v) const { T* p = const_cast<T*>(dynamic_cast<const T*>(this)); if(p) v.push_back(p); for(std::list<GameObject*>::const_iterator it = children.begin(); it != children.end(); ++it) (*it)->getAllObjectsOfType<T>(v); } template<class T> T* getFirstObjectOfType() const { T* p = const_cast<T*>(dynamic_cast<const T*>(this)); if(p) return p; for(std::list<GameObject*>::const_iterator it = children.begin(); it != children.end(); ++it) { p = (*it)->getFirstObjectOfType<T>(); if(p) return p; } return nullptr; } const std::list<GameObject*>& getChildren() const; const int id; protected: Game* getGame() const; const GameObject* getParent() const; virtual void onObjectAdd(GameObject* object); //Model matrix mat4f transform; mutable mat4f fullTransform; private: void removeFromParent(); void propragateTransforms() const; void markForDelete(); virtual void addToContainer(GameObject* obj); virtual void removeFromContainer(GameObject* obj); GameObject* parent; std::list<GameObject*> children; int drawPriority; int updatePriority; std::string name; ContainerObject* container; bool isAlive; friend class ContainerObject; }; #endif // GAMEOBJECT_HPP <|endoftext|>
<commit_before>/* ** Copyright 2012 Merethis ** ** This file is part of Centreon Clib. ** ** Centreon Clib 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. ** ** Centreon Clib 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 Centreon Clib. If not, see ** <http://www.gnu.org/licenses/>. */ #include <cassert> #include <cerrno> #include <cstdlib> #include <cstring> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include "com/centreon/concurrency/locker.hh" #include "com/centreon/exceptions/basic.hh" #include "com/centreon/logging/logger.hh" #include "com/centreon/process.hh" #include "com/centreon/process_listener.hh" #include "com/centreon/process_manager_posix.hh" using namespace com::centreon; // Default varibale. static int const DEFAULT_TIMEOUT = 200; // Class instance. static process_manager* _instance = NULL; /************************************** * * * Public Methods * * * **************************************/ /** * Add process to the process manager. * * @param[in] p The process to manage. * @param[in] obj The object to notify. */ void process_manager::add(process* p) { // Check viability pointer. if (!p) throw (basic_error() << "invalid process: null pointer"); concurrency::locker lock_process(&p->_lock_process); // Check if the process need to be manage. if (p->_process == static_cast<pid_t>(-1)) throw (basic_error() << "invalid process: not running"); concurrency::locker lock(&_lock_processes); // Add pid process to use waitpid. _processes_pid[p->_process] = p; // Monitor err/out output if necessary. if (p->_enable_stream[process::out]) _processes_fd[p->_stream[process::out]] = p; if (p->_enable_stream[process::err]) _processes_fd[p->_stream[process::err]] = p; // Add timeout to kill process if necessary. if (p->_timeout) _processes_timeout.insert(std::make_pair(p->_timeout, p)); // Need to update file descriptor list. _update = true; return; } /** * Get instance of the process manager. * * @return the process manager. */ process_manager& process_manager::instance() { return (*_instance); } /** * Load the process manager. */ void process_manager::load() { delete _instance; _instance = new process_manager(); return; } /** * Unload the process manager. */ void process_manager::unload() { delete _instance; _instance = NULL; return; } /************************************** * * * Private Methods * * * **************************************/ /** * Default constructor. */ process_manager::process_manager() : concurrency::thread(), _fds(new pollfd[64]), _fds_capacity(64), _fds_size(0), _quit(false), _update(false) { // Run process manager thread. exec(); } /** * Copy constructor. * * @param[in] right Object to copy. */ process_manager::process_manager(process_manager const& right) : concurrency::thread() { _internal_copy(right); } /** * Destructor. */ process_manager::~process_manager() throw () { // Exit process manager thread. _quit = true; // Waiting the end of the process manager thread. wait(); // Release memory. delete[] _fds; } /** * Assignment operator. * * @param[in] right Object to copy. * * @return This object. */ process_manager& process_manager::operator=(process_manager const& right) { _internal_copy(right); return (*this); } /** * Close stream. * * @param[in] fd The file descriptor to close. */ void process_manager::_close_stream(int fd) throw () { try { process* p(NULL); // Get process to link with fd and remove this // fd to the process manager. { concurrency::locker lock(&_lock_processes); _update = true; umap<int, process*>::iterator it(_processes_fd.find(fd)); if (it == _processes_fd.end()) { _update = true; throw (basic_error() << "invalid fd: " "not found into processes fd list"); } p = it->second; _processes_fd.erase(it); } // Update process informations. concurrency::locker lock(&p->_lock_process); if (p->_stream[process::out] == fd) p->_close(p->_stream[process::out]); else if (p->_stream[process::err] == fd) p->_close(p->_stream[process::err]); if (!p->_is_running()) { // Release condition variable. p->_cv_buffer_err.wake_one(); p->_cv_buffer_out.wake_one(); p->_cv_process.wake_one(); // Notify listener if necessary. if (p->_listener) { lock.unlock(); (p->_listener->finished)(*p); } } } catch (std::exception const& e) { logging::error(logging::high) << e.what(); } } /** * Remove process from list of processes timeout. * * @param[in] p The process to remove. */ void process_manager::_erase_timeout(process* p) { // Check process viability. if (!p || !p->_timeout) return; umultimap<unsigned int, process*>::iterator it(_processes_timeout.find(p->_timeout)); umultimap<unsigned int, process*>::iterator end(_processes_timeout.end()); // Find and erase process from timeout list. while (it != end && it->first == p->_timeout) { if (it->second == p) { _processes_timeout.erase(it); break; } ++it; } } /** * Copy internal data members. * * @param[in] p Object to copy. */ void process_manager::_internal_copy(process_manager const& right) { (void)right; assert(!"process_manager is not copyable"); abort(); return; } /** * Kill process to reach the timeout. */ void process_manager::_kill_processes_timeout() throw () { // Get the current time. unsigned int now(time(NULL)); umultimap<unsigned int, process*>::iterator it(_processes_timeout.begin()); try { // Kill process who timeout and remove it from timeout list. while (it != _processes_timeout.end() && now >= it->first) { process* p(it->second); p->kill(); p->_is_timeout = true; it = _processes_timeout.erase(it); } } catch (std::exception const& e) { logging::error(logging::high) << e.what(); } } /** * Read stream. * * @param[in] fd The file descriptor to read. */ void process_manager::_read_stream(int fd) throw () { try { process* p(NULL); // Get process to link with fd. { concurrency::locker lock(&_lock_processes); umap<int, process*>::iterator it(_processes_fd.find(fd)); if (it == _processes_fd.end()) { _update = true; throw (basic_error() << "invalid fd: " "not found into processes fd list"); } p = it->second; } concurrency::locker lock(&p->_lock_process); // Read content of the stream and push it. char buffer[4096]; unsigned int size(p->_read(fd, buffer, sizeof(buffer))); if (p->_stream[process::out] == fd) { p->_buffer_out.append(buffer, size); p->_cv_buffer_out.wake_one(); // Notify listener if necessary. if (p->_listener) { lock.unlock(); (p->_listener->data_is_available)(*p); } } else if (p->_stream[process::err] == fd) { p->_buffer_err.append(buffer, size); p->_cv_buffer_err.wake_one(); // Notify listener if necessary. if (p->_listener) { lock.unlock(); (p->_listener->data_is_available_err)(*p); } } } catch (std::exception const& e) { logging::error(logging::high) << e.what(); } } /** * Internal thread to monitor processes. */ void process_manager::_run() { try { while (!_quit) { // Update the file descriptor list. _update_list(); int ret(0); // Sleep if no file descriptor. if (!_fds_size) concurrency::thread::msleep(DEFAULT_TIMEOUT); // Wait event on file descriptor. else if ((ret = poll(_fds, _fds_size, DEFAULT_TIMEOUT)) < 0) { char const* msg(strerror(errno)); throw (basic_error() << "poll failed: " << msg); } for (unsigned int i(0), checked(0); checked < static_cast<unsigned int>(ret) && i < _fds_size; ++i) { // No event. if (!_fds[i].revents) continue; // Data are available. if (_fds[i].revents & (POLLIN | POLLPRI)) _read_stream(_fds[i].fd); // File descriptor was close. else if (_fds[i].revents & POLLHUP) _close_stream(_fds[i].fd); // Error! else if (_fds[i].revents & (POLLERR | POLLNVAL)) { _update = true; logging::error(logging::high) << "invalid fd " << _fds[i].fd << " from process manager"; } ++checked; } // Release finished process. _wait_processes(); // Kill process in timeout. _kill_processes_timeout(); } } catch (std::exception const& e) { logging::error(logging::high) << e.what(); } } /** * Update list of file descriptor to watch. */ void process_manager::_update_list() { concurrency::locker lock(&_lock_processes); // No need update. if (!_update) return; // Resize file descriptor list. if (_processes_fd.size() > _fds_capacity) { delete[] _fds; _fds = new pollfd[_processes_fd.size()]; } // Set file descriptor to wait event. _fds_size = 0; for (umap<int, process*>::const_iterator it(_processes_fd.begin()), end(_processes_fd.end()); it != end; ++it) { _fds[_fds_size].fd = it->first; _fds[_fds_size].events = POLLIN | POLLPRI; _fds[_fds_size].revents = 0; ++_fds_size; } // Disable update. _update = false; } /** * Waiting finished process. */ void process_manager::_wait_processes() throw () { try { while (true) { int status(0); pid_t pid(waitpid(-1, &status, WNOHANG)); // No process are finished. if (!pid) break; // Error! if (pid < 0) { char const* msg(strerror(errno)); throw (basic_error() << "waiting process failed: " << msg); } process* p(NULL); // Get process to link with pid and remove this pid // to the process manager. { concurrency::locker lock(&_lock_processes); umap<pid_t, process*>::iterator it(_processes_pid.find(pid)); if (it == _processes_pid.end()) throw (basic_error() << "waiting process failed: " << pid << " is not register"); p = it->second; _processes_pid.erase(it); } // Update process informations. concurrency::locker lock(&p->_lock_process); p->_end_time = timestamp::now(); p->_status = status; p->_process = static_cast<pid_t>(-1); p->_close(p->_stream[process::in]); _erase_timeout(p); if (!p->_is_running()) { // Release condition variable. p->_cv_buffer_err.wake_one(); p->_cv_buffer_out.wake_one(); p->_cv_process.wake_one(); // Notify listener if necessary. if (p->_listener) { lock.unlock(); (p->_listener->finished)(*p); } } } } catch (std::exception const& e) { logging::error(logging::high) << e.what(); } } <commit_msg>Change function call order (wake/finished) into the process manager.<commit_after>/* ** Copyright 2012 Merethis ** ** This file is part of Centreon Clib. ** ** Centreon Clib 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. ** ** Centreon Clib 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 Centreon Clib. If not, see ** <http://www.gnu.org/licenses/>. */ #include <cassert> #include <cerrno> #include <cstdlib> #include <cstring> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include "com/centreon/concurrency/locker.hh" #include "com/centreon/exceptions/basic.hh" #include "com/centreon/logging/logger.hh" #include "com/centreon/process.hh" #include "com/centreon/process_listener.hh" #include "com/centreon/process_manager_posix.hh" using namespace com::centreon; // Default varibale. static int const DEFAULT_TIMEOUT = 200; // Class instance. static process_manager* _instance = NULL; /************************************** * * * Public Methods * * * **************************************/ /** * Add process to the process manager. * * @param[in] p The process to manage. * @param[in] obj The object to notify. */ void process_manager::add(process* p) { // Check viability pointer. if (!p) throw (basic_error() << "invalid process: null pointer"); concurrency::locker lock_process(&p->_lock_process); // Check if the process need to be manage. if (p->_process == static_cast<pid_t>(-1)) throw (basic_error() << "invalid process: not running"); concurrency::locker lock(&_lock_processes); // Add pid process to use waitpid. _processes_pid[p->_process] = p; // Monitor err/out output if necessary. if (p->_enable_stream[process::out]) _processes_fd[p->_stream[process::out]] = p; if (p->_enable_stream[process::err]) _processes_fd[p->_stream[process::err]] = p; // Add timeout to kill process if necessary. if (p->_timeout) _processes_timeout.insert(std::make_pair(p->_timeout, p)); // Need to update file descriptor list. _update = true; return; } /** * Get instance of the process manager. * * @return the process manager. */ process_manager& process_manager::instance() { return (*_instance); } /** * Load the process manager. */ void process_manager::load() { delete _instance; _instance = new process_manager(); return; } /** * Unload the process manager. */ void process_manager::unload() { delete _instance; _instance = NULL; return; } /************************************** * * * Private Methods * * * **************************************/ /** * Default constructor. */ process_manager::process_manager() : concurrency::thread(), _fds(new pollfd[64]), _fds_capacity(64), _fds_size(0), _quit(false), _update(false) { // Run process manager thread. exec(); } /** * Copy constructor. * * @param[in] right Object to copy. */ process_manager::process_manager(process_manager const& right) : concurrency::thread() { _internal_copy(right); } /** * Destructor. */ process_manager::~process_manager() throw () { // Exit process manager thread. _quit = true; // Waiting the end of the process manager thread. wait(); // Release memory. delete[] _fds; } /** * Assignment operator. * * @param[in] right Object to copy. * * @return This object. */ process_manager& process_manager::operator=(process_manager const& right) { _internal_copy(right); return (*this); } /** * Close stream. * * @param[in] fd The file descriptor to close. */ void process_manager::_close_stream(int fd) throw () { try { process* p(NULL); // Get process to link with fd and remove this // fd to the process manager. { concurrency::locker lock(&_lock_processes); _update = true; umap<int, process*>::iterator it(_processes_fd.find(fd)); if (it == _processes_fd.end()) { _update = true; throw (basic_error() << "invalid fd: " "not found into processes fd list"); } p = it->second; _processes_fd.erase(it); } // Update process informations. concurrency::locker lock(&p->_lock_process); if (p->_stream[process::out] == fd) p->_close(p->_stream[process::out]); else if (p->_stream[process::err] == fd) p->_close(p->_stream[process::err]); if (!p->_is_running()) { // Notify listener if necessary. if (p->_listener) { lock.unlock(); (p->_listener->finished)(*p); lock.relock(); } // Release condition variable. p->_cv_buffer_err.wake_one(); p->_cv_buffer_out.wake_one(); p->_cv_process.wake_one(); } } catch (std::exception const& e) { logging::error(logging::high) << e.what(); } } /** * Remove process from list of processes timeout. * * @param[in] p The process to remove. */ void process_manager::_erase_timeout(process* p) { // Check process viability. if (!p || !p->_timeout) return; umultimap<unsigned int, process*>::iterator it(_processes_timeout.find(p->_timeout)); umultimap<unsigned int, process*>::iterator end(_processes_timeout.end()); // Find and erase process from timeout list. while (it != end && it->first == p->_timeout) { if (it->second == p) { _processes_timeout.erase(it); break; } ++it; } } /** * Copy internal data members. * * @param[in] p Object to copy. */ void process_manager::_internal_copy(process_manager const& right) { (void)right; assert(!"process_manager is not copyable"); abort(); return; } /** * Kill process to reach the timeout. */ void process_manager::_kill_processes_timeout() throw () { // Get the current time. unsigned int now(time(NULL)); umultimap<unsigned int, process*>::iterator it(_processes_timeout.begin()); try { // Kill process who timeout and remove it from timeout list. while (it != _processes_timeout.end() && now >= it->first) { process* p(it->second); p->kill(); p->_is_timeout = true; it = _processes_timeout.erase(it); } } catch (std::exception const& e) { logging::error(logging::high) << e.what(); } } /** * Read stream. * * @param[in] fd The file descriptor to read. */ void process_manager::_read_stream(int fd) throw () { try { process* p(NULL); // Get process to link with fd. { concurrency::locker lock(&_lock_processes); umap<int, process*>::iterator it(_processes_fd.find(fd)); if (it == _processes_fd.end()) { _update = true; throw (basic_error() << "invalid fd: " "not found into processes fd list"); } p = it->second; } concurrency::locker lock(&p->_lock_process); // Read content of the stream and push it. char buffer[4096]; unsigned int size(p->_read(fd, buffer, sizeof(buffer))); if (p->_stream[process::out] == fd) { p->_buffer_out.append(buffer, size); p->_cv_buffer_out.wake_one(); // Notify listener if necessary. if (p->_listener) { lock.unlock(); (p->_listener->data_is_available)(*p); } } else if (p->_stream[process::err] == fd) { p->_buffer_err.append(buffer, size); p->_cv_buffer_err.wake_one(); // Notify listener if necessary. if (p->_listener) { lock.unlock(); (p->_listener->data_is_available_err)(*p); } } } catch (std::exception const& e) { logging::error(logging::high) << e.what(); } } /** * Internal thread to monitor processes. */ void process_manager::_run() { try { while (!_quit) { // Update the file descriptor list. _update_list(); int ret(0); // Sleep if no file descriptor. if (!_fds_size) concurrency::thread::msleep(DEFAULT_TIMEOUT); // Wait event on file descriptor. else if ((ret = poll(_fds, _fds_size, DEFAULT_TIMEOUT)) < 0) { char const* msg(strerror(errno)); throw (basic_error() << "poll failed: " << msg); } for (unsigned int i(0), checked(0); checked < static_cast<unsigned int>(ret) && i < _fds_size; ++i) { // No event. if (!_fds[i].revents) continue; // Data are available. if (_fds[i].revents & (POLLIN | POLLPRI)) _read_stream(_fds[i].fd); // File descriptor was close. else if (_fds[i].revents & POLLHUP) _close_stream(_fds[i].fd); // Error! else if (_fds[i].revents & (POLLERR | POLLNVAL)) { _update = true; logging::error(logging::high) << "invalid fd " << _fds[i].fd << " from process manager"; } ++checked; } // Release finished process. _wait_processes(); // Kill process in timeout. _kill_processes_timeout(); } } catch (std::exception const& e) { logging::error(logging::high) << e.what(); } } /** * Update list of file descriptor to watch. */ void process_manager::_update_list() { concurrency::locker lock(&_lock_processes); // No need update. if (!_update) return; // Resize file descriptor list. if (_processes_fd.size() > _fds_capacity) { delete[] _fds; _fds = new pollfd[_processes_fd.size()]; } // Set file descriptor to wait event. _fds_size = 0; for (umap<int, process*>::const_iterator it(_processes_fd.begin()), end(_processes_fd.end()); it != end; ++it) { _fds[_fds_size].fd = it->first; _fds[_fds_size].events = POLLIN | POLLPRI; _fds[_fds_size].revents = 0; ++_fds_size; } // Disable update. _update = false; } /** * Waiting finished process. */ void process_manager::_wait_processes() throw () { try { while (true) { int status(0); pid_t pid(waitpid(-1, &status, WNOHANG)); // No process are finished. if (!pid) break; // Error! if (pid < 0) { char const* msg(strerror(errno)); throw (basic_error() << "waiting process failed: " << msg); } process* p(NULL); // Get process to link with pid and remove this pid // to the process manager. { concurrency::locker lock(&_lock_processes); umap<pid_t, process*>::iterator it(_processes_pid.find(pid)); if (it == _processes_pid.end()) throw (basic_error() << "waiting process failed: " << pid << " is not register"); p = it->second; _processes_pid.erase(it); } // Update process informations. concurrency::locker lock(&p->_lock_process); p->_end_time = timestamp::now(); p->_status = status; p->_process = static_cast<pid_t>(-1); p->_close(p->_stream[process::in]); _erase_timeout(p); if (!p->_is_running()) { // Notify listener if necessary. if (p->_listener) { lock.unlock(); (p->_listener->finished)(*p); lock.relock(); } // Release condition variable. p->_cv_buffer_err.wake_one(); p->_cv_buffer_out.wake_one(); p->_cv_process.wake_one(); } } } catch (std::exception const& e) { logging::error(logging::high) << e.what(); } } <|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 "net/test/test_server.h" #include <algorithm> #include <string> #include <vector> #include "build/build_config.h" #if defined(OS_WIN) #include <windows.h> #include <wincrypt.h> #elif defined(OS_MACOSX) #include "net/base/x509_certificate.h" #endif #include "base/file_util.h" #include "base/leak_annotations.h" #include "base/logging.h" #include "base/path_service.h" #include "base/string_number_conversions.h" #include "base/utf_string_conversions.h" #include "net/base/cert_test_util.h" #include "net/base/host_resolver.h" #include "net/base/test_completion_callback.h" #include "net/socket/tcp_client_socket.h" #include "net/socket/tcp_pinger.h" #include "testing/platform_test.h" #if defined(OS_WIN) #pragma comment(lib, "crypt32.lib") #endif namespace { // Number of connection attempts for tests. const int kServerConnectionAttempts = 10; // Connection timeout in milliseconds for tests. const int kServerConnectionTimeoutMs = 1000; } // namespace namespace net { #if defined(OS_MACOSX) void SetMacTestCertificate(X509Certificate* cert); #endif // static const char TestServerLauncher::kHostName[] = "127.0.0.1"; const char TestServerLauncher::kMismatchedHostName[] = "localhost"; const int TestServerLauncher::kOKHTTPSPort = 9443; const int TestServerLauncher::kBadHTTPSPort = 9666; // The issuer name of the cert that should be trusted for the test to work. const wchar_t TestServerLauncher::kCertIssuerName[] = L"Test CA"; TestServerLauncher::TestServerLauncher() : process_handle_(base::kNullProcessHandle) { InitCertPath(); } void TestServerLauncher::InitCertPath() { PathService::Get(base::DIR_SOURCE_ROOT, &cert_dir_); cert_dir_ = cert_dir_.Append(FILE_PATH_LITERAL("net")) .Append(FILE_PATH_LITERAL("data")) .Append(FILE_PATH_LITERAL("ssl")) .Append(FILE_PATH_LITERAL("certificates")); } namespace { void AppendToPythonPath(const FilePath& dir) { // Do nothing if dir already on path. #if defined(OS_WIN) const wchar_t kPythonPath[] = L"PYTHONPATH"; // TODO(dkegel): handle longer PYTHONPATH variables wchar_t oldpath[4096]; if (GetEnvironmentVariable(kPythonPath, oldpath, arraysize(oldpath)) == 0) { SetEnvironmentVariableW(kPythonPath, dir.value().c_str()); } else if (!wcsstr(oldpath, dir.value().c_str())) { std::wstring newpath(oldpath); newpath.append(L";"); newpath.append(dir.value()); SetEnvironmentVariableW(kPythonPath, newpath.c_str()); } #elif defined(OS_POSIX) const char kPythonPath[] = "PYTHONPATH"; const char* oldpath = getenv(kPythonPath); // setenv() leaks memory intentionally on Mac if (!oldpath) { setenv(kPythonPath, dir.value().c_str(), 1); } else if (!strstr(oldpath, dir.value().c_str())) { std::string newpath(oldpath); newpath.append(":"); newpath.append(dir.value()); setenv(kPythonPath, newpath.c_str(), 1); } #endif } } // end namespace void TestServerLauncher::SetPythonPath() { FilePath third_party_dir; CHECK(PathService::Get(base::DIR_SOURCE_ROOT, &third_party_dir)); third_party_dir = third_party_dir.Append(FILE_PATH_LITERAL("third_party")); AppendToPythonPath(third_party_dir.Append(FILE_PATH_LITERAL("tlslite"))); AppendToPythonPath(third_party_dir.Append(FILE_PATH_LITERAL("pyftpdlib"))); // Locate the Python code generated by the protocol buffers compiler. FilePath generated_code_dir; CHECK(PathService::Get(base::DIR_EXE, &generated_code_dir)); generated_code_dir = generated_code_dir.Append(FILE_PATH_LITERAL("pyproto")); AppendToPythonPath(generated_code_dir); AppendToPythonPath(generated_code_dir.Append(FILE_PATH_LITERAL("sync_pb"))); } bool TestServerLauncher::Start(Protocol protocol, const std::string& host_name, int port, const FilePath& document_root, const FilePath& cert_path, const std::wstring& file_root_url) { if (!cert_path.value().empty()) { if (!LoadTestRootCert()) return false; if (!CheckCATrusted()) return false; } std::string port_str = base::IntToString(port); // Get path to python server script FilePath testserver_path; if (!PathService::Get(base::DIR_SOURCE_ROOT, &testserver_path)) return false; testserver_path = testserver_path .Append(FILE_PATH_LITERAL("net")) .Append(FILE_PATH_LITERAL("tools")) .Append(FILE_PATH_LITERAL("testserver")) .Append(FILE_PATH_LITERAL("testserver.py")); PathService::Get(base::DIR_SOURCE_ROOT, &document_root_dir_); document_root_dir_ = document_root_dir_.Append(document_root); SetPythonPath(); #if defined(OS_WIN) // Get path to python interpreter FilePath python_exe; if (!PathService::Get(base::DIR_SOURCE_ROOT, &python_exe)) return false; python_exe = python_exe .Append(FILE_PATH_LITERAL("third_party")) .Append(FILE_PATH_LITERAL("python_24")) .Append(FILE_PATH_LITERAL("python.exe")); std::wstring command_line = L"\"" + python_exe.ToWStringHack() + L"\" " + L"\"" + testserver_path.ToWStringHack() + L"\" --port=" + UTF8ToWide(port_str) + L" --data-dir=\"" + document_root_dir_.ToWStringHack() + L"\""; if (protocol == ProtoFTP) command_line.append(L" -f"); if (!cert_path.value().empty()) { command_line.append(L" --https=\""); command_line.append(cert_path.ToWStringHack()); command_line.append(L"\""); } if (!file_root_url.empty()) { command_line.append(L" --file-root-url=\""); command_line.append(file_root_url); command_line.append(L"\""); } if (!LaunchTestServerAsJob(command_line, true, &process_handle_, &job_handle_)) { LOG(ERROR) << "Failed to launch " << command_line; return false; } #elif defined(OS_POSIX) std::vector<std::string> command_line; command_line.push_back("python"); command_line.push_back(testserver_path.value()); command_line.push_back("--port=" + port_str); command_line.push_back("--data-dir=" + document_root_dir_.value()); if (protocol == ProtoFTP) command_line.push_back("-f"); if (!cert_path.value().empty()) command_line.push_back("--https=" + cert_path.value()); base::file_handle_mapping_vector no_mappings; LOG(INFO) << "Trying to launch " << command_line[0] << " ..."; if (!base::LaunchApp(command_line, no_mappings, false, &process_handle_)) { LOG(ERROR) << "Failed to launch " << command_line[0] << " ..."; return false; } #endif // Let the server start, then verify that it's up. // Our server is Python, and takes about 500ms to start // up the first time, and about 200ms after that. if (!WaitToStart(host_name, port)) { LOG(ERROR) << "Failed to connect to server"; Stop(); return false; } LOG(INFO) << "Started on port " << port_str; return true; } bool TestServerLauncher::WaitToStart(const std::string& host_name, int port) { // Verify that the webserver is actually started. // Otherwise tests can fail if they run faster than Python can start. net::AddressList addr; scoped_refptr<net::HostResolver> resolver( net::CreateSystemHostResolver(net::HostResolver::kDefaultParallelism)); net::HostResolver::RequestInfo info(host_name, port); int rv = resolver->Resolve(info, &addr, NULL, NULL, BoundNetLog()); if (rv != net::OK) return false; net::TCPPinger pinger(addr); rv = pinger.Ping( base::TimeDelta::FromMilliseconds(kServerConnectionTimeoutMs), kServerConnectionAttempts); return rv == net::OK; } bool TestServerLauncher::WaitToFinish(int timeout_ms) { if (!process_handle_) return true; bool ret = base::WaitForSingleProcess(process_handle_, timeout_ms); if (ret) { base::CloseProcessHandle(process_handle_); process_handle_ = base::kNullProcessHandle; LOG(INFO) << "Finished."; } else { LOG(INFO) << "Timed out."; } return ret; } bool TestServerLauncher::Stop() { if (!process_handle_) return true; // First check if the process has already terminated. bool ret = base::WaitForSingleProcess(process_handle_, 0); if (!ret) ret = base::KillProcess(process_handle_, 1, true); if (ret) { base::CloseProcessHandle(process_handle_); process_handle_ = base::kNullProcessHandle; LOG(INFO) << "Stopped."; } else { LOG(INFO) << "Kill failed?"; } return ret; } TestServerLauncher::~TestServerLauncher() { #if defined(OS_MACOSX) SetMacTestCertificate(NULL); #endif Stop(); } FilePath TestServerLauncher::GetRootCertPath() { FilePath path(cert_dir_); path = path.AppendASCII("root_ca_cert.crt"); return path; } FilePath TestServerLauncher::GetOKCertPath() { FilePath path(cert_dir_); path = path.AppendASCII("ok_cert.pem"); return path; } FilePath TestServerLauncher::GetExpiredCertPath() { FilePath path(cert_dir_); path = path.AppendASCII("expired_cert.pem"); return path; } bool TestServerLauncher::LoadTestRootCert() { #if defined(USE_NSS) if (cert_) return true; // TODO(dkegel): figure out how to get this to only happen once? // This currently leaks a little memory. // TODO(dkegel): fix the leak and remove the entry in // tools/valgrind/memcheck/suppressions.txt ANNOTATE_SCOPED_MEMORY_LEAK; // Tell heap checker about the leak. cert_ = LoadTemporaryRootCert(GetRootCertPath()); DCHECK(cert_); return (cert_ != NULL); #elif defined(OS_MACOSX) X509Certificate* cert = LoadTemporaryRootCert(GetRootCertPath()); if (!cert) return false; SetMacTestCertificate(cert); return true; #else return true; #endif } bool TestServerLauncher::CheckCATrusted() { #if defined(OS_WIN) HCERTSTORE cert_store = CertOpenSystemStore(NULL, L"ROOT"); if (!cert_store) { LOG(ERROR) << " could not open trusted root CA store"; return false; } PCCERT_CONTEXT cert = CertFindCertificateInStore(cert_store, X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, 0, CERT_FIND_ISSUER_STR, kCertIssuerName, NULL); if (cert) CertFreeCertificateContext(cert); CertCloseStore(cert_store, 0); if (!cert) { LOG(ERROR) << " TEST CONFIGURATION ERROR: you need to import the test ca " "certificate to your trusted roots for this test to work. " "For more info visit:\n" "http://dev.chromium.org/developers/testing\n"; return false; } #endif return true; } #if defined(OS_WIN) bool LaunchTestServerAsJob(const std::wstring& cmdline, bool start_hidden, base::ProcessHandle* process_handle, ScopedHandle* job_handle) { // Launch test server process. STARTUPINFO startup_info = {0}; startup_info.cb = sizeof(startup_info); startup_info.dwFlags = STARTF_USESHOWWINDOW; startup_info.wShowWindow = start_hidden ? SW_HIDE : SW_SHOW; PROCESS_INFORMATION process_info; // If this code is run under a debugger, the test server process is // automatically associated with a job object created by the debugger. // The CREATE_BREAKAWAY_FROM_JOB flag is used to prevent this. if (!CreateProcess(NULL, const_cast<wchar_t*>(cmdline.c_str()), NULL, NULL, FALSE, CREATE_BREAKAWAY_FROM_JOB, NULL, NULL, &startup_info, &process_info)) { LOG(ERROR) << "Could not create process."; return false; } CloseHandle(process_info.hThread); // If the caller wants the process handle, we won't close it. if (process_handle) { *process_handle = process_info.hProcess; } else { CloseHandle(process_info.hProcess); } // Create a JobObject and associate the test server process with it. job_handle->Set(CreateJobObject(NULL, NULL)); if (!job_handle->IsValid()) { LOG(ERROR) << "Could not create JobObject."; return false; } else { JOBOBJECT_EXTENDED_LIMIT_INFORMATION limit_info = {0}; limit_info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; if (0 == SetInformationJobObject(job_handle->Get(), JobObjectExtendedLimitInformation, &limit_info, sizeof(limit_info))) { LOG(ERROR) << "Could not SetInformationJobObject."; return false; } if (0 == AssignProcessToJobObject(job_handle->Get(), process_info.hProcess)) { LOG(ERROR) << "Could not AssignProcessToObject."; return false; } } return true; } #endif } // namespace net <commit_msg>Run tests faster.<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 "net/test/test_server.h" #include <algorithm> #include <string> #include <vector> #include "build/build_config.h" #if defined(OS_WIN) #include <windows.h> #include <wincrypt.h> #elif defined(OS_MACOSX) #include "net/base/x509_certificate.h" #endif #include "base/file_util.h" #include "base/leak_annotations.h" #include "base/logging.h" #include "base/path_service.h" #include "base/string_number_conversions.h" #include "base/utf_string_conversions.h" #include "net/base/cert_test_util.h" #include "net/base/host_resolver.h" #include "net/base/test_completion_callback.h" #include "net/socket/tcp_client_socket.h" #include "net/socket/tcp_pinger.h" #include "testing/platform_test.h" #if defined(OS_WIN) #pragma comment(lib, "crypt32.lib") #endif namespace { // Number of connection attempts for tests. With a timeout of 100ms, this is 60 // seconds. const int kServerConnectionAttempts = 600; // Connection timeout in milliseconds for tests. const int kServerConnectionTimeoutMs = 100; } // namespace namespace net { #if defined(OS_MACOSX) void SetMacTestCertificate(X509Certificate* cert); #endif // static const char TestServerLauncher::kHostName[] = "127.0.0.1"; const char TestServerLauncher::kMismatchedHostName[] = "localhost"; const int TestServerLauncher::kOKHTTPSPort = 9443; const int TestServerLauncher::kBadHTTPSPort = 9666; // The issuer name of the cert that should be trusted for the test to work. const wchar_t TestServerLauncher::kCertIssuerName[] = L"Test CA"; TestServerLauncher::TestServerLauncher() : process_handle_(base::kNullProcessHandle) { InitCertPath(); } void TestServerLauncher::InitCertPath() { PathService::Get(base::DIR_SOURCE_ROOT, &cert_dir_); cert_dir_ = cert_dir_.Append(FILE_PATH_LITERAL("net")) .Append(FILE_PATH_LITERAL("data")) .Append(FILE_PATH_LITERAL("ssl")) .Append(FILE_PATH_LITERAL("certificates")); } namespace { void AppendToPythonPath(const FilePath& dir) { // Do nothing if dir already on path. #if defined(OS_WIN) const wchar_t kPythonPath[] = L"PYTHONPATH"; // TODO(dkegel): handle longer PYTHONPATH variables wchar_t oldpath[4096]; if (GetEnvironmentVariable(kPythonPath, oldpath, arraysize(oldpath)) == 0) { SetEnvironmentVariableW(kPythonPath, dir.value().c_str()); } else if (!wcsstr(oldpath, dir.value().c_str())) { std::wstring newpath(oldpath); newpath.append(L";"); newpath.append(dir.value()); SetEnvironmentVariableW(kPythonPath, newpath.c_str()); } #elif defined(OS_POSIX) const char kPythonPath[] = "PYTHONPATH"; const char* oldpath = getenv(kPythonPath); // setenv() leaks memory intentionally on Mac if (!oldpath) { setenv(kPythonPath, dir.value().c_str(), 1); } else if (!strstr(oldpath, dir.value().c_str())) { std::string newpath(oldpath); newpath.append(":"); newpath.append(dir.value()); setenv(kPythonPath, newpath.c_str(), 1); } #endif } } // end namespace void TestServerLauncher::SetPythonPath() { FilePath third_party_dir; CHECK(PathService::Get(base::DIR_SOURCE_ROOT, &third_party_dir)); third_party_dir = third_party_dir.Append(FILE_PATH_LITERAL("third_party")); AppendToPythonPath(third_party_dir.Append(FILE_PATH_LITERAL("tlslite"))); AppendToPythonPath(third_party_dir.Append(FILE_PATH_LITERAL("pyftpdlib"))); // Locate the Python code generated by the protocol buffers compiler. FilePath generated_code_dir; CHECK(PathService::Get(base::DIR_EXE, &generated_code_dir)); generated_code_dir = generated_code_dir.Append(FILE_PATH_LITERAL("pyproto")); AppendToPythonPath(generated_code_dir); AppendToPythonPath(generated_code_dir.Append(FILE_PATH_LITERAL("sync_pb"))); } bool TestServerLauncher::Start(Protocol protocol, const std::string& host_name, int port, const FilePath& document_root, const FilePath& cert_path, const std::wstring& file_root_url) { if (!cert_path.value().empty()) { if (!LoadTestRootCert()) return false; if (!CheckCATrusted()) return false; } std::string port_str = base::IntToString(port); // Get path to python server script FilePath testserver_path; if (!PathService::Get(base::DIR_SOURCE_ROOT, &testserver_path)) return false; testserver_path = testserver_path .Append(FILE_PATH_LITERAL("net")) .Append(FILE_PATH_LITERAL("tools")) .Append(FILE_PATH_LITERAL("testserver")) .Append(FILE_PATH_LITERAL("testserver.py")); PathService::Get(base::DIR_SOURCE_ROOT, &document_root_dir_); document_root_dir_ = document_root_dir_.Append(document_root); SetPythonPath(); #if defined(OS_WIN) // Get path to python interpreter FilePath python_exe; if (!PathService::Get(base::DIR_SOURCE_ROOT, &python_exe)) return false; python_exe = python_exe .Append(FILE_PATH_LITERAL("third_party")) .Append(FILE_PATH_LITERAL("python_24")) .Append(FILE_PATH_LITERAL("python.exe")); std::wstring command_line = L"\"" + python_exe.ToWStringHack() + L"\" " + L"\"" + testserver_path.ToWStringHack() + L"\" --port=" + UTF8ToWide(port_str) + L" --data-dir=\"" + document_root_dir_.ToWStringHack() + L"\""; if (protocol == ProtoFTP) command_line.append(L" -f"); if (!cert_path.value().empty()) { command_line.append(L" --https=\""); command_line.append(cert_path.ToWStringHack()); command_line.append(L"\""); } if (!file_root_url.empty()) { command_line.append(L" --file-root-url=\""); command_line.append(file_root_url); command_line.append(L"\""); } if (!LaunchTestServerAsJob(command_line, true, &process_handle_, &job_handle_)) { LOG(ERROR) << "Failed to launch " << command_line; return false; } #elif defined(OS_POSIX) std::vector<std::string> command_line; command_line.push_back("python"); command_line.push_back(testserver_path.value()); command_line.push_back("--port=" + port_str); command_line.push_back("--data-dir=" + document_root_dir_.value()); if (protocol == ProtoFTP) command_line.push_back("-f"); if (!cert_path.value().empty()) command_line.push_back("--https=" + cert_path.value()); base::file_handle_mapping_vector no_mappings; LOG(INFO) << "Trying to launch " << command_line[0] << " ..."; if (!base::LaunchApp(command_line, no_mappings, false, &process_handle_)) { LOG(ERROR) << "Failed to launch " << command_line[0] << " ..."; return false; } #endif // Let the server start, then verify that it's up. // Our server is Python, and takes about 500ms to start // up the first time, and about 200ms after that. if (!WaitToStart(host_name, port)) { LOG(ERROR) << "Failed to connect to server"; Stop(); return false; } LOG(INFO) << "Started on port " << port_str; return true; } bool TestServerLauncher::WaitToStart(const std::string& host_name, int port) { // Verify that the webserver is actually started. // Otherwise tests can fail if they run faster than Python can start. net::AddressList addr; scoped_refptr<net::HostResolver> resolver( net::CreateSystemHostResolver(net::HostResolver::kDefaultParallelism)); net::HostResolver::RequestInfo info(host_name, port); int rv = resolver->Resolve(info, &addr, NULL, NULL, BoundNetLog()); if (rv != net::OK) return false; net::TCPPinger pinger(addr); rv = pinger.Ping( base::TimeDelta::FromMilliseconds(kServerConnectionTimeoutMs), kServerConnectionAttempts); return rv == net::OK; } bool TestServerLauncher::WaitToFinish(int timeout_ms) { if (!process_handle_) return true; bool ret = base::WaitForSingleProcess(process_handle_, timeout_ms); if (ret) { base::CloseProcessHandle(process_handle_); process_handle_ = base::kNullProcessHandle; LOG(INFO) << "Finished."; } else { LOG(INFO) << "Timed out."; } return ret; } bool TestServerLauncher::Stop() { if (!process_handle_) return true; // First check if the process has already terminated. bool ret = base::WaitForSingleProcess(process_handle_, 0); if (!ret) ret = base::KillProcess(process_handle_, 1, true); if (ret) { base::CloseProcessHandle(process_handle_); process_handle_ = base::kNullProcessHandle; LOG(INFO) << "Stopped."; } else { LOG(INFO) << "Kill failed?"; } return ret; } TestServerLauncher::~TestServerLauncher() { #if defined(OS_MACOSX) SetMacTestCertificate(NULL); #endif Stop(); } FilePath TestServerLauncher::GetRootCertPath() { FilePath path(cert_dir_); path = path.AppendASCII("root_ca_cert.crt"); return path; } FilePath TestServerLauncher::GetOKCertPath() { FilePath path(cert_dir_); path = path.AppendASCII("ok_cert.pem"); return path; } FilePath TestServerLauncher::GetExpiredCertPath() { FilePath path(cert_dir_); path = path.AppendASCII("expired_cert.pem"); return path; } bool TestServerLauncher::LoadTestRootCert() { #if defined(USE_NSS) if (cert_) return true; // TODO(dkegel): figure out how to get this to only happen once? // This currently leaks a little memory. // TODO(dkegel): fix the leak and remove the entry in // tools/valgrind/memcheck/suppressions.txt ANNOTATE_SCOPED_MEMORY_LEAK; // Tell heap checker about the leak. cert_ = LoadTemporaryRootCert(GetRootCertPath()); DCHECK(cert_); return (cert_ != NULL); #elif defined(OS_MACOSX) X509Certificate* cert = LoadTemporaryRootCert(GetRootCertPath()); if (!cert) return false; SetMacTestCertificate(cert); return true; #else return true; #endif } bool TestServerLauncher::CheckCATrusted() { #if defined(OS_WIN) HCERTSTORE cert_store = CertOpenSystemStore(NULL, L"ROOT"); if (!cert_store) { LOG(ERROR) << " could not open trusted root CA store"; return false; } PCCERT_CONTEXT cert = CertFindCertificateInStore(cert_store, X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, 0, CERT_FIND_ISSUER_STR, kCertIssuerName, NULL); if (cert) CertFreeCertificateContext(cert); CertCloseStore(cert_store, 0); if (!cert) { LOG(ERROR) << " TEST CONFIGURATION ERROR: you need to import the test ca " "certificate to your trusted roots for this test to work. " "For more info visit:\n" "http://dev.chromium.org/developers/testing\n"; return false; } #endif return true; } #if defined(OS_WIN) bool LaunchTestServerAsJob(const std::wstring& cmdline, bool start_hidden, base::ProcessHandle* process_handle, ScopedHandle* job_handle) { // Launch test server process. STARTUPINFO startup_info = {0}; startup_info.cb = sizeof(startup_info); startup_info.dwFlags = STARTF_USESHOWWINDOW; startup_info.wShowWindow = start_hidden ? SW_HIDE : SW_SHOW; PROCESS_INFORMATION process_info; // If this code is run under a debugger, the test server process is // automatically associated with a job object created by the debugger. // The CREATE_BREAKAWAY_FROM_JOB flag is used to prevent this. if (!CreateProcess(NULL, const_cast<wchar_t*>(cmdline.c_str()), NULL, NULL, FALSE, CREATE_BREAKAWAY_FROM_JOB, NULL, NULL, &startup_info, &process_info)) { LOG(ERROR) << "Could not create process."; return false; } CloseHandle(process_info.hThread); // If the caller wants the process handle, we won't close it. if (process_handle) { *process_handle = process_info.hProcess; } else { CloseHandle(process_info.hProcess); } // Create a JobObject and associate the test server process with it. job_handle->Set(CreateJobObject(NULL, NULL)); if (!job_handle->IsValid()) { LOG(ERROR) << "Could not create JobObject."; return false; } else { JOBOBJECT_EXTENDED_LIMIT_INFORMATION limit_info = {0}; limit_info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; if (0 == SetInformationJobObject(job_handle->Get(), JobObjectExtendedLimitInformation, &limit_info, sizeof(limit_info))) { LOG(ERROR) << "Could not SetInformationJobObject."; return false; } if (0 == AssignProcessToJobObject(job_handle->Get(), process_info.hProcess)) { LOG(ERROR) << "Could not AssignProcessToObject."; return false; } } return true; } #endif } // namespace net <|endoftext|>
<commit_before>// Copyright (c) 2011-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "clientmodel.h" #include "bantablemodel.h" #include "guiconstants.h" #include "guiutil.h" #include "peertablemodel.h" #include "chainparams.h" #include "checkpoints.h" #include "clientversion.h" #include "validation.h" #include "net.h" #include "txmempool.h" #include "ui_interface.h" #include "util.h" #include <stdint.h> #include <QDebug> #include <QTimer> #include <boost/bind.hpp> class CBlockIndex; static const int64_t nClientStartupTime = GetTime(); static int64_t nLastHeaderTipUpdateNotification = 0; static int64_t nLastBlockTipUpdateNotification = 0; ClientModel::ClientModel(OptionsModel *_optionsModel, QObject *parent) : QObject(parent), optionsModel(_optionsModel), peerTableModel(0), banTableModel(0), pollTimer(0) { cachedBestHeaderHeight = -1; cachedBestHeaderTime = -1; peerTableModel = new PeerTableModel(this); banTableModel = new BanTableModel(this); pollTimer = new QTimer(this); connect(pollTimer, SIGNAL(timeout()), this, SLOT(updateTimer())); pollTimer->start(MODEL_UPDATE_DELAY); subscribeToCoreSignals(); } ClientModel::~ClientModel() { unsubscribeFromCoreSignals(); } int ClientModel::getNumConnections(unsigned int flags) const { CConnman::NumConnections connections = CConnman::CONNECTIONS_NONE; if(flags == CONNECTIONS_IN) connections = CConnman::CONNECTIONS_IN; else if (flags == CONNECTIONS_OUT) connections = CConnman::CONNECTIONS_OUT; else if (flags == CONNECTIONS_ALL) connections = CConnman::CONNECTIONS_ALL; if(g_connman) return g_connman->GetNodeCount(connections); return 0; } int ClientModel::getNumBlocks() const { LOCK(cs_main); return chainActive.Height(); } int ClientModel::getHeaderTipHeight() const { if (cachedBestHeaderHeight == -1) { // make sure we initially populate the cache via a cs_main lock // otherwise we need to wait for a tip update LOCK(cs_main); if (pindexBestHeader) { cachedBestHeaderHeight = pindexBestHeader->nHeight; cachedBestHeaderTime = pindexBestHeader->GetBlockTime(); } } return cachedBestHeaderHeight; } int64_t ClientModel::getHeaderTipTime() const { if (cachedBestHeaderTime == -1) { LOCK(cs_main); if (pindexBestHeader) { cachedBestHeaderHeight = pindexBestHeader->nHeight; cachedBestHeaderTime = pindexBestHeader->GetBlockTime(); } } return cachedBestHeaderTime; } quint64 ClientModel::getTotalBytesRecv() const { if(!g_connman) return 0; return g_connman->GetTotalBytesRecv(); } quint64 ClientModel::getTotalBytesSent() const { if(!g_connman) return 0; return g_connman->GetTotalBytesSent(); } QDateTime ClientModel::getLastBlockDate() const { LOCK(cs_main); if (chainActive.Tip()) return QDateTime::fromTime_t(chainActive.Tip()->GetBlockTime()); return QDateTime::fromTime_t(Params().GenesisBlock().GetBlockTime()); // Genesis block's time of current network } long ClientModel::getMempoolSize() const { return mempool.size(); } size_t ClientModel::getMempoolDynamicUsage() const { return mempool.DynamicMemoryUsage(); } double ClientModel::getVerificationProgress(const CBlockIndex *tipIn) const { CBlockIndex *tip = const_cast<CBlockIndex *>(tipIn); if (!tip) { LOCK(cs_main); tip = chainActive.Tip(); } return GuessVerificationProgress(Params().TxData(), tip); } void ClientModel::updateTimer() { // no locking required at this point // the following calls will acquire the required lock Q_EMIT mempoolSizeChanged(getMempoolSize(), getMempoolDynamicUsage()); Q_EMIT bytesChanged(getTotalBytesRecv(), getTotalBytesSent()); } void ClientModel::updateNumConnections(int numConnections) { Q_EMIT numConnectionsChanged(numConnections); } void ClientModel::updateNetworkActive(bool networkActive) { Q_EMIT networkActiveChanged(networkActive); } void ClientModel::updateAlert() { Q_EMIT alertsChanged(getStatusBarWarnings()); } bool ClientModel::inInitialBlockDownload() const { return IsInitialBlockDownload(); } enum BlockSource ClientModel::getBlockSource() const { if (fReindex) return BLOCK_SOURCE_REINDEX; else if (fImporting) return BLOCK_SOURCE_DISK; else if (getNumConnections() > 0) return BLOCK_SOURCE_NETWORK; return BLOCK_SOURCE_NONE; } void ClientModel::setNetworkActive(bool active) { if (g_connman) { g_connman->SetNetworkActive(active); } } bool ClientModel::getNetworkActive() const { if (g_connman) { return g_connman->GetNetworkActive(); } return false; } QString ClientModel::getStatusBarWarnings() const { return QString::fromStdString(GetWarnings("gui")); } OptionsModel *ClientModel::getOptionsModel() { return optionsModel; } PeerTableModel *ClientModel::getPeerTableModel() { return peerTableModel; } BanTableModel *ClientModel::getBanTableModel() { return banTableModel; } QString ClientModel::formatFullVersion() const { return QString::fromStdString(FormatFullVersion()); } QString ClientModel::formatSubVersion() const { return QString::fromStdString(strSubVersion); } bool ClientModel::isReleaseVersion() const { return CLIENT_VERSION_IS_RELEASE; } QString ClientModel::formatClientStartupTime() const { return QDateTime::fromTime_t(nClientStartupTime).toString(); } QString ClientModel::dataDir() const { return GUIUtil::boostPathToQString(GetDataDir()); } void ClientModel::updateBanlist() { banTableModel->refresh(); } // Handlers for core signals static void ShowProgress(ClientModel *clientmodel, const std::string &title, int nProgress) { // emits signal "showProgress" QMetaObject::invokeMethod(clientmodel, "showProgress", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(title)), Q_ARG(int, nProgress)); } static void NotifyNumConnectionsChanged(ClientModel *clientmodel, int newNumConnections) { // Too noisy: qDebug() << "NotifyNumConnectionsChanged: " + QString::number(newNumConnections); QMetaObject::invokeMethod(clientmodel, "updateNumConnections", Qt::QueuedConnection, Q_ARG(int, newNumConnections)); } static void NotifyNetworkActiveChanged(ClientModel *clientmodel, bool networkActive) { QMetaObject::invokeMethod(clientmodel, "updateNetworkActive", Qt::QueuedConnection, Q_ARG(bool, networkActive)); } static void NotifyAlertChanged(ClientModel *clientmodel) { qDebug() << "NotifyAlertChanged"; QMetaObject::invokeMethod(clientmodel, "updateAlert", Qt::QueuedConnection); } static void BannedListChanged(ClientModel *clientmodel) { qDebug() << QString("%1: Requesting update for peer banlist").arg(__func__); QMetaObject::invokeMethod(clientmodel, "updateBanlist", Qt::QueuedConnection); } static void BlockTipChanged(ClientModel *clientmodel, bool initialSync, const CBlockIndex *pIndex, bool fHeader) { // lock free async UI updates in case we have a new block tip // during initial sync, only update the UI if the last update // was > 250ms (MODEL_UPDATE_DELAY) ago int64_t now = 0; if (initialSync) now = GetTimeMillis(); int64_t& nLastUpdateNotification = fHeader ? nLastHeaderTipUpdateNotification : nLastBlockTipUpdateNotification; if (fHeader) { // cache best headers time and height to reduce future cs_main locks clientmodel->cachedBestHeaderHeight = pIndex->nHeight; clientmodel->cachedBestHeaderTime = pIndex->GetBlockTime(); } // if we are in-sync, update the UI regardless of last update time if (!initialSync || now - nLastUpdateNotification > MODEL_UPDATE_DELAY) { //pass a async signal to the UI thread QMetaObject::invokeMethod(clientmodel, "numBlocksChanged", Qt::QueuedConnection, Q_ARG(int, pIndex->nHeight), Q_ARG(QDateTime, QDateTime::fromTime_t(pIndex->GetBlockTime())), Q_ARG(double, clientmodel->getVerificationProgress(pIndex)), Q_ARG(bool, fHeader)); nLastUpdateNotification = now; } } void ClientModel::subscribeToCoreSignals() { // Connect signals to client uiInterface.ShowProgress.connect(boost::bind(ShowProgress, this, _1, _2)); uiInterface.NotifyNumConnectionsChanged.connect(boost::bind(NotifyNumConnectionsChanged, this, _1)); uiInterface.NotifyNetworkActiveChanged.connect(boost::bind(NotifyNetworkActiveChanged, this, _1)); uiInterface.NotifyAlertChanged.connect(boost::bind(NotifyAlertChanged, this)); uiInterface.BannedListChanged.connect(boost::bind(BannedListChanged, this)); uiInterface.NotifyBlockTip.connect(boost::bind(BlockTipChanged, this, _1, _2, false)); uiInterface.NotifyHeaderTip.connect(boost::bind(BlockTipChanged, this, _1, _2, true)); } void ClientModel::unsubscribeFromCoreSignals() { // Disconnect signals from client uiInterface.ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2)); uiInterface.NotifyNumConnectionsChanged.disconnect(boost::bind(NotifyNumConnectionsChanged, this, _1)); uiInterface.NotifyNetworkActiveChanged.disconnect(boost::bind(NotifyNetworkActiveChanged, this, _1)); uiInterface.NotifyAlertChanged.disconnect(boost::bind(NotifyAlertChanged, this)); uiInterface.BannedListChanged.disconnect(boost::bind(BannedListChanged, this)); uiInterface.NotifyBlockTip.disconnect(boost::bind(BlockTipChanged, this, _1, _2, false)); uiInterface.NotifyHeaderTip.disconnect(boost::bind(BlockTipChanged, this, _1, _2, true)); } <commit_msg>Fix Build on Boost 1.74<commit_after>// Copyright (c) 2011-2016 The Bitcoin Core developers // Copyright (c) 2011-2023 The Goldcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "clientmodel.h" #include "bantablemodel.h" #include "guiconstants.h" #include "guiutil.h" #include "peertablemodel.h" #include "chainparams.h" #include "checkpoints.h" #include "clientversion.h" #include "validation.h" #include "net.h" #include "txmempool.h" #include "ui_interface.h" #include "util.h" #include <stdint.h> #include <QDebug> #include <QTimer> #include <boost/bind/bind.hpp> class CBlockIndex; static const int64_t nClientStartupTime = GetTime(); static int64_t nLastHeaderTipUpdateNotification = 0; static int64_t nLastBlockTipUpdateNotification = 0; ClientModel::ClientModel(OptionsModel *_optionsModel, QObject *parent) : QObject(parent), optionsModel(_optionsModel), peerTableModel(0), banTableModel(0), pollTimer(0) { cachedBestHeaderHeight = -1; cachedBestHeaderTime = -1; peerTableModel = new PeerTableModel(this); banTableModel = new BanTableModel(this); pollTimer = new QTimer(this); connect(pollTimer, SIGNAL(timeout()), this, SLOT(updateTimer())); pollTimer->start(MODEL_UPDATE_DELAY); subscribeToCoreSignals(); } ClientModel::~ClientModel() { unsubscribeFromCoreSignals(); } int ClientModel::getNumConnections(unsigned int flags) const { CConnman::NumConnections connections = CConnman::CONNECTIONS_NONE; if(flags == CONNECTIONS_IN) connections = CConnman::CONNECTIONS_IN; else if (flags == CONNECTIONS_OUT) connections = CConnman::CONNECTIONS_OUT; else if (flags == CONNECTIONS_ALL) connections = CConnman::CONNECTIONS_ALL; if(g_connman) return g_connman->GetNodeCount(connections); return 0; } int ClientModel::getNumBlocks() const { LOCK(cs_main); return chainActive.Height(); } int ClientModel::getHeaderTipHeight() const { if (cachedBestHeaderHeight == -1) { // make sure we initially populate the cache via a cs_main lock // otherwise we need to wait for a tip update LOCK(cs_main); if (pindexBestHeader) { cachedBestHeaderHeight = pindexBestHeader->nHeight; cachedBestHeaderTime = pindexBestHeader->GetBlockTime(); } } return cachedBestHeaderHeight; } int64_t ClientModel::getHeaderTipTime() const { if (cachedBestHeaderTime == -1) { LOCK(cs_main); if (pindexBestHeader) { cachedBestHeaderHeight = pindexBestHeader->nHeight; cachedBestHeaderTime = pindexBestHeader->GetBlockTime(); } } return cachedBestHeaderTime; } quint64 ClientModel::getTotalBytesRecv() const { if(!g_connman) return 0; return g_connman->GetTotalBytesRecv(); } quint64 ClientModel::getTotalBytesSent() const { if(!g_connman) return 0; return g_connman->GetTotalBytesSent(); } QDateTime ClientModel::getLastBlockDate() const { LOCK(cs_main); if (chainActive.Tip()) return QDateTime::fromTime_t(chainActive.Tip()->GetBlockTime()); return QDateTime::fromTime_t(Params().GenesisBlock().GetBlockTime()); // Genesis block's time of current network } long ClientModel::getMempoolSize() const { return mempool.size(); } size_t ClientModel::getMempoolDynamicUsage() const { return mempool.DynamicMemoryUsage(); } double ClientModel::getVerificationProgress(const CBlockIndex *tipIn) const { CBlockIndex *tip = const_cast<CBlockIndex *>(tipIn); if (!tip) { LOCK(cs_main); tip = chainActive.Tip(); } return GuessVerificationProgress(Params().TxData(), tip); } void ClientModel::updateTimer() { // no locking required at this point // the following calls will acquire the required lock Q_EMIT mempoolSizeChanged(getMempoolSize(), getMempoolDynamicUsage()); Q_EMIT bytesChanged(getTotalBytesRecv(), getTotalBytesSent()); } void ClientModel::updateNumConnections(int numConnections) { Q_EMIT numConnectionsChanged(numConnections); } void ClientModel::updateNetworkActive(bool networkActive) { Q_EMIT networkActiveChanged(networkActive); } void ClientModel::updateAlert() { Q_EMIT alertsChanged(getStatusBarWarnings()); } bool ClientModel::inInitialBlockDownload() const { return IsInitialBlockDownload(); } enum BlockSource ClientModel::getBlockSource() const { if (fReindex) return BLOCK_SOURCE_REINDEX; else if (fImporting) return BLOCK_SOURCE_DISK; else if (getNumConnections() > 0) return BLOCK_SOURCE_NETWORK; return BLOCK_SOURCE_NONE; } void ClientModel::setNetworkActive(bool active) { if (g_connman) { g_connman->SetNetworkActive(active); } } bool ClientModel::getNetworkActive() const { if (g_connman) { return g_connman->GetNetworkActive(); } return false; } QString ClientModel::getStatusBarWarnings() const { return QString::fromStdString(GetWarnings("gui")); } OptionsModel *ClientModel::getOptionsModel() { return optionsModel; } PeerTableModel *ClientModel::getPeerTableModel() { return peerTableModel; } BanTableModel *ClientModel::getBanTableModel() { return banTableModel; } QString ClientModel::formatFullVersion() const { return QString::fromStdString(FormatFullVersion()); } QString ClientModel::formatSubVersion() const { return QString::fromStdString(strSubVersion); } bool ClientModel::isReleaseVersion() const { return CLIENT_VERSION_IS_RELEASE; } QString ClientModel::formatClientStartupTime() const { return QDateTime::fromTime_t(nClientStartupTime).toString(); } QString ClientModel::dataDir() const { return GUIUtil::boostPathToQString(GetDataDir()); } void ClientModel::updateBanlist() { banTableModel->refresh(); } // Handlers for core signals static void ShowProgress(ClientModel *clientmodel, const std::string &title, int nProgress) { // emits signal "showProgress" QMetaObject::invokeMethod(clientmodel, "showProgress", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(title)), Q_ARG(int, nProgress)); } static void NotifyNumConnectionsChanged(ClientModel *clientmodel, int newNumConnections) { // Too noisy: qDebug() << "NotifyNumConnectionsChanged: " + QString::number(newNumConnections); QMetaObject::invokeMethod(clientmodel, "updateNumConnections", Qt::QueuedConnection, Q_ARG(int, newNumConnections)); } static void NotifyNetworkActiveChanged(ClientModel *clientmodel, bool networkActive) { QMetaObject::invokeMethod(clientmodel, "updateNetworkActive", Qt::QueuedConnection, Q_ARG(bool, networkActive)); } static void NotifyAlertChanged(ClientModel *clientmodel) { qDebug() << "NotifyAlertChanged"; QMetaObject::invokeMethod(clientmodel, "updateAlert", Qt::QueuedConnection); } static void BannedListChanged(ClientModel *clientmodel) { qDebug() << QString("%1: Requesting update for peer banlist").arg(__func__); QMetaObject::invokeMethod(clientmodel, "updateBanlist", Qt::QueuedConnection); } static void BlockTipChanged(ClientModel *clientmodel, bool initialSync, const CBlockIndex *pIndex, bool fHeader) { // lock free async UI updates in case we have a new block tip // during initial sync, only update the UI if the last update // was > 250ms (MODEL_UPDATE_DELAY) ago int64_t now = 0; if (initialSync) now = GetTimeMillis(); int64_t& nLastUpdateNotification = fHeader ? nLastHeaderTipUpdateNotification : nLastBlockTipUpdateNotification; if (fHeader) { // cache best headers time and height to reduce future cs_main locks clientmodel->cachedBestHeaderHeight = pIndex->nHeight; clientmodel->cachedBestHeaderTime = pIndex->GetBlockTime(); } // if we are in-sync, update the UI regardless of last update time if (!initialSync || now - nLastUpdateNotification > MODEL_UPDATE_DELAY) { //pass a async signal to the UI thread QMetaObject::invokeMethod(clientmodel, "numBlocksChanged", Qt::QueuedConnection, Q_ARG(int, pIndex->nHeight), Q_ARG(QDateTime, QDateTime::fromTime_t(pIndex->GetBlockTime())), Q_ARG(double, clientmodel->getVerificationProgress(pIndex)), Q_ARG(bool, fHeader)); nLastUpdateNotification = now; } } void ClientModel::subscribeToCoreSignals() { // Connect signals to client uiInterface.ShowProgress.connect(boost::bind(ShowProgress, this, boost::placeholders::_1, boost::placeholders::_2)); uiInterface.NotifyNumConnectionsChanged.connect(boost::bind(NotifyNumConnectionsChanged, this, boost::placeholders::_1)); uiInterface.NotifyNetworkActiveChanged.connect(boost::bind(NotifyNetworkActiveChanged, this, boost::placeholders::_1)); uiInterface.NotifyAlertChanged.connect(boost::bind(NotifyAlertChanged, this, boost::placeholders::_1, boost::placeholders::_2)); uiInterface.BannedListChanged.connect(boost::bind(BannedListChanged, this)); uiInterface.NotifyBlockTip.connect(boost::bind(BlockTipChanged, this, _1, _2, false)); uiInterface.NotifyHeaderTip.connect(boost::bind(BlockTipChanged, this, _1, _2, true)); } void ClientModel::unsubscribeFromCoreSignals() { // Disconnect signals from client uiInterface.ShowProgress.disconnect(boost::bind(ShowProgress, this, boost::placeholders::_1, boost::placeholders::_2)); uiInterface.NotifyNumConnectionsChanged.disconnect(boost::bind(NotifyNumConnectionsChanged, this, boost::placeholders::_1)); uiInterface.NotifyNetworkActiveChanged.disconnect(boost::bind(NotifyNetworkActiveChanged, this, boost::placeholders::_1)); uiInterface.NotifyAlertChanged.disconnect(boost::bind(NotifyAlertChanged, this, boost::placeholders::_1, boost::placeholders::_2)); uiInterface.BannedListChanged.disconnect(boost::bind(BannedListChanged, this)); uiInterface.NotifyBlockTip.disconnect(boost::bind(BlockTipChanged, this, boost::placeholders::_1, boost::placeholders::_2, false)); uiInterface.NotifyHeaderTip.disconnect(boost::bind(BlockTipChanged, this, boost::placeholders::_1, boost::placeholders::_2, true)); } <|endoftext|>
<commit_before>/* * Copyright (C) 2009 by Marc Boris Duerner, Tommi Maekitalo * * 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. * * As a special exception, you may use this file as part of a free * software library without restriction. Specifically, if other files * instantiate templates or use macros or inline functions from this * file, or you compile this file and link it with other files to * produce an executable, this file does not by itself cause the * resulting executable to be covered by the GNU General Public * License. This exception does not however invalidate any other * reasons why the executable file might be covered by the GNU Library * General Public License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "clientimpl.h" #include <cxxtools/http/client.h> #include "parser.h" #include <cxxtools/ioerror.h> #include <cxxtools/textstream.h> #include <cxxtools/base64codec.h> #include <sstream> #include <cxxtools/log.h> log_define("cxxtools.http.client.impl") namespace cxxtools { namespace http { void ClientImpl::ParseEvent::onHttpReturn(unsigned ret, const std::string& text) { _replyHeader.httpReturn(ret, text); } ClientImpl::ClientImpl(Client* client) : _client(client) , _parseEvent(_replyHeader) , _parser(_parseEvent, true) , _request(0) , _stream(8192, true) , _readHeader(true) , _contentLength(0) , _chunkedEncoding(false) , _chunkedIStream(_stream.rdbuf()) { _stream.attachDevice(_socket); cxxtools::connect(_socket.connected, *this, &ClientImpl::onConnect); cxxtools::connect(_socket.errorOccured, *this, &ClientImpl::onErrorOccured); cxxtools::connect(_stream.buffer().outputReady, *this, &ClientImpl::onOutput); cxxtools::connect(_stream.buffer().inputReady, *this, &ClientImpl::onInput); } ClientImpl::ClientImpl(Client* client, const net::AddrInfo& addrinfo) : _client(client) , _parseEvent(_replyHeader) , _parser(_parseEvent, true) , _request(0) , _addrInfo(addrinfo) , _stream(8192, true) , _readHeader(true) , _contentLength(0) , _chunkedEncoding(false) , _chunkedIStream(_stream.rdbuf()) { _stream.attachDevice(_socket); cxxtools::connect(_socket.connected, *this, &ClientImpl::onConnect); cxxtools::connect(_socket.errorOccured, *this, &ClientImpl::onErrorOccured); cxxtools::connect(_stream.buffer().outputReady, *this, &ClientImpl::onOutput); cxxtools::connect(_stream.buffer().inputReady, *this, &ClientImpl::onInput); } ClientImpl::ClientImpl(Client* client, SelectorBase& selector, const net::AddrInfo& addrinfo) : _client(client) , _parseEvent(_replyHeader) , _parser(_parseEvent, true) , _request(0) , _addrInfo(addrinfo) , _stream(8192, true) , _readHeader(true) , _contentLength(0) , _chunkedEncoding(false) , _chunkedIStream(_stream.rdbuf()) { _stream.attachDevice(_socket); cxxtools::connect(_socket.connected, *this, &ClientImpl::onConnect); cxxtools::connect(_socket.errorOccured, *this, &ClientImpl::onErrorOccured); cxxtools::connect(_stream.buffer().outputReady, *this, &ClientImpl::onOutput); cxxtools::connect(_stream.buffer().inputReady, *this, &ClientImpl::onInput); setSelector(selector); } void ClientImpl::setSelector(SelectorBase& selector) { selector.add(_socket); } void ClientImpl::reexecute(const Request& request) { log_debug("reconnect"); _stream.clear(); _stream.buffer().discard(); _socket.connect(_addrInfo); sendRequest(request); _stream.flush(); } void ClientImpl::doparse() { char ch; while (!_parser.end() && _stream.get(ch)) _parser.parse(ch); } const ReplyHeader& ClientImpl::execute(const Request& request, std::size_t timeout) { log_trace("execute request " << request.url()); _replyHeader.clear(); _socket.setTimeout(timeout); bool shouldReconnect = _socket.isConnected(); if (!shouldReconnect) { log_debug("connect"); _socket.connect(_addrInfo); } log_debug("send request"); sendRequest(request); log_debug("flush stream"); _stream.flush(); log_debug("flush stream ready"); if (!_stream && shouldReconnect) { // sending failed and we were not connected before, so try again reexecute(request); shouldReconnect = false; } if (!_stream) throw IOError( CXXTOOLS_ERROR_MSG("error sending HTTP request") ); log_debug("read reply"); _parser.reset(true); _readHeader = true; doparse(); if (_parser.begin() && shouldReconnect) { // reading failed and we were not connected before, so try again reexecute(request); if (!_stream) throw IOError( CXXTOOLS_ERROR_MSG("error sending HTTP request") ); doparse(); } log_debug("reply ready"); if (_stream.fail()) throw IOError( CXXTOOLS_ERROR_MSG("failed to read HTTP reply") ); if (_parser.fail()) throw IOError( CXXTOOLS_ERROR_MSG("invalid HTTP reply") ); if (!_parser.end()) throw IOError( CXXTOOLS_ERROR_MSG("incomplete HTTP reply header") ); return _replyHeader; } void ClientImpl::readBody(std::string& s) { s.clear(); _chunkedEncoding = _replyHeader.chunkedTransferEncoding(); _chunkedIStream.reset(); if (_chunkedEncoding) { log_debug("read body with chunked encoding"); char ch; while (_chunkedIStream.get(ch)) s += ch; log_debug("eod=" << _chunkedIStream.eod()); if (_chunkedIStream.eod()) { _parser.readHeader(); doparse(); if (_parser.fail()) throw std::runtime_error("http parser failed"); // TODO define exception class } else throw std::runtime_error("chunked stream not complete"); } else { unsigned n = _replyHeader.contentLength(); log_debug("read body; content-size: " << n); s.reserve(n); char ch; while (n-- && _stream.get(ch)) s += ch; if (_stream.fail()) throw IOError( CXXTOOLS_ERROR_MSG("error reading HTTP reply body") ); //log_debug("body read: \"" << s << '"'); } if (!_replyHeader.keepAlive()) { log_debug("close socket - no keep alive"); _socket.close(); } else { log_debug("do not close socket - keep alive"); } } std::string ClientImpl::get(const std::string& url, std::size_t timeout) { Request request(url); execute(request, timeout); return readBody(); } void ClientImpl::beginExecute(const Request& request) { _request = &request; _replyHeader.clear(); if (_socket.isConnected()) { sendRequest(*_request); try { _stream.buffer().beginWrite(); } catch (const cxxtools::IOError&) { log_debug("first write failed, so connection is not active any more"); _stream.clear(); _stream.buffer().discard(); _socket.beginConnect(_addrInfo); } } else { _socket.beginConnect(_addrInfo); } } void ClientImpl::wait(std::size_t msecs) { _socket.wait(msecs); } void ClientImpl::sendRequest(const Request& request) { log_debug("send request " << request.url()); static const std::string contentLength = "Content-Length"; static const std::string connection = "Connection"; static const std::string date = "Date"; static const std::string host = "Host"; static const std::string authorization = "Authorization"; _stream << request.method() << ' ' << request.url() << " HTTP/" << request.header().httpVersionMajor() << '.' << request.header().httpVersionMinor() << "\r\n"; for (RequestHeader::const_iterator it = request.header().begin(); it != request.header().end(); ++it) { _stream << it->first << ": " << it->second << "\r\n"; } if (!request.header().hasHeader(contentLength)) { _stream << "Content-Length: " << request.bodySize() << "\r\n"; } if (!request.header().hasHeader(connection)) { _stream << "Connection: keep-alive\r\n"; } if (!request.header().hasHeader(date)) { _stream << "Date: " << MessageHeader::htdateCurrent() << "\r\n"; } if (!request.header().hasHeader(host)) { _stream << "Host: " << _addrInfo.host(); unsigned short port = _addrInfo.port(); if (port != 80) _stream << ':' << port; _stream << "\r\n"; } if (!_username.empty() && !request.header().hasHeader(authorization)) { std::ostringstream d; BasicTextOStream<char, char> b(d, new Base64Codec()); b << _username << ':' << _password; b.terminate(); log_debug("set Authorization to " << d.str()); _stream << "Authorization: Basic " << d.str() << "\r\n"; } _stream << "\r\n"; log_debug("send body; " << request.bodySize() << " bytes"); request.sendBody(_stream); } void ClientImpl::onConnect(net::TcpSocket& socket) { try { log_trace("onConnect"); socket.endConnect(); sendRequest(*_request); log_debug("request sent - begin write"); _stream.buffer().beginWrite(); } catch (const std::exception& e) { _client->errorOccured(*_client, e); } } void ClientImpl::onErrorOccured(IODevice& socket) { try { throw IOError( CXXTOOLS_ERROR_MSG("error occured in i/o-device") ); } catch (const IOError& e) { _client->errorOccured(*_client, e); } } void ClientImpl::onOutput(StreamBuffer& sb) { log_trace("ClientImpl::onOutput; out_avail=" << sb.out_avail()); if( sb.out_avail() > 0 ) { sb.beginWrite(); } else { sb.beginRead(); _client->requestSent(*_client); _parser.reset(true); _readHeader = true; } } void ClientImpl::onInput(StreamBuffer& sb) { try { log_trace("ClientImpl::onInput; readHeader=" << _readHeader); if (_readHeader) { processHeaderAvailable(sb); } else { processBodyAvailable(sb); } } catch (const std::exception& e) { log_warn("error of type " << typeid(e).name() << " occured: " << e.what()); _socket.close(); // TODO propagate exception if signal errorOccured is not connected _client->errorOccured(*_client, e); } } void ClientImpl::processHeaderAvailable(StreamBuffer& sb) { _parser.advance(sb); if (_parser.fail()) throw std::runtime_error("http parser failed"); // TODO define exception class if( _parser.end() ) { _chunkedEncoding = _replyHeader.chunkedTransferEncoding(); _client->headerReceived(*_client); _readHeader = false; if (_chunkedEncoding) { log_debug("chunked transfer encoding used"); _chunkedIStream.reset(); if( sb.in_avail() > 0 ) { processBodyAvailable(sb); } else { sb.beginRead(); } } else { _contentLength = _replyHeader.contentLength(); log_debug("header received - content-length=" << _contentLength); if (_contentLength > 0) { if( sb.in_avail() > 0 ) { processBodyAvailable(sb); } else { sb.beginRead(); } } else { _client->replyFinished(*_client); } } } else { sb.beginRead(); } } void ClientImpl::processBodyAvailable(StreamBuffer& sb) { log_trace("processBodyAvailable"); if (_chunkedEncoding) { if (_chunkedIStream.rdbuf()->in_avail() > 0) { if (!_chunkedIStream.eod()) { log_debug("read chunked encoding body"); while (_chunkedIStream.rdbuf()->in_avail() > 0 && !_chunkedIStream.eod()) { log_debug("bodyAvailable"); _client->bodyAvailable(*_client); } log_debug("in_avail=" << _chunkedIStream.rdbuf()->in_avail() << " eod=" << _chunkedIStream.eod()); if (_chunkedIStream.eod()) { _parser.readHeader(); } } if (_chunkedIStream.eod() && sb.in_avail() > 0) { log_debug("read chunked encoding post headers"); _parser.advance(sb); if (_parser.fail()) throw std::runtime_error("http parser failed"); // TODO define exception class if( _parser.end() ) { log_debug("reply finished"); _client->replyFinished(*_client); } } } if (!_chunkedIStream.eod() || !_parser.end()) { log_debug("call beginRead"); sb.beginRead(); } } else { log_debug("content-length(pre)=" << _contentLength); while (_contentLength > 0 && sb.in_avail() > 0) { _contentLength -= _client->bodyAvailable(*_client); // TODO: may throw exception log_debug("content-length(post)=" << _contentLength); } if( _contentLength <= 0 ) { log_debug("reply finished"); _client->replyFinished(*_client); } else { sb.beginRead(); } } } } // namespace http } // namespace cxxtools <commit_msg>always close socket when keep alive is not enabled in the current request in httpclient<commit_after>/* * Copyright (C) 2009 by Marc Boris Duerner, Tommi Maekitalo * * 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. * * As a special exception, you may use this file as part of a free * software library without restriction. Specifically, if other files * instantiate templates or use macros or inline functions from this * file, or you compile this file and link it with other files to * produce an executable, this file does not by itself cause the * resulting executable to be covered by the GNU General Public * License. This exception does not however invalidate any other * reasons why the executable file might be covered by the GNU Library * General Public License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "clientimpl.h" #include <cxxtools/http/client.h> #include "parser.h" #include <cxxtools/ioerror.h> #include <cxxtools/textstream.h> #include <cxxtools/base64codec.h> #include <sstream> #include <cxxtools/log.h> log_define("cxxtools.http.client.impl") namespace cxxtools { namespace http { void ClientImpl::ParseEvent::onHttpReturn(unsigned ret, const std::string& text) { _replyHeader.httpReturn(ret, text); } ClientImpl::ClientImpl(Client* client) : _client(client) , _parseEvent(_replyHeader) , _parser(_parseEvent, true) , _request(0) , _stream(8192, true) , _readHeader(true) , _contentLength(0) , _chunkedEncoding(false) , _chunkedIStream(_stream.rdbuf()) { _stream.attachDevice(_socket); cxxtools::connect(_socket.connected, *this, &ClientImpl::onConnect); cxxtools::connect(_socket.errorOccured, *this, &ClientImpl::onErrorOccured); cxxtools::connect(_stream.buffer().outputReady, *this, &ClientImpl::onOutput); cxxtools::connect(_stream.buffer().inputReady, *this, &ClientImpl::onInput); } ClientImpl::ClientImpl(Client* client, const net::AddrInfo& addrinfo) : _client(client) , _parseEvent(_replyHeader) , _parser(_parseEvent, true) , _request(0) , _addrInfo(addrinfo) , _stream(8192, true) , _readHeader(true) , _contentLength(0) , _chunkedEncoding(false) , _chunkedIStream(_stream.rdbuf()) { _stream.attachDevice(_socket); cxxtools::connect(_socket.connected, *this, &ClientImpl::onConnect); cxxtools::connect(_socket.errorOccured, *this, &ClientImpl::onErrorOccured); cxxtools::connect(_stream.buffer().outputReady, *this, &ClientImpl::onOutput); cxxtools::connect(_stream.buffer().inputReady, *this, &ClientImpl::onInput); } ClientImpl::ClientImpl(Client* client, SelectorBase& selector, const net::AddrInfo& addrinfo) : _client(client) , _parseEvent(_replyHeader) , _parser(_parseEvent, true) , _request(0) , _addrInfo(addrinfo) , _stream(8192, true) , _readHeader(true) , _contentLength(0) , _chunkedEncoding(false) , _chunkedIStream(_stream.rdbuf()) { _stream.attachDevice(_socket); cxxtools::connect(_socket.connected, *this, &ClientImpl::onConnect); cxxtools::connect(_socket.errorOccured, *this, &ClientImpl::onErrorOccured); cxxtools::connect(_stream.buffer().outputReady, *this, &ClientImpl::onOutput); cxxtools::connect(_stream.buffer().inputReady, *this, &ClientImpl::onInput); setSelector(selector); } void ClientImpl::setSelector(SelectorBase& selector) { selector.add(_socket); } void ClientImpl::reexecute(const Request& request) { log_debug("reconnect"); _stream.clear(); _stream.buffer().discard(); _socket.connect(_addrInfo); sendRequest(request); _stream.flush(); } void ClientImpl::doparse() { char ch; while (!_parser.end() && _stream.get(ch)) _parser.parse(ch); } const ReplyHeader& ClientImpl::execute(const Request& request, std::size_t timeout) { log_trace("execute request " << request.url()); _replyHeader.clear(); _socket.setTimeout(timeout); bool shouldReconnect = _socket.isConnected(); if (!shouldReconnect) { log_debug("connect"); _socket.connect(_addrInfo); } log_debug("send request"); sendRequest(request); log_debug("flush stream"); _stream.flush(); log_debug("flush stream ready"); if (!_stream && shouldReconnect) { // sending failed and we were not connected before, so try again reexecute(request); shouldReconnect = false; } if (!_stream) throw IOError( CXXTOOLS_ERROR_MSG("error sending HTTP request") ); log_debug("read reply"); _parser.reset(true); _readHeader = true; doparse(); if (_parser.begin() && shouldReconnect) { // reading failed and we were not connected before, so try again reexecute(request); if (!_stream) throw IOError( CXXTOOLS_ERROR_MSG("error sending HTTP request") ); doparse(); } log_debug("reply ready"); if (_stream.fail()) throw IOError( CXXTOOLS_ERROR_MSG("failed to read HTTP reply") ); if (_parser.fail()) throw IOError( CXXTOOLS_ERROR_MSG("invalid HTTP reply") ); if (!_parser.end()) throw IOError( CXXTOOLS_ERROR_MSG("incomplete HTTP reply header") ); return _replyHeader; } void ClientImpl::readBody(std::string& s) { s.clear(); _chunkedEncoding = _replyHeader.chunkedTransferEncoding(); _chunkedIStream.reset(); if (_chunkedEncoding) { log_debug("read body with chunked encoding"); char ch; while (_chunkedIStream.get(ch)) s += ch; log_debug("eod=" << _chunkedIStream.eod()); if (_chunkedIStream.eod()) { _parser.readHeader(); doparse(); if (_parser.fail()) throw std::runtime_error("http parser failed"); // TODO define exception class } else throw std::runtime_error("chunked stream not complete"); } else { unsigned n = _replyHeader.contentLength(); log_debug("read body; content-size: " << n); s.reserve(n); char ch; while (n-- && _stream.get(ch)) s += ch; if (_stream.fail()) throw IOError( CXXTOOLS_ERROR_MSG("error reading HTTP reply body") ); //log_debug("body read: \"" << s << '"'); } if (!_replyHeader.keepAlive()) { log_debug("close socket - no keep alive"); _socket.close(); } else { log_debug("do not close socket - keep alive"); } } std::string ClientImpl::get(const std::string& url, std::size_t timeout) { Request request(url); execute(request, timeout); return readBody(); } void ClientImpl::beginExecute(const Request& request) { log_trace("beginExecute"); _request = &request; _replyHeader.clear(); if (_socket.isConnected()) { log_debug("we are connected already"); sendRequest(*_request); try { _stream.buffer().beginWrite(); } catch (const cxxtools::IOError&) { log_debug("first write failed, so connection is not active any more"); _stream.clear(); _stream.buffer().discard(); _socket.beginConnect(_addrInfo); } } else { log_debug("not yet connected - do it now"); _socket.beginConnect(_addrInfo); } } void ClientImpl::wait(std::size_t msecs) { _socket.wait(msecs); } void ClientImpl::sendRequest(const Request& request) { log_debug("send request " << request.url()); static const std::string contentLength = "Content-Length"; static const std::string connection = "Connection"; static const std::string date = "Date"; static const std::string host = "Host"; static const std::string authorization = "Authorization"; _stream << request.method() << ' ' << request.url() << " HTTP/" << request.header().httpVersionMajor() << '.' << request.header().httpVersionMinor() << "\r\n"; for (RequestHeader::const_iterator it = request.header().begin(); it != request.header().end(); ++it) { _stream << it->first << ": " << it->second << "\r\n"; } if (!request.header().hasHeader(contentLength)) { _stream << "Content-Length: " << request.bodySize() << "\r\n"; } if (!request.header().hasHeader(connection)) { _stream << "Connection: keep-alive\r\n"; } if (!request.header().hasHeader(date)) { _stream << "Date: " << MessageHeader::htdateCurrent() << "\r\n"; } if (!request.header().hasHeader(host)) { _stream << "Host: " << _addrInfo.host(); unsigned short port = _addrInfo.port(); if (port != 80) _stream << ':' << port; _stream << "\r\n"; } if (!_username.empty() && !request.header().hasHeader(authorization)) { std::ostringstream d; BasicTextOStream<char, char> b(d, new Base64Codec()); b << _username << ':' << _password; b.terminate(); log_debug("set Authorization to " << d.str()); _stream << "Authorization: Basic " << d.str() << "\r\n"; } _stream << "\r\n"; log_debug("send body; " << request.bodySize() << " bytes"); request.sendBody(_stream); } void ClientImpl::onConnect(net::TcpSocket& socket) { try { log_trace("onConnect"); socket.endConnect(); sendRequest(*_request); log_debug("request sent - begin write"); _stream.buffer().beginWrite(); } catch (const std::exception& e) { log_debug("error occured"); _socket.close(); if (_client->errorOccured.connectionCount() == 0) throw; _client->errorOccured(*_client, e); } } void ClientImpl::onErrorOccured(IODevice& socket) { log_trace("error occured"); try { throw IOError( CXXTOOLS_ERROR_MSG("error occured in i/o-device") ); } catch (const IOError& e) { _socket.close(); if (_client->errorOccured.connectionCount() == 0) throw; _client->errorOccured(*_client, e); } } void ClientImpl::onOutput(StreamBuffer& sb) { log_trace("ClientImpl::onOutput; out_avail=" << sb.out_avail()); if( sb.out_avail() > 0 ) { sb.beginWrite(); } else { sb.beginRead(); _client->requestSent(*_client); _parser.reset(true); _readHeader = true; } } void ClientImpl::onInput(StreamBuffer& sb) { try { log_trace("ClientImpl::onInput; readHeader=" << _readHeader); if (_readHeader) { processHeaderAvailable(sb); } else { processBodyAvailable(sb); } } catch (const std::exception& e) { log_warn("error of type " << typeid(e).name() << " occured: " << e.what()); _socket.close(); if (_client->errorOccured.connectionCount() == 0) throw; _client->errorOccured(*_client, e); } } void ClientImpl::processHeaderAvailable(StreamBuffer& sb) { _parser.advance(sb); if (_parser.fail()) throw std::runtime_error("http parser failed"); // TODO define exception class if( _parser.end() ) { _chunkedEncoding = _replyHeader.chunkedTransferEncoding(); _client->headerReceived(*_client); _readHeader = false; if (_chunkedEncoding) { log_debug("chunked transfer encoding used"); _chunkedIStream.reset(); if( sb.in_avail() > 0 ) { processBodyAvailable(sb); } else { sb.beginRead(); } } else { _contentLength = _replyHeader.contentLength(); log_debug("header received - content-length=" << _contentLength); if (_contentLength > 0) { if( sb.in_avail() > 0 ) { processBodyAvailable(sb); } else { sb.beginRead(); } } else { if (!_replyHeader.keepAlive()) { log_debug("close socket - no keep alive"); _socket.close(); } _client->replyFinished(*_client); } } } else { sb.beginRead(); } } void ClientImpl::processBodyAvailable(StreamBuffer& sb) { log_trace("processBodyAvailable"); if (_chunkedEncoding) { if (_chunkedIStream.rdbuf()->in_avail() > 0) { if (!_chunkedIStream.eod()) { log_debug("read chunked encoding body"); while (_chunkedIStream.rdbuf()->in_avail() > 0 && !_chunkedIStream.eod()) { log_debug("bodyAvailable"); _client->bodyAvailable(*_client); } log_debug("in_avail=" << _chunkedIStream.rdbuf()->in_avail() << " eod=" << _chunkedIStream.eod()); if (_chunkedIStream.eod()) { _parser.readHeader(); } } if (_chunkedIStream.eod() && sb.in_avail() > 0) { log_debug("read chunked encoding post headers"); _parser.advance(sb); if (_parser.fail()) throw std::runtime_error("http parser failed"); // TODO define exception class if( _parser.end() ) { log_debug("reply finished"); if (!_replyHeader.keepAlive()) { log_debug("close socket - no keep alive"); _socket.close(); } _client->replyFinished(*_client); } } } if (!_chunkedIStream.eod() || !_parser.end()) { log_debug("call beginRead"); sb.beginRead(); } } else { log_debug("content-length(pre)=" << _contentLength); while (_contentLength > 0 && sb.in_avail() > 0) { _contentLength -= _client->bodyAvailable(*_client); // TODO: may throw exception log_debug("content-length(post)=" << _contentLength); } if( _contentLength <= 0 ) { log_debug("reply finished"); if (!_replyHeader.keepAlive()) { log_debug("close socket - no keep alive"); _socket.close(); } _client->replyFinished(*_client); } else { sb.beginRead(); } } } } // namespace http } // namespace cxxtools <|endoftext|>
<commit_before>// -*- coding: us-ascii-unix -*- // Copyright 2013 Lukas Kemmer // // 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. #ifndef FAINT_LAYOUT_WX_HH #define FAINT_LAYOUT_WX_HH #include <vector> #include "gui/ui-constants.hh" #include "util/distinct.hh" class wxBoxSizer; class wxButton; class wxDialog; class wxSizer; class wxStaticText; class wxString; class wxTextCtrl; class wxWindow; namespace faint{ namespace layout{ class category_layout_wx; using Proportion = Distinct<int, category_layout_wx, 0>; extern const int EXPAND; extern const int DOWN; extern const int UP; extern const int ALIGN_RIGHT; class SizerItem{ public: SizerItem(wxWindow*, Proportion, int flags, int border=0); SizerItem(wxSizer*, Proportion, int flags, int border=0); SizerItem(wxWindow*); SizerItem(wxButton*); SizerItem(wxButton*, int flags); SizerItem(wxStaticText*); SizerItem(wxSizer*); int border = 0; int flags = 0; Proportion proportion = Proportion(0); wxSizer* sizerItem = nullptr; wxWindow* windowItem = nullptr; }; // Adds the item to the sizer. // Note: Prefer using create_row etc. bool add(wxBoxSizer*, const SizerItem&); wxSizer* create_row(const std::vector<SizerItem>&); wxSizer* create_row(OuterSpacing, ItemSpacing, const std::vector<SizerItem>&); wxSizer* create_row_outer_pad(const std::vector<SizerItem>&); wxSizer* create_row_no_pad(const std::vector<SizerItem>&); wxSizer* create_column(OuterSpacing, ItemSpacing, const std::vector<SizerItem>&); wxSizer* create_column(const std::vector<SizerItem>&); // Sets wxEXPAND (Fixme: Document) SizerItem grow(wxSizer*); SizerItem grow(wxWindow*); SizerItem center(wxSizer*); wxButton* make_default(wxDialog*, wxButton*); wxStaticText* label(wxWindow* parent, const wxString&); // Sets the focus to the passed in window, and returns it, to allow // chaining in create_row etc. template<typename T> T* focused(T* obj){ obj->SetFocus(); return obj; } }} // Namespace #endif <commit_msg>Casing.<commit_after>// -*- coding: us-ascii-unix -*- // Copyright 2013 Lukas Kemmer // // 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. #ifndef FAINT_LAYOUT_WX_HH #define FAINT_LAYOUT_WX_HH #include <vector> #include "gui/ui-constants.hh" #include "util/distinct.hh" class wxBoxSizer; class wxButton; class wxDialog; class wxSizer; class wxStaticText; class wxString; class wxTextCtrl; class wxWindow; namespace faint{ namespace layout{ class category_layout_wx; using Proportion = Distinct<int, category_layout_wx, 0>; extern const int EXPAND; extern const int DOWN; extern const int UP; extern const int ALIGN_RIGHT; class SizerItem{ public: SizerItem(wxWindow*, Proportion, int flags, int border=0); SizerItem(wxSizer*, Proportion, int flags, int border=0); SizerItem(wxWindow*); SizerItem(wxButton*); SizerItem(wxButton*, int flags); SizerItem(wxStaticText*); SizerItem(wxSizer*); int border = 0; int flags = 0; Proportion proportion = Proportion(0); wxSizer* sizerItem = nullptr; wxWindow* windowItem = nullptr; }; // Adds the item to the sizer. // Note: Prefer using create_row etc. bool add(wxBoxSizer*, const SizerItem&); wxSizer* create_row(const std::vector<SizerItem>&); wxSizer* create_row(OuterSpacing, ItemSpacing, const std::vector<SizerItem>&); wxSizer* create_row_outer_pad(const std::vector<SizerItem>&); wxSizer* create_row_no_pad(const std::vector<SizerItem>&); wxSizer* create_column(OuterSpacing, ItemSpacing, const std::vector<SizerItem>&); wxSizer* create_column(const std::vector<SizerItem>&); // Sets wxEXPAND (Fixme: Document) SizerItem grow(wxSizer*); SizerItem grow(wxWindow*); SizerItem center(wxSizer*); wxButton* make_default(wxDialog*, wxButton*); wxStaticText* label(wxWindow* parent, const wxString&); // Sets the focus to the passed in window, and returns it, to allow // chaining in create_row etc. template<typename T> T* focused(T* obj){ obj->SetFocus(); return obj; } }} // namespace #endif <|endoftext|>
<commit_before><commit_msg>Piping now working for xml, phylip and binary cases.<commit_after><|endoftext|>
<commit_before>/* * Copyright (C) 2003, 2006, 2007 Apple Inc. All rights reserved. * Copyright (C) 2007-2009 Torch Mobile, Inc. * Copyright (C) 2011 University of Szeged. 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 APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 vprintf_stderr_common function triggers this error in the Mac build. // Feel free to remove this pragma if this file builds on Mac. // According to http://gcc.gnu.org/onlinedocs/gcc-4.2.1/gcc/Diagnostic-Pragmas.html#Diagnostic-Pragmas // we need to place this directive before any data or functions are defined. #pragma GCC diagnostic ignored "-Wmissing-format-attribute" #include "sky/engine/wtf/Assertions.h" #include "sky/engine/wtf/Compiler.h" #include "sky/engine/wtf/OwnPtr.h" #include "sky/engine/wtf/PassOwnPtr.h" #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #if HAVE(SIGNAL_H) #include <signal.h> #endif #if (OS(LINUX) && !defined(__UCLIBC__) && !defined(FNL_MUSL)) #include <cxxabi.h> #include <dlfcn.h> #include <execinfo.h> #endif #if OS(ANDROID) #include <android/log.h> #endif #include "base/debug/stack_trace.h" extern "C" { WTF_ATTRIBUTE_PRINTF(1, 0) static void vprintf_stderr_common(const char* format, va_list args) { #if OS(ANDROID) __android_log_vprint(ANDROID_LOG_WARN, "WebKit", format, args); #endif vfprintf(stderr, format, args); } #if COMPILER(CLANG) || COMPILER(GCC) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wformat-nonliteral" #endif static void vprintf_stderr_with_prefix(const char* prefix, const char* format, va_list args) { size_t prefixLength = strlen(prefix); size_t formatLength = strlen(format); OwnPtr<char[]> formatWithPrefix = adoptArrayPtr(new char[prefixLength + formatLength + 1]); memcpy(formatWithPrefix.get(), prefix, prefixLength); memcpy(formatWithPrefix.get() + prefixLength, format, formatLength); formatWithPrefix[prefixLength + formatLength] = 0; vprintf_stderr_common(formatWithPrefix.get(), args); } static void vprintf_stderr_with_trailing_newline(const char* format, va_list args) { size_t formatLength = strlen(format); if (formatLength && format[formatLength - 1] == '\n') { vprintf_stderr_common(format, args); return; } OwnPtr<char[]> formatWithNewline = adoptArrayPtr(new char[formatLength + 2]); memcpy(formatWithNewline.get(), format, formatLength); formatWithNewline[formatLength] = '\n'; formatWithNewline[formatLength + 1] = 0; vprintf_stderr_common(formatWithNewline.get(), args); } #if COMPILER(CLANG) || COMPILER(GCC) #pragma GCC diagnostic pop #endif WTF_ATTRIBUTE_PRINTF(1, 2) static void printf_stderr_common(const char* format, ...) { va_list args; va_start(args, format); vprintf_stderr_common(format, args); va_end(args); } static void printCallSite(const char* file, int line, const char* function) { // By using this format, which matches the format used by MSVC for compiler errors, developers // using Visual Studio can double-click the file/line number in the Output Window to have the // editor navigate to that line of code. It seems fine for other developers, too. printf_stderr_common("%s(%d) : %s\n", file, line, function); } void WTFReportAssertionFailure(const char* file, int line, const char* function, const char* assertion) { if (assertion) printf_stderr_common("ASSERTION FAILED: %s\n", assertion); else printf_stderr_common("SHOULD NEVER BE REACHED\n"); printCallSite(file, line, function); } void WTFReportAssertionFailureWithMessage(const char* file, int line, const char* function, const char* assertion, const char* format, ...) { va_list args; va_start(args, format); vprintf_stderr_with_prefix("ASSERTION FAILED: ", format, args); va_end(args); printf_stderr_common("\n%s\n", assertion); printCallSite(file, line, function); } void WTFReportArgumentAssertionFailure(const char* file, int line, const char* function, const char* argName, const char* assertion) { printf_stderr_common("ARGUMENT BAD: %s, %s\n", argName, assertion); printCallSite(file, line, function); } void WTFReportBacktrace() { base::debug::StackTrace().Print(); } void WTFReportFatalError(const char* file, int line, const char* function, const char* format, ...) { va_list args; va_start(args, format); vprintf_stderr_with_prefix("FATAL ERROR: ", format, args); va_end(args); printf_stderr_common("\n"); printCallSite(file, line, function); } void WTFReportError(const char* file, int line, const char* function, const char* format, ...) { va_list args; va_start(args, format); vprintf_stderr_with_prefix("ERROR: ", format, args); va_end(args); printf_stderr_common("\n"); printCallSite(file, line, function); } void WTFLog(WTFLogChannel* channel, const char* format, ...) { if (channel->state != WTFLogChannelOn) return; va_list args; va_start(args, format); vprintf_stderr_with_trailing_newline(format, args); va_end(args); } void WTFLogVerbose(const char* file, int line, const char* function, WTFLogChannel* channel, const char* format, ...) { if (channel->state != WTFLogChannelOn) return; va_list args; va_start(args, format); vprintf_stderr_with_trailing_newline(format, args); va_end(args); printCallSite(file, line, function); } void WTFLogAlways(const char* format, ...) { va_list args; va_start(args, format); vprintf_stderr_with_trailing_newline(format, args); va_end(args); } } // extern "C" <commit_msg>Update ASSERTS in flutter engine to use flutter<commit_after>/* * Copyright (C) 2003, 2006, 2007 Apple Inc. All rights reserved. * Copyright (C) 2007-2009 Torch Mobile, Inc. * Copyright (C) 2011 University of Szeged. 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 APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 vprintf_stderr_common function triggers this error in the Mac build. // Feel free to remove this pragma if this file builds on Mac. // According to http://gcc.gnu.org/onlinedocs/gcc-4.2.1/gcc/Diagnostic-Pragmas.html#Diagnostic-Pragmas // we need to place this directive before any data or functions are defined. #pragma GCC diagnostic ignored "-Wmissing-format-attribute" #include "sky/engine/wtf/Assertions.h" #include "sky/engine/wtf/Compiler.h" #include "sky/engine/wtf/OwnPtr.h" #include "sky/engine/wtf/PassOwnPtr.h" #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #if HAVE(SIGNAL_H) #include <signal.h> #endif #if (OS(LINUX) && !defined(__UCLIBC__) && !defined(FNL_MUSL)) #include <cxxabi.h> #include <dlfcn.h> #include <execinfo.h> #endif #if OS(ANDROID) #include <android/log.h> #endif #include "base/debug/stack_trace.h" extern "C" { WTF_ATTRIBUTE_PRINTF(1, 0) static void vprintf_stderr_common(const char* format, va_list args) { #if OS(ANDROID) __android_log_vprint(ANDROID_LOG_WARN, "flutter", format, args); #endif vfprintf(stderr, format, args); } #if COMPILER(CLANG) || COMPILER(GCC) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wformat-nonliteral" #endif static void vprintf_stderr_with_prefix(const char* prefix, const char* format, va_list args) { size_t prefixLength = strlen(prefix); size_t formatLength = strlen(format); OwnPtr<char[]> formatWithPrefix = adoptArrayPtr(new char[prefixLength + formatLength + 1]); memcpy(formatWithPrefix.get(), prefix, prefixLength); memcpy(formatWithPrefix.get() + prefixLength, format, formatLength); formatWithPrefix[prefixLength + formatLength] = 0; vprintf_stderr_common(formatWithPrefix.get(), args); } static void vprintf_stderr_with_trailing_newline(const char* format, va_list args) { size_t formatLength = strlen(format); if (formatLength && format[formatLength - 1] == '\n') { vprintf_stderr_common(format, args); return; } OwnPtr<char[]> formatWithNewline = adoptArrayPtr(new char[formatLength + 2]); memcpy(formatWithNewline.get(), format, formatLength); formatWithNewline[formatLength] = '\n'; formatWithNewline[formatLength + 1] = 0; vprintf_stderr_common(formatWithNewline.get(), args); } #if COMPILER(CLANG) || COMPILER(GCC) #pragma GCC diagnostic pop #endif WTF_ATTRIBUTE_PRINTF(1, 2) static void printf_stderr_common(const char* format, ...) { va_list args; va_start(args, format); vprintf_stderr_common(format, args); va_end(args); } static void printCallSite(const char* file, int line, const char* function) { // By using this format, which matches the format used by MSVC for compiler errors, developers // using Visual Studio can double-click the file/line number in the Output Window to have the // editor navigate to that line of code. It seems fine for other developers, too. printf_stderr_common("%s(%d) : %s\n", file, line, function); } void WTFReportAssertionFailure(const char* file, int line, const char* function, const char* assertion) { if (assertion) printf_stderr_common("ASSERTION FAILED: %s\n", assertion); else printf_stderr_common("SHOULD NEVER BE REACHED\n"); printCallSite(file, line, function); } void WTFReportAssertionFailureWithMessage(const char* file, int line, const char* function, const char* assertion, const char* format, ...) { va_list args; va_start(args, format); vprintf_stderr_with_prefix("ASSERTION FAILED: ", format, args); va_end(args); printf_stderr_common("\n%s\n", assertion); printCallSite(file, line, function); } void WTFReportArgumentAssertionFailure(const char* file, int line, const char* function, const char* argName, const char* assertion) { printf_stderr_common("ARGUMENT BAD: %s, %s\n", argName, assertion); printCallSite(file, line, function); } void WTFReportBacktrace() { base::debug::StackTrace().Print(); } void WTFReportFatalError(const char* file, int line, const char* function, const char* format, ...) { va_list args; va_start(args, format); vprintf_stderr_with_prefix("FATAL ERROR: ", format, args); va_end(args); printf_stderr_common("\n"); printCallSite(file, line, function); } void WTFReportError(const char* file, int line, const char* function, const char* format, ...) { va_list args; va_start(args, format); vprintf_stderr_with_prefix("ERROR: ", format, args); va_end(args); printf_stderr_common("\n"); printCallSite(file, line, function); } void WTFLog(WTFLogChannel* channel, const char* format, ...) { if (channel->state != WTFLogChannelOn) return; va_list args; va_start(args, format); vprintf_stderr_with_trailing_newline(format, args); va_end(args); } void WTFLogVerbose(const char* file, int line, const char* function, WTFLogChannel* channel, const char* format, ...) { if (channel->state != WTFLogChannelOn) return; va_list args; va_start(args, format); vprintf_stderr_with_trailing_newline(format, args); va_end(args); printCallSite(file, line, function); } void WTFLogAlways(const char* format, ...) { va_list args; va_start(args, format); vprintf_stderr_with_trailing_newline(format, args); va_end(args); } } // extern "C" <|endoftext|>
<commit_before>#include "alert.h" using namespace Alert; Warning::Warning(time_t detect_time, int angle, std::map<int, int> sensor_readings, std::vector<int> triggered_sensors) : detect_time(detect_time), angle(angle*M_PI/180.0), sensor_readings(sensor_readings), triggered_sensors(triggered_sensors) {} void Warning::set(time_t detect_time, std::map<int, int> sensor_readings, std::vector<int> triggered_sensors) { this->detect_time = detect_time; this->sensor_readings = sensor_readings; this->triggered_sensors = triggered_sensors; } double Warning::calculate_v_distance(int sensor) { if (sensor != hip) { return -1; } else { int distance = sensor_readings[sensor]; double vertical_dist = (double) (sin(angle) * distance); return vertical_dist; } } double Warning::calculate_h_distance(int sensor) { int distance = sensor_readings[sensor]; double horizontal_dist = (double) (sin(angle) * distance); return horizontal_dist; } void Warning::add_triggered_sensor(int sensor) { if(std::find(triggered_sensors.begin(), triggered_sensors.end(), sensor) == triggered_sensors.end()) { triggered_sensors.push_back(sensor); } } void Warning::remove_triggered_sensor(int sensor) { for(std::vector<int>::iterator i = triggered_sensors.begin(); i < triggered_sensors.end(); i++) { if(*i == sensor) { triggered_sensors.erase(i); } } } void Warning::print_warning() { std::cout << "**Warning**\n" << "Time: " << detect_time << std::endl; std::cout << "Sensor: Distance:" << std::endl; for(std::map<int, int>::iterator it = sensor_readings.begin(); it != sensor_readings.end(); it++) { switch(it->first) { case 0: // head left std::cout << "Head Left " << it->second << std::endl; break; case 1: // head right std::cout << "Head Right " << it->second << std::endl; break; case 2: // hip std::cout << "Hip " << it->second << std::endl; break; default: break; } } std::cout << std::endl; } time_t Warning::get_time() { return detect_time; } int Warning::get_distance(int sensor) { return sensor_readings[sensor]; } std::vector<int> Warning::get_triggered_sensors() { return triggered_sensors; }<commit_msg>Delete alert.cpp<commit_after><|endoftext|>
<commit_before>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2010, Rice University * 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 Rice University nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ /* Author: Ioan Sucan */ #define BOOST_TEST_MODULE "State" #include <boost/test/unit_test.hpp> #include <boost/thread.hpp> #include <iostream> #include "ompl/base/ScopedState.h" #include "ompl/base/spaces/SE3StateSpace.h" #include "ompl/base/SpaceInformation.h" #include "ompl/util/Time.h" #include "../BoostTestTeamCityReporter.h" using namespace ompl; // define a convenience macro #define BOOST_OMPL_EXPECT_NEAR(a, b, diff) BOOST_CHECK_SMALL((a) - (b), diff) BOOST_AUTO_TEST_CASE(Scoped) { base::SE3StateSpace *mSE3 = new base::SE3StateSpace(); base::StateSpacePtr pSE3(mSE3); base::RealVectorBounds b(3); b.setLow(0); b.setHigh(1); mSE3->setBounds(b); mSE3->setup(); base::CompoundStateSpace *mC0 = new base::CompoundStateSpace(); base::StateSpacePtr pC0(mC0); mC0->addSubspace(pSE3, 1.0); mC0->setup(); base::CompoundStateSpace *mC1 = new base::CompoundStateSpace(); base::StateSpacePtr pC1(mC1); mC1->addSubspace(pC0, 1.0); mC1->setup(); base::CompoundStateSpace *mC2 = new base::CompoundStateSpace(); base::StateSpacePtr pC2(mC2); mC2->addSubspace(mSE3->getSubspace(1), 1.0); mC2->addSubspace(mSE3->getSubspace(0), 1.0); mC2->setup(); base::ScopedState<base::SE3StateSpace> sSE3(pSE3); base::ScopedState<base::RealVectorStateSpace> sSE3_R(mSE3->getSubspace(0)); base::ScopedState<base::SO3StateSpace> sSE3_SO2(mSE3->getSubspace(1)); base::ScopedState<base::CompoundStateSpace> sC0(pC0); base::ScopedState<> sC1(pC1); base::ScopedState<> sC2(pC2); sSE3.random(); sSE3 >> sSE3_SO2; BOOST_CHECK_EQUAL(sSE3->rotation().x, sSE3_SO2->x); BOOST_CHECK_EQUAL(sSE3->rotation().y, sSE3_SO2->y); BOOST_CHECK_EQUAL(sSE3->rotation().z, sSE3_SO2->z); BOOST_CHECK_EQUAL(sSE3->rotation().w, sSE3_SO2->w); base::ScopedState<> sSE3_copy(pSE3); sSE3_copy << sSE3; BOOST_CHECK_EQUAL(sSE3_copy, sSE3); sSE3 >> sSE3_copy; BOOST_CHECK_EQUAL(sSE3_copy, sSE3); sSE3_R << sSE3_copy; BOOST_CHECK_EQUAL(sSE3->getX(), sSE3_R->values[0]); BOOST_CHECK_EQUAL(sSE3->getY(), sSE3_R->values[1]); BOOST_CHECK_EQUAL(sSE3->getZ(), sSE3_R->values[2]); sSE3_SO2 >> sC1; sC1 << sSE3_R; sC1 >> sC0; sSE3_copy = sC0->components[0]; BOOST_CHECK_EQUAL(sSE3_copy, sSE3); sSE3.random(); sSE3 >> sC2; sSE3_copy << sC2; BOOST_CHECK_EQUAL(sSE3_copy, sSE3); sSE3.random(); sSE3 >> sSE3_SO2; sSE3 >> sSE3_R; (sSE3_R ^ sSE3_SO2) >> sSE3_copy; BOOST_CHECK_EQUAL(sSE3_copy, sSE3); BOOST_CHECK_EQUAL(sSE3_copy[pSE3 * sSE3_R.getSpace()], sSE3_R); BOOST_CHECK_EQUAL(sSE3_copy[sSE3_SO2.getSpace()], sSE3_SO2); sSE3->setY(1.0); BOOST_OMPL_EXPECT_NEAR(sSE3.reals()[1], 1.0, 1e-12); BOOST_OMPL_EXPECT_NEAR(sSE3[1], 1.0, 1e-12); sSE3[2] = 0.1; BOOST_OMPL_EXPECT_NEAR(sSE3.reals()[2], 0.1, 1e-12); sSE3.random(); std::vector<double> r = sSE3.reals(); BOOST_CHECK_EQUAL(r.size(), 7u); sSE3_copy = r; BOOST_CHECK_EQUAL(sSE3_copy, sSE3); BOOST_CHECK_EQUAL(sSE3[6], r[6]); BOOST_CHECK_EQUAL(sSE3[0], r[0]); BOOST_CHECK_EQUAL(sSE3.getSpace()->getValueAddressAtIndex(sSE3.get(), 7), (double*)NULL); sSE3_R = 0.5; BOOST_CHECK_EQUAL(sSE3_R[0], 0.5); sSE3 << sSE3_R; pSE3->setName("test"); BOOST_CHECK_EQUAL(sSE3["test"], 0.5); sSE3["test"] = 0.1; BOOST_CHECK_EQUAL(sSE3[0], 0.1); } BOOST_AUTO_TEST_CASE(ScopedRV) { base::StateSpacePtr m(new base::RealVectorStateSpace(2)); base::ScopedState<base::RealVectorStateSpace> s1(m); s1->values[0] = 1.0; s1->values[1] = 2.0; base::ScopedState<base::RealVectorStateSpace> s2 = s1; BOOST_CHECK(s2->values[1] == s1->values[1]); base::ScopedState<> s3(m); s3 = s1; base::ScopedState<> s4 = s3; BOOST_CHECK(s4 == s3); BOOST_CHECK(s4 == s1); base::ScopedState<base::RealVectorStateSpace> s5 = s2; BOOST_CHECK(s5 == s1); s1->values[1] = 4.0; BOOST_CHECK(s5 != s1); base::ScopedState<base::RealVectorStateSpace> s6(s5); BOOST_CHECK(s6 != s1); s1 = s5; s5 = s1; BOOST_CHECK(s6 == s1); } BOOST_AUTO_TEST_CASE(Allocation) { base::StateSpacePtr m(new base::SE3StateSpace()); base::RealVectorBounds b(3); b.setLow(0); b.setHigh(1); m->as<base::SE3StateSpace>()->setBounds(b); base::SpaceInformation si(m); si.setup(); const unsigned int N = 30000; const unsigned int M = 20; std::vector<base::State*> states(N, NULL); ompl::time::point start = ompl::time::now(); for (unsigned int j = 0 ; j < M ; ++j) { for (unsigned int i = 0 ; i < N ; ++i) states[i] = si.allocState(); for (unsigned int i = 0 ; i < N ; ++i) si.freeState(states[i]); } double d = ompl::time::seconds(ompl::time::now() - start); std::cout << (double)N * (double)M / d << " state allocations then frees per second" << std::endl; start = ompl::time::now(); for (unsigned int j = 0 ; j < M ; ++j) { for (unsigned int i = 0 ; i < N ; ++i) { base::State *s = si.allocState(); si.freeState(s); } } d = ompl::time::seconds(ompl::time::now() - start); std::cout << (double)N * (double)M / d << " mixed state allocations & frees per second" << std::endl; start = ompl::time::now(); for (unsigned int j = 0 ; j < M ; ++j) { for (unsigned int i = 0 ; i < N ; ++i) { base::State *s = si.allocState(); si.freeState(s); states[i] = si.allocState(); } for (unsigned int i = 0 ; i < N ; ++i) si.freeState(states[i]); } d = ompl::time::seconds(ompl::time::now() - start); std::cout << (double)N * (double)M / d << " allocations per second" << std::endl; } void randomizedAllocator(const base::SpaceInformation *si) { RNG r; const unsigned int n = 500; std::vector<base::State*> states(n + 1, NULL); for (unsigned int i = 0 ; i < n * 1000 ; ++i) { int j = r.uniformInt(0, n); if (states[j] == NULL) states[j] = si->allocState(); else { si->freeState(states[j]); states[j] = NULL; } } for (unsigned int i = 0 ; i < states.size() ; ++i) if (states[i]) si->freeState(states[i]); } BOOST_AUTO_TEST_CASE(AllocationWithThreads) { base::StateSpacePtr m(new base::SE3StateSpace()); base::RealVectorBounds b(3); b.setLow(0); b.setHigh(1); m->as<base::SE3StateSpace>()->setBounds(b); base::SpaceInformation si(m); si.setup(); const int NT = 10; ompl::time::point start = ompl::time::now(); std::vector<boost::thread*> threads; for (int i = 0 ; i < NT ; ++i) threads.push_back(new boost::thread(boost::bind(&randomizedAllocator, &si))); for (int i = 0 ; i < NT ; ++i) { threads[i]->join(); delete threads[i]; } std::cout << "Time spent randomly allocating & freeing states: " << ompl::time::seconds(ompl::time::now() - start) << std::endl; } <commit_msg>adding test for partial copy & sampling<commit_after>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2010, Rice University * 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 Rice University nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ /* Author: Ioan Sucan */ #define BOOST_TEST_MODULE "State" #include <boost/test/unit_test.hpp> #include <boost/thread.hpp> #include <iostream> #include "ompl/base/ScopedState.h" #include "ompl/base/spaces/SE3StateSpace.h" #include "ompl/base/SpaceInformation.h" #include "ompl/util/Time.h" #include "../BoostTestTeamCityReporter.h" using namespace ompl; // define a convenience macro #define BOOST_OMPL_EXPECT_NEAR(a, b, diff) BOOST_CHECK_SMALL((a) - (b), diff) BOOST_AUTO_TEST_CASE(Scoped) { base::SE3StateSpace *mSE3 = new base::SE3StateSpace(); base::StateSpacePtr pSE3(mSE3); base::RealVectorBounds b(3); b.setLow(0); b.setHigh(1); mSE3->setBounds(b); mSE3->setup(); base::CompoundStateSpace *mC0 = new base::CompoundStateSpace(); base::StateSpacePtr pC0(mC0); mC0->addSubspace(pSE3, 1.0); mC0->setup(); base::CompoundStateSpace *mC1 = new base::CompoundStateSpace(); base::StateSpacePtr pC1(mC1); mC1->addSubspace(pC0, 1.0); mC1->setup(); base::CompoundStateSpace *mC2 = new base::CompoundStateSpace(); base::StateSpacePtr pC2(mC2); mC2->addSubspace(mSE3->getSubspace(1), 1.0); mC2->addSubspace(mSE3->getSubspace(0), 1.0); mC2->setup(); base::ScopedState<base::SE3StateSpace> sSE3(pSE3); base::ScopedState<base::RealVectorStateSpace> sSE3_R(mSE3->getSubspace(0)); base::ScopedState<base::SO3StateSpace> sSE3_SO2(mSE3->getSubspace(1)); base::ScopedState<base::CompoundStateSpace> sC0(pC0); base::ScopedState<> sC1(pC1); base::ScopedState<> sC2(pC2); sSE3.random(); sSE3 >> sSE3_SO2; BOOST_CHECK_EQUAL(sSE3->rotation().x, sSE3_SO2->x); BOOST_CHECK_EQUAL(sSE3->rotation().y, sSE3_SO2->y); BOOST_CHECK_EQUAL(sSE3->rotation().z, sSE3_SO2->z); BOOST_CHECK_EQUAL(sSE3->rotation().w, sSE3_SO2->w); base::ScopedState<> sSE3_copy(pSE3); sSE3_copy << sSE3; BOOST_CHECK_EQUAL(sSE3_copy, sSE3); sSE3 >> sSE3_copy; BOOST_CHECK_EQUAL(sSE3_copy, sSE3); sSE3_R << sSE3_copy; BOOST_CHECK_EQUAL(sSE3->getX(), sSE3_R->values[0]); BOOST_CHECK_EQUAL(sSE3->getY(), sSE3_R->values[1]); BOOST_CHECK_EQUAL(sSE3->getZ(), sSE3_R->values[2]); sSE3_SO2 >> sC1; sC1 << sSE3_R; sC1 >> sC0; sSE3_copy = sC0->components[0]; BOOST_CHECK_EQUAL(sSE3_copy, sSE3); sSE3.random(); sSE3 >> sC2; sSE3_copy << sC2; BOOST_CHECK_EQUAL(sSE3_copy, sSE3); sSE3.random(); sSE3 >> sSE3_SO2; sSE3 >> sSE3_R; (sSE3_R ^ sSE3_SO2) >> sSE3_copy; BOOST_CHECK_EQUAL(sSE3_copy, sSE3); BOOST_CHECK_EQUAL(sSE3_copy[pSE3 * sSE3_R.getSpace()], sSE3_R); BOOST_CHECK_EQUAL(sSE3_copy[sSE3_SO2.getSpace()], sSE3_SO2); sSE3->setY(1.0); BOOST_OMPL_EXPECT_NEAR(sSE3.reals()[1], 1.0, 1e-12); BOOST_OMPL_EXPECT_NEAR(sSE3[1], 1.0, 1e-12); sSE3[2] = 0.1; BOOST_OMPL_EXPECT_NEAR(sSE3.reals()[2], 0.1, 1e-12); sSE3.random(); std::vector<double> r = sSE3.reals(); BOOST_CHECK_EQUAL(r.size(), 7u); sSE3_copy = r; BOOST_CHECK_EQUAL(sSE3_copy, sSE3); BOOST_CHECK_EQUAL(sSE3[6], r[6]); BOOST_CHECK_EQUAL(sSE3[0], r[0]); BOOST_CHECK_EQUAL(sSE3.getSpace()->getValueAddressAtIndex(sSE3.get(), 7), (double*)NULL); sSE3_R = 0.5; BOOST_CHECK_EQUAL(sSE3_R[0], 0.5); sSE3 << sSE3_R; pSE3->setName("test"); BOOST_CHECK_EQUAL(sSE3["test"], 0.5); sSE3["test"] = 0.1; BOOST_CHECK_EQUAL(sSE3[0], 0.1); } BOOST_AUTO_TEST_CASE(ScopedRV) { base::StateSpacePtr m(new base::RealVectorStateSpace(2)); base::ScopedState<base::RealVectorStateSpace> s1(m); s1->values[0] = 1.0; s1->values[1] = 2.0; base::ScopedState<base::RealVectorStateSpace> s2 = s1; BOOST_CHECK(s2->values[1] == s1->values[1]); base::ScopedState<> s3(m); s3 = s1; base::ScopedState<> s4 = s3; BOOST_CHECK(s4 == s3); BOOST_CHECK(s4 == s1); base::ScopedState<base::RealVectorStateSpace> s5 = s2; BOOST_CHECK(s5 == s1); s1->values[1] = 4.0; BOOST_CHECK(s5 != s1); base::ScopedState<base::RealVectorStateSpace> s6(s5); BOOST_CHECK(s6 != s1); s1 = s5; s5 = s1; BOOST_CHECK(s6 == s1); } BOOST_AUTO_TEST_CASE(Allocation) { base::StateSpacePtr m(new base::SE3StateSpace()); base::RealVectorBounds b(3); b.setLow(0); b.setHigh(1); m->as<base::SE3StateSpace>()->setBounds(b); base::SpaceInformation si(m); si.setup(); const unsigned int N = 30000; const unsigned int M = 20; std::vector<base::State*> states(N, NULL); ompl::time::point start = ompl::time::now(); for (unsigned int j = 0 ; j < M ; ++j) { for (unsigned int i = 0 ; i < N ; ++i) states[i] = si.allocState(); for (unsigned int i = 0 ; i < N ; ++i) si.freeState(states[i]); } double d = ompl::time::seconds(ompl::time::now() - start); std::cout << (double)N * (double)M / d << " state allocations then frees per second" << std::endl; start = ompl::time::now(); for (unsigned int j = 0 ; j < M ; ++j) { for (unsigned int i = 0 ; i < N ; ++i) { base::State *s = si.allocState(); si.freeState(s); } } d = ompl::time::seconds(ompl::time::now() - start); std::cout << (double)N * (double)M / d << " mixed state allocations & frees per second" << std::endl; start = ompl::time::now(); for (unsigned int j = 0 ; j < M ; ++j) { for (unsigned int i = 0 ; i < N ; ++i) { base::State *s = si.allocState(); si.freeState(s); states[i] = si.allocState(); } for (unsigned int i = 0 ; i < N ; ++i) si.freeState(states[i]); } d = ompl::time::seconds(ompl::time::now() - start); std::cout << (double)N * (double)M / d << " allocations per second" << std::endl; } void randomizedAllocator(const base::SpaceInformation *si) { RNG r; const unsigned int n = 500; std::vector<base::State*> states(n + 1, NULL); for (unsigned int i = 0 ; i < n * 1000 ; ++i) { int j = r.uniformInt(0, n); if (states[j] == NULL) states[j] = si->allocState(); else { si->freeState(states[j]); states[j] = NULL; } } for (unsigned int i = 0 ; i < states.size() ; ++i) if (states[i]) si->freeState(states[i]); } BOOST_AUTO_TEST_CASE(AllocationWithThreads) { base::StateSpacePtr m(new base::SE3StateSpace()); base::RealVectorBounds b(3); b.setLow(0); b.setHigh(1); m->as<base::SE3StateSpace>()->setBounds(b); base::SpaceInformation si(m); si.setup(); const int NT = 10; ompl::time::point start = ompl::time::now(); std::vector<boost::thread*> threads; for (int i = 0 ; i < NT ; ++i) threads.push_back(new boost::thread(boost::bind(&randomizedAllocator, &si))); for (int i = 0 ; i < NT ; ++i) { threads[i]->join(); delete threads[i]; } std::cout << "Time spent randomly allocating & freeing states: " << ompl::time::seconds(ompl::time::now() - start) << std::endl; } BOOST_AUTO_TEST_CASE(PartialCopy) { base::StateSpacePtr m(new base::SE3StateSpace()); base::RealVectorBounds b(3); b.setLow(0); b.setHigh(1); m->as<base::SE3StateSpace>()->setBounds(b); m->setup(); base::StateSpacePtr r3 = m->as<base::CompoundStateSpace>()->getSubspace(0); base::StateSpacePtr q = m->as<base::CompoundStateSpace>()->getSubspace(1); base::StateSamplerPtr s1 = m->allocSubspaceStateSampler(r3); base::StateSamplerPtr s2 = m->allocSubspaceStateSampler(q); base::ScopedState<base::SE3StateSpace> state(m); base::ScopedState<base::SE3StateSpace> tmp(m); std::vector<std::string> subspaces; m->getCommonSubspaces(m, subspaces); BOOST_CHECK(subspaces.size() == 1); BOOST_CHECK(subspaces[0] == m->getName()); q->getCommonSubspaces(r3, subspaces); BOOST_CHECK(subspaces.size() == 0); m->getCommonSubspaces(q, subspaces); BOOST_CHECK(subspaces.size() == 1); for (int i = 0 ; i < 100 ; ++i) { state.random(); tmp = state; s1->sampleUniform(tmp.get()); BOOST_CHECK(tmp[q] == state[q]); BOOST_CHECK(tmp[r3] != state[r3]); s2->sampleUniform(tmp.get()); BOOST_CHECK(tmp[q] != state[q]); BOOST_CHECK(copyStateData(m, state.get(), q, tmp[q].get(), subspaces) == base::ALL_DATA_COPIED); BOOST_CHECK(tmp[q] == state[q]); BOOST_CHECK(copyStateData(m, state.get(), q, tmp[q].get()) == base::ALL_DATA_COPIED); BOOST_CHECK(copyStateData(q, tmp[q].get(), m, state.get()) == base::SOME_DATA_COPIED); BOOST_CHECK(copyStateData(q, tmp[q].get(), r3, state[r3].get()) == base::NO_DATA_COPIED); } } <|endoftext|>
<commit_before>#include <algorithm> #include <iostream> #include <stdexcept> #include <chrono> #include "config.hpp" #include "requestHandler.hpp" #include "response.hpp" #include "torrent.hpp" #include "utility.hpp" #include "mysql.hpp" TorrentMap RequestHandler::torMap; UserMap RequestHandler::usrMap; Database* RequestHandler::db; std::string RequestHandler::handle(std::string str, std::string ip) { std::pair<Request, std::forward_list<std::string>> infos = Parser::parse(str); // parse the request Request* req = &infos.first; std::forward_list<std::string>* infoHashes = &infos.second; bool gzip = false; try { // check if the client accepts gzip if (req->at("accept-encoding").find("gzip") != std::string::npos) gzip = true; } catch (const std::exception& e) {} std::string check = Parser::check(*req); // check if we have all we need to process (saves time if not the case if (infoHashes->begin() == infoHashes->end()) return error("missing info_hash", gzip); if (check != "success") // missing params return error(check, gzip); if (Config::get("type") == "private" && getUser(req->at("passkey")) == nullptr) return error("passkey not found", gzip); try { req->at("ip") = Utility::ip_hex_encode(req->at("ip")) + Utility::port_hex_encode(req->at("port")); } catch (const std::exception& e) { req->emplace("ip", ip + Utility::port_hex_encode(req->at("port"))); } if (req->at("action") == "announce" && req->find("event") == req->end()) req->at("action") = "scrape"; if (req->at("action") == "announce") return announce(req, infoHashes->front(), gzip); else if (req->at("action") == "scrape") return scrape(infoHashes, gzip); return error("invalid action", gzip); // not possible, since the request is checked, but, well, who knows :3 } std::string RequestHandler::announce(const Request* req, const std::string& infoHash, const bool& gzip) { auto duration = std::chrono::system_clock::now().time_since_epoch(); long long now = std::chrono::duration_cast<std::chrono::seconds>(duration).count(); if (Config::get("type") != "private") torMap.emplace(infoHash, Torrent(0)); Torrent *tor = nullptr; try { tor = &torMap.at(infoHash); } catch (const std::exception& e) { return error("unregistered torrent", gzip); } Peers *peers = nullptr; if (req->at("left") != "0") { if (req->at("event") == "stopped") { if (tor->getLeechers()->getPeer(req->at("peer_id"), now) != nullptr) { db->record(tor->getLeechers()->getPeer(req->at("peer_id"), now)->record(std::stoul(req->at("left")), req->at("peer_id"))); db->record(Peer::remove(req->at("peer_id"), tor->getID())); tor->getLeechers()->removePeer(*req); } } else if (tor->getLeechers()->getPeer(req->at("peer_id"), now) == nullptr) { tor->getLeechers()->addPeer(*req, tor->getID(), now); } else { tor->getLeechers()->getPeer(req->at("peer_id"), now)->updateStats(std::stoul(req->at("downloaded"))/(1-(tor->getFree()/100)), now); } peers = tor->getSeeders(); } else { if (req->at("event") == "stopped" || req->at("event") == "completed") { if (tor->getSeeders()->getPeer(req->at("peer_id"), now) != nullptr) { if (req->at("event") == "completed") { tor->downloadedpp(); tor->getSeeders()->addPeer(*req, tor->getID(), now); tor->getLeechers()->removePeer(*req); } else { db->record(tor->getSeeders()->getPeer(req->at("peer_id"), now)->record(std::stoul(req->at("left")), req->at("peer_id"))); db->record(Peer::remove(req->at("peer_id"), tor->getID())); } } } else if (tor->getSeeders()->getPeer(req->at("peer_id"), now) == nullptr) { tor->getSeeders()->addPeer(*req, tor->getID(), now); } else { tor->getLeechers()->getPeer(req->at("peer_id"), now)->updateStats(std::stoul(req->at("downloaded"))/(1-(tor->getFree()/100)), now); } peers = tor->getLeechers(); } std::string peerlist; unsigned long i = 0; if (req->at("event") != "stopped") { i = 10; try { i = std::stoi(req->at("numwant")); } catch (const std::exception& e) {} i = std::min(i, peers->size()); } while (i-- > 0) { Peer* p = peers->nextPeer(now); if (p != nullptr) peerlist.append(*p->getHexIP()); } return response( ("d8:completei" + std::to_string(tor->getSeeders()->size()) + "e10:incompletei" + std::to_string(tor->getLeechers()->size()) + "e10:downloadedi" + std::to_string(tor->getDownloaded()) + "e8:intervali" + std::to_string(900) + "e12:min intervali" + std::to_string(300) + "e5:peers" + std::to_string(peerlist.length()) + ":" + peerlist + "e"), gzip ); // doesn't look as bad as it is stated on ocelot, needs stresstesting to check } std::string RequestHandler::scrape(const std::forward_list<std::string>* infoHashes, const bool& gzip) { std::string resp("d5:filesd"); for (const auto& infoHash : *infoHashes) { const TorrentMap::iterator it = torMap.find(infoHash); if (it != torMap.end()) { resp += std::to_string(infoHash.length()) + ":" + infoHash + "d8:completei" + std::to_string(it->second.getSeeders()->size()) + "e10:incompletei" + std::to_string(it->second.getLeechers()->size()) + "e10:downloadedi" + std::to_string(it->second.getDownloaded()) + "ee"; } } resp += "ee"; return response(resp, gzip); } std::string RequestHandler::update(const Request* req) { std::string resp; const std::string& type = req->at("type"); if (type == "change_passkey") resp = changePasskey(req); else if (type == "add_torrent") resp = addTorrent(req); else if (type == "delete_torrent") resp = deleteTorrent(req); else if (type == "update_torrent") resp = updateTorrent(req); else if (type == "add_user") resp = addUser(req); else if (type == "remove_user") resp = removeUser(req); return resp; } std::string RequestHandler::changePasskey(const Request* req) { try { const std::string& old = req->at("oldpasskey"); User* user = usrMap.at(old); usrMap.erase(old); usrMap.emplace(req->at("newpasskey"), user); return "success"; } catch (const std::exception& e) { return "failure"; } } std::string RequestHandler::addTorrent(const Request* req) { try { auto t = torMap.emplace(req->at("info_hash"), Torrent(std::stoul(req->at("id")))); if (!t.second) return "failure"; try { if (req->at("freetorrent") == "1") t.first->second.setFree(1); else t.first->second.setFree(0); } catch (const std::exception& e) {} return "success"; } catch (const std::exception& e) { return "failure"; } } std::string RequestHandler::deleteTorrent(const Request* req) { const auto it = torMap.find(req->at("info_hash")); if (it != torMap.end()) torMap.erase(it); return "success"; } std::string RequestHandler::updateTorrent(const Request* req) { auto it = torMap.find(req->at("info_hash")); if (it != torMap.end()) { if (req->at("freetorrent") == "1") it->second.setFree(1); else it->second.setFree(0); return "success"; } return "failure"; } std::string RequestHandler::addUser(const Request* req) { try { return (usrMap.emplace(req->at("passkey"), new User(std::stoul(req->at("id")))).second) ? "success" : "failure"; } catch (const std::exception& e) { return "failure"; } } std::string RequestHandler::removeUser(const Request* req) { return (usrMap.erase(req->at("passkey")) == 1) ? "success" : "failure"; } User* RequestHandler::getUser(const std::string& passkey) { try { return usrMap.at(passkey); } catch (const std::exception& e) { return nullptr; } } void RequestHandler::init() { db = new MySQL(); db->connect(); db->loadUsers(usrMap); db->loadTorrents(torMap); } void RequestHandler::stop() { // TODO record every changes before flushing db->flush(); db->disconnect(); } void RequestHandler::clearTorrentPeers(ev::timer& timer, int revents) { auto duration = std::chrono::system_clock::now().time_since_epoch(); long long now = std::chrono::duration_cast<std::chrono::seconds>(duration).count(); for (auto& t : torMap) { t.second.getSeeders()->timedOut(now); t.second.getLeechers()->timedOut(now); } } <commit_msg>nope nope nope<commit_after>#include <algorithm> #include <iostream> #include <stdexcept> #include <chrono> #include "config.hpp" #include "requestHandler.hpp" #include "response.hpp" #include "torrent.hpp" #include "utility.hpp" #include "mysql.hpp" TorrentMap RequestHandler::torMap; UserMap RequestHandler::usrMap; Database* RequestHandler::db; std::string RequestHandler::handle(std::string str, std::string ip) { std::pair<Request, std::forward_list<std::string>> infos = Parser::parse(str); // parse the request Request* req = &infos.first; std::forward_list<std::string>* infoHashes = &infos.second; bool gzip = false; try { // check if the client accepts gzip if (req->at("accept-encoding").find("gzip") != std::string::npos) gzip = true; } catch (const std::exception& e) {} std::string check = Parser::check(*req); // check if we have all we need to process (saves time if not the case if (infoHashes->begin() == infoHashes->end()) return error("missing info_hash", gzip); if (check != "success") // missing params return error(check, gzip); if (Config::get("type") == "private" && getUser(req->at("passkey")) == nullptr) return error("passkey not found", gzip); try { req->at("ip") = Utility::ip_hex_encode(req->at("ip")) + Utility::port_hex_encode(req->at("port")); } catch (const std::exception& e) { req->emplace("ip", ip + Utility::port_hex_encode(req->at("port"))); } if (req->at("action") == "announce") return announce(req, infoHashes->front(), gzip); else if (req->at("action") == "scrape") return scrape(infoHashes, gzip); return error("invalid action", gzip); // not possible, since the request is checked, but, well, who knows :3 } std::string RequestHandler::announce(const Request* req, const std::string& infoHash, const bool& gzip) { auto duration = std::chrono::system_clock::now().time_since_epoch(); long long now = std::chrono::duration_cast<std::chrono::seconds>(duration).count(); if (Config::get("type") != "private") torMap.emplace(infoHash, Torrent(0)); Torrent *tor = nullptr; try { tor = &torMap.at(infoHash); } catch (const std::exception& e) { return error("unregistered torrent", gzip); } Peers *peers = nullptr; if (req->at("left") != "0") { if (req->at("event") == "stopped") { if (tor->getLeechers()->getPeer(req->at("peer_id"), now) != nullptr) { db->record(tor->getLeechers()->getPeer(req->at("peer_id"), now)->record(std::stoul(req->at("left")), req->at("peer_id"))); db->record(Peer::remove(req->at("peer_id"), tor->getID())); tor->getLeechers()->removePeer(*req); } } else if (tor->getLeechers()->getPeer(req->at("peer_id"), now) == nullptr) { tor->getLeechers()->addPeer(*req, tor->getID(), now); } else { tor->getLeechers()->getPeer(req->at("peer_id"), now)->updateStats(std::stoul(req->at("downloaded"))/(1-(tor->getFree()/100)), now); } peers = tor->getSeeders(); } else { if (req->at("event") == "stopped" || req->at("event") == "completed") { if (tor->getSeeders()->getPeer(req->at("peer_id"), now) != nullptr) { if (req->at("event") == "completed") { tor->downloadedpp(); tor->getSeeders()->addPeer(*req, tor->getID(), now); tor->getLeechers()->removePeer(*req); } else { db->record(tor->getSeeders()->getPeer(req->at("peer_id"), now)->record(std::stoul(req->at("left")), req->at("peer_id"))); db->record(Peer::remove(req->at("peer_id"), tor->getID())); } } } else if (tor->getSeeders()->getPeer(req->at("peer_id"), now) == nullptr) { tor->getSeeders()->addPeer(*req, tor->getID(), now); } else { tor->getLeechers()->getPeer(req->at("peer_id"), now)->updateStats(std::stoul(req->at("downloaded"))/(1-(tor->getFree()/100)), now); } peers = tor->getLeechers(); } std::string peerlist; unsigned long i = 0; if (req->at("event") != "stopped") { i = 10; try { i = std::stoi(req->at("numwant")); } catch (const std::exception& e) {} i = std::min(i, peers->size()); } while (i-- > 0) { Peer* p = peers->nextPeer(now); if (p != nullptr) peerlist.append(*p->getHexIP()); } return response( ("d8:completei" + std::to_string(tor->getSeeders()->size()) + "e10:incompletei" + std::to_string(tor->getLeechers()->size()) + "e10:downloadedi" + std::to_string(tor->getDownloaded()) + "e8:intervali" + std::to_string(900) + "e12:min intervali" + std::to_string(300) + "e5:peers" + std::to_string(peerlist.length()) + ":" + peerlist + "e"), gzip ); // doesn't look as bad as it is stated on ocelot, needs stresstesting to check } std::string RequestHandler::scrape(const std::forward_list<std::string>* infoHashes, const bool& gzip) { std::string resp("d5:filesd"); for (const auto& infoHash : *infoHashes) { const TorrentMap::iterator it = torMap.find(infoHash); if (it != torMap.end()) { resp += std::to_string(infoHash.length()) + ":" + infoHash + "d8:completei" + std::to_string(it->second.getSeeders()->size()) + "e10:incompletei" + std::to_string(it->second.getLeechers()->size()) + "e10:downloadedi" + std::to_string(it->second.getDownloaded()) + "ee"; } } resp += "ee"; return response(resp, gzip); } std::string RequestHandler::update(const Request* req) { std::string resp; const std::string& type = req->at("type"); if (type == "change_passkey") resp = changePasskey(req); else if (type == "add_torrent") resp = addTorrent(req); else if (type == "delete_torrent") resp = deleteTorrent(req); else if (type == "update_torrent") resp = updateTorrent(req); else if (type == "add_user") resp = addUser(req); else if (type == "remove_user") resp = removeUser(req); return resp; } std::string RequestHandler::changePasskey(const Request* req) { try { const std::string& old = req->at("oldpasskey"); User* user = usrMap.at(old); usrMap.erase(old); usrMap.emplace(req->at("newpasskey"), user); return "success"; } catch (const std::exception& e) { return "failure"; } } std::string RequestHandler::addTorrent(const Request* req) { try { auto t = torMap.emplace(req->at("info_hash"), Torrent(std::stoul(req->at("id")))); if (!t.second) return "failure"; try { if (req->at("freetorrent") == "1") t.first->second.setFree(1); else t.first->second.setFree(0); } catch (const std::exception& e) {} return "success"; } catch (const std::exception& e) { return "failure"; } } std::string RequestHandler::deleteTorrent(const Request* req) { const auto it = torMap.find(req->at("info_hash")); if (it != torMap.end()) torMap.erase(it); return "success"; } std::string RequestHandler::updateTorrent(const Request* req) { auto it = torMap.find(req->at("info_hash")); if (it != torMap.end()) { if (req->at("freetorrent") == "1") it->second.setFree(1); else it->second.setFree(0); return "success"; } return "failure"; } std::string RequestHandler::addUser(const Request* req) { try { return (usrMap.emplace(req->at("passkey"), new User(std::stoul(req->at("id")))).second) ? "success" : "failure"; } catch (const std::exception& e) { return "failure"; } } std::string RequestHandler::removeUser(const Request* req) { return (usrMap.erase(req->at("passkey")) == 1) ? "success" : "failure"; } User* RequestHandler::getUser(const std::string& passkey) { try { return usrMap.at(passkey); } catch (const std::exception& e) { return nullptr; } } void RequestHandler::init() { db = new MySQL(); db->connect(); db->loadUsers(usrMap); db->loadTorrents(torMap); } void RequestHandler::stop() { // TODO record every changes before flushing db->flush(); db->disconnect(); } void RequestHandler::clearTorrentPeers(ev::timer& timer, int revents) { auto duration = std::chrono::system_clock::now().time_since_epoch(); long long now = std::chrono::duration_cast<std::chrono::seconds>(duration).count(); for (auto& t : torMap) { t.second.getSeeders()->timedOut(now); t.second.getLeechers()->timedOut(now); } } <|endoftext|>
<commit_before>/** * Copyright 2008 Matthew Graham * 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 "request_reader.h" #include <iostream> #include <sys/socket.h> #include <errno.h> #include "request.h" request_reader_c::request_reader_c( int connection ) { m_connection = connection; } request_reader_c::~request_reader_c() { close(); } void request_reader_c::close() { if ( m_connection ) { shutdown( m_connection, SHUT_RDWR ); m_connection = 0; } } int request_reader_c::release_connection() { int connection( m_connection ); m_connection = 0; return connection; } request_c * request_reader_c::create_request() { std::string request_line( readline() ); if ( request_line.empty() ) { // no input here return NULL; } std::istringstream stream( request_line ); std::string request; std::string session_id; stream >> request; stream >> session_id; request_type_e req_type = get_request_type( request ); // std::cerr << "req_type = " << (int) req_type << std::endl; request_c *req = new request_c( req_type, session_id ); std::string token_name; // check if this is a close request if ( req_type == RT_CLOSE ) { std::cerr << "close!\n"; close(); return NULL; } else if ( req_type == RT_NULL ) { // do nothing here. return it with an RT_NULL for now. // return NULL; } else if ( req_type == RT_STORE_TOKEN ) { stream >> token_name; req->set_token_name( token_name ); req->set_token_value( readline() ); } else if ( req_type == RT_REQUEST_TOKEN ) { stream >> token_name; req->set_token_name( token_name ); } return req; } std::string request_reader_c::readline() const { char buffer[256]; ssize_t bytes = read( m_connection, buffer, sizeof( buffer ) ); if ( bytes == -1 ) { if ( errno == EWOULDBLOCK ) { return std::string(); } else { perror( "request read failure" ); } } // remove the new lines char *nl = strchr( buffer, '\n' ); if ( nl ) { *nl = '\0'; } nl = strchr( buffer, '\r' ); if ( nl ) { *nl = '\0'; } return buffer; } request_type_e request_reader_c::get_request_type( const std::string& req_type ) { // std::cerr << "request = '" << req_type << "'\n"; request_type_e rt( RT_NULL ); if ( req_type == "store" ) { return RT_STORE_SESSION; } else if ( req_type == "store_token" ) { return RT_STORE_TOKEN; } else if ( req_type == "kill" ) { return RT_KILL_SESSION; } else if ( req_type == "status" ) { return RT_SESSION_STATUS; } else if ( req_type == "token" ) { return RT_REQUEST_TOKEN; } else if ( req_type == "close" ) { return RT_CLOSE; } else { return RT_NULL; } } <commit_msg>added comments about releasing the connection before a reader is deleted<commit_after>/** * Copyright 2008 Matthew Graham * 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 "request_reader.h" #include <iostream> #include <sys/socket.h> #include <errno.h> #include "request.h" request_reader_c::request_reader_c( int connection ) { m_connection = connection; } request_reader_c::~request_reader_c() { close(); } void request_reader_c::close() { if ( m_connection ) { // this should have been released already // but shut it down if it hasn't shutdown( m_connection, SHUT_RDWR ); m_connection = 0; } } int request_reader_c::release_connection() { int connection( m_connection ); m_connection = 0; return connection; } request_c * request_reader_c::create_request() { std::string request_line( readline() ); if ( request_line.empty() ) { // no input here return NULL; } std::istringstream stream( request_line ); std::string request; std::string session_id; stream >> request; stream >> session_id; request_type_e req_type = get_request_type( request ); // std::cerr << "req_type = " << (int) req_type << std::endl; request_c *req = new request_c( req_type, session_id ); std::string token_name; // check if this is a close request if ( req_type == RT_CLOSE ) { std::cerr << "close!\n"; close(); return NULL; } else if ( req_type == RT_NULL ) { // do nothing here. return it with an RT_NULL for now. // return NULL; } else if ( req_type == RT_STORE_TOKEN ) { stream >> token_name; req->set_token_name( token_name ); req->set_token_value( readline() ); } else if ( req_type == RT_REQUEST_TOKEN ) { stream >> token_name; req->set_token_name( token_name ); } return req; } std::string request_reader_c::readline() const { char buffer[256]; ssize_t bytes = read( m_connection, buffer, sizeof( buffer ) ); if ( bytes == -1 ) { if ( errno == EWOULDBLOCK ) { return std::string(); } else { perror( "request read failure" ); } } // remove the new lines char *nl = strchr( buffer, '\n' ); if ( nl ) { *nl = '\0'; } nl = strchr( buffer, '\r' ); if ( nl ) { *nl = '\0'; } return buffer; } request_type_e request_reader_c::get_request_type( const std::string& req_type ) { // std::cerr << "request = '" << req_type << "'\n"; request_type_e rt( RT_NULL ); if ( req_type == "store" ) { return RT_STORE_SESSION; } else if ( req_type == "store_token" ) { return RT_STORE_TOKEN; } else if ( req_type == "kill" ) { return RT_KILL_SESSION; } else if ( req_type == "status" ) { return RT_SESSION_STATUS; } else if ( req_type == "token" ) { return RT_REQUEST_TOKEN; } else if ( req_type == "close" ) { return RT_CLOSE; } else { return RT_NULL; } } <|endoftext|>
<commit_before>#include <QClipboard> #include <QDebug> #include <QFile> #include <QKeyEvent> #include <QLineEdit> #include <QMessageBox> #include <QPoint> #include <QSettings> #include <QSize> #include <algorithm> #include <stdexcept> #include <typeinfo> #include "CorpusWidget.hh" #include "StatisticsWindow.hh" #include "Query.hh" #include "QueryModel.hh" #include "PercentageCellDelegate.hh" #include "ValidityColor.hh" #include "XPathValidator.hh" #include "XSLTransformer.hh" #include "ui_StatisticsWindow.h" StatisticsWindow::StatisticsWindow(QWidget *parent) : CorpusWidget(parent), d_ui(QSharedPointer<Ui::StatisticsWindow>(new Ui::StatisticsWindow)) { d_ui->setupUi(this); createActions(); readNodeAttributes(); readSettings(); // Pick a sane default attribute. int idx = d_ui->attributeComboBox->findText("word"); if (idx != -1) d_ui->attributeComboBox->setCurrentIndex(idx); } StatisticsWindow::~StatisticsWindow() { writeSettings(); } void StatisticsWindow::attributeChanged(int index) { Q_UNUSED(index); if (!d_model.isNull()) startQuery(); } void StatisticsWindow::queryFailed(QString error) { QMessageBox::critical(this, tr("Error processing query"), tr("Could not process query: ") + error, QMessageBox::Ok); } void StatisticsWindow::switchCorpus(QSharedPointer<alpinocorpus::CorpusReader> corpusReader) { d_corpusReader = corpusReader; //d_xpathValidator->setCorpusReader(d_corpusReader); setModel(new QueryModel(corpusReader)); } void StatisticsWindow::setFilter(QString const &filter) { d_filter = filter; startQuery(); } void StatisticsWindow::setAggregateAttribute(QString const &detail) { // @TODO: update d_ui->attributeComboBox.currentIndex when changed from outside // to reflect the current (changed) state of the window. } void StatisticsWindow::setModel(QueryModel *model) { d_model = QSharedPointer<QueryModel>(model); d_ui->resultsTable->setModel(d_model.data()); connect(d_model.data(), SIGNAL(queryFailed(QString)), SLOT(queryFailed(QString))); connect(d_model.data(), SIGNAL(queryEntryFound(QString)), SLOT(updateResultsTotalCount())); connect(d_model.data(), SIGNAL(queryStarted(int)), SLOT(progressStarted(int))); connect(d_model.data(), SIGNAL(queryStopped(int, int)), SLOT(progressStopped(int, int))); } void StatisticsWindow::updateResultsTotalCount() { d_ui->totalHitsLabel->setText(QString("%1").arg(d_model->totalHits())); } void StatisticsWindow::applyValidityColor(QString const &) { ::applyValidityColor(sender()); } void StatisticsWindow::cancelQuery() { if (d_model) d_model->cancelQuery(); } void StatisticsWindow::copy() const { QString csv = selectionAsCSV("\t"); if (!csv.isEmpty()) QApplication::clipboard()->setText(csv); } void StatisticsWindow::createActions() { // @TODO: move this non action related ui code to somewhere else. The .ui file preferably. // Requires initialized UI. //d_ui->resultsTable->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch); d_ui->resultsTable->verticalHeader()->hide(); d_ui->resultsTable->sortByColumn(1, Qt::DescendingOrder); d_ui->resultsTable->setItemDelegateForColumn(2, new PercentageCellDelegate()); // Only allow valid xpath queries to be submitted //d_ui->filterLineEdit->setValidator(d_xpathValidator.data()); // When a row is activated, generate a query to be used in the main window to // filter all the results so only the results which are accumulated in this // row will be shown. connect(d_ui->resultsTable, SIGNAL(activated(QModelIndex const &)), SLOT(generateQuery(QModelIndex const &))); // Toggle percentage column checkbox (is this needed?) connect(d_ui->percentageCheckBox, SIGNAL(toggled(bool)), SLOT(showPercentageChanged())); connect(d_ui->attributeComboBox, SIGNAL(currentIndexChanged(int)), SLOT(attributeChanged(int))); } void StatisticsWindow::generateQuery(QModelIndex const &index) { // Get the text from the first column, that is the found value QString data = index.sibling(index.row(), 0).data(Qt::UserRole).toString(); QString query = ::generateQuery( d_filter, d_ui->attributeComboBox->currentText(), data); emit entryActivated(data, query); } QString StatisticsWindow::selectionAsCSV(QString const &separator) const { // If there is no model attached (e.g. no corpus loaded) do nothing if (!d_model) return QString(); QModelIndexList rows = d_ui->resultsTable->selectionModel()->selectedRows(); // If there is nothing selected, do nothing if (rows.isEmpty()) return QString(); QStringList output; foreach (QModelIndex const &row, rows) { // This only works if the selection behavior is SelectRows output << d_model->data(row).toString() // value << separator << d_model->data(row.sibling(row.row(), 1)).toString() // count << "\n"; } // Remove superfluous newline separator output.removeLast(); return output.join(QString()); } void StatisticsWindow::showPercentage(bool show) { d_ui->resultsTable->setColumnHidden(2, !show); d_ui->percentageCheckBox->setChecked(show); } void StatisticsWindow::startQuery() { setAggregateAttribute(d_ui->attributeComboBox->currentText()); d_ui->resultsTable->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch); d_ui->resultsTable->horizontalHeader()->setResizeMode(1, QHeaderView::ResizeToContents); d_ui->resultsTable->horizontalHeader()->setResizeMode(2, QHeaderView::Stretch); d_ui->totalHitsLabel->clear(); d_model->runQuery(QString("%1/@%2") .arg(d_filter) .arg(d_ui->attributeComboBox->currentText())); } void StatisticsWindow::showPercentageChanged() { showPercentage(d_ui->percentageCheckBox->isChecked()); } void StatisticsWindow::progressStarted(int total) { d_ui->filterProgress->setMaximum(total); d_ui->filterProgress->setDisabled(false); d_ui->filterProgress->setVisible(true); } void StatisticsWindow::progressChanged(int n, int total) { d_ui->filterProgress->setValue(n); } void StatisticsWindow::progressStopped(int n, int total) { d_ui->filterProgress->setVisible(false); } void StatisticsWindow::closeEvent(QCloseEvent *event) { writeSettings(); event->accept(); } void StatisticsWindow::readNodeAttributes() { QFile dtdFile(":/dtd/alpino_ds.dtd"); // XXX - hardcode? if (!dtdFile.open(QFile::ReadOnly)) { qWarning() << "StatisticsWindow::readNodeAttributes(): Could not read DTD."; return; } QByteArray dtdData(dtdFile.readAll()); xmlParserInputBufferPtr input = xmlParserInputBufferCreateMem(dtdData.constData(), dtdData.size(), XML_CHAR_ENCODING_8859_1); // Note: xmlFreeParserInputBuffer() seems to segfault in input. It's probably because // xmlIOParseDTD takes (some?) ownership. xmlDtdPtr dtd = xmlIOParseDTD(NULL, input, XML_CHAR_ENCODING_8859_1); if (dtd == NULL) { qWarning() << "StatisticsWindow::readNodeAttributes(): Could not parse DTD."; return; } if (dtd->elements == NULL) { qWarning() << "StatisticsWindow::readNodeAttributes(): DTD hashtable contains no elements."; xmlFreeDtd(dtd); return; } xmlNode *elem = reinterpret_cast<xmlNode *>(xmlHashLookup( reinterpret_cast<xmlHashTablePtr>(dtd->elements), reinterpret_cast<xmlChar const *>("node"))); if (elem == NULL) { qWarning() << "StatisticsWindow::readNodeAttributes(): could not finde 'node' element."; xmlFreeDtd(dtd); return; } // Should be safe to clear items now... d_ui->attributeComboBox->clear(); QStringList attrs; for (xmlAttr *attr = elem->properties; attr != NULL; attr = attr->next) if (attr->type == XML_ATTRIBUTE_DECL) attrs.push_back(reinterpret_cast<char const *>(attr->name)); std::sort(attrs.begin(), attrs.end()); d_ui->attributeComboBox->addItems(attrs); xmlFreeDtd(dtd); } void StatisticsWindow::readSettings() { QSettings settings; bool show = settings.value("query_show_percentage", false).toBool(); showPercentage(show); // Window geometry. QPoint pos = settings.value("query_pos", QPoint(200, 200)).toPoint(); QSize size = settings.value("query_size", QSize(350, 400)).toSize(); resize(size); // Move. move(pos); } void StatisticsWindow::writeSettings() { QSettings settings; settings.setValue("query_show_percentage", d_ui->percentageCheckBox->isChecked()); // Window geometry settings.setValue("query_pos", pos()); settings.setValue("query_size", size()); } <commit_msg>StatisticsWindow: show percentages by default.<commit_after>#include <QClipboard> #include <QDebug> #include <QFile> #include <QKeyEvent> #include <QLineEdit> #include <QMessageBox> #include <QPoint> #include <QSettings> #include <QSize> #include <algorithm> #include <stdexcept> #include <typeinfo> #include "CorpusWidget.hh" #include "StatisticsWindow.hh" #include "Query.hh" #include "QueryModel.hh" #include "PercentageCellDelegate.hh" #include "ValidityColor.hh" #include "XPathValidator.hh" #include "XSLTransformer.hh" #include "ui_StatisticsWindow.h" StatisticsWindow::StatisticsWindow(QWidget *parent) : CorpusWidget(parent), d_ui(QSharedPointer<Ui::StatisticsWindow>(new Ui::StatisticsWindow)) { d_ui->setupUi(this); createActions(); readNodeAttributes(); readSettings(); // Pick a sane default attribute. int idx = d_ui->attributeComboBox->findText("word"); if (idx != -1) d_ui->attributeComboBox->setCurrentIndex(idx); } StatisticsWindow::~StatisticsWindow() { writeSettings(); } void StatisticsWindow::attributeChanged(int index) { Q_UNUSED(index); if (!d_model.isNull()) startQuery(); } void StatisticsWindow::queryFailed(QString error) { QMessageBox::critical(this, tr("Error processing query"), tr("Could not process query: ") + error, QMessageBox::Ok); } void StatisticsWindow::switchCorpus(QSharedPointer<alpinocorpus::CorpusReader> corpusReader) { d_corpusReader = corpusReader; //d_xpathValidator->setCorpusReader(d_corpusReader); setModel(new QueryModel(corpusReader)); } void StatisticsWindow::setFilter(QString const &filter) { d_filter = filter; startQuery(); } void StatisticsWindow::setAggregateAttribute(QString const &detail) { // @TODO: update d_ui->attributeComboBox.currentIndex when changed from outside // to reflect the current (changed) state of the window. } void StatisticsWindow::setModel(QueryModel *model) { d_model = QSharedPointer<QueryModel>(model); d_ui->resultsTable->setModel(d_model.data()); connect(d_model.data(), SIGNAL(queryFailed(QString)), SLOT(queryFailed(QString))); connect(d_model.data(), SIGNAL(queryEntryFound(QString)), SLOT(updateResultsTotalCount())); connect(d_model.data(), SIGNAL(queryStarted(int)), SLOT(progressStarted(int))); connect(d_model.data(), SIGNAL(queryStopped(int, int)), SLOT(progressStopped(int, int))); } void StatisticsWindow::updateResultsTotalCount() { d_ui->totalHitsLabel->setText(QString("%1").arg(d_model->totalHits())); } void StatisticsWindow::applyValidityColor(QString const &) { ::applyValidityColor(sender()); } void StatisticsWindow::cancelQuery() { if (d_model) d_model->cancelQuery(); } void StatisticsWindow::copy() const { QString csv = selectionAsCSV("\t"); if (!csv.isEmpty()) QApplication::clipboard()->setText(csv); } void StatisticsWindow::createActions() { // @TODO: move this non action related ui code to somewhere else. The .ui file preferably. // Requires initialized UI. //d_ui->resultsTable->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch); d_ui->resultsTable->verticalHeader()->hide(); d_ui->resultsTable->sortByColumn(1, Qt::DescendingOrder); d_ui->resultsTable->setItemDelegateForColumn(2, new PercentageCellDelegate()); // Only allow valid xpath queries to be submitted //d_ui->filterLineEdit->setValidator(d_xpathValidator.data()); // When a row is activated, generate a query to be used in the main window to // filter all the results so only the results which are accumulated in this // row will be shown. connect(d_ui->resultsTable, SIGNAL(activated(QModelIndex const &)), SLOT(generateQuery(QModelIndex const &))); // Toggle percentage column checkbox (is this needed?) connect(d_ui->percentageCheckBox, SIGNAL(toggled(bool)), SLOT(showPercentageChanged())); connect(d_ui->attributeComboBox, SIGNAL(currentIndexChanged(int)), SLOT(attributeChanged(int))); } void StatisticsWindow::generateQuery(QModelIndex const &index) { // Get the text from the first column, that is the found value QString data = index.sibling(index.row(), 0).data(Qt::UserRole).toString(); QString query = ::generateQuery( d_filter, d_ui->attributeComboBox->currentText(), data); emit entryActivated(data, query); } QString StatisticsWindow::selectionAsCSV(QString const &separator) const { // If there is no model attached (e.g. no corpus loaded) do nothing if (!d_model) return QString(); QModelIndexList rows = d_ui->resultsTable->selectionModel()->selectedRows(); // If there is nothing selected, do nothing if (rows.isEmpty()) return QString(); QStringList output; foreach (QModelIndex const &row, rows) { // This only works if the selection behavior is SelectRows output << d_model->data(row).toString() // value << separator << d_model->data(row.sibling(row.row(), 1)).toString() // count << "\n"; } // Remove superfluous newline separator output.removeLast(); return output.join(QString()); } void StatisticsWindow::showPercentage(bool show) { d_ui->resultsTable->setColumnHidden(2, !show); d_ui->percentageCheckBox->setChecked(show); } void StatisticsWindow::startQuery() { setAggregateAttribute(d_ui->attributeComboBox->currentText()); d_ui->resultsTable->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch); d_ui->resultsTable->horizontalHeader()->setResizeMode(1, QHeaderView::ResizeToContents); d_ui->resultsTable->horizontalHeader()->setResizeMode(2, QHeaderView::Stretch); d_ui->totalHitsLabel->clear(); d_model->runQuery(QString("%1/@%2") .arg(d_filter) .arg(d_ui->attributeComboBox->currentText())); } void StatisticsWindow::showPercentageChanged() { showPercentage(d_ui->percentageCheckBox->isChecked()); } void StatisticsWindow::progressStarted(int total) { d_ui->filterProgress->setMaximum(total); d_ui->filterProgress->setDisabled(false); d_ui->filterProgress->setVisible(true); } void StatisticsWindow::progressChanged(int n, int total) { d_ui->filterProgress->setValue(n); } void StatisticsWindow::progressStopped(int n, int total) { d_ui->filterProgress->setVisible(false); } void StatisticsWindow::closeEvent(QCloseEvent *event) { writeSettings(); event->accept(); } void StatisticsWindow::readNodeAttributes() { QFile dtdFile(":/dtd/alpino_ds.dtd"); // XXX - hardcode? if (!dtdFile.open(QFile::ReadOnly)) { qWarning() << "StatisticsWindow::readNodeAttributes(): Could not read DTD."; return; } QByteArray dtdData(dtdFile.readAll()); xmlParserInputBufferPtr input = xmlParserInputBufferCreateMem(dtdData.constData(), dtdData.size(), XML_CHAR_ENCODING_8859_1); // Note: xmlFreeParserInputBuffer() seems to segfault in input. It's probably because // xmlIOParseDTD takes (some?) ownership. xmlDtdPtr dtd = xmlIOParseDTD(NULL, input, XML_CHAR_ENCODING_8859_1); if (dtd == NULL) { qWarning() << "StatisticsWindow::readNodeAttributes(): Could not parse DTD."; return; } if (dtd->elements == NULL) { qWarning() << "StatisticsWindow::readNodeAttributes(): DTD hashtable contains no elements."; xmlFreeDtd(dtd); return; } xmlNode *elem = reinterpret_cast<xmlNode *>(xmlHashLookup( reinterpret_cast<xmlHashTablePtr>(dtd->elements), reinterpret_cast<xmlChar const *>("node"))); if (elem == NULL) { qWarning() << "StatisticsWindow::readNodeAttributes(): could not finde 'node' element."; xmlFreeDtd(dtd); return; } // Should be safe to clear items now... d_ui->attributeComboBox->clear(); QStringList attrs; for (xmlAttr *attr = elem->properties; attr != NULL; attr = attr->next) if (attr->type == XML_ATTRIBUTE_DECL) attrs.push_back(reinterpret_cast<char const *>(attr->name)); std::sort(attrs.begin(), attrs.end()); d_ui->attributeComboBox->addItems(attrs); xmlFreeDtd(dtd); } void StatisticsWindow::readSettings() { QSettings settings; bool show = settings.value("query_show_percentage", true).toBool(); showPercentage(show); // Window geometry. QPoint pos = settings.value("query_pos", QPoint(200, 200)).toPoint(); QSize size = settings.value("query_size", QSize(350, 400)).toSize(); resize(size); // Move. move(pos); } void StatisticsWindow::writeSettings() { QSettings settings; settings.setValue("query_show_percentage", d_ui->percentageCheckBox->isChecked()); // Window geometry settings.setValue("query_pos", pos()); settings.setValue("query_size", size()); } <|endoftext|>
<commit_before>#include "Scheduler0.hpp" #include "Funwrap3.hpp" #include "Thread0.hpp" #include "queue_lockfree_total.hpp" #include <thread> Scheduler0::Scheduler0(){ _thread.settask( [=](){ this->task(); } ); //set the scheduler task } Scheduler0::~Scheduler0(){ _thread.setaction( IThread::Action::END ); } bool Scheduler0::add( Funwrap3 & f){ return _queue.enqueue( f ); //enqueue into top half } bool Scheduler0::get( Funwrap3 & f ){ return _queue_sched.dequeue( f ); //deque from bottom half } bool Scheduler0::run(){ return _thread.setaction( IThread::Action::START ); } bool Scheduler0::stop(){ return _thread.setaction( IThread::Action::END ); } void Scheduler0::flush(){ _queue.clear(); } void Scheduler0::task(){ //push enqueued tasks from the top half into the bottom half queue Funwrap3 f; if( _queue.dequeue( f ) ){ _queue_sched.enqueue( f ); }else{ std::this_thread::yield(); } } size_t Scheduler0::size_scheduled(){ return _queue_sched.size(); } <commit_msg>modified minor call to container due to interface change.<commit_after>#include "Scheduler0.hpp" #include "Funwrap3.hpp" #include "Thread0.hpp" #include "queue_lockfree_total.hpp" #include <thread> Scheduler0::Scheduler0(){ _thread.settask( [=](){ this->task(); } ); //set the scheduler task } Scheduler0::~Scheduler0(){ _thread.setaction( IThread::Action::END ); } bool Scheduler0::add( Funwrap3 & f){ return _queue.put( f ); //enqueue into top half } bool Scheduler0::get( Funwrap3 & f ){ return _queue_sched.get( f ); //deque from bottom half } bool Scheduler0::run(){ return _thread.setaction( IThread::Action::START ); } bool Scheduler0::stop(){ return _thread.setaction( IThread::Action::END ); } void Scheduler0::flush(){ _queue.clear(); } void Scheduler0::task(){ //push enqueued tasks from the top half into the bottom half queue Funwrap3 f; if( _queue.get( f ) ){ _queue_sched.put( f ); }else{ std::this_thread::yield(); } } size_t Scheduler0::size_scheduled(){ return _queue_sched.size(); } <|endoftext|>
<commit_before>/** * \file * \brief SignalInformationQueue class header * * \author Copyright (C) 2015-2017 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * 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/. */ #ifndef INCLUDE_DISTORTOS_INTERNAL_SYNCHRONIZATION_SIGNALINFORMATIONQUEUE_HPP_ #define INCLUDE_DISTORTOS_INTERNAL_SYNCHRONIZATION_SIGNALINFORMATIONQUEUE_HPP_ #include "distortos/SignalInformation.hpp" #include "estd/IntrusiveForwardList.hpp" #include <memory> namespace distortos { class SignalSet; namespace internal { /// SignalInformationQueue class can be used for queuing of SignalInformation objects class SignalInformationQueue { public: /// single node of internal forward list - estd::IntrusiveForwardListNode and SignalInformation struct QueueNode { /// node for intrusive forward list estd::IntrusiveForwardListNode node; /// queued SignalInformation SignalInformation signalInformation; }; /// type of uninitialized storage for QueueNode using Storage = typename std::aligned_storage<sizeof(QueueNode), alignof(QueueNode)>::type; /// unique_ptr (with deleter) to Storage[] using StorageUniquePointer = std::unique_ptr<Storage[], void(&)(Storage*)>; /** * \brief SignalInformationQueue's constructor * * \param [in] storageUniquePointer is a rvalue reference to StorageUniquePointer with storage for queue elements * (sufficiently large for \a maxElements Storage objects) and appropriate deleter * \param [in] maxElements is the number of elements in \a storage array */ SignalInformationQueue(StorageUniquePointer&& storageUniquePointer, size_t maxElements); /** * \brief SignalInformationQueue's destructor */ ~SignalInformationQueue(); /** * \brief Accepts (dequeues) one of signals that are queued. * * This should be called when the signal is "accepted". * * \param [in] signalNumber is the signal that will be accepted, [0; 31] * * \return pair with return code (0 on success, error code otherwise) and dequeued SignalInformation object; error * codes: * - EAGAIN - no SignalInformation object with signal number equal to \a signalNumber was queued; */ std::pair<int, SignalInformation> acceptQueuedSignal(uint8_t signalNumber); /** * \return set of currently queued signals */ SignalSet getQueuedSignalSet() const; /** * \brief Adds the signalNumber and signal value (sigval union) to list of queued SignalInformation objects. * * \param [in] signalNumber is the signal that will be queued, [0; 31] * \param [in] value is the signal value * * \return 0 on success, error code otherwise: * - EAGAIN - no resources are available to queue the signal, \a maxElements signals are already queued; * - EINVAL - \a signalNumber value is invalid; */ int queueSignal(uint8_t signalNumber, sigval value); SignalInformationQueue(const SignalInformationQueue&) = delete; SignalInformationQueue(SignalInformationQueue&&) = default; const SignalInformationQueue& operator=(const SignalInformationQueue&) = delete; SignalInformationQueue& operator=(SignalInformationQueue&&) = delete; private: /// type of container with SignalInformation objects using List = estd::IntrusiveForwardList<QueueNode, &QueueNode::node>; /// storage for queue elements StorageUniquePointer storageUniquePointer_; /// list of queued SignalInformation objects List signalInformationList_; /// list of "free" SignalInformation objects List freeSignalInformationList_; }; } // namespace internal } // namespace distortos #endif // INCLUDE_DISTORTOS_INTERNAL_SYNCHRONIZATION_SIGNALINFORMATIONQUEUE_HPP_ <commit_msg>Add SignalInformationQueue::canQueueSignal()<commit_after>/** * \file * \brief SignalInformationQueue class header * * \author Copyright (C) 2015-2017 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * 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/. */ #ifndef INCLUDE_DISTORTOS_INTERNAL_SYNCHRONIZATION_SIGNALINFORMATIONQUEUE_HPP_ #define INCLUDE_DISTORTOS_INTERNAL_SYNCHRONIZATION_SIGNALINFORMATIONQUEUE_HPP_ #include "distortos/SignalInformation.hpp" #include "estd/IntrusiveForwardList.hpp" #include <memory> namespace distortos { class SignalSet; namespace internal { /// SignalInformationQueue class can be used for queuing of SignalInformation objects class SignalInformationQueue { public: /// single node of internal forward list - estd::IntrusiveForwardListNode and SignalInformation struct QueueNode { /// node for intrusive forward list estd::IntrusiveForwardListNode node; /// queued SignalInformation SignalInformation signalInformation; }; /// type of uninitialized storage for QueueNode using Storage = typename std::aligned_storage<sizeof(QueueNode), alignof(QueueNode)>::type; /// unique_ptr (with deleter) to Storage[] using StorageUniquePointer = std::unique_ptr<Storage[], void(&)(Storage*)>; /** * \brief SignalInformationQueue's constructor * * \param [in] storageUniquePointer is a rvalue reference to StorageUniquePointer with storage for queue elements * (sufficiently large for \a maxElements Storage objects) and appropriate deleter * \param [in] maxElements is the number of elements in \a storage array */ SignalInformationQueue(StorageUniquePointer&& storageUniquePointer, size_t maxElements); /** * \brief SignalInformationQueue's destructor */ ~SignalInformationQueue(); /** * \brief Accepts (dequeues) one of signals that are queued. * * This should be called when the signal is "accepted". * * \param [in] signalNumber is the signal that will be accepted, [0; 31] * * \return pair with return code (0 on success, error code otherwise) and dequeued SignalInformation object; error * codes: * - EAGAIN - no SignalInformation object with signal number equal to \a signalNumber was queued; */ std::pair<int, SignalInformation> acceptQueuedSignal(uint8_t signalNumber); /** * \return true if at least one object can be queued, false otherwise */ bool canQueueSignal() const { return freeSignalInformationList_.empty() == false; } /** * \return set of currently queued signals */ SignalSet getQueuedSignalSet() const; /** * \brief Adds the signalNumber and signal value (sigval union) to list of queued SignalInformation objects. * * \param [in] signalNumber is the signal that will be queued, [0; 31] * \param [in] value is the signal value * * \return 0 on success, error code otherwise: * - EAGAIN - no resources are available to queue the signal, \a maxElements signals are already queued; * - EINVAL - \a signalNumber value is invalid; */ int queueSignal(uint8_t signalNumber, sigval value); SignalInformationQueue(const SignalInformationQueue&) = delete; SignalInformationQueue(SignalInformationQueue&&) = default; const SignalInformationQueue& operator=(const SignalInformationQueue&) = delete; SignalInformationQueue& operator=(SignalInformationQueue&&) = delete; private: /// type of container with SignalInformation objects using List = estd::IntrusiveForwardList<QueueNode, &QueueNode::node>; /// storage for queue elements StorageUniquePointer storageUniquePointer_; /// list of queued SignalInformation objects List signalInformationList_; /// list of "free" SignalInformation objects List freeSignalInformationList_; }; } // namespace internal } // namespace distortos #endif // INCLUDE_DISTORTOS_INTERNAL_SYNCHRONIZATION_SIGNALINFORMATIONQUEUE_HPP_ <|endoftext|>
<commit_before>//***************************************************************************** // Copyright 2017-2018 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //***************************************************************************** #pragma once #include "ngraph/node.hpp" namespace ngraph { namespace op { NodeVector get_output_elements(const std::shared_ptr<Node>& mon); /// \brief Operation to get an output from a node. class GetOutputElement : public Node { public: /// \brief Constructs a get-tuple-element operation. /// /// \param arg The input tuple. /// \param n The index of the tuple element to get. GetOutputElement(const std::shared_ptr<Node>& arg, size_t n); virtual std::shared_ptr<Node> copy_with_new_args(const NodeVector& new_args) const override; /// \return The index of the tuple element to get. size_t get_n() const { return m_n; } virtual NodeVector get_arguments() const override; protected: virtual void generate_adjoints(autodiff::Adjoints& adjoints, const NodeVector& deltas) override; size_t m_n; }; } inline std::shared_ptr<Node> get_output_element(const std::shared_ptr<Node> node, size_t i = 0) { return ((i == 0) && node->get_input_size() == 1) ? node : std::make_shared<op::GetOutputElement>(node, i); } } <commit_msg>fix a bug in get_output_element (#1653)<commit_after>//***************************************************************************** // Copyright 2017-2018 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //***************************************************************************** #pragma once #include "ngraph/node.hpp" namespace ngraph { namespace op { NodeVector get_output_elements(const std::shared_ptr<Node>& mon); /// \brief Operation to get an output from a node. class GetOutputElement : public Node { public: /// \brief Constructs a get-tuple-element operation. /// /// \param arg The input tuple. /// \param n The index of the tuple element to get. GetOutputElement(const std::shared_ptr<Node>& arg, size_t n); virtual std::shared_ptr<Node> copy_with_new_args(const NodeVector& new_args) const override; /// \return The index of the tuple element to get. size_t get_n() const { return m_n; } virtual NodeVector get_arguments() const override; protected: virtual void generate_adjoints(autodiff::Adjoints& adjoints, const NodeVector& deltas) override; size_t m_n; }; } inline std::shared_ptr<Node> get_output_element(const std::shared_ptr<Node> node, size_t i = 0) { return ((i == 0) && node->get_output_size() == 1) ? node : std::make_shared<op::GetOutputElement>(node, i); } } <|endoftext|>
<commit_before> // Copyright (c) 2010 libmv authors. // // 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. // Copyright (c) 2012, 2013 Pierre MOULON. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "openMVG/multiview/projection.hpp" namespace openMVG { /// Compute P = K[R|t] void P_From_KRt(const Mat3 &K, const Mat3 &R, const Vec3 &t, Mat34 *P) { *P = K * HStack(R,t); } void KRt_From_P(const Mat34 &P, Mat3 *Kp, Mat3 *Rp, Vec3 *tp) { // Decompose using the RQ decomposition HZ A4.1.1 pag.579. Mat3 K = P.block(0, 0, 3, 3); Mat3 Q; Q.setIdentity(); // Set K(2,1) to zero. if (K(2,1) != 0) { double c = -K(2,2); double s = K(2,1); const double l = sqrt(c * c + s * s); c /= l; s /= l; Mat3 Qx; Qx << 1, 0, 0, 0, c, -s, 0, s, c; K = K * Qx; Q = Qx.transpose() * Q; } // Set K(2,0) to zero. if (K(2,0) != 0) { double c = K(2,2); double s = K(2,0); const double l = sqrt(c * c + s * s); c /= l; s /= l; Mat3 Qy; Qy << c, 0, s, 0, 1, 0, -s, 0, c; K = K * Qy; Q = Qy.transpose() * Q; } // Set K(1,0) to zero. if (K(1,0) != 0) { double c = -K(1,1); double s = K(1,0); const double l = sqrt(c * c + s * s); c /= l; s /= l; Mat3 Qz; Qz << c,-s, 0, s, c, 0, 0, 0, 1; K = K * Qz; Q = Qz.transpose() * Q; } Mat3 R = Q; //Mat3 H = P.block(0, 0, 3, 3); // RQ decomposition //Eigen::HouseholderQR<Mat3> qr(H); //Mat3 K = qr.matrixQR().triangularView<Eigen::Upper>(); //Mat3 R = qr.householderQ(); // Ensure that the diagonal is positive and R determinant == 1. if (K(2,2) < 0) { K = -K; R = -R; } if (K(1,1) < 0) { Mat3 S; S << 1, 0, 0, 0,-1, 0, 0, 0, 1; K = K * S; R = S * R; } if (K(0,0) < 0) { Mat3 S; S << -1, 0, 0, 0, 1, 0, 0, 0, 1; K = K * S; R = S * R; } // Compute translation. Eigen::PartialPivLU<Mat3> lu(K); Vec3 t = lu.solve(P.col(3)); if(R.determinant() < 0) { R = -R; t = -t; } // scale K so that K(2,2) = 1 K = K / K(2,2); *Kp = K; *Rp = R; *tp = t; } Mat3 F_from_P(const Mat34 & P1, const Mat34 & P2) { Mat3 F12; typedef Eigen::Matrix<double, 2, 4> Mat24; Mat24 X1 = P1.block<2, 4>(1, 0); Mat24 X2; X2 << P1.row(2), P1.row(0); Mat24 X3 = P1.block<2, 4>(0, 0); Mat24 Y1 = P2.block<2, 4>(1, 0); Mat24 Y2; Y2 << P2.row(2), P2.row(0); Mat24 Y3 = P2.block<2, 4>(0, 0); Mat4 X1Y1, X2Y1, X3Y1, X1Y2, X2Y2, X3Y2, X1Y3, X2Y3, X3Y3; X1Y1 << X1, Y1; X2Y1 << X2, Y1; X3Y1 << X3, Y1; X1Y2 << X1, Y2; X2Y2 << X2, Y2; X3Y2 << X3, Y2; X1Y3 << X1, Y3; X2Y3 << X2, Y3; X3Y3 << X3, Y3; F12 << X1Y1.determinant(), X2Y1.determinant(), X3Y1.determinant(), X1Y2.determinant(), X2Y2.determinant(), X3Y2.determinant(), X1Y3.determinant(), X2Y3.determinant(), X3Y3.determinant(); return F12; } Vec2 Project(const Mat34 &P, const Vec3 &X) { Vec4 HX; HX << X, 1.0; Vec3 hx = P * HX; return hx.head<2>() / hx(2); } void Project(const Mat34 &P, const Mat3X &X, Mat2X *x) { x->resize(2, X.cols()); for (size_t c = 0; c < static_cast<size_t>(X.cols()); ++c) { x->col(c) = Project(P, Vec3(X.col(c))); } } void Project(const Mat34 &P, const Mat4X &X, Mat2X *x) { x->resize(2, X.cols()); for (Mat4X::Index c = 0; c < X.cols(); ++c) { Vec3 hx = P * X.col(c); x->col(c) = hx.head<2>() / hx(2); } } Mat2X Project(const Mat34 &P, const Mat3X &X) { Mat2X x(2, X.cols()); Project(P, X, &x); return x; } Mat2X Project(const Mat34 &P, const Mat4X &X) { Mat2X x(2, X.cols()); Project(P, X, &x); return x; } void HomogeneousToEuclidean(const Vec4 &H, Vec3 *X) { assert(X != nullptr); *X = H.hnormalized(); } void EuclideanToHomogeneous(const Mat &X, Mat *H) { assert(H != nullptr); *H = X.colwise().homogeneous(); } double Depth(const Mat3 &R, const Vec3 &t, const Vec3 &X) { return (R*X)[2] + t[2]; } Vec3 EuclideanToHomogeneous(const Vec2 &x) { return x.homogeneous(); } void HomogeneousToEuclidean(const Mat &H, Mat *X) { assert(X != nullptr); *X = H.colwise().hnormalized(); } Mat3X EuclideanToHomogeneous(const Mat2X &x) { return x.colwise().homogeneous(); } void EuclideanToHomogeneous(const Mat2X &x, Mat3X *h) { assert(h != nullptr); *h = x.colwise().homogeneous(); } void HomogeneousToEuclidean(const Mat3X &h, Mat2X *e) { assert(e != nullptr); *e = h.colwise().hnormalized(); } void EuclideanToNormalizedCamera(const Mat2X &x, const Mat3 &K, Mat2X *n) { Mat3X x_image_h; EuclideanToHomogeneous(x, &x_image_h); Mat3X x_camera_h = K.inverse() * x_image_h; HomogeneousToEuclidean(x_camera_h, n); } void HomogeneousToNormalizedCamera(const Mat3X &x, const Mat3 &K, Mat2X *n) { Mat3X x_camera_h = K.inverse() * x; HomogeneousToEuclidean(x_camera_h, n); } /// Estimates the root mean square error (2D) double RootMeanSquareError(const Mat2X &x_image, const Mat4X &X_world, const Mat34 &P) { const std::size_t num_points = x_image.cols(); const Mat2X dx = Project(P, X_world) - x_image; return dx.norm() / num_points; } /// Estimates the root mean square error (2D) double RootMeanSquareError(const Mat2X &x_image, const Mat3X &X_world, const Mat3 &K, const Mat3 &R, const Vec3 &t) { Mat34 P; P_From_KRt(K, R, t, &P); const std::size_t num_points = x_image.cols(); const Mat2X dx = Project(P, X_world) - x_image; return dx.norm() / num_points; } } // namespace openMVG <commit_msg>[multiview] checking nullptr<commit_after> // Copyright (c) 2010 libmv authors. // // 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. // Copyright (c) 2012, 2013 Pierre MOULON. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "openMVG/multiview/projection.hpp" namespace openMVG { /// Compute P = K[R|t] void P_From_KRt(const Mat3 &K, const Mat3 &R, const Vec3 &t, Mat34 *P) { assert(P != nullptr); *P = K * HStack(R,t); } void KRt_From_P(const Mat34 &P, Mat3 *Kp, Mat3 *Rp, Vec3 *tp) { // Decompose using the RQ decomposition HZ A4.1.1 pag.579. Mat3 K = P.block(0, 0, 3, 3); Mat3 Q; Q.setIdentity(); // Set K(2,1) to zero. if (K(2,1) != 0) { double c = -K(2,2); double s = K(2,1); const double l = sqrt(c * c + s * s); c /= l; s /= l; Mat3 Qx; Qx << 1, 0, 0, 0, c, -s, 0, s, c; K = K * Qx; Q = Qx.transpose() * Q; } // Set K(2,0) to zero. if (K(2,0) != 0) { double c = K(2,2); double s = K(2,0); const double l = sqrt(c * c + s * s); c /= l; s /= l; Mat3 Qy; Qy << c, 0, s, 0, 1, 0, -s, 0, c; K = K * Qy; Q = Qy.transpose() * Q; } // Set K(1,0) to zero. if (K(1,0) != 0) { double c = -K(1,1); double s = K(1,0); const double l = sqrt(c * c + s * s); c /= l; s /= l; Mat3 Qz; Qz << c,-s, 0, s, c, 0, 0, 0, 1; K = K * Qz; Q = Qz.transpose() * Q; } Mat3 R = Q; //Mat3 H = P.block(0, 0, 3, 3); // RQ decomposition //Eigen::HouseholderQR<Mat3> qr(H); //Mat3 K = qr.matrixQR().triangularView<Eigen::Upper>(); //Mat3 R = qr.householderQ(); // Ensure that the diagonal is positive and R determinant == 1. if (K(2,2) < 0) { K = -K; R = -R; } if (K(1,1) < 0) { Mat3 S; S << 1, 0, 0, 0,-1, 0, 0, 0, 1; K = K * S; R = S * R; } if (K(0,0) < 0) { Mat3 S; S << -1, 0, 0, 0, 1, 0, 0, 0, 1; K = K * S; R = S * R; } // Compute translation. Eigen::PartialPivLU<Mat3> lu(K); Vec3 t = lu.solve(P.col(3)); if(R.determinant() < 0) { R = -R; t = -t; } // scale K so that K(2,2) = 1 K = K / K(2,2); *Kp = K; *Rp = R; *tp = t; } Mat3 F_from_P(const Mat34 & P1, const Mat34 & P2) { Mat3 F12; typedef Eigen::Matrix<double, 2, 4> Mat24; Mat24 X1 = P1.block<2, 4>(1, 0); Mat24 X2; X2 << P1.row(2), P1.row(0); Mat24 X3 = P1.block<2, 4>(0, 0); Mat24 Y1 = P2.block<2, 4>(1, 0); Mat24 Y2; Y2 << P2.row(2), P2.row(0); Mat24 Y3 = P2.block<2, 4>(0, 0); Mat4 X1Y1, X2Y1, X3Y1, X1Y2, X2Y2, X3Y2, X1Y3, X2Y3, X3Y3; X1Y1 << X1, Y1; X2Y1 << X2, Y1; X3Y1 << X3, Y1; X1Y2 << X1, Y2; X2Y2 << X2, Y2; X3Y2 << X3, Y2; X1Y3 << X1, Y3; X2Y3 << X2, Y3; X3Y3 << X3, Y3; F12 << X1Y1.determinant(), X2Y1.determinant(), X3Y1.determinant(), X1Y2.determinant(), X2Y2.determinant(), X3Y2.determinant(), X1Y3.determinant(), X2Y3.determinant(), X3Y3.determinant(); return F12; } Vec2 Project(const Mat34 &P, const Vec3 &X) { Vec4 HX; HX << X, 1.0; Vec3 hx = P * HX; return hx.head<2>() / hx(2); } void Project(const Mat34 &P, const Mat3X &X, Mat2X *x) { assert(x != nullptr); x->resize(2, X.cols()); for (size_t c = 0; c < static_cast<size_t>(X.cols()); ++c) { x->col(c) = Project(P, Vec3(X.col(c))); } } void Project(const Mat34 &P, const Mat4X &X, Mat2X *x) { assert(x != nullptr); x->resize(2, X.cols()); for (Mat4X::Index c = 0; c < X.cols(); ++c) { Vec3 hx = P * X.col(c); x->col(c) = hx.head<2>() / hx(2); } } Mat2X Project(const Mat34 &P, const Mat3X &X) { Mat2X x(2, X.cols()); Project(P, X, &x); return x; } Mat2X Project(const Mat34 &P, const Mat4X &X) { Mat2X x(2, X.cols()); Project(P, X, &x); return x; } void HomogeneousToEuclidean(const Vec4 &H, Vec3 *X) { assert(X != nullptr); *X = H.hnormalized(); } void EuclideanToHomogeneous(const Mat &X, Mat *H) { assert(H != nullptr); *H = X.colwise().homogeneous(); } double Depth(const Mat3 &R, const Vec3 &t, const Vec3 &X) { return (R*X)[2] + t[2]; } Vec3 EuclideanToHomogeneous(const Vec2 &x) { return x.homogeneous(); } void HomogeneousToEuclidean(const Mat &H, Mat *X) { assert(X != nullptr); *X = H.colwise().hnormalized(); } Mat3X EuclideanToHomogeneous(const Mat2X &x) { return x.colwise().homogeneous(); } void EuclideanToHomogeneous(const Mat2X &x, Mat3X *h) { assert(h != nullptr); *h = x.colwise().homogeneous(); } void HomogeneousToEuclidean(const Mat3X &h, Mat2X *e) { assert(e != nullptr); *e = h.colwise().hnormalized(); } void EuclideanToNormalizedCamera(const Mat2X &x, const Mat3 &K, Mat2X *n) { assert(n != nullptr); Mat3X x_image_h; EuclideanToHomogeneous(x, &x_image_h); Mat3X x_camera_h = K.inverse() * x_image_h; HomogeneousToEuclidean(x_camera_h, n); } void HomogeneousToNormalizedCamera(const Mat3X &x, const Mat3 &K, Mat2X *n) { assert(n != nullptr); Mat3X x_camera_h = K.inverse() * x; HomogeneousToEuclidean(x_camera_h, n); } /// Estimates the root mean square error (2D) double RootMeanSquareError(const Mat2X &x_image, const Mat4X &X_world, const Mat34 &P) { const std::size_t num_points = x_image.cols(); const Mat2X dx = Project(P, X_world) - x_image; return dx.norm() / num_points; } /// Estimates the root mean square error (2D) double RootMeanSquareError(const Mat2X &x_image, const Mat3X &X_world, const Mat3 &K, const Mat3 &R, const Vec3 &t) { Mat34 P; P_From_KRt(K, R, t, &P); const std::size_t num_points = x_image.cols(); const Mat2X dx = Project(P, X_world) - x_image; return dx.norm() / num_points; } } // namespace openMVG <|endoftext|>