<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER
 * (c)LGPL2+
 *
 * Razor - a lightweight, Qt based, desktop toolset
 * http://razor-qt.org
 *
 * Copyright: 2012 Razor team
 * Authors:
 *   Johannes Zellner <webmaster@nebulon.de>
 *
 * This program or library is free software; you can redistribute it
 * and/or modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.

 * You should have received a copy of the GNU Lesser General
 * Public License along with this library; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301 USA
 *
 * END_COMMON_COPYRIGHT_HEADER */

#include "razorvolume.h"

#include <QtGui/QMessageBox>
#include <QtDebug>
#include <qtxdg/xdgicon.h>

#include "volumebutton.h"
#include "volumepopup.h"
#include "razorvolumeconfiguration.h"
#include "pulseaudioengine.h"
#include "pulseaudiodevice.h"

EXPORT_RAZOR_PANEL_PLUGIN_CPP(RazorVolume)

RazorVolume::RazorVolume(const RazorPanelPluginStartInfo* startInfo, QWidget* parent):
        RazorPanelPlugin(startInfo, parent),
        m_defaultSinkIndex(0),
        m_defaultSink(0)
{
    setObjectName("Volume");

    m_volumeButton = new VolumeButton(panel(), this);
    addWidget(m_volumeButton);

    m_configWindow = new RazorVolumeConfiguration(settings(), this);

    m_paEngine = new PulseAudioEngine(this);
    connect(m_paEngine, SIGNAL(sinkListChanged()), this, SLOT(updateConfigurationSinkList()));
    updateConfigurationSinkList();
}

RazorVolume::~RazorVolume()
{
}

void RazorVolume::showConfigureDialog()
{
    m_configWindow->show();
    m_configWindow->raise();
    m_configWindow->activateWindow();
}

void RazorVolume::settingsChanged()
{
    m_defaultSinkIndex = settings().value("defaultSink", 0).toInt();
    if (m_paEngine->sinks().at(m_defaultSinkIndex)) {
        m_defaultSink = m_paEngine->sinks().at(m_defaultSinkIndex);
        m_volumeButton->m_volumePopup->setDevice(m_defaultSink);
    }

    m_volumeButton->setShowOnClicked(settings().value("showOnClick", false).toBool());
    m_volumeButton->setMuteOnMiddleClick(settings().value("muteOnMiddleClick", true).toBool());
    m_volumeButton->setMixerCommand(settings().value("mixerCommand", "pavucontrol").toString());
}

void RazorVolume::updateConfigurationSinkList()
{
    m_configWindow->setSinkList(m_paEngine->sinks());
    settingsChanged();
}

<commit_msg>panel-volume: Finally fix the default behavior to show popup<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER
 * (c)LGPL2+
 *
 * Razor - a lightweight, Qt based, desktop toolset
 * http://razor-qt.org
 *
 * Copyright: 2012 Razor team
 * Authors:
 *   Johannes Zellner <webmaster@nebulon.de>
 *
 * This program or library is free software; you can redistribute it
 * and/or modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.

 * You should have received a copy of the GNU Lesser General
 * Public License along with this library; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301 USA
 *
 * END_COMMON_COPYRIGHT_HEADER */

#include "razorvolume.h"

#include <QtGui/QMessageBox>
#include <QtDebug>
#include <qtxdg/xdgicon.h>

#include "volumebutton.h"
#include "volumepopup.h"
#include "razorvolumeconfiguration.h"
#include "pulseaudioengine.h"
#include "pulseaudiodevice.h"

EXPORT_RAZOR_PANEL_PLUGIN_CPP(RazorVolume)

RazorVolume::RazorVolume(const RazorPanelPluginStartInfo* startInfo, QWidget* parent):
        RazorPanelPlugin(startInfo, parent),
        m_defaultSinkIndex(0),
        m_defaultSink(0)
{
    setObjectName("Volume");

    m_volumeButton = new VolumeButton(panel(), this);
    addWidget(m_volumeButton);

    m_configWindow = new RazorVolumeConfiguration(settings(), this);

    m_paEngine = new PulseAudioEngine(this);
    connect(m_paEngine, SIGNAL(sinkListChanged()), this, SLOT(updateConfigurationSinkList()));
    updateConfigurationSinkList();
}

RazorVolume::~RazorVolume()
{
}

void RazorVolume::showConfigureDialog()
{
    m_configWindow->show();
    m_configWindow->raise();
    m_configWindow->activateWindow();
}

void RazorVolume::settingsChanged()
{
    m_defaultSinkIndex = settings().value("defaultSink", 0).toInt();
    if (m_paEngine->sinks().at(m_defaultSinkIndex)) {
        m_defaultSink = m_paEngine->sinks().at(m_defaultSinkIndex);
        m_volumeButton->m_volumePopup->setDevice(m_defaultSink);
    }

    m_volumeButton->setShowOnClicked(settings().value("showOnClick", true).toBool());
    m_volumeButton->setMuteOnMiddleClick(settings().value("muteOnMiddleClick", true).toBool());
    m_volumeButton->setMixerCommand(settings().value("mixerCommand", "pavucontrol").toString());
}

void RazorVolume::updateConfigurationSinkList()
{
    m_configWindow->setSinkList(m_paEngine->sinks());
    settingsChanged();
}

<|endoftext|>


<commit_before>// -*- Mode: c++-mode; c-basic-offset: 2; indent-tabs-mode: t; tab-width: 2; -*-
//////////////////////////////////////////////////////////////////////////////
// gaduprotocol.cpp																													//
//																																					//
// Copyright (C)	2002	Zack Rusin <zack@kde.org>														//
//																																					//
// This program is free software; you can redistribute it and/or						//
// modify it under the terms of the GNU General Public License							//
// as published by the Free Software Foundation; either version 2						//
// of the License, or (at your option) any later version.										//
//																																					//
// This program is distributed in the hope that it will be useful,					//
// but WITHOUT ANY WARRANTY; without even the implied warranty of						//
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	 See the						//
// GNU General Public License for more details.															//
//																																					//
// You should have received a copy of the GNU General Public License				//
// along with this program; if not, write to the Free Software							//
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA								//
// 02111-1307, USA.																													//
//////////////////////////////////////////////////////////////////////////////

#include <kdebug.h>
#include <kgenericfactory.h>
#include <kconfig.h>

#include "gaduaccount.h"

#include "kopeteaccountmanager.h"
#include "kopeteaccount.h"
#include "kopetemetacontact.h"

#include "gaducontact.h"
#include "gaduprotocol.h"

#include "gadueditaccount.h"
#include "gaduaddcontactpage.h"
#include "gadupreferences.h"

#include <libgadu.h>

K_EXPORT_COMPONENT_FACTORY( kopete_gadu, KGenericFactory<GaduProtocol>( "kopete_gadu" )  );

GaduProtocol* GaduProtocol::protocolStatic_ = 0L;

GaduProtocol::GaduProtocol( QObject* parent, const char* name, const QStringList & )
	:		KopeteProtocol( parent, name ),
			gaduStatusOffline_( KopeteOnlineStatus::Offline, 0, this, GG_STATUS_NOT_AVAIL,
				"gg_offline", i18n( "Go O&ffline" ), i18n( "Offline" ) ),
			gaduStatusOfflineDescr_( KopeteOnlineStatus::Away, 2, this,
				GG_STATUS_NOT_AVAIL_DESCR,
				"gg_offline_d",	 i18n( "Go A&way" ), i18n( "Offline" ) ),
			gaduStatusMaybeOffline_( KopeteOnlineStatus::Offline, 4, this, 0x0,
				"gg_away", i18n( "Go O&ffline" ), i18n( "Offline" ) ),
			gaduStatusBusy_(KopeteOnlineStatus::Away, 20, this, GG_STATUS_BUSY,
				"gg_busy",i18n( "Go B&usy" ), i18n( "Busy" ) ),
			gaduStatusBusyDescr_(KopeteOnlineStatus::Away, 25, this, GG_STATUS_BUSY_DESCR,
				"gg_busy_d",i18n( "Go B&usy" ),i18n( "Busy" ) ),
			gaduStatusInvisible_( KopeteOnlineStatus::Away,	5, this, GG_STATUS_INVISIBLE,
				"gg_invi",i18n( "Go I&nvisible" ), i18n( "Invisible" ) ),
			gaduStatusInvisibleDescr_(KopeteOnlineStatus::Away, 10, this, GG_STATUS_INVISIBLE_DESCR,
				"gg_invi_d",i18n( "Go I&nvisible" ), i18n( "Invisible" ) ),
			gaduStatusAvail_(KopeteOnlineStatus::Online, 30, this, GG_STATUS_AVAIL,
				"gg_online",	i18n( "Go &Online" ),		 i18n( "Online" ) ),
			gaduStatusAvailDescr_(KopeteOnlineStatus::Online, 30, this, GG_STATUS_AVAIL_DESCR,
				"gg_online_d",	i18n( "Go &Online" ), i18n( "Online" ) ),
			gaduConnecting_(KopeteOnlineStatus::Offline, 1, this, GG_STATUS_CONNECTING,
				"gg_con", i18n( "Connect"), i18n("Connecting") ),
			defaultAccount_( 0 )
{
	if ( protocolStatic_ )
		kdDebug(14100)<<"####"<<"GaduProtocol already initialized"<<endl;
	else
		protocolStatic_ = this;

	prefs_ = new GaduPreferences( "gadu_protocol", this );
	QObject::connect( prefs_, SIGNAL(saved()), this, SLOT(settingsChanged()) );
	addAddressBookField( "messaging/gadu", KopetePlugin::MakeIndexField );
}

GaduProtocol::~GaduProtocol()
{
	protocolStatic_ = 0L;
}

GaduProtocol*
GaduProtocol::protocol()
{
	return protocolStatic_;
}

AddContactPage*
GaduProtocol::createAddContactWidget( QWidget* parent, KopeteAccount* account )
{
	return new GaduAddContactPage( static_cast<GaduAccount*>( account ), parent );
}

void
GaduProtocol::settingsChanged()
{

}

void
GaduProtocol::deserializeContact( KopeteMetaContact *metaContact,
				const QMap<QString, QString> &serializedData,
				const QMap<QString, QString> & /* addressBookData */ )
{
	kdDebug(14100)<<"Adding "<<serializedData[ "contactId" ]<<" || "<< serializedData[ "displayName" ] <<endl;

	const QString aid = serializedData[ "accountId" ];
	const QString cid = serializedData[ "contactId" ];
	const QString dn  = serializedData[ "displayName" ];

	QDict<KopeteAccount> daccounts = KopeteAccountManager::manager()->accounts(this);

	KopeteAccount *account = daccounts[aid];
	if (!account){
	    account = createNewAccount(aid);
	}

	GaduAccount *gaccount = static_cast<GaduAccount *>(account);

	GaduContact *c= new GaduContact( cid.toUInt(), dn,
					account, metaContact );

	c->setParentIdentity( aid );
	gaccount->addNotify( cid.toUInt() );

	c->setInfo(	serializedData["email"],
			serializedData["FirstName"],
			serializedData["SecondName"],
			serializedData["NickName"],
			serializedData["telephone"]);

}

uint
GaduProtocol::statusToWithDescription( KopeteOnlineStatus status )
{

    if ( status==gaduStatusOffline_ || status==gaduStatusOfflineDescr_){
	return GG_STATUS_NOT_AVAIL_DESCR;
    }

    if ( status==gaduStatusBusyDescr_ || status==gaduStatusBusy_){
	return GG_STATUS_BUSY_DESCR;
    }

    if ( status==gaduStatusInvisibleDescr_ || status==gaduStatusInvisible_){
	return GG_STATUS_INVISIBLE_DESCR;
    }

    // this and everything else matches next return
    //
    //if ( status==gaduStatusAvailDescr_ || status==gaduStatusAvail_){
    //	return GG_STATUS_AVAIL_DESCR;
    //}

    return GG_STATUS_AVAIL_DESCR;

}

bool
GaduProtocol::statusWithDesciption( uint status )
{
    switch( status )
    {
	case GG_STATUS_NOT_AVAIL:
	case GG_STATUS_BUSY:
	case GG_STATUS_INVISIBLE:
	case GG_STATUS_AVAIL:
	case GG_STATUS_CONNECTING:
	    return false;
	case GG_STATUS_INVISIBLE_DESCR:
	case GG_STATUS_NOT_AVAIL_DESCR:
	case GG_STATUS_BUSY_DESCR:
	case GG_STATUS_AVAIL_DESCR:
	    return true;
    }

    return false;
}

KopeteOnlineStatus
GaduProtocol::convertStatus( uint status ) const
{
	switch( status )
	{
	case GG_STATUS_NOT_AVAIL:
		return gaduStatusOffline_;
	case GG_STATUS_NOT_AVAIL_DESCR:
		return gaduStatusOfflineDescr_;
	case GG_STATUS_BUSY:
		return gaduStatusBusy_;
	case GG_STATUS_BUSY_DESCR:
		return gaduStatusBusyDescr_;
	case GG_STATUS_INVISIBLE:
		return gaduStatusInvisible_;
	case GG_STATUS_INVISIBLE_DESCR:
		return gaduStatusInvisibleDescr_;
	case GG_STATUS_AVAIL:
		return gaduStatusAvail_;
	case GG_STATUS_AVAIL_DESCR:
		return gaduStatusAvailDescr_;
	case GG_STATUS_CONNECTING:
		return gaduConnecting_;
	default:
		return gaduStatusOffline_;
	}
}

KopeteAccount*
GaduProtocol::createNewAccount( const QString& accountId )
{
	defaultAccount_ = new GaduAccount( this, accountId );
	return defaultAccount_ ;
}

EditAccountWidget*
GaduProtocol::createEditAccountWidget( KopeteAccount *account, QWidget *parent )
{
	return	(new GaduEditAccount( this, account, parent ) );
}

