<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: xmltxtimp.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 01:16: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 _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif

#ifndef _COM_SUN_STAR_IO_XACTIVEDATACONTROL_HPP_
#include <com/sun/star/io/XActiveDataControl.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XACTIVEDATASOURCE_HPP_
#include <com/sun/star/io/XActiveDataSource.hpp>
#endif
#ifndef _COM_SUN_STAR_XML_SAX_XPARSER_HPP_
#include <com/sun/star/xml/sax/XParser.hpp>
#endif
#ifndef _COM_SUN_STAR_XML_SAX_XDOCUMENTHANDLER_HPP_
#include <com/sun/star/xml/sax/XDocumentHandler.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XOUTPUTSTREAM_HPP_
#include <com/sun/star/io/XOutputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_TEXT_XTEXT_HPP_
#include <com/sun/star/text/XText.hpp>
#endif

#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif

#ifndef _UTL_STREAM_WRAPPER_HXX_
#include <unotools/streamwrap.hxx>
#endif

#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif

#ifndef _SVSTOR_HXX
#include <sot/storage.hxx>
#endif

#ifndef _SFX_ITEMPROP_HXX
#include <svtools/itemprop.hxx>
#endif

#ifndef _SFXDOCFILE_HXX
#include <sfx2/docfile.hxx>
#endif

#ifndef _XMLOFF_XMLIMP_HXX
#include <xmloff/xmlimp.hxx>
#endif

#ifndef _XMLOFF_XMLMETAE_HXX
#include "xmloff/xmlmetae.hxx"
#endif
#ifndef _XMLOFF_XMLICTXT_HXX
#include <xmloff/xmlictxt.hxx>
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include <xmloff/xmlnmspe.hxx>
#endif
#ifndef _XMLOFF_XMLSTYLE_HXX
#include <xmloff/xmlstyle.hxx>
#endif

#ifndef _SVX_EDITSOURCE_HXX
#include "editsource.hxx"
#endif

#ifndef _SVX_UNOTEXT_HXX
#include "unotext.hxx"
#endif

using namespace com::sun::star;
using namespace com::sun::star::document;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::xml::sax;
using namespace com::sun::star::text;
using namespace ::rtl;
using namespace cppu;
using namespace xmloff::token;

///////////////////////////////////////////////////////////////////////

class SvxXMLTextImportContext : public SvXMLImportContext
{
public:
    SvxXMLTextImportContext( SvXMLImport& rImport, USHORT nPrfx, const OUString& rLName, const Reference< XAttributeList >& xAttrList, const Reference< XText >& xText );
    virtual ~SvxXMLTextImportContext();

    virtual SvXMLImportContext *CreateChildContext( USHORT nPrefix, const OUString& rLocalName, const Reference< XAttributeList >& xAttrList );

//  SvxXMLXTableImport& getImport() const { return *(SvxXMLXTableImport*)&GetImport(); }

private:
    const Reference< XText > mxText;
};

///////////////////////////////////////////////////////////////////////

SvxXMLTextImportContext::SvxXMLTextImportContext( SvXMLImport& rImport, USHORT nPrfx, const OUString& rLName, const Reference< XAttributeList >& xAttrList, const Reference< XText >& xText )
: SvXMLImportContext( rImport, nPrfx, rLName ), mxText( xText )
{
}

SvxXMLTextImportContext::~SvxXMLTextImportContext()
{
}

SvXMLImportContext *SvxXMLTextImportContext::CreateChildContext( USHORT nPrefix, const OUString& rLocalName, const Reference< XAttributeList >& xAttrList )
{
    SvXMLImportContext* pContext = NULL;
    if(XML_NAMESPACE_OFFICE == nPrefix && IsXMLToken( rLocalName, XML_BODY ) )
    {
        pContext = new SvxXMLTextImportContext( GetImport(), nPrefix, rLocalName, xAttrList, mxText );
    }
    else if( XML_NAMESPACE_OFFICE == nPrefix && IsXMLToken( rLocalName, XML_AUTOMATIC_STYLES ) )
    {
        pContext = new SvXMLStylesContext( GetImport(), nPrefix, rLocalName, xAttrList );
        GetImport().GetTextImport()->SetAutoStyles( (SvXMLStylesContext*)pContext );

    }
    else
    {
        pContext = GetImport().GetTextImport()->CreateTextChildContext( GetImport(), nPrefix, rLocalName, xAttrList );
    }

    if( NULL == pContext )
        pContext = new SvXMLImportContext( GetImport(), nPrefix, rLocalName );

    return pContext;
}

///////////////////////////////////////////////////////////////////////

class SvxXMLXTextImportComponent : public SvXMLImport
{
public:
    // #110680#
    SvxXMLXTextImportComponent(
        const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory,
        const Reference< XText > & xText );

    virtual ~SvxXMLXTextImportComponent() throw ();

    static sal_Bool load( const rtl::OUString& rUrl, const com::sun::star::uno::Reference< com::sun::star::container::XNameContainer >& xTable ) throw();
protected:
    virtual SvXMLImportContext *CreateChildContext( USHORT nPrefix, const OUString& rLocalName, const Reference< XAttributeList >& xAttrList );

private:
    const Reference< XText > mxText;
};

// --------------------------------------------------------------------

// #110680#
SvxXMLXTextImportComponent::SvxXMLXTextImportComponent(
    const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory,
    const Reference< XText > & xText )
:   SvXMLImport(xServiceFactory),
    mxText( xText )
{
    GetTextImport()->SetCursor( mxText->createTextCursor() );
}

SvxXMLXTextImportComponent::~SvxXMLXTextImportComponent() throw ()
{
}