#include "gaduprotocol.moc"
<commit_msg>make it new kopeteprotocol class compatible.<commit_after>// -*- Mode: c++-mode; c-basic-offset: 2; indent-tabs-mode: t; tab-width: 2; -*-
//////////////////////////////////////////////////////////////////////////////
// gaduprotocol.cpp																													//
//																																					//
// Copyright (C)	2002	Zack Rusin <zack@kde.org>														//
//																																					//
// This program is free software; you can redistribute it and/or						//
// modify it under the terms of the GNU General Public License							//
// as published by the Free Software Foundation; either version 2						//
// of the License, or (at your option) any later version.										//
//																																					//
// This program is distributed in the hope that it will be useful,					//
// but WITHOUT ANY WARRANTY; without even the implied warranty of						//
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	 See the						//
// GNU General Public License for more details.															//
//																																					//
// You should have received a copy of the GNU General Public License				//
// along with this program; if not, write to the Free Software							//
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA								//
// 02111-1307, USA.																													//
//////////////////////////////////////////////////////////////////////////////

#include <kdebug.h>
#include <kgenericfactory.h>
#include <kconfig.h>

#include "gaduaccount.h"

#include "kopeteaccountmanager.h"
#include "kopeteaccount.h"
#include "kopetemetacontact.h"

#include "gaducontact.h"
#include "gaduprotocol.h"

#include "gadueditaccount.h"
#include "gaduaddcontactpage.h"
#include "gadupreferences.h"

#include <libgadu.h>

typedef KGenericFactory<GaduProtocol> GaduProtocolFactory;

K_EXPORT_COMPONENT_FACTORY( kopete_gadu, KGenericFactory<GaduProtocol>( "kopete_gadu" )  );

GaduProtocol* GaduProtocol::protocolStatic_ = 0L;

GaduProtocol::GaduProtocol( QObject* parent, const char* name, const QStringList & )
	:		KopeteProtocol( GaduProtocolFactory::instance(), parent, name ),
			gaduStatusOffline_( KopeteOnlineStatus::Offline, 0, this, GG_STATUS_NOT_AVAIL,
				"gg_offline", i18n( "Go O&ffline" ), i18n( "Offline" ) ),
			gaduStatusOfflineDescr_( KopeteOnlineStatus::Away, 2, this,
				GG_STATUS_NOT_AVAIL_DESCR,
				"gg_offline_d",	 i18n( "Go A&way" ), i18n( "Offline" ) ),
			gaduStatusMaybeOffline_( KopeteOnlineStatus::Offline, 4, this, 0x0,
				"gg_away", i18n( "Go O&ffline" ), i18n( "Offline" ) ),
			gaduStatusBusy_(KopeteOnlineStatus::Away, 20, this, GG_STATUS_BUSY,
				"gg_busy",i18n( "Go B&usy" ), i18n( "Busy" ) ),
			gaduStatusBusyDescr_(KopeteOnlineStatus::Away, 25, this, GG_STATUS_BUSY_DESCR,
				"gg_busy_d",i18n( "Go B&usy" ),i18n( "Busy" ) ),
			gaduStatusInvisible_( KopeteOnlineStatus::Away,	5, this, GG_STATUS_INVISIBLE,
				"gg_invi",i18n( "Go I&nvisible" ), i18n( "Invisible" ) ),
			gaduStatusInvisibleDescr_(KopeteOnlineStatus::Away, 10, this, GG_STATUS_INVISIBLE_DESCR,
				"gg_invi_d",i18n( "Go I&nvisible" ), i18n( "Invisible" ) ),
			gaduStatusAvail_(KopeteOnlineStatus::Online, 30, this, GG_STATUS_AVAIL,
				"gg_online",	i18n( "Go &Online" ),		 i18n( "Online" ) ),
			gaduStatusAvailDescr_(KopeteOnlineStatus::Online, 30, this, GG_STATUS_AVAIL_DESCR,
				"gg_online_d",	i18n( "Go &Online" ), i18n( "Online" ) ),
			gaduConnecting_(KopeteOnlineStatus::Offline, 1, this, GG_STATUS_CONNECTING,
				"gg_con", i18n( "Connect"), i18n("Connecting") ),
			defaultAccount_( 0 )
{
	if ( protocolStatic_ )
		kdDebug(14100)<<"####"<<"GaduProtocol already initialized"<<endl;
	else
		protocolStatic_ = this;

	prefs_ = new GaduPreferences( "gadu_protocol", this );
	QObject::connect( prefs_, SIGNAL(saved()), this, SLOT(settingsChanged()) );
	addAddressBookField( "messaging/gadu", KopetePlugin::MakeIndexField );
}

GaduProtocol::~GaduProtocol()
{
	protocolStatic_ = 0L;
}

GaduProtocol*
GaduProtocol::protocol()
{
	return protocolStatic_;
}

AddContactPage*
GaduProtocol::createAddContactWidget( QWidget* parent, KopeteAccount* account )
{
	return new GaduAddContactPage( static_cast<GaduAccount*>( account ), parent );
}

void
GaduProtocol::settingsChanged()
{

}

void
GaduProtocol::deserializeContact( KopeteMetaContact *metaContact,
				const QMap<QString, QString> &serializedData,
				const QMap<QString, QString> & /* addressBookData */ )
{
	kdDebug(14100)<<"Adding "<<serializedData[ "contactId" ]<<" || "<< serializedData[ "displayName" ] <<endl;

	const QString aid = serializedData[ "accountId" ];
	const QString cid = serializedData[ "contactId" ];
	const QString dn  = serializedData[ "displayName" ];

	QDict<KopeteAccount> daccounts = KopeteAccountManager::manager()->accounts(this);

	KopeteAccount *account = daccounts[aid];
	if (!account){
	    account = createNewAccount(aid);
	}

	GaduAccount *gaccount = static_cast<GaduAccount *>(account);

	GaduContact *c= new GaduContact( cid.toUInt(), dn,
					account, metaContact );

	c->setParentIdentity( aid );
	gaccount->addNotify( cid.toUInt() );

	c->setInfo(	serializedData["email"],
			serializedData["FirstName"],
			serializedData["SecondName"],
			serializedData["NickName"],
			serializedData["telephone"]);

}

uint
GaduProtocol::statusToWithDescription( KopeteOnlineStatus status )
{

    if ( status==gaduStatusOffline_ || status==gaduStatusOfflineDescr_){
	return GG_STATUS_NOT_AVAIL_DESCR;
    }

    if ( status==gaduStatusBusyDescr_ || status==gaduStatusBusy_){
	return GG_STATUS_BUSY_DESCR;
    }

    if ( status==gaduStatusInvisibleDescr_ || status==gaduStatusInvisible_){
	return GG_STATUS_INVISIBLE_DESCR;
    }

    // this and everything else matches next return
    //
    //if ( status==gaduStatusAvailDescr_ || status==gaduStatusAvail_){
    //	return GG_STATUS_AVAIL_DESCR;
    //}

    return GG_STATUS_AVAIL_DESCR;

}

bool
GaduProtocol::statusWithDesciption( uint status )
{
    switch( status )
    {
	case GG_STATUS_NOT_AVAIL:
	case GG_STATUS_BUSY:
	case GG_STATUS_INVISIBLE:
	case GG_STATUS_AVAIL:
	case GG_STATUS_CONNECTING:
	    return false;
	case GG_STATUS_INVISIBLE_DESCR:
	case GG_STATUS_NOT_AVAIL_DESCR:
	case GG_STATUS_BUSY_DESCR:
	case GG_STATUS_AVAIL_DESCR:
	    return true;
    }

    return false;
}

KopeteOnlineStatus
GaduProtocol::convertStatus( uint status ) const
{
	switch( status )
	{
	case GG_STATUS_NOT_AVAIL:
		return gaduStatusOffline_;
	case GG_STATUS_NOT_AVAIL_DESCR:
		return gaduStatusOfflineDescr_;
	case GG_STATUS_BUSY:
		return gaduStatusBusy_;
	case GG_STATUS_BUSY_DESCR:
		return gaduStatusBusyDescr_;
	case GG_STATUS_INVISIBLE:
		return gaduStatusInvisible_;
	case GG_STATUS_INVISIBLE_DESCR:
		return gaduStatusInvisibleDescr_;
	case GG_STATUS_AVAIL:
		return gaduStatusAvail_;
	case GG_STATUS_AVAIL_DESCR:
		return gaduStatusAvailDescr_;
	case GG_STATUS_CONNECTING:
		return gaduConnecting_;
	default:
		return gaduStatusOffline_;
	}
}

KopeteAccount*
GaduProtocol::createNewAccount( const QString& accountId )
{
	defaultAccount_ = new GaduAccount( this, accountId );
	return defaultAccount_ ;
}

EditAccountWidget*
GaduProtocol::createEditAccountWidget( KopeteAccount *account, QWidget *parent )
{
	return	(new GaduEditAccount( this, account, parent ) );
}

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


<commit_before>// Standard includes
#include <iostream>
#include <cstdlib>
#include <unistd.h>
#include <cmath>
#include <string.h>
#include <inttypes.h>
#include <fstream>
#include <sys/time.h>
#include <limits.h>

// Serial includes
#include <stdio.h>   /* Standard input/output definitions */
#include <string.h>  /* String function definitions */
#include <unistd.h>  /* UNIX standard function definitions */
#include <fcntl.h>   /* File control definitions */
#include <errno.h>   /* Error number definitions */
#include <termios.h> /* POSIX terminal control definitions */
#
#ifdef __linux
#include <sys/ioctl.h>
#endif

//#include "serialwifly.h" 	// this is from Louis' wifly code, which will be a library
#include "serial_lib/wifly_serial.h" // include the new class for handling a wifly
#include "common.h"
#include "wifly_thread.h"
// #include "test.h" 			// for bearing calculation
#include "commander.h"
#include "bearing_lib/bearing.h"		// this should be all the functions required for bearing calculations

using std::string;
using std::vector;
using namespace std;

/* this is to help with some of the rotation logic */
bool in_rotation = false;

/* keep track of the previous hunt state, as hunt state is sent periodically, not just on updates */
uint8_t prev_hunt_state = 10;

/* whether or not we are currently rotating */
bool rotating = false;

/* whether or not we are currently moving */
bool moving = false;

/* microsecond timestamp of the previous loop iteration */
unsigned long prev_loop_timestamp = 0;

void update_state(uint8_t &new_state) {

	switch (new_state) {
	case TRACKING_HUNT_STATE_ROTATE:
		rotating = true;
		break;
	case TRACKING_HUNT_STATE_MOVE:
		moving = true;
		break;
	case TRACKING_HUNT_STATE_OFF:
		// finished = true;
		break;
	case TRACKING_HUNT_STATE_START:
		// starting = true;
		break;
	}
}

void *wifly_thread(void *param) {

	// retrieve the MAVInfo struct that is sent to this function as a parameter
	struct MAVInfo *uavData = (struct MAVInfo *)param;

	// some constants that all need to become parameters
	int num_samples = 1;
	char *ssid = (char *) "JAMMER01";
	char *file_name = (char *) "wifly.csv";
	char *file_name2 = (char *) "wifly2.csv";
	char *bearing_file_name = (char *) "bearing_calc_cc.csv";
	char *bearing_mle_file_name = (char *) "bearing_calc_mle.csv";
	// char *port = (char *) "/dev/ttyUSB0";

	// connect to the first wifly
	WiflySerial* wifly1 = new WiflySerial(verbose, wifly_port1);
	if (wifly1->fd < 0) {
		printf("Error opening wifly connection\n");
		return NULL;
	}

	// connect to the second wifly
	WiflySerial* wifly2 = nullptr;
	if (dual_wifly) {
		wifly2 = new WiflySerial(verbose, wifly_port2);
		if (wifly2->fd < 0) {
			printf("Error opening wifly connection\n");
			return NULL;
		}
	}

	/* Go into command mode */
	wifly1->enter_commandmode();
	if (dual_wifly) {
		wifly2->enter_commandmode();
	}

	/* Open a file to write values to */
	/* Appending values */
	FILE *wifly_file = fopen(file_name, "a");
	if (wifly_file == NULL)
	{
		// TODO: figure out what we do want to return when there is an error
		printf("Error opening wifly output file\n");
		return NULL;
	}

	FILE *wifly_file2 = NULL;
	if (dual_wifly) {
		wifly_file2 = fopen(file_name2, "a");
		if (wifly_file2 == NULL) {
			// TODO: figure out what we do want to return when there is an error
			printf("Error opening wifly2 output file\n");
			return NULL;
		}
	}

	/* Open a file to write bearing calcs to */
	FILE *bearing_file = fopen(bearing_file_name, "a");
	if (bearing_file == NULL)
	{
		// TODO: figure out what we do want to return when there is an error
		printf("Error opening bearing output file\n");
		return NULL;
	}

	FILE *bearing_file_mle = NULL;
	if (dual_wifly) {
		bearing_file_mle = fopen(bearing_mle_file_name, "a");
		if (bearing_file_mle == NULL) {
			printf("Error opening bearing mle output file\n");
			return NULL;
		}
	}

	if (get_commands) {
		bool loaded = load_move_commands();
		if (!loaded) {
			printf("Error loading move commands\n");
			return NULL;
		}
	}

	vector<double> angles;
	vector<double> gains;
	vector<double> omni_gains;
	vector<int> norm_gains;

	struct timeval tv;

	// main loop that should be constantly taking measurements
	// until the main program is stopped
	while (RUNNING_FLAG) {

		// only want to execute this at most ever 30 ms
		// basically does a dynamic sleep in the sense that if there is a lot of processing time for doing the bearing
		// calculation, we will only pause as long as required so measurements are really made every 30 ms
		// (unless of course bearing calculations take too long)
		gettimeofday(&tv, NULL);
		unsigned long current_loop_time = 1000000 * tv.tv_sec + tv.tv_usec;
		if (prev_loop_timestamp != 0 && (current_loop_time - prev_loop_timestamp) < 30000) {
			continue;
		}
		prev_loop_timestamp = current_loop_time;

		// handle hunt state changes required (sending of commands)
		if (uavData->tracking_status.hunt_mode_state != prev_hunt_state) {

			printf("State changed from %u to %u\n", prev_hunt_state, uavData->tracking_status.hunt_mode_state);

			if (uavData->tracking_status.hunt_mode_state == TRACKING_HUNT_STATE_WAIT) {
				send_next_command(prev_hunt_state, uavData->tracking_status.hunt_mode_state);

				// TODO: maybe want to update the state immediately here...
			} else {
				update_state(uavData->tracking_status.hunt_mode_state);
			}

			// update the prev hunt state to be this new state
			prev_hunt_state = uavData->tracking_status.hunt_mode_state;
			printf("Prev State changed to: %u\n", prev_hunt_state);
		}

		// make measurements (depending on the current state)
		int dir_rssi = INT_MAX;
		int omni_rssi = INT_MAX;

		/* check if we are in an official rotation */
		if (rotating) {
			if (!in_rotation) {
				printf("rotation started\n");
				// set our logic to mark we are now running the rotation logic
				in_rotation = true;

				// clear the vectors
				angles.clear();
				gains.clear();
				omni_gains.clear();
				norm_gains.clear();
			}

			printf("rotating\n");
			angles.push_back((double) uavData->vfr_hud.heading);
			dir_rssi = wifly1->scanrssi(ssid);
			gains.push_back(dir_rssi);

			if (dual_wifly) {
				omni_rssi = wifly2->scanrssi(ssid);
				omni_gains.push_back(omni_rssi);

				// calculate the normalized gains
				norm_gains.push_back(gains2normgain(dir_rssi, omni_rssi));

				// do constant calculation of bearing
				printf("calculating bearing mle\n");
				double curr_bearing_est = get_bearing_mle(angles, norm_gains);
				fprintf(bearing_file_mle, "%llu,%i,%i,%f,%f\n", uavData->sys_time_us.time_unix_usec,
					uavData->gps_position.lat, uavData->gps_position.lon, uavData->vfr_hud.alt, curr_bearing_est);

				// TODO: send mle bearing message here!

			}
		}

		/* catch the end of a rotation in order to do the cc gain measurement */
		if (!rotating && in_rotation) {
			printf("ended rotation\n");
			in_rotation = false;

			printf("calculating cc bearing\n");
			// do bearing calculation at this point
			// double bearing = get_bearing_cc(angles, gains);
			double bearing = 32.0;

			// write the lat, lon, alt and bearing to file
			fprintf(bearing_file, "%llu,%i,%i,%f,%f\n", uavData->sys_time_us.time_unix_usec,
				uavData->gps_position.lat, uavData->gps_position.lon, uavData->vfr_hud.alt, bearing);

			// send a mavlink message of the calculated bearing
			send_bearing_message(bearing, uavData->gps_position.lat, uavData->gps_position.lon, uavData->vfr_hud.alt);

			// tell pixhawk we are finished with the rotation
			// send_finish_command();
		}

		/* no need to make another measurement to write to the file if we already made one */
		if (rotating) {
			printf("writing directly to file\n");
			/* write the directional measurement information */
			fprintf(wifly_file, "%llu,%u,%i,%i,%i,%f,%i\n",
				uavData->sys_time_us.time_unix_usec, uavData->custom_mode, uavData->vfr_hud.heading,
				uavData->gps_position.lat, uavData->gps_position.lon, uavData->vfr_hud.alt, dir_rssi);

			/* write the omni measurement as needed */
			if (dual_wifly) {
				fprintf(wifly_file2, "%llu,%u,%i,%i,%i,%f,%i\n",
					uavData->sys_time_us.time_unix_usec, uavData->custom_mode, uavData->vfr_hud.heading,
					uavData->gps_position.lat, uavData->gps_position.lon, uavData->vfr_hud.alt, omni_rssi);
			}

		} else { /* need to make a measurement to save to the file */

			printf("making measurement for writing to file\n");

			std::cout << "wifly1 fd " << wifly1->fd << "\n";

			/* Scan values to this file */
			/* Add degree at which you measure first */
			fprintf(wifly_file, "%llu,%u,%i,%i,%i,%f,",
				uavData->sys_time_us.time_unix_usec, uavData->custom_mode, uavData->vfr_hud.heading,
				uavData->gps_position.lat, uavData->gps_position.lon, uavData->vfr_hud.alt);

			dir_rssi = wifly1->scanrssi_f(ssid, wifly_file, num_samples);
			cout << uavData->vfr_hud.heading << ": wifly1: " << dir_rssi << "\n";

			if (dual_wifly) {

				fprintf(wifly_file2, "%llu,%u,%i,%i,%i,%f,",
					uavData->sys_time_us.time_unix_usec, uavData->custom_mode, uavData->vfr_hud.heading,
					uavData->gps_position.lat, uavData->gps_position.lon, uavData->vfr_hud.alt);

				omni_rssi = wifly2->scanrssi_f(ssid, wifly_file2, num_samples);
				cout << uavData->vfr_hud.heading << ": wifly2: " << omni_rssi << "\n";
			}

		}

		// send a mavlink message with the current rssi
		send_rssi_message(dir_rssi, uavData->vfr_hud.heading, uavData->gps_position.lat, uavData->gps_position.lon, uavData->vfr_hud.alt);

		// TODO: send mavlink message of calculated rssi...

		// send a message with a rotate command for testing purposes at the moment
		// sendRotateCommand(-1.0);

		/* sleep for some time before making another measurement (30 ms for now) */
		// usleep(30000);

	}

	/* Be sure to close the output file and connection */
	fclose(wifly_file);
	fclose(bearing_file);
	wifly1->end_serial();

	if (dual_wifly) {
		fclose(wifly_file2);
		fclose(bearing_file_mle);
		wifly2->end_serial();
	}

	return NULL;
}
<commit_msg>looking for ADL again for testing<commit_after>// Standard includes
#include <iostream>
#include <cstdlib>
#include <unistd.h>
#include <cmath>
#include <string.h>
#include <inttypes.h>
#include <fstream>
#include <sys/time.h>
#include <limits.h>

// Serial includes
#include <stdio.h>   /* Standard input/output definitions */
#include <string.h>  /* String function definitions */
#include <unistd.h>  /* UNIX standard function definitions */
#include <fcntl.h>   /* File control definitions */
#include <errno.h>   /* Error number definitions */
#include <termios.h> /* POSIX terminal control definitions */
#
#ifdef __linux
#include <sys/ioctl.h>
#endif

//#include "serialwifly.h" 	// this is from Louis' wifly code, which will be a library
#include "serial_lib/wifly_serial.h" // include the new class for handling a wifly
#include "common.h"
#include "wifly_thread.h"
// #include "test.h" 			// for bearing calculation
#include "commander.h"
#include "bearing_lib/bearing.h"		// this should be all the functions required for bearing calculations

using std::string;
using std::vector;
using namespace std;

/* this is to help with some of the rotation logic */
bool in_rotation = false;

/* keep track of the previous hunt state, as hunt state is sent periodically, not just on updates */
uint8_t prev_hunt_state = 10;

/* whether or not we are currently rotating */
bool rotating = false;

/* whether or not we are currently moving */
bool moving = false;

/* microsecond timestamp of the previous loop iteration */
unsigned long prev_loop_timestamp = 0;

void update_state(uint8_t &new_state) {

	switch (new_state) {
	case TRACKING_HUNT_STATE_ROTATE:
		rotating = true;
		break;
	case TRACKING_HUNT_STATE_MOVE:
		moving = true;
		break;
	case TRACKING_HUNT_STATE_OFF:
		// finished = true;
		break;
	case TRACKING_HUNT_STATE_START:
		// starting = true;
		break;
	}
}

void *wifly_thread(void *param) {

	// retrieve the MAVInfo struct that is sent to this function as a parameter
	struct MAVInfo *uavData = (struct MAVInfo *)param;

	// some constants that all need to become parameters
	int num_samples = 1;
	char *ssid = (char *) "ADL"; // "JAMMER01";
	char *file_name = (char *) "wifly.csv";
	char *file_name2 = (char *) "wifly2.csv";
	char *bearing_file_name = (char *) "bearing_calc_cc.csv";
	char *bearing_mle_file_name = (char *) "bearing_calc_mle.csv";
	// char *port = (char *) "/dev/ttyUSB0";

	// connect to the first wifly
	WiflySerial* wifly1 = new WiflySerial(verbose, wifly_port1);
	if (wifly1->fd < 0) {
		printf("Error opening wifly connection\n");
		return NULL;
	}

	// connect to the second wifly
	WiflySerial* wifly2 = nullptr;
	if (dual_wifly) {
		wifly2 = new WiflySerial(verbose, wifly_port2);
		if (wifly2->fd < 0) {
			printf("Error opening wifly connection\n");
			return NULL;
		}
	}

	/* Go into command mode */
	wifly1->enter_commandmode();
	if (dual_wifly) {
		wifly2->enter_commandmode();
	}

	/* Open a file to write values to */
	/* Appending values */
	FILE *wifly_file = fopen(file_name, "a");
	if (wifly_file == NULL)
	{
		// TODO: figure out what we do want to return when there is an error
		printf("Error opening wifly output file\n");
		return NULL;
	}

	FILE *wifly_file2 = NULL;
	if (dual_wifly) {
		wifly_file2 = fopen(file_name2, "a");
		if (wifly_file2 == NULL) {
			// TODO: figure out what we do want to return when there is an error
			printf("Error opening wifly2 output file\n");
			return NULL;
		}
	}

	/* Open a file to write bearing calcs to */
	FILE *bearing_file = fopen(bearing_file_name, "a");
	if (bearing_file == NULL)
	{
		// TODO: figure out what we do want to return when there is an error
		printf("Error opening bearing output file\n");
		return NULL;
	}

	FILE *bearing_file_mle = NULL;
	if (dual_wifly) {
		bearing_file_mle = fopen(bearing_mle_file_name, "a");
		if (bearing_file_mle == NULL) {
			printf("Error opening bearing mle output file\n");
			return NULL;
		}
	}

	if (get_commands) {
		bool loaded = load_move_commands();
		if (!loaded) {
			printf("Error loading move commands\n");
			return NULL;
		}
	}

	vector<double> angles;
	vector<double> gains;
	vector<double> omni_gains;
	vector<int> norm_gains;

	struct timeval tv;

	// main loop that should be constantly taking measurements
	// until the main program is stopped
	while (RUNNING_FLAG) {

		// only want to execute this at most ever 30 ms
		// basically does a dynamic sleep in the sense that if there is a lot of processing time for doing the bearing
		// calculation, we will only pause as long as required so measurements are really made every 30 ms
		// (unless of course bearing calculations take too long)
		gettimeofday(&tv, NULL);
		unsigned long current_loop_time = 1000000 * tv.tv_sec + tv.tv_usec;
		if (prev_loop_timestamp != 0 && (current_loop_time - prev_loop_timestamp) < 30000) {
			continue;
		}
		prev_loop_timestamp = current_loop_time;

		// handle hunt state changes required (sending of commands)
		if (uavData->tracking_status.hunt_mode_state != prev_hunt_state) {

			printf("State changed from %u to %u\n", prev_hunt_state, uavData->tracking_status.hunt_mode_state);

			if (uavData->tracking_status.hunt_mode_state == TRACKING_HUNT_STATE_WAIT) {
				send_next_command(prev_hunt_state, uavData->tracking_status.hunt_mode_state);

				// TODO: maybe want to update the state immediately here...
			} else {
				update_state(uavData->tracking_status.hunt_mode_state);
			}

			// update the prev hunt state to be this new state
			prev_hunt_state = uavData->tracking_status.hunt_mode_state;
			printf("Prev State changed to: %u\n", prev_hunt_state);
		}

		// make measurements (depending on the current state)
		int dir_rssi = INT_MAX;
		int omni_rssi = INT_MAX;

		/* check if we are in an official rotation */
		if (rotating) {
			if (!in_rotation) {
				printf("rotation started\n");
				// set our logic to mark we are now running the rotation logic
				in_rotation = true;

				// clear the vectors
				angles.clear();
				gains.clear();
				omni_gains.clear();
				norm_gains.clear();
			}

			printf("rotating\n");
			angles.push_back((double) uavData->vfr_hud.heading);
			dir_rssi = wifly1->scanrssi(ssid);
			gains.push_back(dir_rssi);

			if (dual_wifly) {
				omni_rssi = wifly2->scanrssi(ssid);
				omni_gains.push_back(omni_rssi);

				// calculate the normalized gains
				norm_gains.push_back(gains2normgain(dir_rssi, omni_rssi));

				// do constant calculation of bearing
				printf("calculating bearing mle\n");
				double curr_bearing_est = get_bearing_mle(angles, norm_gains);
				fprintf(bearing_file_mle, "%llu,%i,%i,%f,%f\n", uavData->sys_time_us.time_unix_usec,
					uavData->gps_position.lat, uavData->gps_position.lon, uavData->vfr_hud.alt, curr_bearing_est);

				// TODO: send mle bearing message here!

			}
		}

		/* catch the end of a rotation in order to do the cc gain measurement */
		if (!rotating && in_rotation) {
			printf("ended rotation\n");
			in_rotation = false;

			printf("calculating cc bearing\n");
			// do bearing calculation at this point
			// double bearing = get_bearing_cc(angles, gains);
			double bearing = 32.0;

			// write the lat, lon, alt and bearing to file
			fprintf(bearing_file, "%llu,%i,%i,%f,%f\n", uavData->sys_time_us.time_unix_usec,
				uavData->gps_position.lat, uavData->gps_position.lon, uavData->vfr_hud.alt, bearing);

			// send a mavlink message of the calculated bearing
			send_bearing_message(bearing, uavData->gps_position.lat, uavData->gps_position.lon, uavData->vfr_hud.alt);

			// tell pixhawk we are finished with the rotation
			// send_finish_command();
		}

		/* no need to make another measurement to write to the file if we already made one */
		if (rotating) {
			printf("writing directly to file\n");
			/* write the directional measurement information */
			fprintf(wifly_file, "%llu,%u,%i,%i,%i,%f,%i\n",
				uavData->sys_time_us.time_unix_usec, uavData->custom_mode, uavData->vfr_hud.heading,
				uavData->gps_position.lat, uavData->gps_position.lon, uavData->vfr_hud.alt, dir_rssi);

			/* write the omni measurement as needed */
			if (dual_wifly) {
				fprintf(wifly_file2, "%llu,%u,%i,%i,%i,%f,%i\n",
					uavData->sys_time_us.time_unix_usec, uavData->custom_mode, uavData->vfr_hud.heading,
					uavData->gps_position.lat, uavData->gps_position.lon, uavData->vfr_hud.alt, omni_rssi);
			}

		} else { /* need to make a measurement to save to the file */

			printf("making measurement for writing to file\n");

			std::cout << "wifly1 fd " << wifly1->fd << "\n";

			/* Scan values to this file */
			/* Add degree at which you measure first */
			fprintf(wifly_file, "%llu,%u,%i,%i,%i,%f,",
				uavData->sys_time_us.time_unix_usec, uavData->custom_mode, uavData->vfr_hud.heading,
				uavData->gps_position.lat, uavData->gps_position.lon, uavData->vfr_hud.alt);

			dir_rssi = wifly1->scanrssi_f(ssid, wifly_file, num_samples);
			cout << uavData->vfr_hud.heading << ": wifly1: " << dir_rssi << "\n";

			if (dual_wifly) {

				fprintf(wifly_file2, "%llu,%u,%i,%i,%i,%f,",
					uavData->sys_time_us.time_unix_usec, uavData->custom_mode, uavData->vfr_hud.heading,
					uavData->gps_position.lat, uavData->gps_position.lon, uavData->vfr_hud.alt);

				omni_rssi = wifly2->scanrssi_f(ssid, wifly_file2, num_samples);
				cout << uavData->vfr_hud.heading << ": wifly2: " << omni_rssi << "\n";
			}

		}

		// send a mavlink message with the current rssi
		send_rssi_message(dir_rssi, uavData->vfr_hud.heading, uavData->gps_position.lat, uavData->gps_position.lon, uavData->vfr_hud.alt);

		// TODO: send mavlink message of calculated rssi...

		// send a message with a rotate command for testing purposes at the moment
		// sendRotateCommand(-1.0);

		/* sleep for some time before making another measurement (30 ms for now) */
		// usleep(30000);

	}

	/* Be sure to close the output file and connection */
	fclose(wifly_file);
	fclose(bearing_file);
	wifly1->end_serial();

	if (dual_wifly) {
		fclose(wifly_file2);
		fclose(bearing_file_mle);
		wifly2->end_serial();
	}

	return NULL;
}
<|endoftext|>