void SvxReadXML( EditEngine& rEditEngine, SvStream& rStream, const ESelection& rSel )
{
    SvxEditEngineSource aEditSource( &rEditEngine );

    static const SfxItemPropertyMap SvxXMLTextImportComponentPropertyMap[] =
    {
        SVX_UNOEDIT_CHAR_PROPERTIES,
        SVX_UNOEDIT_FONT_PROPERTIES,
//      SVX_UNOEDIT_OUTLINER_PROPERTIES,
        SVX_UNOEDIT_PARA_PROPERTIES,
        {0,0}
    };

    uno::Reference<text::XText > xParent;
    SvxUnoText* pUnoText = new SvxUnoText( &aEditSource, SvxXMLTextImportComponentPropertyMap, xParent );
    pUnoText->SetSelection( rSel );
    uno::Reference<text::XText > xText( pUnoText );

    try
    {
        do
        {
            uno::Reference<lang::XMultiServiceFactory> xServiceFactory( ::comphelper::getProcessServiceFactory() );
            if( !xServiceFactory.is() )
            {
                DBG_ERROR( "SvxXMLXTableImport::load: got no service manager" );
                break;
            }

            uno::Reference< xml::sax::XParser > xParser( xServiceFactory->createInstance( OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.xml.sax.Parser" ) ) ), uno::UNO_QUERY );
            if( !xParser.is() )
            {
                DBG_ERROR( "com.sun.star.xml.sax.Parser service missing" );
                break;
            }

            Reference<io::XInputStream> xInputStream = new utl::OInputStreamWrapper( rStream );

/* testcode
            const OUString aURL( RTL_CONSTASCII_USTRINGPARAM( "file:///e:/test.xml" ) );
            SfxMedium aMedium( aURL, STREAM_READ | STREAM_NOCREATE, TRUE );
            aMedium.IsRemote();
            uno::Reference<io::XOutputStream> xOut( new utl::OOutputStreamWrapper( *aMedium.GetOutStream() ) );

            aMedium.GetInStream()->Seek( 0 );
            uno::Reference< io::XActiveDataSource > xSource( aMedium.GetDataSource() );

            if( !xSource.is() )
            {
                DBG_ERROR( "got no data source from medium" );
                break;
            }

            Reference< XInterface > xPipe( xServiceFactory->createInstance(OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.io.Pipe") ) ) );
            if( !xPipe.is() )
            {
                DBG_ERROR( "XMLReader::Read: com.sun.star.io.Pipe service missing" );
                break;
            }

            // connect pipe's output stream to the data source
            xSource->setOutputStream( Reference< io::XOutputStream >::query( xPipe ) );

            xml::sax::InputSource aParserInput;
            aParserInput.aInputStream = uno::Reference< io::XInputStream >::query( xPipe );
            aParserInput.sSystemId = aMedium.GetName();

            if( xSource.is() )
            {
                Reference< io::XActiveDataControl > xSourceControl( xSource, UNO_QUERY );
                xSourceControl->start();
            }

*/

            // #110680#
            // Reference< XDocumentHandler > xHandler( new SvxXMLXTextImportComponent( xText ) );
            Reference< XDocumentHandler > xHandler( new SvxXMLXTextImportComponent( xServiceFactory, xText ) );

            xParser->setDocumentHandler( xHandler );

            xml::sax::InputSource aParserInput;
            aParserInput.aInputStream = xInputStream;
//          aParserInput.sSystemId = aMedium.GetName();
            xParser->parseStream( aParserInput );
        }
        while(0);
    }
    catch( uno::Exception& e )
    {
    }
}

SvXMLImportContext *SvxXMLXTextImportComponent::CreateChildContext( USHORT nPrefix, const OUString& rLocalName, const Reference< XAttributeList >& xAttrList )
{
    SvXMLImportContext* pContext;
    if(XML_NAMESPACE_OFFICE == nPrefix && ( IsXMLToken( rLocalName, XML_DOCUMENT ) || IsXMLToken( rLocalName, XML_DOCUMENT_CONTENT ) ) )
    {
         pContext = new SvxXMLTextImportContext(*this, nPrefix, rLocalName, xAttrList, mxText );
    }
    else
    {
        pContext = SvXMLImport::CreateContext(nPrefix, rLocalName, xAttrList);
    }
    return pContext;
}

<commit_msg>INTEGRATION: CWS warnings01 (1.5.222); FILE MERGED 2006/05/12 12:25:32 ab 1.5.222.1: #i53898# Removed warnings for unxlngi6/unxlngi6.pro<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: xmltxtimp.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 17: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
 *
 ************************************************************************/

#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif

#ifndef _COM_SUN_STAR_IO_XACTIVEDATACONTROL_HPP_
#include <com/sun/star/io/XActiveDataControl.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XACTIVEDATASOURCE_HPP_
#include <com/sun/star/io/XActiveDataSource.hpp>
#endif
#ifndef _COM_SUN_STAR_XML_SAX_XPARSER_HPP_
#include <com/sun/star/xml/sax/XParser.hpp>
#endif
#ifndef _COM_SUN_STAR_XML_SAX_XDOCUMENTHANDLER_HPP_
#include <com/sun/star/xml/sax/XDocumentHandler.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XOUTPUTSTREAM_HPP_
#include <com/sun/star/io/XOutputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_TEXT_XTEXT_HPP_
#include <com/sun/star/text/XText.hpp>
#endif

#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif

#ifndef _UTL_STREAM_WRAPPER_HXX_
#include <unotools/streamwrap.hxx>
#endif

#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif

#ifndef _SVSTOR_HXX
#include <sot/storage.hxx>
#endif

#ifndef _SFX_ITEMPROP_HXX
#include <svtools/itemprop.hxx>
#endif

#ifndef _SFXDOCFILE_HXX
#include <sfx2/docfile.hxx>
#endif

#ifndef _XMLOFF_XMLIMP_HXX
#include <xmloff/xmlimp.hxx>
#endif

#ifndef _XMLOFF_XMLMETAE_HXX
#include "xmloff/xmlmetae.hxx"
#endif
#ifndef _XMLOFF_XMLICTXT_HXX
#include <xmloff/xmlictxt.hxx>
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include <xmloff/xmlnmspe.hxx>
#endif
#ifndef _XMLOFF_XMLSTYLE_HXX
#include <xmloff/xmlstyle.hxx>
#endif

#ifndef _SVX_EDITSOURCE_HXX
#include "editsource.hxx"
#endif

#ifndef _SVX_UNOTEXT_HXX
#include "unotext.hxx"
#endif

using namespace com::sun::star;
using namespace com::sun::star::document;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::xml::sax;
using namespace com::sun::star::text;
using namespace ::rtl;
using namespace cppu;
using namespace xmloff::token;

///////////////////////////////////////////////////////////////////////

class SvxXMLTextImportContext : public SvXMLImportContext
{
public:
    SvxXMLTextImportContext( SvXMLImport& rImport, USHORT nPrfx, const OUString& rLName, const Reference< XAttributeList >& xAttrList, const Reference< XText >& xText );
    virtual ~SvxXMLTextImportContext();

    virtual SvXMLImportContext *CreateChildContext( USHORT nPrefix, const OUString& rLocalName, const Reference< XAttributeList >& xAttrList );

//  SvxXMLXTableImport& getImport() const { return *(SvxXMLXTableImport*)&GetImport(); }

private:
    const Reference< XText > mxText;
};

///////////////////////////////////////////////////////////////////////

SvxXMLTextImportContext::SvxXMLTextImportContext( SvXMLImport& rImport, USHORT nPrfx, const OUString& rLName, const Reference< XAttributeList >&, const Reference< XText >& xText )
: SvXMLImportContext( rImport, nPrfx, rLName ), mxText( xText )
{
}

SvxXMLTextImportContext::~SvxXMLTextImportContext()
{
}

SvXMLImportContext *SvxXMLTextImportContext::CreateChildContext( USHORT nPrefix, const OUString& rLocalName, const Reference< XAttributeList >& xAttrList )
{
    SvXMLImportContext* pContext = NULL;
    if(XML_NAMESPACE_OFFICE == nPrefix && IsXMLToken( rLocalName, XML_BODY ) )
    {
        pContext = new SvxXMLTextImportContext( GetImport(), nPrefix, rLocalName, xAttrList, mxText );
    }
    else if( XML_NAMESPACE_OFFICE == nPrefix && IsXMLToken( rLocalName, XML_AUTOMATIC_STYLES ) )
    {
        pContext = new SvXMLStylesContext( GetImport(), nPrefix, rLocalName, xAttrList );
        GetImport().GetTextImport()->SetAutoStyles( (SvXMLStylesContext*)pContext );

    }
    else
    {
        pContext = GetImport().GetTextImport()->CreateTextChildContext( GetImport(), nPrefix, rLocalName, xAttrList );
    }

    if( NULL == pContext )
        pContext = new SvXMLImportContext( GetImport(), nPrefix, rLocalName );

    return pContext;
}

///////////////////////////////////////////////////////////////////////

class SvxXMLXTextImportComponent : public SvXMLImport
{
public:
    // #110680#
    SvxXMLXTextImportComponent(
        const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory,
        const Reference< XText > & xText );

    virtual ~SvxXMLXTextImportComponent() throw ();

    static sal_Bool load( const rtl::OUString& rUrl, const com::sun::star::uno::Reference< com::sun::star::container::XNameContainer >& xTable ) throw();
protected:
    virtual SvXMLImportContext *CreateChildContext( USHORT nPrefix, const OUString& rLocalName, const Reference< XAttributeList >& xAttrList );

private:
    const Reference< XText > mxText;
};

// --------------------------------------------------------------------

// #110680#
SvxXMLXTextImportComponent::SvxXMLXTextImportComponent(
    const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory,
    const Reference< XText > & xText )
:   SvXMLImport(xServiceFactory),
    mxText( xText )
{
    GetTextImport()->SetCursor( mxText->createTextCursor() );
}

SvxXMLXTextImportComponent::~SvxXMLXTextImportComponent() throw ()
{
}

void SvxReadXML( EditEngine& rEditEngine, SvStream& rStream, const ESelection& rSel )
{
    SvxEditEngineSource aEditSource( &rEditEngine );

    static const SfxItemPropertyMap SvxXMLTextImportComponentPropertyMap[] =
    {
        SVX_UNOEDIT_CHAR_PROPERTIES,
        SVX_UNOEDIT_FONT_PROPERTIES,
//      SVX_UNOEDIT_OUTLINER_PROPERTIES,
        SVX_UNOEDIT_PARA_PROPERTIES,
        {0,0,0,0,0,0}
    };

    uno::Reference<text::XText > xParent;
    SvxUnoText* pUnoText = new SvxUnoText( &aEditSource, SvxXMLTextImportComponentPropertyMap, xParent );
    pUnoText->SetSelection( rSel );
    uno::Reference<text::XText > xText( pUnoText );

    try
    {
        do
        {
            uno::Reference<lang::XMultiServiceFactory> xServiceFactory( ::comphelper::getProcessServiceFactory() );
            if( !xServiceFactory.is() )
            {
                DBG_ERROR( "SvxXMLXTableImport::load: got no service manager" );
                break;
            }

            uno::Reference< xml::sax::XParser > xParser( xServiceFactory->createInstance( OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.xml.sax.Parser" ) ) ), uno::UNO_QUERY );
            if( !xParser.is() )
            {
                DBG_ERROR( "com.sun.star.xml.sax.Parser service missing" );
                break;
            }

            Reference<io::XInputStream> xInputStream = new utl::OInputStreamWrapper( rStream );

/* testcode
            const OUString aURL( RTL_CONSTASCII_USTRINGPARAM( "file:///e:/test.xml" ) );
            SfxMedium aMedium( aURL, STREAM_READ | STREAM_NOCREATE, TRUE );
            aMedium.IsRemote();
            uno::Reference<io::XOutputStream> xOut( new utl::OOutputStreamWrapper( *aMedium.GetOutStream() ) );

            aMedium.GetInStream()->Seek( 0 );
            uno::Reference< io::XActiveDataSource > xSource( aMedium.GetDataSource() );

            if( !xSource.is() )
            {
                DBG_ERROR( "got no data source from medium" );
                break;
            }

            Reference< XInterface > xPipe( xServiceFactory->createInstance(OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.io.Pipe") ) ) );
            if( !xPipe.is() )
            {
                DBG_ERROR( "XMLReader::Read: com.sun.star.io.Pipe service missing" );
                break;
            }

            // connect pipe's output stream to the data source
            xSource->setOutputStream( Reference< io::XOutputStream >::query( xPipe ) );

            xml::sax::InputSource aParserInput;
            aParserInput.aInputStream = uno::Reference< io::XInputStream >::query( xPipe );
            aParserInput.sSystemId = aMedium.GetName();

            if( xSource.is() )
            {
                Reference< io::XActiveDataControl > xSourceControl( xSource, UNO_QUERY );
                xSourceControl->start();
            }

*/

            // #110680#
            // Reference< XDocumentHandler > xHandler( new SvxXMLXTextImportComponent( xText ) );
            Reference< XDocumentHandler > xHandler( new SvxXMLXTextImportComponent( xServiceFactory, xText ) );

            xParser->setDocumentHandler( xHandler );

            xml::sax::InputSource aParserInput;
            aParserInput.aInputStream = xInputStream;
//          aParserInput.sSystemId = aMedium.GetName();
            xParser->parseStream( aParserInput );
        }
        while(0);
    }
    catch( uno::Exception& e )
    {
    }
}

SvXMLImportContext *SvxXMLXTextImportComponent::CreateChildContext( USHORT nPrefix, const OUString& rLocalName, const Reference< XAttributeList >& xAttrList )
{
    SvXMLImportContext* pContext;
    if(XML_NAMESPACE_OFFICE == nPrefix && ( IsXMLToken( rLocalName, XML_DOCUMENT ) || IsXMLToken( rLocalName, XML_DOCUMENT_CONTENT ) ) )
    {
         pContext = new SvxXMLTextImportContext(*this, nPrefix, rLocalName, xAttrList, mxText );
    }
    else
    {
        pContext = SvXMLImport::CreateContext(nPrefix, rLocalName, xAttrList);
    }
    return pContext;
}

<|endoftext|>


<commit_before>#include "WPILib.h"
#include "Commands/Command.h"
#include "Commands/ExampleCommand.h"
#include "CommandBase.h"
#include "XboxController.h"
#include "Subsystems/Shooter.h"
#include "Subsystems/BallCollector.h"

class Robot: public IterativeRobot {

private:
	std::unique_ptr<Command> autonomousCommand;
	SendableChooser *chooser;
	std::unique_ptr<XboxController> controller;
	std::unique_ptr<RobotDrive> robot_drive;
	std::unique_ptr<Shooter> shooter;
	std::unique_ptr<BallCollector> picker_upper;

	void RobotInit() {
		CommandBase::init();
		chooser = new SendableChooser();
		chooser->AddDefault("Default Auto", new ExampleCommand());
		//chooser->AddObject("My Auto", new MyAutoCommand());
		SmartDashboard::PutData("Auto Modes", chooser);
		controller = std::unique_ptr<XboxController>(new XboxController(0));
		robot_drive = std::unique_ptr<RobotDrive> (new RobotDrive(1,2,3,4));
		shooter = std::unique_ptr<Shooter> (new Shooter());
		picker_upper = std::unique_ptr<BallCollector> (new BallCollector());
	}

	/**
     * This function is called once each time the robot enters Disabled mode.
     * You can use it to reset any subsystem information you want to clear when
	 * the robot is disabled.
     */
	void DisabledInit() {
	}

	void DisabledPeriodic() {
		Scheduler::GetInstance()->Run();
	}

	/**
	 * This autonomous (along with the chooser code above) shows how to select between different autonomous modes
	 * using the dashboard. The sendable chooser code works with the Java SmartDashboard. If you prefer the LabVIEW
	 * Dashboard, remove all of the chooser code and uncomment the GetString code to get the auto name from the text box
	 * below the Gyro
	 *
	 * You can add additional auto modes by adding additional commands to the chooser code above (like the commented example)
	 * or additional comparisons to the if-else structure below with additional strings & commands.
	 */
	void AutonomousInit() {
		/* std::string autoSelected = SmartDashboard::GetString("Auto Selector", "Default");
		if(autoSelected == "My Auto") {
			autonomousCommand.reset(new MyAutoCommand());
		} else {
			autonomousCommand.reset(new ExampleCommand());
		} */

		autonomousCommand.reset((Command *)chooser->GetSelected());

		if (autonomousCommand != NULL)
			autonomousCommand->Start();
	}

	void AutonomousPeriodic() {
		Scheduler::GetInstance()->Run();
	}

	void TeleopInit() {
		// This makes sure that the autonomous stops running when
		// teleop starts running. If you want the autonomous to
		// continue until interrupted by another command, remove
		// this line or comment it out.
		if (autonomousCommand != NULL)
			autonomousCommand->Cancel();
	}

	void TeleopPeriodic() {
		Scheduler::GetInstance()->Run();

		std::unique_ptr<Vector> left_stick_vector = std::unique_ptr<Vector>(controller->GetLeftVector());
		std::unique_ptr<Vector> right_stick_vector = std::unique_ptr<Vector>(controller->GetRightVector());

		robot_drive->TankDrive(left_stick_vector->magnitude, right_stick_vector->magnitude, false);

		if (controller->GetTrigger(controller->RightTrigger,controller->RightTriggerOffset) >= 0.5){
			shooter->run_shooter();
		}else{
			shooter->stop_shooter();
		}

		if (controller->GetTrigger(controller->LeftTrigger,controller->LeftTriggerOffset) >= 0.5){
			picker_upper->Start();
		}else{
			picker_upper->Stop();
		}
	}

	void TestPeriodic() {
		LiveWindow::GetInstance()->Run();
	}
};

START_ROBOT_CLASS(Robot)

<commit_msg>Removed old command base code<commit_after>#include "WPILib.h"
#include "XboxController.h"
#include "Subsystems/Shooter.h"
#include "Subsystems/BallCollector.h"

class Robot: public IterativeRobot {
private:
	std::unique_ptr<XboxController> controller;
	std::unique_ptr<RobotDrive> robot_drive;
	std::unique_ptr<Shooter> shooter;
	std::unique_ptr<BallCollector> ball_collector;

	void RobotInit() {
		// Initialize Subsystems
		controller = std::unique_ptr<XboxController>(new XboxController(0));
		robot_drive = std::unique_ptr<RobotDrive> (new RobotDrive(1,2,3,4));
		shooter = std::unique_ptr<Shooter> (new Shooter());
		ball_collector = std::unique_ptr<BallCollector> (new BallCollector());
	}

	void DisabledInit() {
	}

	void DisabledPeriodic() {
		Scheduler::GetInstance()->Run();
	}

	void AutonomousInit() {

	}

	void AutonomousPeriodic() {

	}

	void TeleopInit() {

	}

	void TeleopPeriodic() {
		std::unique_ptr<Vector> left_stick_vector = std::unique_ptr<Vector>(controller->GetLeftVector());
		std::unique_ptr<Vector> right_stick_vector = std::unique_ptr<Vector>(controller->GetRightVector());

		robot_drive->TankDrive(left_stick_vector->magnitude, right_stick_vector->magnitude, false);

		if (controller->GetTrigger(controller->RightTrigger,controller->RightTriggerOffset) >= 0.5){
			shooter->run_shooter();
		}else{
			shooter->stop_shooter();
		}

		if (controller->GetTrigger(controller->LeftTrigger,controller->LeftTriggerOffset) >= 0.5){
			ball_collector->Start();
		}else{
			ball_collector->Stop();
		}
	}

	void TestPeriodic() {

	}
};

START_ROBOT_CLASS(Robot)

<|endoftext|>


<commit_before>/**
 * This file is part of the CernVM File System.
 */

#include "gtest/gtest.h"

#include "json_document.h"
#include "json_document_write.h"
#include "platform.h"
#include "statistics.h"
#include "util/pointer.h"

using namespace std;  // NOLINT

namespace perf {

TEST(T_Statistics, Counter) {
  Counter counter;
  EXPECT_EQ(0, counter.Get());
  counter.Set(1);
  EXPECT_EQ(1, counter.Get());
  counter.Inc();
  EXPECT_EQ(2, counter.Get());
  counter.Dec();
  EXPECT_EQ(1, counter.Get());
  EXPECT_EQ(1, counter.Xadd(-1));
  EXPECT_EQ(0, counter.Get());
  counter.Dec();
  EXPECT_EQ(-1, counter.Get());

  counter.Set(1024*1024);
  EXPECT_EQ("1048576", counter.Print());
  EXPECT_EQ("1024", counter.PrintKi());
  EXPECT_EQ("1048", counter.PrintK());
  EXPECT_EQ("1", counter.PrintM());
  EXPECT_EQ("1", counter.PrintMi());

  Counter counter2;
  EXPECT_EQ("inf", counter.PrintRatio(counter2));
  counter2.Set(1024);
  EXPECT_EQ("1024.000", counter.PrintRatio(counter2));
}

TEST(T_Statistics, Statistics) {
  Statistics statistics;

  Counter *counter = statistics.Register("test.counter", "a test counter");
  ASSERT_TRUE(counter != NULL);
  EXPECT_EQ(0, counter->Get());

  ASSERT_DEATH(statistics.Register("test.counter", "Name Clash"), ".*");
  EXPECT_EQ(0, statistics.Lookup("test.counter")->Get());
  EXPECT_EQ("a test counter", statistics.LookupDesc("test.counter"));

  EXPECT_EQ(NULL, statistics.Lookup("test.unknown"));

  EXPECT_EQ("test.counter|0|a test counter\n",
            statistics.PrintList(Statistics::kPrintSimple));
}

TEST(T_Statistics, Fork) {
  Statistics stat_father;

  Counter *cnt_father = stat_father.Register("father", "a test counter");
  perf::Inc(cnt_father);
  EXPECT_EQ(1, stat_father.Lookup("father")->Get());
  Statistics *stat_child = stat_father.Fork();
  EXPECT_EQ(1, stat_child->Lookup("father")->Get());
  perf::Inc(cnt_father);
  EXPECT_EQ(2, stat_father.Lookup("father")->Get());
  EXPECT_EQ(2, stat_child->Lookup("father")->Get());

  Counter *cnt_fork_father = stat_father.Register("fork", "a test counter");
  stat_child->Register("fork", "a test counter");
  perf::Inc(cnt_fork_father);
  EXPECT_EQ(1, stat_father.Lookup("fork")->Get());
  EXPECT_EQ(0, stat_child->Lookup("fork")->Get());

  delete stat_child;
  EXPECT_EQ(2, stat_father.Lookup("father")->Get());
}

TEST(T_Statistics, StatisticsTemplate) {
  Statistics statistics;
  StatisticsTemplate stat_template1("template1", &statistics);
  StatisticsTemplate stat_template2("template2", &statistics);
  StatisticsTemplate stat_sub("sub", stat_template1);

  Counter *cnt1 = stat_template1.RegisterTemplated("value", "a test counter");
  Counter *cnt2 = stat_template2.RegisterTemplated("value", "a test counter");
  Counter *cnt_sub = stat_sub.RegisterTemplated("value", "test");
  EXPECT_EQ(cnt1, statistics.Lookup("template1.value"));
  EXPECT_EQ(cnt2, statistics.Lookup("template2.value"));
  EXPECT_EQ(cnt_sub, statistics.Lookup("template1.sub.value"));
}

TEST(T_Statistics, RecorderConstruct) {
  Recorder recorder(5, 10);
  EXPECT_EQ(10U, recorder.capacity_s());
  Recorder recorder2(5, 9);
  EXPECT_EQ(10U, recorder2.capacity_s());
  Recorder recorder3(5, 6);
  EXPECT_EQ(10U, recorder3.capacity_s());
  Recorder recorder4(1, 10);
  EXPECT_EQ(10U, recorder4.capacity_s());
}

TEST(T_Statistics, RecorderTick) {
  Recorder recorder(1, 10);

  EXPECT_EQ(0U, recorder.GetNoTicks(0));
  EXPECT_EQ(0U, recorder.GetNoTicks(1));
  EXPECT_EQ(0U, recorder.GetNoTicks(uint32_t(-1)));

  recorder.Tick();
  recorder.TickAt(platform_monotonic_time() - 5);
  EXPECT_EQ(1U, recorder.GetNoTicks(1));
  EXPECT_EQ(2U, recorder.GetNoTicks(uint32_t(-1)));

  // Don't record tick in the distant past
  recorder.TickAt(0);
  EXPECT_EQ(2U, recorder.GetNoTicks(uint32_t(-1)));

  // Many ticks in a past period
  Recorder recorder2(1, 10);
  for (unsigned i = 0; i < 10; ++i)
    recorder2.TickAt(i);
  EXPECT_EQ(0U, recorder2.GetNoTicks(1));
  EXPECT_EQ(10U, recorder2.GetNoTicks(uint32_t(-1)));
  // Long gap with no ticks
  recorder2.Tick();
  EXPECT_EQ(1U, recorder2.GetNoTicks(uint32_t(-1)));

  // Ticks not starting at zero
  Recorder recorder3(1, 10);
  for (unsigned i = 2; i < 12; ++i)
    recorder3.TickAt(i);
  EXPECT_EQ(0U, recorder3.GetNoTicks(1));
  EXPECT_EQ(10U, recorder3.GetNoTicks(uint32_t(-1)));

  // More coarse-grained binning, ring buffer overflow
  Recorder recorder4(2, 10);
  for (unsigned i = 2; i < 22; ++i)
    recorder4.TickAt(i);
  EXPECT_EQ(0U, recorder4.GetNoTicks(1));
  EXPECT_EQ(10U, recorder4.GetNoTicks(uint32_t(-1)));

  // Clear bins
  Recorder recorder5(1, 10);
  for (unsigned i = 2; i < 12; ++i)
    recorder5.TickAt(i);
  recorder5.TickAt(14);
  EXPECT_EQ(8U, recorder5.GetNoTicks(uint32_t(-1)));
}

TEST(T_Statistics, MultiRecorder) {
  MultiRecorder recorder;
  recorder.Tick();
  EXPECT_EQ(0U, recorder.GetNoTicks(uint32_t(-1)));

  recorder.AddRecorder(1, 10);
  recorder.AddRecorder(2, 20);
  for (unsigned i = 2; i < 22; ++i)
    recorder.TickAt(i);
  EXPECT_EQ(20U, recorder.GetNoTicks(uint32_t(-1)));
  recorder.Tick();
  EXPECT_EQ(1U, recorder.GetNoTicks(1));
  EXPECT_EQ(1U, recorder.GetNoTicks(uint32_t(-1)));
}

TEST(T_Statistics, GenerateCorrectJsonEvenWithoutInput) {
  Statistics stats;
  std::string output = stats.PrintJSON();

  UniquePtr<JsonDocument> json(JsonDocument::Create(output));
  ASSERT_TRUE(json.IsValid());
}

}  // namespace perf
<commit_msg>T_Statistics: add unittest for PrintJSON()<commit_after>/**
 * This file is part of the CernVM File System.
 */

#include "gtest/gtest.h"

#include "json_document.h"
#include "json_document_write.h"
#include "platform.h"
#include "statistics.h"
#include "util/pointer.h"

using namespace std;  // NOLINT

namespace perf {

TEST(T_Statistics, Counter) {
  Counter counter;
  EXPECT_EQ(0, counter.Get());
  counter.Set(1);
  EXPECT_EQ(1, counter.Get());
  counter.Inc();
  EXPECT_EQ(2, counter.Get());
  counter.Dec();
  EXPECT_EQ(1, counter.Get());
  EXPECT_EQ(1, counter.Xadd(-1));
  EXPECT_EQ(0, counter.Get());
  counter.Dec();
  EXPECT_EQ(-1, counter.Get());

  counter.Set(1024*1024);
  EXPECT_EQ("1048576", counter.Print());
  EXPECT_EQ("1024", counter.PrintKi());
  EXPECT_EQ("1048", counter.PrintK());
  EXPECT_EQ("1", counter.PrintM());
  EXPECT_EQ("1", counter.PrintMi());

  Counter counter2;
  EXPECT_EQ("inf", counter.PrintRatio(counter2));
  counter2.Set(1024);
  EXPECT_EQ("1024.000", counter.PrintRatio(counter2));
}

TEST(T_Statistics, Statistics) {
  Statistics statistics;

  Counter *counter = statistics.Register("test.counter", "a test counter");
  ASSERT_TRUE(counter != NULL);
  EXPECT_EQ(0, counter->Get());

  ASSERT_DEATH(statistics.Register("test.counter", "Name Clash"), ".*");
  EXPECT_EQ(0, statistics.Lookup("test.counter")->Get());
  EXPECT_EQ("a test counter", statistics.LookupDesc("test.counter"));

  EXPECT_EQ(NULL, statistics.Lookup("test.unknown"));

  EXPECT_EQ("test.counter|0|a test counter\n",
            statistics.PrintList(Statistics::kPrintSimple));
}

TEST(T_Statistics, Fork) {
  Statistics stat_father;

  Counter *cnt_father = stat_father.Register("father", "a test counter");
  perf::Inc(cnt_father);
  EXPECT_EQ(1, stat_father.Lookup("father")->Get());
  Statistics *stat_child = stat_father.Fork();
  EXPECT_EQ(1, stat_child->Lookup("father")->Get());
  perf::Inc(cnt_father);
  EXPECT_EQ(2, stat_father.Lookup("father")->Get());
  EXPECT_EQ(2, stat_child->Lookup("father")->Get());

  Counter *cnt_fork_father = stat_father.Register("fork", "a test counter");
  stat_child->Register("fork", "a test counter");
  perf::Inc(cnt_fork_father);
  EXPECT_EQ(1, stat_father.Lookup("fork")->Get());
  EXPECT_EQ(0, stat_child->Lookup("fork")->Get());

  delete stat_child;
  EXPECT_EQ(2, stat_father.Lookup("father")->Get());
}

TEST(T_Statistics, StatisticsTemplate) {
  Statistics statistics;
  StatisticsTemplate stat_template1("template1", &statistics);
  StatisticsTemplate stat_template2("template2", &statistics);
  StatisticsTemplate stat_sub("sub", stat_template1);

  Counter *cnt1 = stat_template1.RegisterTemplated("value", "a test counter");
  Counter *cnt2 = stat_template2.RegisterTemplated("value", "a test counter");
  Counter *cnt_sub = stat_sub.RegisterTemplated("value", "test");
  EXPECT_EQ(cnt1, statistics.Lookup("template1.value"));
  EXPECT_EQ(cnt2, statistics.Lookup("template2.value"));
  EXPECT_EQ(cnt_sub, statistics.Lookup("template1.sub.value"));
}

TEST(T_Statistics, RecorderConstruct) {
  Recorder recorder(5, 10);
  EXPECT_EQ(10U, recorder.capacity_s());
  Recorder recorder2(5, 9);
  EXPECT_EQ(10U, recorder2.capacity_s());
  Recorder recorder3(5, 6);
  EXPECT_EQ(10U, recorder3.capacity_s());
  Recorder recorder4(1, 10);
  EXPECT_EQ(10U, recorder4.capacity_s());
}

TEST(T_Statistics, RecorderTick) {
  Recorder recorder(1, 10);

  EXPECT_EQ(0U, recorder.GetNoTicks(0));
  EXPECT_EQ(0U, recorder.GetNoTicks(1));
  EXPECT_EQ(0U, recorder.GetNoTicks(uint32_t(-1)));

  recorder.Tick();
  recorder.TickAt(platform_monotonic_time() - 5);
  EXPECT_EQ(1U, recorder.GetNoTicks(1));
  EXPECT_EQ(2U, recorder.GetNoTicks(uint32_t(-1)));

  // Don't record tick in the distant past
  recorder.TickAt(0);
  EXPECT_EQ(2U, recorder.GetNoTicks(uint32_t(-1)));

  // Many ticks in a past period
  Recorder recorder2(1, 10);
  for (unsigned i = 0; i < 10; ++i)
    recorder2.TickAt(i);
  EXPECT_EQ(0U, recorder2.GetNoTicks(1));
  EXPECT_EQ(10U, recorder2.GetNoTicks(uint32_t(-1)));
  // Long gap with no ticks
  recorder2.Tick();
  EXPECT_EQ(1U, recorder2.GetNoTicks(uint32_t(-1)));

  // Ticks not starting at zero
  Recorder recorder3(1, 10);
  for (unsigned i = 2; i < 12; ++i)
    recorder3.TickAt(i);
  EXPECT_EQ(0U, recorder3.GetNoTicks(1));
  EXPECT_EQ(10U, recorder3.GetNoTicks(uint32_t(-1)));

  // More coarse-grained binning, ring buffer overflow
  Recorder recorder4(2, 10);
  for (unsigned i = 2; i < 22; ++i)
    recorder4.TickAt(i);
  EXPECT_EQ(0U, recorder4.GetNoTicks(1));
  EXPECT_EQ(10U, recorder4.GetNoTicks(uint32_t(-1)));

  // Clear bins
  Recorder recorder5(1, 10);
  for (unsigned i = 2; i < 12; ++i)
    recorder5.TickAt(i);
  recorder5.TickAt(14);
  EXPECT_EQ(8U, recorder5.GetNoTicks(uint32_t(-1)));
}

TEST(T_Statistics, MultiRecorder) {
  MultiRecorder recorder;
  recorder.Tick();
  EXPECT_EQ(0U, recorder.GetNoTicks(uint32_t(-1)));

  recorder.AddRecorder(1, 10);
  recorder.AddRecorder(2, 20);
  for (unsigned i = 2; i < 22; ++i)
    recorder.TickAt(i);
  EXPECT_EQ(20U, recorder.GetNoTicks(uint32_t(-1)));
  recorder.Tick();
  EXPECT_EQ(1U, recorder.GetNoTicks(1));
  EXPECT_EQ(1U, recorder.GetNoTicks(uint32_t(-1)));
}

TEST(T_Statistics, GenerateCorrectJsonEvenWithoutInput) {
  Statistics stats;
  std::string output = stats.PrintJSON();

  UniquePtr<JsonDocument> json(JsonDocument::Create(output));
  ASSERT_TRUE(json.IsValid());
}

TEST(T_Statistics, GenerateJSONStatisticsTemplates) {
  Statistics stats;
  StatisticsTemplate stat_template1("template1", &stats);
  StatisticsTemplate stat_template2("template2", &stats);
  StatisticsTemplate stat_template_empty("emptytemplate", &stats);

  Counter *cnt1 = stat_template1.RegisterTemplated("valueA", "test counter A");
  Counter *cnt2 = stat_template1.RegisterTemplated("valueB", "test counter B");
  Counter *cnt3 = stat_template2.RegisterTemplated("valueC", "test counter C");
  cnt1->Set(420);
  cnt2->Set(0);
  cnt3->Set(-42);

  std::string json_observed = stats.PrintJSON();
  std::string json_expected =
    "{\"template1\":{\"valueA\":420,\"valueB\":0},"
    "\"template2\":{\"valueC\":-42}}";

  EXPECT_EQ(json_expected, json_observed);
}

}  // namespace perf
<|endoftext|>


<commit_before>/*
Pololu Motor Driver Code for Use with Arduino Microcontroller.
Adapted from https://github.com/pololu/qik-arduino, a pololu supplied library
Author: Alex Sher, 17 Oct 2013
*/

#include "serial_interface.h"

// serial command buffer storage
char cmd[5];

// C++ serial interface stuff
using namespace LibSerial;
SerialStream serial_port;
char readBuffer[1];
int numBytesRead;

// Pololu Object, works for models 2s9v1 and 2s12v10
PololuQik::PololuQik(char serial_port_filename[])
{
  // Open port for reading and writing
  serial_port.Open(serial_port_filename);
  if(!serial_port.good()){
    printf("Error, can't open serial port ya dingwad \n");
    exit(0);
  }
  serial_port.SetBaudRate(SerialStreamBuf::BAUD_9600);
  if(!serial_port.good()){
    printf("Error setting baud rate, exiting \n");
    exit(0);
  }
  // Tell Pololu Motor Driver to autodetect Baud Rate
  memset(cmd, 0, 5);
  cmd[0] = 0xAA;
  serial_port.write(cmd, 1);
}
/*
Will develop once Set Speed works as expected
// Return Firmware Version
char PololuQik::getFirmwareVersion()
{
  write(QIK_GET_FIRMWARE_VERSION);
  while (available() < 1);
  memset(readBuffer, 0, 1);
  return fread(readBuffer, sizeof(char), serPort);
}

// Return Error Byte (definitions here: http://www.pololu.com/docs/0J29/5.c)
byte PololuQik::getErrors()
{
  write(QIK_GET_ERROR_BYTE);
  while (available() < 1);
  return fread(readBuffer, sizeof(char), serPort);
}

// Return Configuration Parameters (see PololuQik.h for list of parameters)
byte PololuQik::getConfigurationParameter(byte parameter)
{
  listen();
  cmd[0] = QIK_GET_CONFIGURATION_PARAMETER;
  cmd[1] = parameter;
  write(cmd, 2);
  while (available() < 1);
  return fread(readBuffer, sizeof(char), serPort);
}

// Set Configuration parameters (see PololuQik.h for info on parameters)
byte PololuQik::setConfigurationParameter(byte parameter, byte value)
{
  listen();
  cmd[0] = QIK_SET_CONFIGURATION_PARAMETER;
  cmd[1] = parameter;
  cmd[2] = value;
  cmd[3] = 0x55;
  cmd[4] = 0x2A;
  write(cmd, 5);
  while (available() < 1);
  return read();
return fread(readBuffer, sizeof(char), serPort);
}
*/
// Set Speed command
void PololuQik::setM0Speed(int speed)
{
  // Direction value
  bool reverse = 0;

  // Handle negative direction speeds
  if (speed < 0)
  {
    // make speed a positive quantity
    speed = -speed;
    // preserve the direction
    reverse = 1;
  }

  // Clamp speed at Max readable speed
  if (speed > 255)
  {
    speed = 255;
  }

  // Reset Command byte
  memset(cmd, 0, 5);

  if (speed > 127)
  {
    // 8-bit mode: actual speed is (speed + 128)
    cmd[0] = reverse ? QIK_MOTOR_M0_REVERSE_8_BIT : QIK_MOTOR_M0_FORWARD_8_BIT;
    cmd[1] = speed - 128;
  }
  else
  {
    // lower bit mode, can physically write speed in normal mode
    cmd[0] = reverse ? QIK_MOTOR_M0_REVERSE : QIK_MOTOR_M0_FORWARD;
    cmd[1] = speed;
  }

  serial_port.write(cmd, 2);
}

// Set Speed command for second channel, see above for explanations
void PololuQik::setM1Speed(int speed)
{
  bool reverse = 0;

  if (speed < 0)
  {
    speed = -speed;
    reverse = 1;
  }

  if (speed > 255)
  {
    speed = 255;
  }

  memset(cmd, 0, 5);

  if (speed > 127)
  {
    cmd[0] = reverse ? QIK_MOTOR_M1_REVERSE_8_BIT : QIK_MOTOR_M1_FORWARD_8_BIT;
    cmd[1] = speed - 128;
  }
  else
  {
    cmd[0] = reverse ? QIK_MOTOR_M1_REVERSE : QIK_MOTOR_M1_FORWARD;
    cmd[1] = speed;
  }

  serial_port.write(cmd, 2);
}

// Set speeds on both channels
void PololuQik::setSpeeds(int m0Speed, int m1Speed)
{
  // Simply use commands written above
  setM0Speed(m0Speed);
  setM1Speed(m1Speed);
}

// 2s12v10 specific stuff

// Brake Command
void PololuQik2s12v10::setM0Brake(unsigned char brake)
{
  // Limit to 127, the brake limit
  if (brake > 127)
  {
    brake = 127;
  }

  // Reset Command buffer
  memset(cmd, 0, 5);

  // pack the command array
  cmd[0] = QIK_2S12V10_MOTOR_M0_BRAKE;
  cmd[1] = brake;

  // Serial write
  serial_port.write(cmd, 2);
}

// Brake command for second channel, see above for explanations
void PololuQik2s12v10::setM1Brake(unsigned char brake)
{
  if (brake > 127)
  {
    brake = 127;
  }

  memset(cmd, 0, 5);

  cmd[0] = QIK_2S12V10_MOTOR_M1_BRAKE;
  cmd[1] = brake;
  serial_port.write(cmd, 2);
}

// Dual Channel Brake Command
void PololuQik2s12v10::setBrakes(unsigned char m0Brake, unsigned char m1Brake)
{
  // Utlizie pre=written Brake Functions
  setM0Brake(m0Brake);
  setM1Brake(m1Brake);
}
/*
Under Development once we get main functionality working
// Get Current
unsigned char PololuQik2s12v10::getM0Current()
{
  // Make sure device is still there
  listen();
  // Write command byte
  write(QIK_2S12V10_GET_MOTOR_M0_CURRENT);
  // Wait for response
  while (available() < 1);
  // Return response
  return read();
  return fread(readBuffer, sizeof(char), serPort);
}

// Current command for second channel, see above for explanation
unsigned char PololuQik2s12v10::getM1Current()
{
  listen();
  write(QIK_2S12V10_GET_MOTOR_M1_CURRENT);
  while (available() < 1);
  return fread(readBuffer, sizeof(char), serPort);
}

// Current command for mA
unsigned int PololuQik2s12v10::getM0CurrentMilliamps()
{
  // Use regular current call and scale
  return getM0Current() * 150;
}

// Current command for second channel, see above for explanation
unsigned int PololuQik2s12v10::getM1CurrentMilliamps()
{
  return getM1Current() * 150;
}

// Get speed command
unsigned char PololuQik2s12v10::getM0Speed()
{
  // Make sure device is still there
  listen();
  // Write command byte
  write(QIK_2S12V10_GET_MOTOR_M0_SPEED);
  // Wait for a response
  while (available() < 1);
  // Return response
  return fread(readBuffer, sizeof(char), serPort);
}

// Speed command for second channel, see above for explanation
unsigned char PololuQik2s12v10::getM1Speed()
{
  listen();
  write(QIK_2S12V10_GET_MOTOR_M1_SPEED);
  while (available() < 1);
  return fread(readBuffer, sizeof(char), serPort);
}
*/
<commit_msg>Added Base Control launch file for launching all nodes necessary to control motors from computer.<commit_after>/*
Pololu Motor Driver Code for Use with Arduino Microcontroller.
Adapted from https://github.com/pololu/qik-arduino, a pololu supplied library
Author: Alex Sher, 17 Oct 2013
*/

#include "serial_interface.h"

// serial command buffer storage
char cmd[5];

// C++ serial interface stuff
using namespace LibSerial;
SerialStream serial_port;
char readBuffer[1];
int numBytesRead;

// Pololu Object, works for models 2s9v1 and 2s12v10
PololuQik::PololuQik(char serial_port_filename[])
{
  // Open port for reading and writing
  serial_port.Open(serial_port_filename);
  if(!serial_port.good()){
    printf("Error, can't open serial port ya dingwad \n");
    exit(1);
  }
  serial_port.SetBaudRate(SerialStreamBuf::BAUD_9600);
  if(!serial_port.good()){
    printf("Error setting baud rate, exiting \n");
    exit(1);
  }
  // Tell Pololu Motor Driver to autodetect Baud Rate
  memset(cmd, 0, 5);
  cmd[0] = 0xAA;
  serial_port.write(cmd, 1);
}
/*
Will develop once Set Speed works as expected
// Return Firmware Version
char PololuQik::getFirmwareVersion()
{
  write(QIK_GET_FIRMWARE_VERSION);
  while (available() < 1);
  memset(readBuffer, 0, 1);
  return fread(readBuffer, sizeof(char), serPort);
}

// Return Error Byte (definitions here: http://www.pololu.com/docs/0J29/5.c)
byte PololuQik::getErrors()
{
  write(QIK_GET_ERROR_BYTE);
  while (available() < 1);
  return fread(readBuffer, sizeof(char), serPort);
}

// Return Configuration Parameters (see PololuQik.h for list of parameters)
byte PololuQik::getConfigurationParameter(byte parameter)
{
  listen();
  cmd[0] = QIK_GET_CONFIGURATION_PARAMETER;
  cmd[1] = parameter;
  write(cmd, 2);
  while (available() < 1);
  return fread(readBuffer, sizeof(char), serPort);
}

// Set Configuration parameters (see PololuQik.h for info on parameters)
byte PololuQik::setConfigurationParameter(byte parameter, byte value)
{
  listen();
  cmd[0] = QIK_SET_CONFIGURATION_PARAMETER;
  cmd[1] = parameter;
  cmd[2] = value;
  cmd[3] = 0x55;
  cmd[4] = 0x2A;
  write(cmd, 5);
  while (available() < 1);
  return read();
return fread(readBuffer, sizeof(char), serPort);
}
*/
// Set Speed command
void PololuQik::setM0Speed(int speed)
{
  // Direction value
  bool reverse = 0;

  // Handle negative direction speeds
  if (speed < 0)
  {
    // make speed a positive quantity
    speed = -speed;
    // preserve the direction
    reverse = 1;
  }

  // Clamp speed at Max readable speed
  if (speed > 255)
  {
    speed = 255;
  }

  // Reset Command byte
  memset(cmd, 0, 5);

  if (speed > 127)
  {
    // 8-bit mode: actual speed is (speed + 128)
    cmd[0] = reverse ? QIK_MOTOR_M0_REVERSE_8_BIT : QIK_MOTOR_M0_FORWARD_8_BIT;
    cmd[1] = speed - 128;
  }
  else
  {
    // lower bit mode, can physically write speed in normal mode
    cmd[0] = reverse ? QIK_MOTOR_M0_REVERSE : QIK_MOTOR_M0_FORWARD;
    cmd[1] = speed;
  }

  serial_port.write(cmd, 2);
}

// Set Speed command for second channel, see above for explanations
void PololuQik::setM1Speed(int speed)
{
  bool reverse = 0;

  if (speed < 0)
  {
    speed = -speed;
    reverse = 1;
  }

  if (speed > 255)
  {
    speed = 255;
  }

  memset(cmd, 0, 5);

  if (speed > 127)
  {
    cmd[0] = reverse ? QIK_MOTOR_M1_REVERSE_8_BIT : QIK_MOTOR_M1_FORWARD_8_BIT;
    cmd[1] = speed - 128;
  }
  else
  {
    cmd[0] = reverse ? QIK_MOTOR_M1_REVERSE : QIK_MOTOR_M1_FORWARD;
    cmd[1] = speed;
  }

  serial_port.write(cmd, 2);
}

// Set speeds on both channels
void PololuQik::setSpeeds(int m0Speed, int m1Speed)
{
  // Simply use commands written above
  setM0Speed(m0Speed);
  setM1Speed(m1Speed);
}

// 2s12v10 specific stuff

// Brake Command
void PololuQik2s12v10::setM0Brake(unsigned char brake)
{
  // Limit to 127, the brake limit
  if (brake > 127)
  {
    brake = 127;
  }

  // Reset Command buffer
  memset(cmd, 0, 5);

  // pack the command array
  cmd[0] = QIK_2S12V10_MOTOR_M0_BRAKE;
  cmd[1] = brake;

  // Serial write
  serial_port.write(cmd, 2);
}

// Brake command for second channel, see above for explanations
void PololuQik2s12v10::setM1Brake(unsigned char brake)
{
  if (brake > 127)
  {
    brake = 127;
  }

  memset(cmd, 0, 5);

  cmd[0] = QIK_2S12V10_MOTOR_M1_BRAKE;
  cmd[1] = brake;
  serial_port.write(cmd, 2);
}

// Dual Channel Brake Command
void PololuQik2s12v10::setBrakes(unsigned char m0Brake, unsigned char m1Brake)
{
  // Utlizie pre=written Brake Functions
  setM0Brake(m0Brake);
  setM1Brake(m1Brake);
}
/*
Under Development once we get main functionality working
// Get Current
unsigned char PololuQik2s12v10::getM0Current()
{
  // Make sure device is still there
  listen();
  // Write command byte
  write(QIK_2S12V10_GET_MOTOR_M0_CURRENT);
  // Wait for response
  while (available() < 1);
  // Return response
  return read();
  return fread(readBuffer, sizeof(char), serPort);
}

// Current command for second channel, see above for explanation
unsigned char PololuQik2s12v10::getM1Current()
{
  listen();
  write(QIK_2S12V10_GET_MOTOR_M1_CURRENT);
  while (available() < 1);
  return fread(readBuffer, sizeof(char), serPort);
}

// Current command for mA
unsigned int PololuQik2s12v10::getM0CurrentMilliamps()
{
  // Use regular current call and scale
  return getM0Current() * 150;
}

// Current command for second channel, see above for explanation
unsigned int PololuQik2s12v10::getM1CurrentMilliamps()
{
  return getM1Current() * 150;
}

// Get speed command
unsigned char PololuQik2s12v10::getM0Speed()
{
  // Make sure device is still there
  listen();
  // Write command byte
  write(QIK_2S12V10_GET_MOTOR_M0_SPEED);
  // Wait for a response
  while (available() < 1);
  // Return response
  return fread(readBuffer, sizeof(char), serPort);
}

// Speed command for second channel, see above for explanation
unsigned char PololuQik2s12v10::getM1Speed()
{
  listen();
  write(QIK_2S12V10_GET_MOTOR_M1_SPEED);
  while (available() < 1);
  return fread(readBuffer, sizeof(char), serPort);
}
*/
<|endoftext|>


<commit_before>/***************************************************************************
*   Copyright (C) 2003 by                                                 *
*   Unai Garro (ugarro@users.sourceforge.net)                             *
*                                                                         *
*   This program is free software; you can redistribute it and/or modify  *
*   it under the terms of the GNU General Public License as published by  *
*   the Free Software Foundation; either version 2 of the License, or     *
*   (at your option) any later version.                                   *
***************************************************************************/

#include "ingredientmatcherdialog.h"

#include "datablocks/recipelist.h"
#include "widgets/ingredientlistview.h"
#include "datablocks/elementlist.h"
#include "backends/recipedb.h"
#include "widgets/krelistview.h"
#include "widgets/unitcombobox.h"
#include "widgets/fractioninput.h"
#include "widgets/amountunitinput.h"
#include "datablocks/mixednumber.h"
#include "recipeactionshandler.h"

#include <q3header.h>
#include <qpainter.h>
#include <qstringlist.h>
#include <qlayout.h>
#include <q3groupbox.h>
//Added by qt3to4:
#include <QHBoxLayout>
#include <Q3ValueList>
#include <QLabel>
#include <QVBoxLayout>

#include <kapplication.h>
#include <kcursor.h>
#include <kiconloader.h>
#include <klocale.h>
#include <knuminput.h>
#include <kconfig.h>
#include <kglobal.h>
#include <kdebug.h>
#include <kdialog.h>
#include <kvbox.h>

#include "profiling.h"

IngredientMatcherDialog::IngredientMatcherDialog( QWidget *parent, RecipeDB *db ) : QWidget( parent )
{
	// Initialize internal variables
	database = db;

	//Design the dialog

	QVBoxLayout *dialogLayout = new QVBoxLayout( this );
   dialogLayout->setMargin( 11 );
   dialogLayout->setSpacing( 6 );

	// Ingredient list
	QHBoxLayout *layout2 = new QHBoxLayout();
   layout2->setObjectName( "layout2" );
   layout2->setMargin( 0 );
   layout2->setSpacing( 6 );

	allIngListView = new KreListView( this, QString::null, true, 0 );
	StdIngredientListView *list_view = new StdIngredientListView(allIngListView,database);
	list_view->setSelectionMode( Q3ListView::Multi );
 	allIngListView->setListView(list_view);
	layout2->addWidget( allIngListView );

	QVBoxLayout *layout1 = new QVBoxLayout();
   layout1->setMargin( 0 );
   layout1->setSpacing( 6 );
   layout1->setObjectName( "layout1" );

	//KIconLoader *il = KIconLoader::global();

	addButton = new KPushButton( this );
   addButton->setObjectName( "addButton" );
	//addButton->setIconSet( il->loadIconSet( "go-next", KIcon::Small ) );
	addButton->setFixedSize( QSize( 32, 32 ) );
	layout1->addWidget( addButton );

	removeButton = new KPushButton( this );
   removeButton->setObjectName( "removeButton" );
	//removeButton->setIconSet( il->loadIconSet( "go-previous", KIcon::Small ) );
	removeButton->setFixedSize( QSize( 32, 32 ) );
	layout1->addWidget( removeButton );
	QSpacerItem *spacer1 = new QSpacerItem( 51, 191, QSizePolicy::Minimum, QSizePolicy::Expanding );
	layout1->addItem( spacer1 );
	layout2->addLayout( layout1 );

	ingListView = new KreListView( this, QString::null, true );
	ingListView->listView() ->addColumn( i18n( "Ingredient (required?)" ) );
	ingListView->listView() ->addColumn( i18n( "Amount Available" ) );
	layout2->addWidget( ingListView );
	dialogLayout->addLayout( layout2 );

	// Box to select allowed number of missing ingredients
	missingBox = new KHBox( this );
	missingNumberLabel = new QLabel( missingBox );
	missingNumberLabel->setText( i18n( "Missing ingredients allowed:" ) );
	missingNumberSpinBox = new KIntSpinBox( missingBox );
	missingNumberSpinBox->setMinimum( -1 );
	missingNumberSpinBox->setSpecialValueText( i18n( "Any" ) );
	dialogLayout->addWidget(missingBox);

	// Found recipe list
	recipeListView = new KreListView( this, i18n( "Matching Recipes" ), false, 1, missingBox );
	recipeListView->listView() ->setSizePolicy( QSizePolicy::Ignored, QSizePolicy::Ignored );
	recipeListView->listView() ->setAllColumnsShowFocus( true );

	recipeListView->listView() ->addColumn( i18n( "Title" ) );

	KConfigGroup config( KGlobal::config(), "Advanced" );
	bool show_id = config.readEntry( "ShowID", false );
	recipeListView->listView() ->addColumn( i18n( "Id" ), show_id ? -1 : 0 );

	recipeListView->listView() ->addColumn( i18n( "Missing Ingredients" ) );

	recipeListView->listView() ->setSorting( -1 );
	dialogLayout->addWidget(recipeListView);

	RecipeActionsHandler *actionHandler = new RecipeActionsHandler( recipeListView->listView(), database, RecipeActionsHandler::Open | RecipeActionsHandler::Edit | RecipeActionsHandler::Export );

	KHBox *buttonBox = new KHBox( this );

	okButton = new KPushButton( buttonBox );
	//okButton->setIconSet( il->loadIconSet( "dialog-ok", KIcon::Small ) );
	okButton->setText( i18n( "Find matching recipes" ) );

	//buttonBox->layout()->addItem( new QSpacerItem( 10,10, QSizePolicy::MinimumExpanding, QSizePolicy::Fixed ) );

	clearButton = new KPushButton( buttonBox );
	//clearButton->setIconSet( il->loadIconSet( "edit-clear", KIcon::Small ) );
	clearButton->setText( i18n( "Clear" ) );
	dialogLayout->addWidget(buttonBox);

	// Connect signals & slots
	connect ( okButton, SIGNAL( clicked() ), this, SLOT( findRecipes() ) );
	connect ( clearButton, SIGNAL( clicked() ), recipeListView->listView(), SLOT( clear() ) );
	connect ( clearButton, SIGNAL( clicked() ), this, SLOT( unselectIngredients() ) );
	connect ( actionHandler, SIGNAL( recipeSelected( int, int ) ), SIGNAL( recipeSelected( int, int ) ) );
	connect( addButton, SIGNAL( clicked() ), this, SLOT( addIngredient() ) );
	connect( removeButton, SIGNAL( clicked() ), this, SLOT( removeIngredient() ) );
	connect( ingListView->listView(), SIGNAL( doubleClicked( Q3ListViewItem*, const QPoint &, int ) ), SLOT( itemRenamed( Q3ListViewItem*, const QPoint &, int ) ) );
}

IngredientMatcherDialog::~IngredientMatcherDialog()
{
}

void IngredientMatcherDialog::itemRenamed( Q3ListViewItem* item, const QPoint &, int col )
{
	if ( col == 1 ) {
		KDialog amountEditDialog(this);
                amountEditDialog.setCaption(i18n("Enter amount"));
                amountEditDialog.setButtons(KDialog::Cancel | KDialog::Ok);
                amountEditDialog.setDefaultButton(KDialog::Ok);
                amountEditDialog.setModal( false );
		Q3GroupBox *box = new Q3GroupBox( 1, Qt::Horizontal, i18n("Amount"), &amountEditDialog );
		AmountUnitInput *amountEdit = new AmountUnitInput( box, database );
		// Set the values from the item
		if ( !item->text(1).isEmpty() ) {
			amountEdit->setAmount( MixedNumber::fromString(item->text(2)) );
			Unit u;
			u.id = item->text(3).toInt();
			amountEdit->setUnit( u );
		} else {
			amountEdit->setAmount( -1 );
			Unit u;
			u.id = -1;
			amountEdit->setUnit( u );
		}

		amountEditDialog.setMainWidget(box);

		if ( amountEditDialog.exec() == QDialog::Accepted ) {
			MixedNumber amount = amountEdit->amount();
			Unit unit = amountEdit->unit();

			if ( amount.toDouble() <= 1e-5 ) {
				amount = -1;
				unit.id = -1;

				item->setText(1,QString::null);
			} else {
				item->setText(1,amount.toString()+" "+((amount.toDouble()>1)?unit.plural:unit.name));
			}

			item->setText(2,amount.toString());
			item->setText(3,QString::number(unit.id));

			IngredientList::iterator ing_it = m_item_ing_map[item];
			(*ing_it).amount = amount.toDouble();
			(*ing_it).units = unit;
		}
	}
}

void IngredientMatcherDialog::addIngredient()
{
    /*
	QList<Q3ListViewItem> items = allIngListView->listView()->selectedItems();
	if ( !items.isEmpty() ) {
                for (int i = 0; i < items.size(); ++i) {
			bool dup = false;
			for ( Q3ListViewItem *exists_it = ingListView->listView()->firstChild(); exists_it; exists_it = exists_it->nextSibling() ) {
				if ( exists_it->text( 0 ) == item->text( 0 ) ) {
					dup = true;
					break;
				}
			}

			if ( !dup ) {
				Q3ListViewItem * new_item = new Q3CheckListItem( ingListView->listView(), item->text( 0 ), Q3CheckListItem::CheckBox );

				ingListView->listView() ->setSelected( new_item, true );
				ingListView->listView() ->ensureItemVisible( new_item );
				allIngListView->listView() ->setSelected( item, false );

				m_item_ing_map.insert( new_item, m_ingredientList.append( Ingredient( item->text( 0 ), 0, Unit(), -1, item->text( 1 ).toInt() ) ) );
			}
			++it;
		}
	}
    */
}

void IngredientMatcherDialog::removeIngredient()
{
    /*
	Q3ListViewItem * item = ingListView->listView() ->selectedItem();
	if ( item ) {
		for ( IngredientList::iterator it = m_ingredientList.begin(); it != m_ingredientList.end(); ++it ) {
			if ( *m_item_ing_map.find( item ) == it ) {
				m_ingredientList.remove( it );
				m_item_ing_map.remove( item );
				break;
			}
		}
		delete item;
	}
    */
}

void IngredientMatcherDialog::unselectIngredients()
{
	ingListView->listView()->clear();
	for ( Q3ListViewItem *it = allIngListView->listView()->firstChild(); it; it = it->nextSibling() )
		allIngListView->listView()->setSelected(it,false);
}

void IngredientMatcherDialog::findRecipes( void )
{
	KApplication::setOverrideCursor( Qt::WaitCursor );

	START_TIMER("Ingredient Matcher: loading database data");

	RecipeList rlist;
	database->loadRecipes( &rlist, RecipeDB::Title | RecipeDB::NamesOnly | RecipeDB::Ingredients | RecipeDB::IngredientAmounts );

	END_TIMER();
	START_TIMER("Ingredient Matcher: analyzing data for matching recipes");

	// Clear the list
	recipeListView->listView() ->clear();

	// Now show the recipes with ingredients that are contained in the previous set
	// of ingredients
	RecipeList incompleteRecipes;
	QList <int> missingNumbers;
	Q3ValueList <IngredientList> missingIngredients;

	RecipeList::Iterator it;
	for ( it = rlist.begin();it != rlist.end();++it ) {
		IngredientList il = ( *it ).ingList;
		if ( il.isEmpty() )
			continue;

		IngredientList missing;
		if ( m_ingredientList.containsSubSet( il, missing, true, database ) ) {
			new CustomRecipeListItem( recipeListView->listView(), *it );
		}
		else {
			incompleteRecipes.append( *it );
			missingIngredients.append( missing );
			missingNumbers.append( missing.count() );
		}
	}
	END_TIMER();

	//Check if the user wants to show missing ingredients

	if ( missingNumberSpinBox->value() == 0 ) {
		KApplication::restoreOverrideCursor();
		return ;
	} //"None"

	START_TIMER("Ingredient Matcher: searching for and displaying partial matches");

	IngredientList requiredIngredients;
	for ( Q3ListViewItem *it = ingListView->listView()->firstChild(); it; it = it->nextSibling() ) {
		if ( ((Q3CheckListItem*)it)->isOn() )
			requiredIngredients << *m_item_ing_map[it];
	}

	// Classify recipes with missing ingredients in different lists by ammount
	QList<int>::Iterator nit;
	Q3ValueList<IngredientList>::Iterator ilit;
	int missingNoAllowed = missingNumberSpinBox->value();

	if ( missingNoAllowed == -1 )  // "Any"
	{
		for ( nit = missingNumbers.begin();nit != missingNumbers.end();++nit )
			if ( ( *nit ) > missingNoAllowed )
				missingNoAllowed = ( *nit );
	}

	for ( int missingNo = 1; missingNo <= missingNoAllowed; missingNo++ ) {
		nit = missingNumbers.begin();
		ilit = missingIngredients.begin();

		bool titleShownYet = false;

		for ( it = incompleteRecipes.begin();it != incompleteRecipes.end();++it, ++nit, ++ilit ) {
			if ( !( *it ).ingList.containsAny( m_ingredientList ) )
				continue;

			if ( !( *it ).ingList.containsSubSet( requiredIngredients ) )
				continue;

			if ( ( *nit ) == missingNo ) {
				if ( !titleShownYet ) {
					new SectionItem( recipeListView->listView(), i18np( "You are missing 1 ingredient for:", "You are missing %1 ingredients for:", missingNo ) );
					titleShownYet = true;
				}
				new CustomRecipeListItem( recipeListView->listView(), *it, *ilit );
			}
		}
	}
	END_TIMER();

	KApplication::restoreOverrideCursor();
}

void IngredientMatcherDialog::reload( ReloadFlags flag )
{
	( ( StdIngredientListView* ) allIngListView->listView() ) ->reload(flag);
}

void SectionItem::paintCell ( QPainter * p, const QColorGroup & /*cg*/, int column, int width, int /*align*/ )
{
	// Draw the section's deco
	p->setPen( KGlobalSettings::activeTitleColor() );
	p->setBrush( KGlobalSettings::activeTitleColor() );
	p->drawRect( 0, 0, width, height() );

	// Draw the section's text
	if ( column == 0 ) {
		QFont titleFont = KGlobalSettings::windowTitleFont ();
		p->setFont( titleFont );

		p->setPen( KGlobalSettings::activeTextColor() );
		p->drawText( 0, 0, width, height(), Qt::AlignLeft | Qt::AlignVCenter, mText );
	}
}

#include "ingredientmatcherdialog.moc"
<commit_msg>Restored the icons for the buttons in the ingredient matcher dialog.<commit_after>/***************************************************************************
*   Copyright (C) 2003 by                                                 *
*   Unai Garro (ugarro@users.sourceforge.net)                             *
*                                                                         *
*   This program is free software; you can redistribute it and/or modify  *
*   it under the terms of the GNU General Public License as published by  *
*   the Free Software Foundation; either version 2 of the License, or     *
*   (at your option) any later version.                                   *
***************************************************************************/

#include "ingredientmatcherdialog.h"

#include "datablocks/recipelist.h"
#include "widgets/ingredientlistview.h"
#include "datablocks/elementlist.h"
#include "backends/recipedb.h"
#include "widgets/krelistview.h"
#include "widgets/unitcombobox.h"
#include "widgets/fractioninput.h"
#include "widgets/amountunitinput.h"
#include "datablocks/mixednumber.h"
#include "recipeactionshandler.h"

#include <q3header.h>
#include <qpainter.h>
#include <qstringlist.h>
#include <qlayout.h>
#include <q3groupbox.h>
//Added by qt3to4:
#include <QHBoxLayout>
#include <Q3ValueList>
#include <QLabel>
#include <QVBoxLayout>

#include <kapplication.h>
#include <kcursor.h>
#include <kiconloader.h>
#include <klocale.h>
#include <knuminput.h>
#include <kconfig.h>
#include <kglobal.h>
#include <kdebug.h>
#include <kdialog.h>
#include <kvbox.h>

#include "profiling.h"

IngredientMatcherDialog::IngredientMatcherDialog( QWidget *parent, RecipeDB *db ) : QWidget( parent )
{
	// Initialize internal variables
	database = db;

	//Design the dialog

	QVBoxLayout *dialogLayout = new QVBoxLayout( this );
   dialogLayout->setMargin( 11 );
   dialogLayout->setSpacing( 6 );

	// Ingredient list
	QHBoxLayout *layout2 = new QHBoxLayout();
   layout2->setObjectName( "layout2" );
   layout2->setMargin( 0 );
   layout2->setSpacing( 6 );

	allIngListView = new KreListView( this, QString::null, true, 0 );
	StdIngredientListView *list_view = new StdIngredientListView(allIngListView,database);
	list_view->setSelectionMode( Q3ListView::Multi );
 	allIngListView->setListView(list_view);
	layout2->addWidget( allIngListView );

	QVBoxLayout *layout1 = new QVBoxLayout();
   layout1->setMargin( 0 );
   layout1->setSpacing( 6 );
   layout1->setObjectName( "layout1" );

	KIconLoader *il = KIconLoader::global();

	addButton = new KPushButton( this );
   addButton->setObjectName( "addButton" );
	il->loadIcon( "go-next", KIconLoader::Small );
	addButton->setIcon( KIcon( "go-next", il ) );
	addButton->setFixedSize( QSize( 32, 32 ) );
	layout1->addWidget( addButton );

	removeButton = new KPushButton( this );
   removeButton->setObjectName( "removeButton" );
	il->loadIcon( "go-previous", KIconLoader::Small );
	removeButton->setIcon( KIcon( "go-previous", il ) );
	removeButton->setFixedSize( QSize( 32, 32 ) );
	layout1->addWidget( removeButton );
	QSpacerItem *spacer1 = new QSpacerItem( 51, 191, QSizePolicy::Minimum, QSizePolicy::Expanding );
	layout1->addItem( spacer1 );
	layout2->addLayout( layout1 );

	ingListView = new KreListView( this, QString::null, true );
	ingListView->listView() ->addColumn( i18n( "Ingredient (required?)" ) );
	ingListView->listView() ->addColumn( i18n( "Amount Available" ) );
	layout2->addWidget( ingListView );
	dialogLayout->addLayout( layout2 );

	// Box to select allowed number of missing ingredients
	missingBox = new KHBox( this );
	missingNumberLabel = new QLabel( missingBox );
	missingNumberLabel->setText( i18n( "Missing ingredients allowed:" ) );
	missingNumberSpinBox = new KIntSpinBox( missingBox );
	missingNumberSpinBox->setMinimum( -1 );
	missingNumberSpinBox->setSpecialValueText( i18n( "Any" ) );
	dialogLayout->addWidget(missingBox);

	// Found recipe list
	recipeListView = new KreListView( this, i18n( "Matching Recipes" ), false, 1, missingBox );
	recipeListView->listView() ->setSizePolicy( QSizePolicy::Ignored, QSizePolicy::Ignored );
	recipeListView->listView() ->setAllColumnsShowFocus( true );

	recipeListView->listView() ->addColumn( i18n( "Title" ) );

	KConfigGroup config( KGlobal::config(), "Advanced" );
	bool show_id = config.readEntry( "ShowID", false );
	recipeListView->listView() ->addColumn( i18n( "Id" ), show_id ? -1 : 0 );

	recipeListView->listView() ->addColumn( i18n( "Missing Ingredients" ) );

	recipeListView->listView() ->setSorting( -1 );
	dialogLayout->addWidget(recipeListView);

	RecipeActionsHandler *actionHandler = new RecipeActionsHandler( recipeListView->listView(), database, RecipeActionsHandler::Open | RecipeActionsHandler::Edit | RecipeActionsHandler::Export );

	KHBox *buttonBox = new KHBox( this );

	okButton = new KPushButton( buttonBox );
	il->loadIcon( "dialog-ok", KIconLoader::Small );
	okButton->setIcon( KIcon( "dialog-ok", il ) );
	okButton->setText( i18n( "Find matching recipes" ) );

	//buttonBox->layout()->addItem( new QSpacerItem( 10,10, QSizePolicy::MinimumExpanding, QSizePolicy::Fixed ) );

	clearButton = new KPushButton( buttonBox );
	il->loadIcon( "edit-clear", KIconLoader::Small );
	clearButton->setIcon( KIcon( "edit-clear", il ) );
	clearButton->setText( i18n( "Clear" ) );
	dialogLayout->addWidget(buttonBox);

	// Connect signals & slots
	connect ( okButton, SIGNAL( clicked() ), this, SLOT( findRecipes() ) );
	connect ( clearButton, SIGNAL( clicked() ), recipeListView->listView(), SLOT( clear() ) );
	connect ( clearButton, SIGNAL( clicked() ), this, SLOT( unselectIngredients() ) );
	connect ( actionHandler, SIGNAL( recipeSelected( int, int ) ), SIGNAL( recipeSelected( int, int ) ) );
	connect( addButton, SIGNAL( clicked() ), this, SLOT( addIngredient() ) );
	connect( removeButton, SIGNAL( clicked() ), this, SLOT( removeIngredient() ) );
	connect( ingListView->listView(), SIGNAL( doubleClicked( Q3ListViewItem*, const QPoint &, int ) ), SLOT( itemRenamed( Q3ListViewItem*, const QPoint &, int ) ) );
}

IngredientMatcherDialog::~IngredientMatcherDialog()
{
}

void IngredientMatcherDialog::itemRenamed( Q3ListViewItem* item, const QPoint &, int col )
{
	if ( col == 1 ) {
		KDialog amountEditDialog(this);
                amountEditDialog.setCaption(i18n("Enter amount"));
                amountEditDialog.setButtons(KDialog::Cancel | KDialog::Ok);
                amountEditDialog.setDefaultButton(KDialog::Ok);
                amountEditDialog.setModal( false );
		Q3GroupBox *box = new Q3GroupBox( 1, Qt::Horizontal, i18n("Amount"), &amountEditDialog );
		AmountUnitInput *amountEdit = new AmountUnitInput( box, database );
		// Set the values from the item
		if ( !item->text(1).isEmpty() ) {
			amountEdit->setAmount( MixedNumber::fromString(item->text(2)) );
			Unit u;
			u.id = item->text(3).toInt();
			amountEdit->setUnit( u );
		} else {
			amountEdit->setAmount( -1 );
			Unit u;
			u.id = -1;
			amountEdit->setUnit( u );
		}

		amountEditDialog.setMainWidget(box);

		if ( amountEditDialog.exec() == QDialog::Accepted ) {
			MixedNumber amount = amountEdit->amount();
			Unit unit = amountEdit->unit();

			if ( amount.toDouble() <= 1e-5 ) {
				amount = -1;
				unit.id = -1;

				item->setText(1,QString::null);
			} else {
				item->setText(1,amount.toString()+" "+((amount.toDouble()>1)?unit.plural:unit.name));
			}

			item->setText(2,amount.toString());
			item->setText(3,QString::number(unit.id));

			IngredientList::iterator ing_it = m_item_ing_map[item];
			(*ing_it).amount = amount.toDouble();
			(*ing_it).units = unit;
		}
	}
}

void IngredientMatcherDialog::addIngredient()
{
    /*
	QList<Q3ListViewItem> items = allIngListView->listView()->selectedItems();
	if ( !items.isEmpty() ) {
                for (int i = 0; i < items.size(); ++i) {
			bool dup = false;
			for ( Q3ListViewItem *exists_it = ingListView->listView()->firstChild(); exists_it; exists_it = exists_it->nextSibling() ) {
				if ( exists_it->text( 0 ) == item->text( 0 ) ) {
					dup = true;
					break;
				}
			}

			if ( !dup ) {
				Q3ListViewItem * new_item = new Q3CheckListItem( ingListView->listView(), item->text( 0 ), Q3CheckListItem::CheckBox );

				ingListView->listView() ->setSelected( new_item, true );
				ingListView->listView() ->ensureItemVisible( new_item );
				allIngListView->listView() ->setSelected( item, false );

				m_item_ing_map.insert( new_item, m_ingredientList.append( Ingredient( item->text( 0 ), 0, Unit(), -1, item->text( 1 ).toInt() ) ) );
			}
			++it;
		}
	}
    */
}

void IngredientMatcherDialog::removeIngredient()
{
    /*
	Q3ListViewItem * item = ingListView->listView() ->selectedItem();
	if ( item ) {
		for ( IngredientList::iterator it = m_ingredientList.begin(); it != m_ingredientList.end(); ++it ) {
			if ( *m_item_ing_map.find( item ) == it ) {
				m_ingredientList.remove( it );
				m_item_ing_map.remove( item );
				break;
			}
		}
		delete item;
	}
    */
}

void IngredientMatcherDialog::unselectIngredients()
{
	ingListView->listView()->clear();
	for ( Q3ListViewItem *it = allIngListView->listView()->firstChild(); it; it = it->nextSibling() )
		allIngListView->listView()->setSelected(it,false);
}

void IngredientMatcherDialog::findRecipes( void )
{
	KApplication::setOverrideCursor( Qt::WaitCursor );

	START_TIMER("Ingredient Matcher: loading database data");

	RecipeList rlist;
	database->loadRecipes( &rlist, RecipeDB::Title | RecipeDB::NamesOnly | RecipeDB::Ingredients | RecipeDB::IngredientAmounts );

	END_TIMER();
	START_TIMER("Ingredient Matcher: analyzing data for matching recipes");

	// Clear the list
	recipeListView->listView() ->clear();

	// Now show the recipes with ingredients that are contained in the previous set
	// of ingredients
	RecipeList incompleteRecipes;
	QList <int> missingNumbers;
	Q3ValueList <IngredientList> missingIngredients;

	RecipeList::Iterator it;
	for ( it = rlist.begin();it != rlist.end();++it ) {
		IngredientList il = ( *it ).ingList;
		if ( il.isEmpty() )
			continue;

		IngredientList missing;
		if ( m_ingredientList.containsSubSet( il, missing, true, database ) ) {
			new CustomRecipeListItem( recipeListView->listView(), *it );
		}
		else {
			incompleteRecipes.append( *it );
			missingIngredients.append( missing );
			missingNumbers.append( missing.count() );
		}
	}
	END_TIMER();

	//Check if the user wants to show missing ingredients

	if ( missingNumberSpinBox->value() == 0 ) {
		KApplication::restoreOverrideCursor();
		return ;
	} //"None"

	START_TIMER("Ingredient Matcher: searching for and displaying partial matches");

	IngredientList requiredIngredients;
	for ( Q3ListViewItem *it = ingListView->listView()->firstChild(); it; it = it->nextSibling() ) {
		if ( ((Q3CheckListItem*)it)->isOn() )
			requiredIngredients << *m_item_ing_map[it];
	}

	// Classify recipes with missing ingredients in different lists by ammount
	QList<int>::Iterator nit;
	Q3ValueList<IngredientList>::Iterator ilit;
	int missingNoAllowed = missingNumberSpinBox->value();

	if ( missingNoAllowed == -1 )  // "Any"
	{
		for ( nit = missingNumbers.begin();nit != missingNumbers.end();++nit )
			if ( ( *nit ) > missingNoAllowed )
				missingNoAllowed = ( *nit );
	}

	for ( int missingNo = 1; missingNo <= missingNoAllowed; missingNo++ ) {
		nit = missingNumbers.begin();
		ilit = missingIngredients.begin();

		bool titleShownYet = false;

		for ( it = incompleteRecipes.begin();it != incompleteRecipes.end();++it, ++nit, ++ilit ) {
			if ( !( *it ).ingList.containsAny( m_ingredientList ) )
				continue;

			if ( !( *it ).ingList.containsSubSet( requiredIngredients ) )
				continue;

			if ( ( *nit ) == missingNo ) {
				if ( !titleShownYet ) {
					new SectionItem( recipeListView->listView(), i18np( "You are missing 1 ingredient for:", "You are missing %1 ingredients for:", missingNo ) );
					titleShownYet = true;
				}
				new CustomRecipeListItem( recipeListView->listView(), *it, *ilit );
			}
		}
	}
	END_TIMER();

	KApplication::restoreOverrideCursor();
}

void IngredientMatcherDialog::reload( ReloadFlags flag )
{
	( ( StdIngredientListView* ) allIngListView->listView() ) ->reload(flag);
}

void SectionItem::paintCell ( QPainter * p, const QColorGroup & /*cg*/, int column, int width, int /*align*/ )
{
	// Draw the section's deco
	p->setPen( KGlobalSettings::activeTitleColor() );
	p->setBrush( KGlobalSettings::activeTitleColor() );
	p->drawRect( 0, 0, width, height() );

	// Draw the section's text
	if ( column == 0 ) {
		QFont titleFont = KGlobalSettings::windowTitleFont ();
		p->setFont( titleFont );

		p->setPen( KGlobalSettings::activeTextColor() );
		p->drawText( 0, 0, width, height(), Qt::AlignLeft | Qt::AlignVCenter, mText );
	}
}

#include "ingredientmatcherdialog.moc"
<|endoftext|>


<commit_before># include "particle-functions.h"
# include <application.h>

extern WeatherData weather;

void WeatherData :: message(int data)     // defined outside class definition
{
 Serial.print("Timestamp: "); Serial.println(_weatherTime);
 Serial.print("Temp (F): "); Serial.println(_greenhouseTemp);
 Serial.print("Humidity (%): "); Serial.println(_greenhouseHumidity);
}

void WeatherData :: weatherData()
{
    _weatherTime = 0;
 _greenhouseTemp = 0;
 _greenhouseHumidity = 0;
 _backupGreenhouseTemp = 0;
 _backupGreenhouseHumidity = 0;
 _outsideTemp = 0;
 _outsideHumidity = 0;
  _solar = 0;
 _high = 0;
 _low = 0;
}

void WeatherData :: weatherData(unsigned int weatherTime, int greenhouseTemp,int greenhouseHumidity,
                                int backupGreenhouseTemp, int backupGreenhouseHumidity,int outsideTemp,
                                int outsideHumidity, int solar, int high, int low)
 {
 _weatherTime = weatherTime;
 _greenhouseTemp = greenhouseTemp;
 _greenhouseHumidity = greenhouseHumidity;
 _backupGreenhouseTemp = backupGreenhouseTemp;
 _backupGreenhouseHumidity = backupGreenhouseHumidity;
 _outsideTemp = outsideTemp;
 _outsideHumidity = outsideHumidity;
  _solar = solar;
 _high = high;
 _low = low;
 }

void WeatherData :: init()
{
 Spark.function("ghData", greenhouseData);
}

int greenhouseData(String data)
    {

    //Expected parameters in CSV format
    // 1. Unix time stamp
    // 2. current greenhouse temperature
    // 3. current greenhouse humidity
    // 4. backup sensor current greenhouse temperature
    // 5. backup sensor current greenhouse humidity
    // 6. current outside temperature
    // 7. current outside humidity
    // 8. solar radiation
    // 9. forecast high
    // 10. forecast low

    char copyStr[64];
    data.toCharArray(copyStr,64);
    char *p = strtok(copyStr, ",");

    unsigned int weatherTime = atoi(p);
    p = strtok(NULL,",");
    int greenhouseTemp = atoi(p);
    p = strtok(NULL,",");
    int greenhouseHumidity = atoi(p);
    p = strtok(NULL,",");
    int backupGreenhouseTemp = atoi(p);
    p = strtok(NULL,",");
    int backupGreenhouseHumidity = atoi(p);
    p = strtok(NULL,",");
    int outsideTemp = atoi(p);
    p = strtok(NULL,",");
    int outsideHumidity = atoi(p);
    p = strtok(NULL,",");
    int solar = atoi(p);
    p = strtok(NULL,",");
    int high = atoi(p);
    p = strtok(NULL,",");
    int low = atoi(p);

    weather.weatherData(weatherTime, greenhouseTemp, greenhouseHumidity, backupGreenhouseTemp,
                        backupGreenhouseHumidity, outsideTemp, outsideHumidity, solar, high, low);

return 1;
}

<commit_msg>Update particle-functions.cpp<commit_after># include "particle-functions.h"
# include <application.h>

extern WeatherData weather;

void WeatherData :: message(int data)     // defined outside class definition
{
 Serial.print("Timestamp: "); Serial.println(_weatherTime);
 Serial.print("Temp (F): "); Serial.println(_greenhouseTemp);
 Serial.print("Humidity (%): "); Serial.println(_greenhouseHumidity);
}

void WeatherData :: weatherData()
{
    _weatherTime = 0;
 _greenhouseTemp = 0;
 _greenhouseHumidity = 0;
 _backupGreenhouseTemp = 0;
 _backupGreenhouseHumidity = 0;
 _outsideTemp = 0;
 _outsideHumidity = 0;
  _solar = 0;
 _high = 0;
 _low = 0;
}

void WeatherData :: weatherData(unsigned int weatherTime, int greenhouseTemp,int greenhouseHumidity,
                                int backupGreenhouseTemp, int backupGreenhouseHumidity,int outsideTemp,
                                int outsideHumidity, int solar, int high, int low)
 {
 _weatherTime = weatherTime;
 _greenhouseTemp = greenhouseTemp;
 _greenhouseHumidity = greenhouseHumidity;
 _backupGreenhouseTemp = backupGreenhouseTemp;
 _backupGreenhouseHumidity = backupGreenhouseHumidity;
 _outsideTemp = outsideTemp;
 _outsideHumidity = outsideHumidity;
  _solar = solar;
 _high = high;
 _low = low;
 }

int greenhouseData(String data)
    {

    //Expected parameters in CSV format
    // 1. Unix time stamp
    // 2. current greenhouse temperature
    // 3. current greenhouse humidity
    // 4. backup sensor current greenhouse temperature
    // 5. backup sensor current greenhouse humidity
    // 6. current outside temperature
    // 7. current outside humidity
    // 8. solar radiation
    // 9. forecast high
    // 10. forecast low

    char copyStr[64];
    data.toCharArray(copyStr,64);
    char *p = strtok(copyStr, ",");

    unsigned int weatherTime = atoi(p);
    p = strtok(NULL,",");
    int greenhouseTemp = atoi(p);
    p = strtok(NULL,",");
    int greenhouseHumidity = atoi(p);
    p = strtok(NULL,",");
    int backupGreenhouseTemp = atoi(p);
    p = strtok(NULL,",");
    int backupGreenhouseHumidity = atoi(p);
    p = strtok(NULL,",");
    int outsideTemp = atoi(p);
    p = strtok(NULL,",");
    int outsideHumidity = atoi(p);
    p = strtok(NULL,",");
    int solar = atoi(p);
    p = strtok(NULL,",");
    int high = atoi(p);
    p = strtok(NULL,",");
    int low = atoi(p);

    weather.weatherData(weatherTime, greenhouseTemp, greenhouseHumidity, backupGreenhouseTemp,
                        backupGreenhouseHumidity, outsideTemp, outsideHumidity, solar, high, low);

return 1;
}

void particleInit()
{
 // time function setup
  Time.zone(tzOffset);
  Alarm.alarmRepeat(AMsetback,0,0, MorningAlarm);
  Alarm.alarmRepeat(PMsetback,0,0, EveningAlarm);

 // setup particle functions
 Spark.function("ghData", greenhouseData);
 Spark.function("test_call",call_function);
 Spark.function("setSeason", setSeason);
}
<|endoftext|>


<commit_before>/*
may need to code against htslib rather than samtools.

For each read in the BAM file:
    calculate the 5' ends of the fragment:
    if last 5' end seen is less than the current 5' end:
        flush buffers, gathering stats on duplicates
    if last 5' end seen is greater than the current 5' end BAM is unsorted and freak out
    create signature and add to buffer

on buffer flush:
    for each signatures:
        skip if count is 1
        add number of reads in signature to histogram of duplicate fragments
        sort into bins by tile
        for each tile, create distance matrix
            increment counts in distance histogram
    clear out signatures hash

for each read we need:
    read name
    chromosome
    position
    a populated mate cigar tag (MC:Z:)
    tlen

we need a method to parse out readnames
we need a method to determine how far apart two readnames are
we need a method to generate a signature
we need a method to expand the cigar strings for the signature
we need a histogram template

we need a small amount of test data

diagnose_dups -i bam_file -o dup_stats
*/

#include "common/Options.hpp"
#include "diagnose_dups/Read.hpp"
#include "diagnose_dups/Signature.hpp"
#include "diagnose_dups/SignatureBundle.hpp"
#include "io/BamRecord.hpp"
#include "io/SamReader.hpp"

#include <sam.h>

#include <boost/unordered_map.hpp>

#include <iostream>
#include <numeric>

using namespace std;

namespace {
    typedef boost::unordered_map<uint64_t, uint64_t> histogram;
    typedef vector<Read> read_vector;
    typedef boost::unordered_map<Signature, read_vector> signature_map;

    struct BundleProcessor {
        histogram dup_insert_sizes;
        histogram nondup_insert_sizes;
        histogram distances;
        histogram number_of_dups;

        void process(SignatureBundle const& bundle) {
            std::vector<SigRead> const& sigreads = bundle.data();

            signature_map sigmap;
            for (std::size_t i = 0; i < sigreads.size(); ++i) {
                sigmap[sigreads[i].sig].push_back(sigreads[i].read);
            }

            for(signature_map::const_iterator i = sigmap.begin(); i != sigmap.end(); ++i) {
                if (i->second.size() > 1) {
                        ++number_of_dups[i->second.size()];

                        typedef vector<Read>::const_iterator read_vec_iter;
                        for(read_vec_iter cri = i->second.begin(); cri != i->second.end() - 1; ++cri) {
                            ++dup_insert_sizes[abs(cri->insert_size)];
                            nondup_insert_sizes[abs(cri->insert_size)] += 0;
                            for(read_vec_iter dci = cri + 1; dci != i->second.end(); ++dci) {
                                if(is_on_same_tile(*cri, *dci)) {
                                    uint64_t flow_cell_distance = euclidean_distance(*cri, *dci);
                                    distances[flow_cell_distance] += 1;
                                }
                            }
                        }
                }
            }
        }
    };
}

int main(int argc, char** argv) {
    Options opts = Options(argc, argv);

    SamReader reader(opts.vm["input"].as<string>().c_str(), "r");
    reader.required_flags(BAM_FPROPER_PAIR);
    reader.skip_flags(BAM_FSECONDARY | BAM_FQCFAIL | BAM_FREAD2 | BAM_FSUPPLEMENTARY);

    BamRecord record;
    SignatureBundle bundle;
    std::vector<std::size_t> sig_sizes;
    std::size_t n_bundles;
    std::size_t bundle_size_sum;
    BundleProcessor proc;
    while(reader.next(record)) {
        int rv = bundle.add(record);
        if (rv == -1) {
            std::cerr << "Failed to parse bam record, name = " << bam_get_qname(record) << "\n";
            // XXX: would you rather abort?
            continue;
        }
        else if (rv == 0) {
            bundle_size_sum += bundle.size();
            ++n_bundles;
            proc.process(bundle);
            bundle.clear();
        }
    }
    proc.process(bundle);
    bundle_size_sum += bundle.size();
    ++n_bundles;

    cout << "Inter-tile distance\tFrequency\n";
    for(histogram::iterator i = proc.distances.begin(); i != proc.distances.end(); ++i) {
        cout << i->first << "\t" << i->second << "\n";
    }
    cout << "\n";

    cout << "Number of dups at location\tFrequency\n";
    for(histogram::iterator i = proc.number_of_dups.begin(); i != proc.number_of_dups.end(); ++i) {
        cout << i->first << "\t" << i->second << "\n";
    }
    cout << "\n";

    cout << "Size\tUniq frequency\tDup Frequency\n";
    for(histogram::iterator i = proc.nondup_insert_sizes.begin(); i != proc.nondup_insert_sizes.end(); ++i) {
        cout << i->first << "\t" << i->second << "\t" << proc.dup_insert_sizes[i->first] << "\n";
    }

    double mu = bundle_size_sum / double(n_bundles);
    std::cerr << n_bundles << " bundles.\n";
    std::cerr << "avg bundle size: " << mu << "\n";

    return 0;
}
<commit_msg>fix uninitialized vars<commit_after>/*
may need to code against htslib rather than samtools.

For each read in the BAM file:
    calculate the 5' ends of the fragment:
    if last 5' end seen is less than the current 5' end:
        flush buffers, gathering stats on duplicates
    if last 5' end seen is greater than the current 5' end BAM is unsorted and freak out
    create signature and add to buffer

on buffer flush:
    for each signatures:
        skip if count is 1
        add number of reads in signature to histogram of duplicate fragments
        sort into bins by tile
        for each tile, create distance matrix
            increment counts in distance histogram
    clear out signatures hash

for each read we need:
    read name
    chromosome
    position
    a populated mate cigar tag (MC:Z:)
    tlen

we need a method to parse out readnames
we need a method to determine how far apart two readnames are
we need a method to generate a signature
we need a method to expand the cigar strings for the signature
we need a histogram template

we need a small amount of test data

diagnose_dups -i bam_file -o dup_stats
*/

#include "common/Options.hpp"
#include "diagnose_dups/Read.hpp"
#include "diagnose_dups/Signature.hpp"
#include "diagnose_dups/SignatureBundle.hpp"
#include "io/BamRecord.hpp"
#include "io/SamReader.hpp"

#include <sam.h>

#include <boost/unordered_map.hpp>

#include <iostream>
#include <numeric>

using namespace std;

namespace {
    typedef boost::unordered_map<uint64_t, uint64_t> histogram;
    typedef vector<Read> read_vector;
    typedef boost::unordered_map<Signature, read_vector> signature_map;

    struct BundleProcessor {
        histogram dup_insert_sizes;
        histogram nondup_insert_sizes;
        histogram distances;
        histogram number_of_dups;

        void process(SignatureBundle const& bundle) {
            std::vector<SigRead> const& sigreads = bundle.data();

            signature_map sigmap;
            for (std::size_t i = 0; i < sigreads.size(); ++i) {
                sigmap[sigreads[i].sig].push_back(sigreads[i].read);
            }

            for(signature_map::const_iterator i = sigmap.begin(); i != sigmap.end(); ++i) {
                if (i->second.size() > 1) {
                        ++number_of_dups[i->second.size()];

                        typedef vector<Read>::const_iterator read_vec_iter;
                        for(read_vec_iter cri = i->second.begin(); cri != i->second.end() - 1; ++cri) {
                            ++dup_insert_sizes[abs(cri->insert_size)];
                            nondup_insert_sizes[abs(cri->insert_size)] += 0;
                            for(read_vec_iter dci = cri + 1; dci != i->second.end(); ++dci) {
                                if(is_on_same_tile(*cri, *dci)) {
                                    uint64_t flow_cell_distance = euclidean_distance(*cri, *dci);
                                    distances[flow_cell_distance] += 1;
                                }
                            }
                        }
                }
            }
        }
    };
}

int main(int argc, char** argv) {
    Options opts = Options(argc, argv);

    SamReader reader(opts.vm["input"].as<string>().c_str(), "r");
    reader.required_flags(BAM_FPROPER_PAIR);
    reader.skip_flags(BAM_FSECONDARY | BAM_FQCFAIL | BAM_FREAD2 | BAM_FSUPPLEMENTARY);

    BamRecord record;
    SignatureBundle bundle;
    std::vector<std::size_t> sig_sizes;
    std::size_t n_bundles = 0;
    std::size_t bundle_size_sum = 0;
    BundleProcessor proc;
    while(reader.next(record)) {
        int rv = bundle.add(record);
        if (rv == -1) {
            std::cerr << "Failed to parse bam record, name = " << bam_get_qname(record) << "\n";
            // XXX: would you rather abort?
            continue;
        }
        else if (rv == 0) {
            bundle_size_sum += bundle.size();
            ++n_bundles;
            proc.process(bundle);
            bundle.clear();
        }
    }
    proc.process(bundle);
    bundle_size_sum += bundle.size();
    ++n_bundles;

    cout << "Inter-tile distance\tFrequency\n";
    for(histogram::iterator i = proc.distances.begin(); i != proc.distances.end(); ++i) {
        cout << i->first << "\t" << i->second << "\n";
    }
    cout << "\n";

    cout << "Number of dups at location\tFrequency\n";
    for(histogram::iterator i = proc.number_of_dups.begin(); i != proc.number_of_dups.end(); ++i) {
        cout << i->first << "\t" << i->second << "\n";
    }
    cout << "\n";

    cout << "Size\tUniq frequency\tDup Frequency\n";
    for(histogram::iterator i = proc.nondup_insert_sizes.begin(); i != proc.nondup_insert_sizes.end(); ++i) {
        cout << i->first << "\t" << i->second << "\t" << proc.dup_insert_sizes[i->first] << "\n";
    }

    double mu = bundle_size_sum / double(n_bundles);
    std::cerr << n_bundles << " bundles.\n";
    std::cerr << "avg bundle size: " << mu << "\n";

    return 0;
}
<|endoftext|>