<commit_before>// KMail startup and initialize code
// Author: Stefan Taferner <taferner@alpin.or.at>

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>

#include <kuniqueapplication.h>
#include <klocale.h>
#include <kglobal.h>
#include <dcopclient.h>
#include <kcrash.h>

#include "kmkernel.h" //control center

#undef Status // stupid X headers
#include "kmailIface_stub.h" // to call control center of master kmail

#include <kaboutdata.h>

#include "kmversion.h"

// OLD about text.  This is horrbly outdated.
/*const char* aboutText =
    "KMail [" KMAIL_VERSION "] by\n\n"
    "Stefan Taferner <taferner@kde.org>,\n"
    "Markus Wbben <markus.wuebben@kde.org>\n\n"
    "based on the work of:\n"
    "Lynx <lynx@topaz.hknet.com>,\n"
    "Stephan Meyer <Stephan.Meyer@pobox.com>,\n"
    "and the above authors.\n\n"
    "This program is covered by the GPL.\n\n"
    "Please send bugreports to taferner@kde.org";
*/

static KCmdLineOptions kmoptions[] =
{
  { "s", 0 , 0 },
  { "subject <subject>",	I18N_NOOP("Set subject of msg."), 0 },
  { "c", 0 , 0 },
  { "cc <address>",		I18N_NOOP("Send CC: to 'address'."), 0 },
  { "b", 0 , 0 },
  { "bcc <address>",		I18N_NOOP("Send BCC: to 'addres'."), 0 },
  { "h", 0 , 0 },
  { "header <header>",		I18N_NOOP("Add 'header' to msg."), 0 },
  { "msg <file>",		I18N_NOOP("Read msg-body from 'file'."), 0 },
  { "body <text>",              I18N_NOOP("Set body of msg."), 0 },
  { "attach <url>",             I18N_NOOP("Add an attachment to the mail, this can be repeated"), 0 },
  { "check",			I18N_NOOP("Check for new mail only."), 0 },
  { "composer",			I18N_NOOP("Open only composer window."), 0 },
  { "+[address]",		I18N_NOOP("Send msg to 'address'."), 0 },
//  { "+[file]",                  I18N_NOOP("Show message from file 'file'."), 0 },
  { 0, 0, 0}
};

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

extern "C" {

static void setSignalHandler(void (*handler)(int));

// Crash recovery signal handler
static void signalHandler(int sigId)
{
  setSignalHandler(SIG_DFL);
  fprintf(stderr, "*** KMail got signal %d (Exiting)\n", sigId);
  // try to cleanup all windows
  kernel->dumpDeadLetters();
  ::exit(-1); //
}

// Crash recovery signal handler
static void crashHandler(int sigId)
{
  setSignalHandler(SIG_DFL);
  fprintf(stderr, "*** KMail got signal %d (Crashing)\n", sigId);
  // try to cleanup all windows
  kernel->dumpDeadLetters();
  // Return to DrKonqi.
}
//-----------------------------------------------------------------------------

static void setSignalHandler(void (*handler)(int))
{
  signal(SIGKILL, handler);
  signal(SIGTERM, handler);
  signal(SIGHUP,  handler);
  KCrash::setEmergencySaveFunction(crashHandler);
}

}
//-----------------------------------------------------------------------------

class KMailApplication : public KUniqueApplication
{
public:
  KMailApplication() : KUniqueApplication() { };

  virtual int newInstance();

  void commitData(QSessionManager& sm) {
    kernel->notClosedByUser();
    KApplication::commitData( sm );
  }
};

int KMailApplication::newInstance()
{
  QString to, cc, bcc, subj, body;
  KURL messageFile = QString::null;
  KURL::List attachURLs;
  bool mailto = false;
  bool checkMail = false;
  //bool viewOnly = false;

  // process args:
  KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
  if (args->getOption("subject"))
  {
     mailto = true;
     subj = QString::fromLocal8Bit(args->getOption("subject"));
  }

  if (args->getOption("cc"))
  {
     mailto = true;
     cc = QString::fromLocal8Bit(args->getOption("cc"));
  }

  if (args->getOption("bcc"))
  {
     mailto = true;
     bcc = QString::fromLocal8Bit(args->getOption("bcc"));
  }

  if (args->getOption("msg"))
  {
     mailto = true;
     messageFile = QString::fromLocal8Bit(args->getOption("msg"));
  }

  if (args->getOption("body"))
  {
     mailto = true;
     body = QString::fromLocal8Bit(args->getOption("body"));
  }

  QCStringList attachList = args->getOptionList("attach");
  if (!attachList.isEmpty())
  {
     mailto = true;
     for ( QCStringList::Iterator it = attachList.begin() ; it != attachList.end() ; ++it )
         attachURLs += KURL( QString::fromLocal8Bit( *it ) );
  }

  if (args->isSet("composer"))
    mailto = true;

  if (args->isSet("check"))
    checkMail = true;

  for(int i= 0; i < args->count(); i++)
  {
    if (!to.isEmpty())
      to += ", ";
     if (strncasecmp(args->arg(i),"mailto:",7)==0)
       to += args->arg(i);
     else
       to += args->arg(i);
     mailto = true;
  }

  args->clear();

  kernel->action (mailto, checkMail, to, cc, bcc, subj, body, messageFile, attachURLs);
  return 0;
}

int main(int argc, char *argv[])
{
  // WABA: KMail is a KUniqueApplication. Unfortunately this makes debugging
  // a bit harder: You should pass --nofork as commandline argument when using
  // a debugger. In gdb you can do this by typing "set args --nofork" before
  // typing "run".

  KAboutData about("kmail", I18N_NOOP("KMail"),
                   KMAIL_VERSION,
		   I18N_NOOP("The KDE Email client."),
		   KAboutData::License_GPL,
                   I18N_NOOP("(c) 1997-2001, The KMail developers"),
		   0,
		   "http://kmail.kde.org");
  about.addAuthor( "Michael H\303\244ckel", I18N_NOOP("Current maintainer"), "michael@haeckel.net" );
  about.addAuthor( "Don Sanders", I18N_NOOP("Current maintainer"), "sanders@kde.org" );
  about.addAuthor( "Stefan Taferner ", 0, "taferner@kde.org" );
  about.addAuthor( "Daniel Naber", I18N_NOOP("Documentation"), "daniel.naber@t-online.de" );
  about.addAuthor( "Andreas Gungl", I18N_NOOP("Encryption"), "a.gungl@gmx.de" );
  about.addAuthor( "Toyohiro Asukai", 0, "toyohiro@ksmplus.com" );
  about.addAuthor( "Waldo Bastian", 0, "bastian@kde.org" );
  about.addAuthor( "Steven Brown", 0, "swbrown@ucsd.edu" );
  about.addAuthor( "Cristi Dumitrescu", 0, "cristid@chip.ro" );
  about.addAuthor( "Philippe Fremy", 0, "pfremy@chez.com" );
  about.addAuthor( "Kurt Granroth", 0, "granroth@kde.org" );
  about.addAuthor( "Igor Janssen", 0, "rm@linux.ru.net" );
  about.addAuthor( "Matt Johnston", 0, "matt@caifex.org" );
  about.addAuthor( "Christer Kaivo-oja", 0, "whizkid@telia.com" );
  about.addAuthor( "Ingo Kl\303\266cker", 0, "ingo.kloecker@epost.de" );
  about.addAuthor( "Lars Knoll", 0, "knoll@kde.org" );
  about.addAuthor( "J. Nick Koston", 0, "bdraco@darkorb.net" );
  about.addAuthor( "Stephan Kulow", 0, "coolo@kde.org" );
  about.addAuthor( "Guillaume Laurent", 0, "glaurent@telegraph-road.org" );
  about.addAuthor( "Sam Magnuson", 0, "sam@trolltech.com" );
  about.addAuthor( "Laurent Montel", 0, "lmontel@mandrakesoft.com" );
  about.addAuthor( "Marc Mutz", 0, "mutz@kde.org" );
  about.addAuthor( "Matt Newell", 0, "newellm@proaxis.com" );
  about.addAuthor( "Denis Perchine", 0, "dyp@perchine.com" );
  about.addAuthor( "Carsten Pfeiffer", 0, "pfeiffer@kde.org" );
  about.addAuthor( "Sven Radej", 0, "radej@kde.org" );
  about.addAuthor( "Mark Roberts", 0, "mark@taurine.demon.co.uk" );
  about.addAuthor( "Wolfgang Rohdewald", 0, "WRohdewald@dplanet.ch" );
  about.addAuthor( "Espen Sand", 0, "espen@kde.org" );
  about.addAuthor( "George Staikos", 0, "staikos@kde.org" );
  about.addAuthor( "Jason Stephenson", 0, "panda@mis.net" );
  about.addAuthor( "Jacek Stolarczyk", 0, "jacek@mer.chemia.polsl.gliwice.pl" );
  about.addAuthor( "Roberto S. Teixeira", 0, "maragato@kde.org" );
  about.addAuthor( "Mario Weilguni", 0, "mweilguni@sime.com" );
  about.addAuthor( "Wynn Wilkes", 0, "wynnw@calderasystems.com" );
  about.addAuthor( "Robert D. Williams", 0, "rwilliams@kde.org" );
  about.addAuthor( "Markus Wuebben", 0, "markus.wuebben@kde.org" );
  about.addAuthor( "Karl-Heinz Zimmer", 0, "khz@kde.org" );

  KCmdLineArgs::init(argc, argv, &about);
  KCmdLineArgs::addCmdLineOptions( kmoptions ); // Add kmail options

  if (!KMailApplication::start())
     return 0;

  KMailApplication app;
  KGlobal::locale()->insertCatalogue("libkdenetwork");

  kapp->dcopClient()->suspend(); // Don't handle DCOP requests yet

  //local, do the init
  KMKernel kmailKernel;
  kmailKernel.init();
  kapp->dcopClient()->setDefaultObject( kmailKernel.objId() );

  // and session management
  kmailKernel.doSessionManagement();

  // any dead letters?
  kmailKernel.recoverDeadLetters();

  setSignalHandler(signalHandler);

  kapp->dcopClient()->resume(); // Ok. We are ready for DCOP requests.
  // Go!
  int ret = kapp->exec();

  // clean up
  kmailKernel.cleanup();
  return ret;
}

<commit_msg>Make it impossible to run KMail twice on the same time on different X displays by creating a lock file because KUniqueApplication doesn't prevent that.<commit_after>// KMail startup and initialize code
// Author: Stefan Taferner <taferner@alpin.or.at>

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include <kuniqueapplication.h>
#include <klocale.h>
#include <kglobal.h>
#include <ksimpleconfig.h>
#include <kstandarddirs.h>
#include <knotifyclient.h>
#include <dcopclient.h>
#include <kcrash.h>

#include "kmkernel.h" //control center

#undef Status // stupid X headers
#include "kmailIface_stub.h" // to call control center of master kmail

#include <kaboutdata.h>

#include "kmversion.h"

// OLD about text.  This is horrbly outdated.
/*const char* aboutText =
    "KMail [" KMAIL_VERSION "] by\n\n"
    "Stefan Taferner <taferner@kde.org>,\n"
    "Markus Wbben <markus.wuebben@kde.org>\n\n"
    "based on the work of:\n"
    "Lynx <lynx@topaz.hknet.com>,\n"
    "Stephan Meyer <Stephan.Meyer@pobox.com>,\n"
    "and the above authors.\n\n"
    "This program is covered by the GPL.\n\n"
    "Please send bugreports to taferner@kde.org";
*/

static KCmdLineOptions kmoptions[] =
{
  { "s", 0 , 0 },
  { "subject <subject>",	I18N_NOOP("Set subject of msg."), 0 },
  { "c", 0 , 0 },
  { "cc <address>",		I18N_NOOP("Send CC: to 'address'."), 0 },
  { "b", 0 , 0 },
  { "bcc <address>",		I18N_NOOP("Send BCC: to 'addres'."), 0 },
  { "h", 0 , 0 },
  { "header <header>",		I18N_NOOP("Add 'header' to msg."), 0 },
  { "msg <file>",		I18N_NOOP("Read msg-body from 'file'."), 0 },
  { "body <text>",              I18N_NOOP("Set body of msg."), 0 },
  { "attach <url>",             I18N_NOOP("Add an attachment to the mail, this can be repeated"), 0 },
  { "check",			I18N_NOOP("Check for new mail only."), 0 },
  { "composer",			I18N_NOOP("Open only composer window."), 0 },
  { "+[address]",		I18N_NOOP("Send msg to 'address'."), 0 },
//  { "+[file]",                  I18N_NOOP("Show message from file 'file'."), 0 },
  { 0, 0, 0}
};

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

extern "C" {

static void setSignalHandler(void (*handler)(int));

// Crash recovery signal handler
static void signalHandler(int sigId)
{
  setSignalHandler(SIG_DFL);
  fprintf(stderr, "*** KMail got signal %d (Exiting)\n", sigId);
  // try to cleanup all windows
  kernel->dumpDeadLetters();
  ::exit(-1); //
}

// Crash recovery signal handler
static void crashHandler(int sigId)
{
  setSignalHandler(SIG_DFL);
  fprintf(stderr, "*** KMail got signal %d (Crashing)\n", sigId);
  // try to cleanup all windows
  kernel->dumpDeadLetters();
  // Return to DrKonqi.
}
//-----------------------------------------------------------------------------

static void setSignalHandler(void (*handler)(int))
{
  signal(SIGKILL, handler);
  signal(SIGTERM, handler);
  signal(SIGHUP,  handler);
  KCrash::setEmergencySaveFunction(crashHandler);
}

}
//-----------------------------------------------------------------------------

class KMailApplication : public KUniqueApplication
{
public:
  KMailApplication() : KUniqueApplication() { };

  virtual int newInstance();

  void commitData(QSessionManager& sm) {
    kernel->notClosedByUser();
    KApplication::commitData( sm );
  }
};

int KMailApplication::newInstance()
{
  QString to, cc, bcc, subj, body;
  KURL messageFile = QString::null;
  KURL::List attachURLs;
  bool mailto = false;
  bool checkMail = false;
  //bool viewOnly = false;

  // process args:
  KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
  if (args->getOption("subject"))
  {
     mailto = true;
     subj = QString::fromLocal8Bit(args->getOption("subject"));
  }

  if (args->getOption("cc"))
  {
     mailto = true;
     cc = QString::fromLocal8Bit(args->getOption("cc"));
  }

  if (args->getOption("bcc"))
  {
     mailto = true;
     bcc = QString::fromLocal8Bit(args->getOption("bcc"));
  }

  if (args->getOption("msg"))
  {
     mailto = true;
     messageFile = QString::fromLocal8Bit(args->getOption("msg"));
  }

  if (args->getOption("body"))
  {
     mailto = true;
     body = QString::fromLocal8Bit(args->getOption("body"));
  }

  QCStringList attachList = args->getOptionList("attach");
  if (!attachList.isEmpty())
  {
     mailto = true;
     for ( QCStringList::Iterator it = attachList.begin() ; it != attachList.end() ; ++it )
         attachURLs += KURL( QString::fromLocal8Bit( *it ) );
  }

  if (args->isSet("composer"))
    mailto = true;

  if (args->isSet("check"))
    checkMail = true;

  for(int i= 0; i < args->count(); i++)
  {
    if (!to.isEmpty())
      to += ", ";
     if (strncasecmp(args->arg(i),"mailto:",7)==0)
       to += args->arg(i);
     else
       to += args->arg(i);
     mailto = true;
  }

  args->clear();

  kernel->action (mailto, checkMail, to, cc, bcc, subj, body, messageFile, attachURLs);
  return 0;
}

int main(int argc, char *argv[])
{
  // WABA: KMail is a KUniqueApplication. Unfortunately this makes debugging
  // a bit harder: You should pass --nofork as commandline argument when using
  // a debugger. In gdb you can do this by typing "set args --nofork" before
  // typing "run".

  KAboutData about("kmail", I18N_NOOP("KMail"),
                   KMAIL_VERSION,
		   I18N_NOOP("The KDE Email client."),
		   KAboutData::License_GPL,
                   I18N_NOOP("(c) 1997-2001, The KMail developers"),
		   0,
		   "http://kmail.kde.org");
  about.addAuthor( "Michael H\303\244ckel", I18N_NOOP("Current maintainer"), "michael@haeckel.net" );
  about.addAuthor( "Don Sanders", I18N_NOOP("Current maintainer"), "sanders@kde.org" );
  about.addAuthor( "Stefan Taferner ", 0, "taferner@kde.org" );
  about.addAuthor( "Daniel Naber", I18N_NOOP("Documentation"), "daniel.naber@t-online.de" );
  about.addAuthor( "Andreas Gungl", I18N_NOOP("Encryption"), "a.gungl@gmx.de" );
  about.addAuthor( "Toyohiro Asukai", 0, "toyohiro@ksmplus.com" );
  about.addAuthor( "Waldo Bastian", 0, "bastian@kde.org" );
  about.addAuthor( "Steven Brown", 0, "swbrown@ucsd.edu" );
  about.addAuthor( "Cristi Dumitrescu", 0, "cristid@chip.ro" );
  about.addAuthor( "Philippe Fremy", 0, "pfremy@chez.com" );
  about.addAuthor( "Kurt Granroth", 0, "granroth@kde.org" );
  about.addAuthor( "Igor Janssen", 0, "rm@linux.ru.net" );
  about.addAuthor( "Matt Johnston", 0, "matt@caifex.org" );
  about.addAuthor( "Christer Kaivo-oja", 0, "whizkid@telia.com" );
  about.addAuthor( "Ingo Kl\303\266cker", 0, "ingo.kloecker@epost.de" );
  about.addAuthor( "Lars Knoll", 0, "knoll@kde.org" );
  about.addAuthor( "J. Nick Koston", 0, "bdraco@darkorb.net" );
  about.addAuthor( "Stephan Kulow", 0, "coolo@kde.org" );
  about.addAuthor( "Guillaume Laurent", 0, "glaurent@telegraph-road.org" );
  about.addAuthor( "Sam Magnuson", 0, "sam@trolltech.com" );
  about.addAuthor( "Laurent Montel", 0, "lmontel@mandrakesoft.com" );
  about.addAuthor( "Marc Mutz", 0, "mutz@kde.org" );
  about.addAuthor( "Matt Newell", 0, "newellm@proaxis.com" );
  about.addAuthor( "Denis Perchine", 0, "dyp@perchine.com" );
  about.addAuthor( "Carsten Pfeiffer", 0, "pfeiffer@kde.org" );
  about.addAuthor( "Sven Radej", 0, "radej@kde.org" );
  about.addAuthor( "Mark Roberts", 0, "mark@taurine.demon.co.uk" );
  about.addAuthor( "Wolfgang Rohdewald", 0, "WRohdewald@dplanet.ch" );
  about.addAuthor( "Espen Sand", 0, "espen@kde.org" );
  about.addAuthor( "George Staikos", 0, "staikos@kde.org" );
  about.addAuthor( "Jason Stephenson", 0, "panda@mis.net" );
  about.addAuthor( "Jacek Stolarczyk", 0, "jacek@mer.chemia.polsl.gliwice.pl" );
  about.addAuthor( "Roberto S. Teixeira", 0, "maragato@kde.org" );
  about.addAuthor( "Mario Weilguni", 0, "mweilguni@sime.com" );
  about.addAuthor( "Wynn Wilkes", 0, "wynnw@calderasystems.com" );
  about.addAuthor( "Robert D. Williams", 0, "rwilliams@kde.org" );
  about.addAuthor( "Markus Wuebben", 0, "markus.wuebben@kde.org" );
  about.addAuthor( "Karl-Heinz Zimmer", 0, "khz@kde.org" );

  KCmdLineArgs::init(argc, argv, &about);
  KCmdLineArgs::addCmdLineOptions( kmoptions ); // Add kmail options

  if (!KMailApplication::start())
     return 0;

  KMailApplication app;
  KGlobal::locale()->insertCatalogue("libkdenetwork");

  KSimpleConfig config(locateLocal("appdata", "lock"));
  int oldPid = config.readNumEntry("pid", -1);
  if (oldPid != -1 && getsid(oldPid) != -1)
  {
    QString msg = i18n("KMail can only run once at the same time. "
      "It is already running on a different display with PID %1.").arg(oldPid);
    KNotifyClient::userEvent( msg,  KNotifyClient::Messagebox,
      KNotifyClient::Error );
    fprintf(stderr, "*** KMail is already running with PID %d\n", oldPid);
    return 1;
  }

  config.writeEntry("pid", getpid());
  config.sync();

  kapp->dcopClient()->suspend(); // Don't handle DCOP requests yet

  //local, do the init
  KMKernel kmailKernel;
  kmailKernel.init();
  kapp->dcopClient()->setDefaultObject( kmailKernel.objId() );

  // and session management
  kmailKernel.doSessionManagement();

  // any dead letters?
  kmailKernel.recoverDeadLetters();

  setSignalHandler(signalHandler);

  kapp->dcopClient()->resume(); // Ok. We are ready for DCOP requests.
  // Go!
  int ret = kapp->exec();

  // clean up
  kmailKernel.cleanup();
  config.writeEntry("pid", -1);
  config.sync();
  return ret;
}

<|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 "camera.hpp"
#include "camera_info_definitions.hpp"
#include "../tools/alvisiondefinitions.h" // for kTop...

/**
* ROS includes
*/
#include <cv_bridge/cv_bridge.h>

/**
* CV includes
*/
#include <opencv2/imgproc/imgproc.hpp>

/**
* BOOST includes
*/
#include <boost/foreach.hpp>
#define for_each BOOST_FOREACH

namespace alros
{
namespace converter
{

namespace camera_info_definitions
{

const sensor_msgs::CameraInfo& getCameraInfo( int camera_source, int resolution )
{
  /** RETURN VALUE OPTIMIZATION (RVO)
  * since there is no C++11 initializer list nor lamda functions
  */
  if ( camera_source == AL::kTopCamera)
  {
    if ( resolution == AL::kVGA )
    {
      static const sensor_msgs::CameraInfo cam_info_msg = createCameraInfoTOPVGA();
      return cam_info_msg;
    }
    else if( resolution == AL::kQVGA )
    {
      static const sensor_msgs::CameraInfo cam_info_msg = createCameraInfoTOPQVGA();
      return cam_info_msg;
    }
    else if( resolution == AL::kQQVGA )
    {
      static const sensor_msgs::CameraInfo cam_info_msg = createCameraInfoTOPQQVGA();
      return cam_info_msg;
    }
    else{
      std::cout << "no camera information found for camera_source " << camera_source << " and res: " << resolution << std::endl;
    }
  }
  else if ( camera_source == AL::kBottomCamera )
  {
    if ( resolution == AL::kVGA )
    {
      static const sensor_msgs::CameraInfo cam_info_msg = createCameraInfoBOTTOMVGA();
      return cam_info_msg;
    }
    else if( resolution == AL::kQVGA )
    {
      static const sensor_msgs::CameraInfo cam_info_msg = createCameraInfoBOTTOMQVGA();
      return cam_info_msg;
    }
    else if( resolution == AL::kQQVGA )
    {
      static const sensor_msgs::CameraInfo cam_info_msg = createCameraInfoBOTTOMQQVGA();
      return cam_info_msg;
    }
    else{
      std::cout << "no camera information found for camera_source " << camera_source << " and res: " << resolution << std::endl;
    }
  }
  else if ( camera_source == AL::kDepthCamera )
  {
    if ( resolution == AL::kVGA )
    {
      static const sensor_msgs::CameraInfo cam_info_msg = createCameraInfoDEPTHVGA();
      return cam_info_msg;
    }
    else if( resolution == AL::kQVGA )
    {
      static const sensor_msgs::CameraInfo cam_info_msg = createCameraInfoDEPTHQVGA();
      return cam_info_msg;
    }
    else if( resolution == AL::kQQVGA )
    {
      static const sensor_msgs::CameraInfo cam_info_msg = createCameraInfoDEPTHQQVGA();
      return cam_info_msg;
    }
    else{
      std::cout << "no camera information found for camera_source " << camera_source << " and res: " << resolution << std::endl;
    }
  }
}

} // camera_info_definitions

CameraConverter::CameraConverter( const std::string& name, const float& frequency, const qi::SessionPtr& session, const int& camera_source, const int& resolution )
  : BaseConverter( name, frequency, session ),
    p_video_( session->service("ALVideoDevice") ),
    camera_source_(camera_source),
    resolution_(resolution),
    // change in case of depth camera
    colorspace_( (camera_source_!=AL::kDepthCamera)?AL::kBGRColorSpace:AL::kDepthColorSpace ),
    msg_colorspace_( (camera_source_!=AL::kDepthCamera)?"bgr8":"16UC1" ),
    cv_mat_type_( (camera_source_!=AL::kDepthCamera)?CV_8UC3:CV_16U ),
    camera_info_( camera_info_definitions::getCameraInfo(camera_source, resolution) )
{
  if ( camera_source == AL::kTopCamera )
  {
    msg_frameid_ = "CameraTop_optical_frame";
  }
  else if (camera_source == AL::kBottomCamera )
  {
    msg_frameid_ = "CameraBottom_optical_frame";
  }
  else if (camera_source_ == AL::kDepthCamera )
  {
    msg_frameid_ = "CameraDepth_optical_frame";
  }
}

CameraConverter::~CameraConverter()
{
  if (!handle_.empty())
  {
    std::cout << "Unsubscribe camera handle " << handle_ << std::endl;
    p_video_.call<qi::AnyValue>("unsubscribe", handle_);
    handle_.clear();
  }
}

void CameraConverter::reset()
{
  if (!handle_.empty())
  {
    p_video_.call<qi::AnyValue>("unsubscribe", handle_);
    handle_.clear();
  }

  handle_ = p_video_.call<std::string>(
                         "subscribeCamera",
                          name_,
                          camera_source_,
                          resolution_,
                          colorspace_,
                          frequency_
                          );
}

void CameraConverter::registerCallback( const message_actions::MessageAction action, Callback_t cb )
{
  callbacks_[action] = cb;
}

void CameraConverter::callAll( const std::vector<message_actions::MessageAction>& actions )
{

  if (handle_.empty() )
  {
    std::cerr << "Camera Handle is empty - cannot retrieve image" << std::endl;
    return;
  }

  qi::AnyValue image_anyvalue = p_video_.call<qi::AnyValue>("getImageRemote", handle_);
  qi::AnyReferenceVector image_anyref = image_anyvalue.asListValuePtr();

  int width, height;
  void* image_buffer;

  // Create a cv::Mat of the right dimensions
  width = image_anyref[0].content().asInt32();
  height = image_anyref[1].content().asInt32();
  image_buffer = (void*)(image_anyref[6].content().asRaw().first);
  cv::Mat cv_img(height, width, cv_mat_type_, image_buffer);
  msg_ = cv_bridge::CvImage(std_msgs::Header(), msg_colorspace_, cv_img).toImageMsg();
  msg_->header.frame_id = msg_frameid_;

  ros::Time now = ros::Time::now();
  msg_->header.stamp = now;
  camera_info_.header.stamp = now;

  for_each( const message_actions::MessageAction& action, actions )
  {
    callbacks_[action]( msg_, camera_info_ );
  }
}

} // publisher
} //alros
<commit_msg>Add security when getting image (in case no image is retrieved)<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 "camera.hpp"
#include "camera_info_definitions.hpp"
#include "../tools/alvisiondefinitions.h" // for kTop...

/**
* ROS includes
*/
#include <cv_bridge/cv_bridge.h>

/**
* CV includes
*/
#include <opencv2/imgproc/imgproc.hpp>

/**
* BOOST includes
*/
#include <boost/foreach.hpp>
#define for_each BOOST_FOREACH

namespace alros
{
namespace converter
{

namespace camera_info_definitions
{

const sensor_msgs::CameraInfo& getCameraInfo( int camera_source, int resolution )
{
  /** RETURN VALUE OPTIMIZATION (RVO)
  * since there is no C++11 initializer list nor lamda functions
  */
  if ( camera_source == AL::kTopCamera)
  {
    if ( resolution == AL::kVGA )
    {
      static const sensor_msgs::CameraInfo cam_info_msg = createCameraInfoTOPVGA();
      return cam_info_msg;
    }
    else if( resolution == AL::kQVGA )
    {
      static const sensor_msgs::CameraInfo cam_info_msg = createCameraInfoTOPQVGA();
      return cam_info_msg;
    }
    else if( resolution == AL::kQQVGA )
    {
      static const sensor_msgs::CameraInfo cam_info_msg = createCameraInfoTOPQQVGA();
      return cam_info_msg;
    }
    else{
      std::cout << "no camera information found for camera_source " << camera_source << " and res: " << resolution << std::endl;
    }
  }
  else if ( camera_source == AL::kBottomCamera )
  {
    if ( resolution == AL::kVGA )
    {
      static const sensor_msgs::CameraInfo cam_info_msg = createCameraInfoBOTTOMVGA();
      return cam_info_msg;
    }
    else if( resolution == AL::kQVGA )
    {
      static const sensor_msgs::CameraInfo cam_info_msg = createCameraInfoBOTTOMQVGA();
      return cam_info_msg;
    }
    else if( resolution == AL::kQQVGA )
    {
      static const sensor_msgs::CameraInfo cam_info_msg = createCameraInfoBOTTOMQQVGA();
      return cam_info_msg;
    }
    else{
      std::cout << "no camera information found for camera_source " << camera_source << " and res: " << resolution << std::endl;
    }
  }
  else if ( camera_source == AL::kDepthCamera )
  {
    if ( resolution == AL::kVGA )
    {
      static const sensor_msgs::CameraInfo cam_info_msg = createCameraInfoDEPTHVGA();
      return cam_info_msg;
    }
    else if( resolution == AL::kQVGA )
    {
      static const sensor_msgs::CameraInfo cam_info_msg = createCameraInfoDEPTHQVGA();
      return cam_info_msg;
    }
    else if( resolution == AL::kQQVGA )
    {
      static const sensor_msgs::CameraInfo cam_info_msg = createCameraInfoDEPTHQQVGA();
      return cam_info_msg;
    }
    else{
      std::cout << "no camera information found for camera_source " << camera_source << " and res: " << resolution << std::endl;
    }
  }
}

} // camera_info_definitions

CameraConverter::CameraConverter( const std::string& name, const float& frequency, const qi::SessionPtr& session, const int& camera_source, const int& resolution )
  : BaseConverter( name, frequency, session ),
    p_video_( session->service("ALVideoDevice") ),
    camera_source_(camera_source),
    resolution_(resolution),
    // change in case of depth camera
    colorspace_( (camera_source_!=AL::kDepthCamera)?AL::kBGRColorSpace:AL::kDepthColorSpace ),
    msg_colorspace_( (camera_source_!=AL::kDepthCamera)?"bgr8":"16UC1" ),
    cv_mat_type_( (camera_source_!=AL::kDepthCamera)?CV_8UC3:CV_16U ),
    camera_info_( camera_info_definitions::getCameraInfo(camera_source, resolution) )
{
  if ( camera_source == AL::kTopCamera )
  {
    msg_frameid_ = "CameraTop_optical_frame";
  }
  else if (camera_source == AL::kBottomCamera )
  {
    msg_frameid_ = "CameraBottom_optical_frame";
  }
  else if (camera_source_ == AL::kDepthCamera )
  {
    msg_frameid_ = "CameraDepth_optical_frame";
  }
}

CameraConverter::~CameraConverter()
{
  if (!handle_.empty())
  {
    std::cout << "Unsubscribe camera handle " << handle_ << std::endl;
    p_video_.call<qi::AnyValue>("unsubscribe", handle_);
    handle_.clear();
  }
}

void CameraConverter::reset()
{
  if (!handle_.empty())
  {
    p_video_.call<qi::AnyValue>("unsubscribe", handle_);
    handle_.clear();
  }

  handle_ = p_video_.call<std::string>(
                         "subscribeCamera",
                          name_,
                          camera_source_,
                          resolution_,
                          colorspace_,
                          frequency_
                          );
}

void CameraConverter::registerCallback( const message_actions::MessageAction action, Callback_t cb )
{
  callbacks_[action] = cb;
}

void CameraConverter::callAll( const std::vector<message_actions::MessageAction>& actions )
{

  if (handle_.empty() )
  {
    std::cerr << "Camera Handle is empty - cannot retrieve image" << std::endl;
    return;
  }

  qi::AnyValue image_anyvalue = p_video_.call<qi::AnyValue>("getImageRemote", handle_);
  qi::AnyReferenceVector image_anyref;
  try{
    image_anyref = image_anyvalue.asListValuePtr();
  }
  catch(std::runtime_error& e)
  {
    std::cout << "Cannot retrieve image" << std::endl;
    return;
  }

  int width, height;
  void* image_buffer;

  // Create a cv::Mat of the right dimensions
  width = image_anyref[0].content().asInt32();
  height = image_anyref[1].content().asInt32();
  image_buffer = (void*)(image_anyref[6].content().asRaw().first);
  cv::Mat cv_img(height, width, cv_mat_type_, image_buffer);
  msg_ = cv_bridge::CvImage(std_msgs::Header(), msg_colorspace_, cv_img).toImageMsg();
  msg_->header.frame_id = msg_frameid_;

  ros::Time now = ros::Time::now();
  msg_->header.stamp = now;
  camera_info_.header.stamp = now;

  for_each( const message_actions::MessageAction& action, actions )
  {
    callbacks_[action]( msg_, camera_info_ );
  }
}

} // publisher
} //alros
<|endoftext|>


<commit_before>// 6 april 2015
#include "uipriv_windows.hpp"

HINSTANCE hInstance;
int nCmdShow;

HFONT hMessageFont;

// LONGTERM needed?
HBRUSH hollowBrush;

// the returned pointer is actually to the second character
// if the first character is - then free, otherwise don't
static const char *initerr(const char *message, const WCHAR *label, DWORD value)
{
	WCHAR *sysmsg;
	BOOL hassysmsg;
	WCHAR *wmessage;
	WCHAR *wout;
	char *out;

	hassysmsg = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, value, 0, (LPWSTR) (&sysmsg), 0, NULL) != 0;
	if (!hassysmsg)
		sysmsg = L"";
	wmessage = toUTF16(message + 1);
	wout = strf(L"-error initializing libui: %s; code %I32d (0x%08I32X) %s",
		wmessage,
		value, value,
		sysmsg);
	uiFree(wmessage);
	if (hassysmsg)
		LocalFree(sysmsg);		// ignore error
	out = toUTF8(wout);
	uiFree(wout);
	return out + 1;
}

#define ieLastErr(msg) initerr("=" msg, L"GetLastError() ==", GetLastError())
#define ieHRESULT(msg, hr) initerr("=" msg, L"HRESULT", (DWORD) hr)

// LONGTERM make common
uiInitOptions options;

#define wantedICCClasses ( \
	ICC_STANDARD_CLASSES |	/* user32.dll controls */		\
	ICC_PROGRESS_CLASS |		/* progress bars */			\
	ICC_TAB_CLASSES |			/* tabs */					\
	ICC_LISTVIEW_CLASSES |		/* table headers */			\
	ICC_UPDOWN_CLASS |		/* spinboxes */			\
	ICC_BAR_CLASSES |			/* trackbar */				\
	ICC_DATE_CLASSES |		/* date/time picker */		\
	0)

const char *uiInit(uiInitOptions *o)
{
	STARTUPINFOW si;
	const char *ce;
	HICON hDefaultIcon;
	HCURSOR hDefaultCursor;
	NONCLIENTMETRICSW ncm;
	INITCOMMONCONTROLSEX icc;
	HRESULT hr;

	options = *o;

	initAlloc();

	nCmdShow = SW_SHOWDEFAULT;
	GetStartupInfoW(&si);
	if ((si.dwFlags & STARTF_USESHOWWINDOW) != 0)
		nCmdShow = si.wShowWindow;

	// LONGTERM set DPI awareness

	hDefaultIcon = LoadIconW(NULL, IDI_APPLICATION);
	if (hDefaultIcon == NULL)
		return ieLastErr("loading default icon for window classes");
	hDefaultCursor = LoadCursorW(NULL, IDC_ARROW);
	if (hDefaultCursor == NULL)
		return ieLastErr("loading default cursor for window classes");

	ce = initUtilWindow(hDefaultIcon, hDefaultCursor);
	if (ce != NULL)
		return initerr(ce, L"GetLastError() ==", GetLastError());

	if (registerWindowClass(hDefaultIcon, hDefaultCursor) == 0)
		return ieLastErr("registering uiWindow window class");

	ZeroMemory(&ncm, sizeof (NONCLIENTMETRICSW));
	ncm.cbSize = sizeof (NONCLIENTMETRICSW);
	if (SystemParametersInfoW(SPI_GETNONCLIENTMETRICS, sizeof (NONCLIENTMETRICSW), &ncm, sizeof (NONCLIENTMETRICSW)) == 0)
		return ieLastErr("getting default fonts");
	hMessageFont = CreateFontIndirectW(&(ncm.lfMessageFont));
	if (hMessageFont == NULL)
		return ieLastErr("loading default messagebox font; this is the default UI font");

	if (initContainer(hDefaultIcon, hDefaultCursor) == 0)
		return ieLastErr("initializing uiWindowsMakeContainer() window class");

	hollowBrush = (HBRUSH) GetStockObject(HOLLOW_BRUSH);
	if (hollowBrush == NULL)
		return ieLastErr("getting hollow brush");

	ZeroMemory(&icc, sizeof (INITCOMMONCONTROLSEX));
	icc.dwSize = sizeof (INITCOMMONCONTROLSEX);
	icc.dwICC = wantedICCClasses;
	if (InitCommonControlsEx(&icc) == 0)
		return ieLastErr("initializing Common Controls");

	hr = CoInitialize(NULL);
	if (hr != S_OK && hr != S_FALSE)
		return ieHRESULT("initializing COM", hr);
	// LONGTERM initialize COM security
	// LONGTERM (windows vista) turn off COM exception handling

	hr = initDraw();
	if (hr != S_OK)
		return ieHRESULT("initializing Direct2D", hr);

	hr = initDrawText();
	if (hr != S_OK)
		return ieHRESULT("initializing DirectWrite", hr);

	if (registerAreaClass(hDefaultIcon, hDefaultCursor) == 0)
		return ieLastErr("registering uiArea window class");

	if (registerMessageFilter() == 0)
		return ieLastErr("registering libui message filter");

	if (registerD2DScratchClass(hDefaultIcon, hDefaultCursor) == 0)
		return ieLastErr("initializing D2D scratch window class");

	return NULL;
}

void uiUninit(void)
{
	uninitMenus();
	unregisterD2DScratchClass();
	unregisterMessageFilter();
	unregisterArea();
	uninitDrawText();
	uninitDraw();
	CoUninitialize();
	if (DeleteObject(hollowBrush) == 0)
		logLastError(L"error freeing hollow brush");
	uninitContainer();
	if (DeleteObject(hMessageFont) == 0)
		logLastError(L"error deleting control font");
	unregisterWindowClass();
	// no need to delete the default icon or cursor; see http://stackoverflow.com/questions/30603077/
	uninitUtilWindow();
	uninitAlloc();
}

void uiFreeInitError(const char *err)
{
	if (*(err - 1) == '-')
		uiFree((void *) err);
}

BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
	if (fdwReason == DLL_PROCESS_ATTACH)
		hInstance = hinstDLL;
	return TRUE;
}
<commit_msg>Fixed a latent bug in uiFreeInitError() on Windows.<commit_after>// 6 april 2015
#include "uipriv_windows.hpp"

HINSTANCE hInstance;
int nCmdShow;

HFONT hMessageFont;

// LONGTERM needed?
HBRUSH hollowBrush;

// the returned pointer is actually to the second character
// if the first character is - then free, otherwise don't
static const char *initerr(const char *message, const WCHAR *label, DWORD value)
{
	WCHAR *sysmsg;
	BOOL hassysmsg;
	WCHAR *wmessage;
	WCHAR *wout;
	char *out;

	hassysmsg = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, value, 0, (LPWSTR) (&sysmsg), 0, NULL) != 0;
	if (!hassysmsg)
		sysmsg = L"";
	wmessage = toUTF16(message + 1);
	wout = strf(L"-error initializing libui: %s; code %I32d (0x%08I32X) %s",
		wmessage,
		value, value,
		sysmsg);
	uiFree(wmessage);
	if (hassysmsg)
		LocalFree(sysmsg);		// ignore error
	out = toUTF8(wout);
	uiFree(wout);
	return out + 1;
}

#define ieLastErr(msg) initerr("=" msg, L"GetLastError() ==", GetLastError())
#define ieHRESULT(msg, hr) initerr("=" msg, L"HRESULT", (DWORD) hr)

// LONGTERM make common
uiInitOptions options;

#define wantedICCClasses ( \
	ICC_STANDARD_CLASSES |	/* user32.dll controls */		\
	ICC_PROGRESS_CLASS |		/* progress bars */			\
	ICC_TAB_CLASSES |			/* tabs */					\
	ICC_LISTVIEW_CLASSES |		/* table headers */			\
	ICC_UPDOWN_CLASS |		/* spinboxes */			\
	ICC_BAR_CLASSES |			/* trackbar */				\
	ICC_DATE_CLASSES |		/* date/time picker */		\
	0)

const char *uiInit(uiInitOptions *o)
{
	STARTUPINFOW si;
	const char *ce;
	HICON hDefaultIcon;
	HCURSOR hDefaultCursor;
	NONCLIENTMETRICSW ncm;
	INITCOMMONCONTROLSEX icc;
	HRESULT hr;

	options = *o;

	initAlloc();

	nCmdShow = SW_SHOWDEFAULT;
	GetStartupInfoW(&si);
	if ((si.dwFlags & STARTF_USESHOWWINDOW) != 0)
		nCmdShow = si.wShowWindow;

	// LONGTERM set DPI awareness

	hDefaultIcon = LoadIconW(NULL, IDI_APPLICATION);
	if (hDefaultIcon == NULL)
		return ieLastErr("loading default icon for window classes");
	hDefaultCursor = LoadCursorW(NULL, IDC_ARROW);
	if (hDefaultCursor == NULL)
		return ieLastErr("loading default cursor for window classes");

	ce = initUtilWindow(hDefaultIcon, hDefaultCursor);
	if (ce != NULL)
		return initerr(ce, L"GetLastError() ==", GetLastError());

	if (registerWindowClass(hDefaultIcon, hDefaultCursor) == 0)
		return ieLastErr("registering uiWindow window class");

	ZeroMemory(&ncm, sizeof (NONCLIENTMETRICSW));
	ncm.cbSize = sizeof (NONCLIENTMETRICSW);
	if (SystemParametersInfoW(SPI_GETNONCLIENTMETRICS, sizeof (NONCLIENTMETRICSW), &ncm, sizeof (NONCLIENTMETRICSW)) == 0)
		return ieLastErr("getting default fonts");
	hMessageFont = CreateFontIndirectW(&(ncm.lfMessageFont));
	if (hMessageFont == NULL)
		return ieLastErr("loading default messagebox font; this is the default UI font");

	if (initContainer(hDefaultIcon, hDefaultCursor) == 0)
		return ieLastErr("initializing uiWindowsMakeContainer() window class");

	hollowBrush = (HBRUSH) GetStockObject(HOLLOW_BRUSH);
	if (hollowBrush == NULL)
		return ieLastErr("getting hollow brush");

	ZeroMemory(&icc, sizeof (INITCOMMONCONTROLSEX));
	icc.dwSize = sizeof (INITCOMMONCONTROLSEX);
	icc.dwICC = wantedICCClasses;
	if (InitCommonControlsEx(&icc) == 0)
		return ieLastErr("initializing Common Controls");

	hr = CoInitialize(NULL);
	if (hr != S_OK && hr != S_FALSE)
		return ieHRESULT("initializing COM", hr);
	// LONGTERM initialize COM security
	// LONGTERM (windows vista) turn off COM exception handling

	hr = initDraw();
	if (hr != S_OK)
		return ieHRESULT("initializing Direct2D", hr);

	hr = initDrawText();
	if (hr != S_OK)
		return ieHRESULT("initializing DirectWrite", hr);

	if (registerAreaClass(hDefaultIcon, hDefaultCursor) == 0)
		return ieLastErr("registering uiArea window class");

	if (registerMessageFilter() == 0)
		return ieLastErr("registering libui message filter");

	if (registerD2DScratchClass(hDefaultIcon, hDefaultCursor) == 0)
		return ieLastErr("initializing D2D scratch window class");

	return NULL;
}

void uiUninit(void)
{
	uninitMenus();
	unregisterD2DScratchClass();
	unregisterMessageFilter();
	unregisterArea();
	uninitDrawText();
	uninitDraw();
	CoUninitialize();
	if (DeleteObject(hollowBrush) == 0)
		logLastError(L"error freeing hollow brush");
	uninitContainer();
	if (DeleteObject(hMessageFont) == 0)
		logLastError(L"error deleting control font");
	unregisterWindowClass();
	// no need to delete the default icon or cursor; see http://stackoverflow.com/questions/30603077/
	uninitUtilWindow();
	uninitAlloc();
}

void uiFreeInitError(const char *err)
{
	if (*(err - 1) == '-')
		uiFree((void *) (err - 1));
}

BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
	if (fdwReason == DLL_PROCESS_ATTACH)
		hInstance = hinstDLL;
	return TRUE;
}
<|endoftext|>


<commit_before>#include "include/a_devdiag.h"
#include "include/netstructures.h"

void a_devdiag() {
	pcap_if_t *alldevs;
	char errbuf[PCAP_ERRBUF_SIZE];

	if (pcap_findalldevs(&alldevs, errbuf) == -1) {
		printf("Error in pcap_findalldevs: %s\n", errbuf);
		exit(1);
	}

	int i = 0;
	pcap_if_t *d;
	for (d = alldevs; d; d = d->next) {
		printf("%d. %s", ++i, d->name);
		if (d->description) {
			printf(" (%s)\n", d->description);
		}
	}

	int inum;
	printf("Enter the interface number (1-%d): ", i);
	scanf_s("%d", &inum);

	for (d = alldevs, i = 0; i< inum - 1; d = d->next, i++);

	pcap_t *adhandle;
	if ((adhandle = pcap_open_live(d->name, 65536, 1000, NULL, errbuf)) == NULL) {
		printf("Unable to open the network adapter. %s is not supported by WinPcap\n", d->name);
		pcap_freealldevs(alldevs);
		exit(1);
	}

	pcap_freealldevs(alldevs);
	printf("Starting active diagnostics...\n");

	pcap_loop(adhandle, INFINITE, a_packethandler, NULL);
}

void a_packethandler(u_char *param, const struct pcap_pkthdr *header, const u_char *pkt_data) {
	struct tm ltime;
	char timestr[16];
	ip_header *ih;
	udp_header *uh;
	u_int ip_len;
	u_short sport, dport;
	time_t local_tv_sec;

	(VOID)(param);

	local_tv_sec = header->ts.tv_sec;
	localtime_s(&ltime, &local_tv_sec);
	strftime(timestr, sizeof(timestr), "%H:%M:%S", &ltime);
	printf("%s,%.6d len:%d  ", timestr, header->ts.tv_usec, header->len);

	ih = (ip_header *)(pkt_data + 14);

	ip_len = (ih->ver_ihl & 0xf) * 4;
	uh = (udp_header *)((u_char *)ih + ip_len);

	sport = ntohs(uh->sport);
	dport = ntohs(uh->dport);

	printf("%d.%d.%d.%d.%d -> %d.%d.%d.%d.%d           \n",
		ih->saddr.byte1,
		ih->saddr.byte2,
		ih->saddr.byte3,
		ih->saddr.byte4,
		sport,
		ih->daddr.byte1,
		ih->daddr.byte2,
		ih->daddr.byte3,
		ih->daddr.byte4,
		dport);

	//struct sockaddr *sa = new sockaddr;
	//char host[1024];
	//char service[20];
	//getnameinfo(sa, sizeof(sa), host, sizeof(host), service, sizeof(service), 0);
	//printf("host: %s", host);
	//printf("service: %s\n", service);
}<commit_msg>Added DLT ethernet check<commit_after>#include "include/a_devdiag.h"
#include "include/netstructures.h"

void a_devdiag() {
	pcap_if_t *alldevs;
	char errbuf[PCAP_ERRBUF_SIZE];

	if (pcap_findalldevs(&alldevs, errbuf) == -1) {
		printf("Error in pcap_findalldevs: %s\n", errbuf);
		exit(1);
	}

	int i = 0;
	pcap_if_t *d;
	for (d = alldevs; d; d = d->next) {
		printf("%d. %s", ++i, d->name);
		if (d->description) {
			printf(" (%s)\n", d->description);
		}
	}

	int inum;
	printf("Enter the interface number (1-%d): ", i);
	scanf_s("%d", &inum);

	for (d = alldevs, i = 0; i< inum - 1; d = d->next, i++);

	pcap_t *adhandle;
	if ((adhandle = pcap_open_live(d->name, 65536, 1000, NULL, errbuf)) == NULL) {
		printf("Unable to open the network adapter. %s is not supported by WinPcap\n", d->name);
		pcap_freealldevs(alldevs);
		exit(1);
	}

	if (pcap_datalink(adhandle) != DLT_EN10MB) {
		printf("Not using an ethernet device: output may not always be correct.\n");
	}

	pcap_freealldevs(alldevs);
	printf("Starting active diagnostics...\n");

	pcap_loop(adhandle, INFINITE, a_packethandler, NULL);
}

void a_packethandler(u_char *param, const struct pcap_pkthdr *header, const u_char *pkt_data) {
	struct tm ltime;
	char timestr[16];
	ip_header *ih;
	udp_header *uh;
	u_int ip_len;
	u_short sport, dport;
	time_t local_tv_sec;

	(VOID)(param);

	local_tv_sec = header->ts.tv_sec;
	localtime_s(&ltime, &local_tv_sec);
	strftime(timestr, sizeof(timestr), "%H:%M:%S", &ltime);
	printf("%s,%.6d len:%d  ", timestr, header->ts.tv_usec, header->len);

	ih = (ip_header *)(pkt_data + 14);

	ip_len = (ih->ver_ihl & 0xf) * 4;
	uh = (udp_header *)((u_char *)ih + ip_len);

	sport = ntohs(uh->sport);
	dport = ntohs(uh->dport);

	printf("%d.%d.%d.%d.%d -> %d.%d.%d.%d.%d           \r",
		ih->saddr.byte1,
		ih->saddr.byte2,
		ih->saddr.byte3,
		ih->saddr.byte4,
		sport,
		ih->daddr.byte1,
		ih->daddr.byte2,
		ih->daddr.byte3,
		ih->daddr.byte4,
		dport);
}<|endoftext|>


<commit_before>/***
 * @file core.hpp
 *
 * Include all of the base components required to write MLPACK methods, and the
 * main MLPACK Doxygen documentation.
 */
#ifndef __MLPACK_CORE_HPP
#define __MLPACK_CORE_HPP

/**
 * @mainpage MLPACK Documentation
 *
 * @section intro_sec Introduction
 *
 * MLPACK is an intuitive, fast, scalable C++ machine learning library, meant to
 * be a machine learning analog to LAPACK.  It aims to implement a wide array of
 * machine learning methods and function as a "swiss army knife" for machine
 * learning researchers.  The MLPACK development website can be found at
 * http://mlpack.org.
 *
 * MLPACK uses the Armadillo C++ matrix library (http://arma.sourceforge.net)
 * for general matrix, vector, and linear algebra support.  MLPACK also uses the
 * program_options, math_c99, and unit_test_framework components of the Boost
 * library; in addition, LibXml2 is used.
 *
 * @section howto How To Use This Documentation
 *
 * This documentation is API documentation similar to Javadoc.  It isn't
 * necessarily a tutorial, but it does provide detailed documentation on every
 * namespace, method, and class.
 *
 * Each MLPACK namespace generally refers to one machine learning method, so
 * browsing the list of namespaces provides some insight as to the breadth of
 * the methods contained in the library.
 *
 * To generate this documentation in your own local copy of MLPACK, you can
 * simply use Doxygen, from the root directory (@c /mlpack/trunk/ ):
 *
 * @code
 * $ doxygen
 * @endcode
 *
 * @section executables Executables
 *
 * MLPACK provides several executables so that MLPACK methods can be used
 * without any need for knowledge of C++.  These executables are all
 * self-documented, and that documentation can be accessed by running the
 * executables with the '-h' or '--help' flag.
 *
 * A full list of executables is given below:
 *
 * allkfn, allknn, emst, gmm, hmm_train, hmm_loglik, hmm_viterbi, hmm_generate,
 * kernel_pca, kmeans, lars, linear_regression, local_coordinate_coding, mvu,
 * nbc, nca, pca, radical, sparse_coding
 *
 * @section tutorial Tutorials
 *
 * A few short tutorials on how to use MLPACK are given below.
 *
 *  - @ref build
 *  - @ref matrices
 *  - @ref iodoc
 *  - @ref timer
 *  - @ref sample
 *
 * Tutorials on specific methods are also available.
 *
 *  - @ref nstutorial
 *  - @ref lrtutorial
 *  - @ref rstutorial
 *  - @ref dettutorial
 *  - @ref emst_tutorial
 *
 * @section methods Methods in MLPACK
 *
 * The following methods are included in MLPACK:
 *
 *  - Euclidean Minimum Spanning Trees - mlpack::emst::DualTreeBoruvka
 *  - Gaussian Mixture Models (GMMs) - mlpack::gmm::GMM
 *  - Hidden Markov Models (HMMs) - mlpack::hmm::HMM
 *  - Kernel PCA - mlpack::kpca::KernelPCA
 *  - K-Means Clustering - mlpack::kmeans::KMeans
 *  - Least-Angle Regression (LARS/LASSO) - mlpack::regression::LARS
 *  - Local Coordinate Coding - mlpack::lcc::LocalCoordinateCoding
 *  - Naive Bayes Classifier - mlpack::naive_bayes::NaiveBayesClassifier
 *  - Neighborhood Components Analysis (NCA) - mlpack::nca::NCA
 *  - Principal Components Analysis (PCA) - mlpack::pca::PCA
 *  - RADICAL (ICA) - mlpack::radical::Radical
 *  - Simple Least-Squares Linear Regression -
 *      mlpack::regression::LinearRegression
 *  - Sparse Coding - mlpack::sparse_coding::SparseCoding
 *  - Tree-based neighbor search (AllkNN, AllkFN) -
 *      mlpack::neighbor::NeighborSearch
 *  - Tree-based range search - mlpack::range::RangeSearch
 *
 * @section remarks Final Remarks
 *
 * This software was written in the FASTLab (http://www.fast-lab.org), which is
 * in the School of Computational Science and Engineering at the Georgia
 * Institute of Technology.
 *
 * MLPACK contributors include:
 *
 *   - Ryan Curtin <gth671b@mail.gatech.edu>
 *   - James Cline <james.cline@gatech.edu>
 *   - Neil Slagle <nslagle3@gatech.edu>
 *   - Matthew Amidon <mamidon@gatech.edu>
 *   - Vlad Grantcharov <vlad321@gatech.edu>
 *   - Ajinkya Kale <kaleajinkya@gmail.com>
 *   - Bill March <march@gatech.edu>
 *   - Dongryeol Lee <dongryel@cc.gatech.edu>
 *   - Nishant Mehta <niche@cc.gatech.edu>
 *   - Parikshit Ram <p.ram@gatech.edu>
 *   - Chip Mappus <cmappus@gatech.edu>
 *   - Hua Ouyang <houyang@gatech.edu>
 *   - Long Quoc Tran <tqlong@gmail.com>
 *   - Noah Kauffman <notoriousnoah@gmail.com>
 *   - Guillermo Colon <gcolon7@mail.gatech.edu>
 *   - Wei Guan <wguan@cc.gatech.edu>
 *   - Ryan Riegel <rriegel@cc.gatech.edu>
 *   - Nikolaos Vasiloglou <nvasil@ieee.org>
 *   - Garry Boyer <garryb@gmail.com>
 *   - Andreas Löf <andreas.lof@cs.waikato.ac.nz>
 */

// First, standard includes.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <limits.h>
#include <float.h>
#include <stdint.h>
#include <iostream>

// Defining __USE_MATH_DEFINES should set M_PI.
#define _USE_MATH_DEFINES
#include <math.h>

// For tgamma().
#include <boost/math/special_functions/gamma.hpp>

// But if it's not defined, we'll do it.
#ifndef M_PI
  #define M_PI 3.141592653589793238462643383279
#endif

// Now MLPACK-specific includes.
#include <mlpack/core/arma_extend/arma_extend.hpp> // Includes Armadillo.
#include <mlpack/core/util/log.hpp>
#include <mlpack/core/util/cli.hpp>
#include <mlpack/core/data/load.hpp>
#include <mlpack/core/data/save.hpp>
#include <mlpack/core/math/clamp.hpp>
#include <mlpack/core/math/random.hpp>
#include <mlpack/core/math/range.hpp>
#include <mlpack/core/math/round.hpp>
#include <mlpack/core/util/save_restore_utility.hpp>
#include <mlpack/core/dists/discrete_distribution.hpp>
#include <mlpack/core/dists/gaussian_distribution.hpp>

// Clean up unfortunate Windows preprocessor definitions.
// Use std::min and std::max!
#ifdef _WIN32
  #ifdef min
    #undef min
  #endif

  #ifdef max
    #undef max
  #endif
#endif

#endif
<commit_msg>Include linear algebra utilities.<commit_after>/***
 * @file core.hpp
 *
 * Include all of the base components required to write MLPACK methods, and the
 * main MLPACK Doxygen documentation.
 */
#ifndef __MLPACK_CORE_HPP
#define __MLPACK_CORE_HPP

/**
 * @mainpage MLPACK Documentation
 *
 * @section intro_sec Introduction
 *
 * MLPACK is an intuitive, fast, scalable C++ machine learning library, meant to
 * be a machine learning analog to LAPACK.  It aims to implement a wide array of
 * machine learning methods and function as a "swiss army knife" for machine
 * learning researchers.  The MLPACK development website can be found at
 * http://mlpack.org.
 *
 * MLPACK uses the Armadillo C++ matrix library (http://arma.sourceforge.net)
 * for general matrix, vector, and linear algebra support.  MLPACK also uses the
 * program_options, math_c99, and unit_test_framework components of the Boost
 * library; in addition, LibXml2 is used.
 *
 * @section howto How To Use This Documentation
 *
 * This documentation is API documentation similar to Javadoc.  It isn't
 * necessarily a tutorial, but it does provide detailed documentation on every
 * namespace, method, and class.
 *
 * Each MLPACK namespace generally refers to one machine learning method, so
 * browsing the list of namespaces provides some insight as to the breadth of
 * the methods contained in the library.
 *
 * To generate this documentation in your own local copy of MLPACK, you can
 * simply use Doxygen, from the root directory (@c /mlpack/trunk/ ):
 *
 * @code
 * $ doxygen
 * @endcode
 *
 * @section executables Executables
 *
 * MLPACK provides several executables so that MLPACK methods can be used
 * without any need for knowledge of C++.  These executables are all
 * self-documented, and that documentation can be accessed by running the
 * executables with the '-h' or '--help' flag.
 *
 * A full list of executables is given below:
 *
 * allkfn, allknn, emst, gmm, hmm_train, hmm_loglik, hmm_viterbi, hmm_generate,
 * kernel_pca, kmeans, lars, linear_regression, local_coordinate_coding, mvu,
 * nbc, nca, pca, radical, sparse_coding
 *
 * @section tutorial Tutorials
 *
 * A few short tutorials on how to use MLPACK are given below.
 *
 *  - @ref build
 *  - @ref matrices
 *  - @ref iodoc
 *  - @ref timer
 *  - @ref sample
 *
 * Tutorials on specific methods are also available.
 *
 *  - @ref nstutorial
 *  - @ref lrtutorial
 *  - @ref rstutorial
 *  - @ref dettutorial
 *  - @ref emst_tutorial
 *
 * @section methods Methods in MLPACK
 *
 * The following methods are included in MLPACK:
 *
 *  - Euclidean Minimum Spanning Trees - mlpack::emst::DualTreeBoruvka
 *  - Gaussian Mixture Models (GMMs) - mlpack::gmm::GMM
 *  - Hidden Markov Models (HMMs) - mlpack::hmm::HMM
 *  - Kernel PCA - mlpack::kpca::KernelPCA
 *  - K-Means Clustering - mlpack::kmeans::KMeans
 *  - Least-Angle Regression (LARS/LASSO) - mlpack::regression::LARS
 *  - Local Coordinate Coding - mlpack::lcc::LocalCoordinateCoding
 *  - Naive Bayes Classifier - mlpack::naive_bayes::NaiveBayesClassifier
 *  - Neighborhood Components Analysis (NCA) - mlpack::nca::NCA
 *  - Principal Components Analysis (PCA) - mlpack::pca::PCA
 *  - RADICAL (ICA) - mlpack::radical::Radical
 *  - Simple Least-Squares Linear Regression -
 *      mlpack::regression::LinearRegression
 *  - Sparse Coding - mlpack::sparse_coding::SparseCoding
 *  - Tree-based neighbor search (AllkNN, AllkFN) -
 *      mlpack::neighbor::NeighborSearch
 *  - Tree-based range search - mlpack::range::RangeSearch
 *
 * @section remarks Final Remarks
 *
 * This software was written in the FASTLab (http://www.fast-lab.org), which is
 * in the School of Computational Science and Engineering at the Georgia
 * Institute of Technology.
 *
 * MLPACK contributors include:
 *
 *   - Ryan Curtin <gth671b@mail.gatech.edu>
 *   - James Cline <james.cline@gatech.edu>
 *   - Neil Slagle <nslagle3@gatech.edu>
 *   - Matthew Amidon <mamidon@gatech.edu>
 *   - Vlad Grantcharov <vlad321@gatech.edu>
 *   - Ajinkya Kale <kaleajinkya@gmail.com>
 *   - Bill March <march@gatech.edu>
 *   - Dongryeol Lee <dongryel@cc.gatech.edu>
 *   - Nishant Mehta <niche@cc.gatech.edu>
 *   - Parikshit Ram <p.ram@gatech.edu>
 *   - Chip Mappus <cmappus@gatech.edu>
 *   - Hua Ouyang <houyang@gatech.edu>
 *   - Long Quoc Tran <tqlong@gmail.com>
 *   - Noah Kauffman <notoriousnoah@gmail.com>
 *   - Guillermo Colon <gcolon7@mail.gatech.edu>
 *   - Wei Guan <wguan@cc.gatech.edu>
 *   - Ryan Riegel <rriegel@cc.gatech.edu>
 *   - Nikolaos Vasiloglou <nvasil@ieee.org>
 *   - Garry Boyer <garryb@gmail.com>
 *   - Andreas Löf <andreas.lof@cs.waikato.ac.nz>
 */

// First, standard includes.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <limits.h>
#include <float.h>
#include <stdint.h>
#include <iostream>

// Defining __USE_MATH_DEFINES should set M_PI.
#define _USE_MATH_DEFINES
#include <math.h>

// For tgamma().
#include <boost/math/special_functions/gamma.hpp>

// But if it's not defined, we'll do it.
#ifndef M_PI
  #define M_PI 3.141592653589793238462643383279
#endif

// Now MLPACK-specific includes.
#include <mlpack/core/arma_extend/arma_extend.hpp> // Includes Armadillo.
#include <mlpack/core/util/log.hpp>
#include <mlpack/core/util/cli.hpp>
#include <mlpack/core/data/load.hpp>
#include <mlpack/core/data/save.hpp>
#include <mlpack/core/math/clamp.hpp>
#include <mlpack/core/math/random.hpp>
#include <mlpack/core/math/lin_alg.hpp>
#include <mlpack/core/math/range.hpp>
#include <mlpack/core/math/round.hpp>
#include <mlpack/core/util/save_restore_utility.hpp>
#include <mlpack/core/dists/discrete_distribution.hpp>
#include <mlpack/core/dists/gaussian_distribution.hpp>

// Clean up unfortunate Windows preprocessor definitions.
// Use std::min and std::max!
#ifdef _WIN32
  #ifdef min
    #undef min
  #endif

  #ifdef max
    #undef max
  #endif
#endif

#endif
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main(int argc, char const *argv[]) {

	return 0;
}
<commit_msg>adding<commit_after>//http://codeforces.com/problemset/problem/601/A
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main(int argc, char const *argv[]) {

	return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main(int argc, char const *argv[]) {

	return 0;
}
<commit_msg>adding<commit_after>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
bool g[3001][3001];
int main(int argc, char const *argv[]) {
	int n,m;
	cin>>n>>m;
	std::vector<int> neigh[n];
	for(int i=0;i<m;i++){
		int a,b;
		cin>>a>>b;

	}
	return 0;
}
<|endoftext|>