<commit_before>#undef QT_NO_ASCII_CAST
// kmacctlocal.cpp

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <qdatetime.h>
#include <qfileinfo.h>
#include "kmacctlocal.h"
#include "kmfolder.h"
#include "kmmessage.h"
#include "kmacctfolder.h"
#include "kmglobal.h"
#include "kmbroadcaststatus.h"

#include <kapp.h>
#include <kconfig.h>

#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <kdebug.h>

#ifdef HAVE_PATHS_H
#include <paths.h>	/* defines _PATH_MAILDIR */
#endif

#ifndef _PATH_MAILDIR
#define _PATH_MAILDIR "/var/spool/mail"
#endif
#undef None

//-----------------------------------------------------------------------------
KMAcctLocal::KMAcctLocal(KMAcctMgr* aOwner, const char* aAccountName):
  KMAcctLocalInherited(aOwner, aAccountName)
{
  mLock = procmail_lockfile;
}

//-----------------------------------------------------------------------------
KMAcctLocal::~KMAcctLocal()
{
  mLocation = "";
}

//-----------------------------------------------------------------------------
const char* KMAcctLocal::type(void) const
{
  return "local";
}

//-----------------------------------------------------------------------------
void KMAcctLocal::init(void)
{
  mLocation = getenv("MAIL");
  if (mLocation.isNull()) {
    mLocation = _PATH_MAILDIR;
    mLocation += "/";
    mLocation += getenv("USER");
  }
  setProcmailLockFileName("");
}

//-----------------------------------------------------------------------------
void KMAcctLocal::pseudoAssign(KMAccount *account)
{
  assert(account->type() == "local");
  KMAcctLocal *acct = static_cast<KMAcctLocal*>(account);
  setName(acct->name());
  setLocation(acct->location());
  setCheckInterval(acct->checkInterval());
  setCheckExclude(acct->checkExclude());
  setLockType(acct->lockType());
  setProcmailLockFileName(acct->procmailLockFileName());
  setFolder(acct->folder());
  setPrecommand(acct->precommand());
}

//-----------------------------------------------------------------------------
void KMAcctLocal::processNewMail(bool)
{
  QTime t;
  hasNewMail = false;

  if ( precommand().isEmpty() ) {
    QFileInfo fi( location() );
    if ( fi.size() == 0 ) {
      emit finishedCheck(hasNewMail);
      return;
    }
  }

  KMFolder mailFolder(NULL, location());
  mailFolder.setLockType( mLock );
  if ( mLock == procmail_lockfile)
    mailFolder.setProcmailLockFileName( mProcmailLockFileName );

  long num = 0;
  long i;
  int rc;
  KMMessage* msg;
  bool addedOk;

  if (!mFolder) {
    emit finishedCheck(hasNewMail);
    return;
  }

  KMBroadcastStatus::instance()->reset();
  KMBroadcastStatus::instance()->setStatusMsg(
	i18n("Preparing transmission from %1...").arg(mailFolder.name()));

  // run the precommand
  if (!runPrecommand(precommand()))
    {
        perror("cannot run precommand "+precommand());
	emit finishedCheck(hasNewMail);
    }

  mailFolder.setAutoCreateIndex(FALSE);

  rc = mailFolder.open();
  if (rc)
  {
    QString aStr;
    aStr = i18n("Cannot open file:");
    aStr += mailFolder.path()+"/"+mailFolder.name();
    KMessageBox::sorry(0, aStr);
    perror("cannot open file "+mailFolder.path()+"/"+mailFolder.name());
    emit finishedCheck(hasNewMail);
    KMBroadcastStatus::instance()->setStatusMsg( i18n( "Transmission completed." ));
    return;
  }

  if (mailFolder.isReadOnly()) { // mailFolder is locked
    kdDebug() << "mailFolder could not be locked" << endl;
    mailFolder.close();
    emit finishedCheck(hasNewMail);
    KMBroadcastStatus::instance()->setStatusMsg( i18n( "Transmission completed." ));
    return;
  }

  mFolder->quiet(TRUE);
  mFolder->open();

  num = mailFolder.count();

  addedOk = true;
  t.start();

  KMBroadcastStatus::instance()->setStatusProgressEnable( true );
  for (i=0; i<num; i++)
  {

    if (!addedOk) break;
    if (KMBroadcastStatus::instance()->abortRequested()) break;

    KMBroadcastStatus::instance()->setStatusMsg( i18n("Message ") +
			                QString("%1/%2").arg(i).arg(num) );
    KMBroadcastStatus::instance()->setStatusProgressPercent( (i*100) / num );

    msg = mailFolder.take(0);
    if (msg)
    {
      msg->setStatus(msg->headerField("Status"), msg->headerField("X-Status"));
      addedOk = processNewMsg(msg);
      if (addedOk)
	hasNewMail = true;
    }

    if (t.elapsed() >= 200) { //hardwired constant
      kapp->processEvents();
      t.start();
    }

  }
  KMBroadcastStatus::instance()->setStatusProgressEnable( false );
  KMBroadcastStatus::instance()->reset();

  if (addedOk)
  {
  rc = mailFolder.expunge();
  if (rc)
    KMessageBox::information( 0, i18n("Cannot remove mail from\nmailbox `%1':\n%2").arg(mailFolder.location().arg(strerror(rc))));
    KMBroadcastStatus::instance()->setStatusMsg( i18n( "Transmission completed." ));
  }
  // else warning is written already

  mailFolder.close();
  mFolder->close();
  mFolder->quiet(FALSE);

  emit finishedCheck(hasNewMail);

  return;
}

//-----------------------------------------------------------------------------
void KMAcctLocal::readConfig(KConfig& config)
{
  KMAcctLocalInherited::readConfig(config);
  mLocation = config.readEntry("Location", mLocation);
  QString locktype = config.readEntry("LockType", "procmail_lockfile" );

  if( locktype == "procmail_lockfile" ) {
    mLock = procmail_lockfile;
    mProcmailLockFileName = config.readEntry("ProcmailLockFile",
      mLocation + ".lock");
  } else if( locktype == "mutt_dotlock" )
    mLock = mutt_dotlock;
  else if( locktype == "mutt_dotlock_privileged" )
    mLock = mutt_dotlock_privileged;
  else if( locktype == "none" )
    mLock = None;
  else mLock = FCNTL;
}

//-----------------------------------------------------------------------------
void KMAcctLocal::writeConfig(KConfig& config)
{
  KMAcctLocalInherited::writeConfig(config);

  config.writeEntry("Location", mLocation);

  QString st = "fcntl";
  if (mLock == procmail_lockfile) st = "procmail_lockfile";
  else if (mLock == mutt_dotlock) st = "mutt_dotlock";
  else if (mLock == mutt_dotlock_privileged) st = "mutt_dotlock_privileged";
  else if (mLock == None) st = "none";
  config.writeEntry("LockType", st);

  if (mLock == procmail_lockfile) {
    config.writeEntry("ProcmailLockFile", mProcmailLockFileName);
  }

}

//-----------------------------------------------------------------------------
void KMAcctLocal::setLocation(const QString& aLocation)
{
  mLocation = aLocation;
}

void
KMAcctLocal::setProcmailLockFileName(QString s)
{
  if (s && !s.isEmpty())
    mProcmailLockFileName = s;
  else
    mProcmailLockFileName = mLocation + ".lock";
}

<commit_msg>Found another bug, while cleaning up data types. -    KMessageBox::information( 0, i18n("Cannot remove mail from\nmailbox `%1':\n%2").arg(mailFolder.location().arg(strerror(rc)))); +    KMessageBox::information( 0, i18n("Cannot remove mail from\nmailbox `%1':\n%2").arg(mailFolder.location()).arg(strerror(rc)));<commit_after>#undef QT_NO_ASCII_CAST
// kmacctlocal.cpp

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <qdatetime.h>
#include <qfileinfo.h>
#include "kmacctlocal.h"
#include "kmfolder.h"
#include "kmmessage.h"
#include "kmacctfolder.h"
#include "kmglobal.h"
#include "kmbroadcaststatus.h"

#include <kapp.h>
#include <kconfig.h>

#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <kdebug.h>

#ifdef HAVE_PATHS_H
#include <paths.h>	/* defines _PATH_MAILDIR */
#endif

#ifndef _PATH_MAILDIR
#define _PATH_MAILDIR "/var/spool/mail"
#endif
#undef None

//-----------------------------------------------------------------------------
KMAcctLocal::KMAcctLocal(KMAcctMgr* aOwner, const char* aAccountName):
  KMAcctLocalInherited(aOwner, aAccountName)
{
  mLock = procmail_lockfile;
}

//-----------------------------------------------------------------------------
KMAcctLocal::~KMAcctLocal()
{
  mLocation = "";
}

//-----------------------------------------------------------------------------
const char* KMAcctLocal::type(void) const
{
  return "local";
}

//-----------------------------------------------------------------------------
void KMAcctLocal::init(void)
{
  mLocation = getenv("MAIL");
  if (mLocation.isNull()) {
    mLocation = _PATH_MAILDIR;
    mLocation += "/";
    mLocation += getenv("USER");
  }
  setProcmailLockFileName("");
}

//-----------------------------------------------------------------------------
void KMAcctLocal::pseudoAssign(KMAccount *account)
{
  assert(account->type() == "local");
  KMAcctLocal *acct = static_cast<KMAcctLocal*>(account);
  setName(acct->name());
  setLocation(acct->location());
  setCheckInterval(acct->checkInterval());
  setCheckExclude(acct->checkExclude());
  setLockType(acct->lockType());
  setProcmailLockFileName(acct->procmailLockFileName());
  setFolder(acct->folder());
  setPrecommand(acct->precommand());
}

//-----------------------------------------------------------------------------
void KMAcctLocal::processNewMail(bool)
{
  QTime t;
  hasNewMail = false;

  if ( precommand().isEmpty() ) {
    QFileInfo fi( location() );
    if ( fi.size() == 0 ) {
      emit finishedCheck(hasNewMail);
      return;
    }
  }

  KMFolder mailFolder(NULL, location());
  mailFolder.setLockType( mLock );
  if ( mLock == procmail_lockfile)
    mailFolder.setProcmailLockFileName( mProcmailLockFileName );

  long num = 0;
  long i;
  int rc;
  KMMessage* msg;
  bool addedOk;

  if (!mFolder) {
    emit finishedCheck(hasNewMail);
    return;
  }

  KMBroadcastStatus::instance()->reset();
  KMBroadcastStatus::instance()->setStatusMsg(
	i18n("Preparing transmission from %1...").arg(mailFolder.name()));

  // run the precommand
  if (!runPrecommand(precommand()))
    {
        perror("cannot run precommand "+precommand());
	emit finishedCheck(hasNewMail);
    }

  mailFolder.setAutoCreateIndex(FALSE);

  rc = mailFolder.open();
  if (rc)
  {
    QString aStr;
    aStr = i18n("Cannot open file:");
    aStr += mailFolder.path()+"/"+mailFolder.name();
    KMessageBox::sorry(0, aStr);
    perror("cannot open file "+mailFolder.path()+"/"+mailFolder.name());
    emit finishedCheck(hasNewMail);
    KMBroadcastStatus::instance()->setStatusMsg( i18n( "Transmission completed." ));
    return;
  }

  if (mailFolder.isReadOnly()) { // mailFolder is locked
    kdDebug() << "mailFolder could not be locked" << endl;
    mailFolder.close();
    emit finishedCheck(hasNewMail);
    KMBroadcastStatus::instance()->setStatusMsg( i18n( "Transmission completed." ));
    return;
  }

  mFolder->quiet(TRUE);
  mFolder->open();

  num = mailFolder.count();

  addedOk = true;
  t.start();

  KMBroadcastStatus::instance()->setStatusProgressEnable( true );
  for (i=0; i<num; i++)
  {

    if (!addedOk) break;
    if (KMBroadcastStatus::instance()->abortRequested()) break;

    KMBroadcastStatus::instance()->setStatusMsg( i18n("Message ") +
			                QString("%1/%2").arg(i).arg(num) );
    KMBroadcastStatus::instance()->setStatusProgressPercent( (i*100) / num );

    msg = mailFolder.take(0);
    if (msg)
    {
      msg->setStatus(msg->headerField("Status"), msg->headerField("X-Status"));
      addedOk = processNewMsg(msg);
      if (addedOk)
	hasNewMail = true;
    }

    if (t.elapsed() >= 200) { //hardwired constant
      kapp->processEvents();
      t.start();
    }

  }
  KMBroadcastStatus::instance()->setStatusProgressEnable( false );
  KMBroadcastStatus::instance()->reset();

  if (addedOk)
  {
  rc = mailFolder.expunge();
  if (rc)
    KMessageBox::information( 0, i18n("Cannot remove mail from\nmailbox `%1':\n%2").arg(mailFolder.location()).arg(strerror(rc)));
    KMBroadcastStatus::instance()->setStatusMsg( i18n( "Transmission completed." ));
  }
  // else warning is written already

  mailFolder.close();
  mFolder->close();
  mFolder->quiet(FALSE);

  emit finishedCheck(hasNewMail);

  return;
}

//-----------------------------------------------------------------------------
void KMAcctLocal::readConfig(KConfig& config)
{
  KMAcctLocalInherited::readConfig(config);
  mLocation = config.readEntry("Location", mLocation);
  QString locktype = config.readEntry("LockType", "procmail_lockfile" );

  if( locktype == "procmail_lockfile" ) {
    mLock = procmail_lockfile;
    mProcmailLockFileName = config.readEntry("ProcmailLockFile",
      mLocation + ".lock");
  } else if( locktype == "mutt_dotlock" )
    mLock = mutt_dotlock;
  else if( locktype == "mutt_dotlock_privileged" )
    mLock = mutt_dotlock_privileged;
  else if( locktype == "none" )
    mLock = None;
  else mLock = FCNTL;
}

//-----------------------------------------------------------------------------
void KMAcctLocal::writeConfig(KConfig& config)
{
  KMAcctLocalInherited::writeConfig(config);

  config.writeEntry("Location", mLocation);

  QString st = "fcntl";
  if (mLock == procmail_lockfile) st = "procmail_lockfile";
  else if (mLock == mutt_dotlock) st = "mutt_dotlock";
  else if (mLock == mutt_dotlock_privileged) st = "mutt_dotlock_privileged";
  else if (mLock == None) st = "none";
  config.writeEntry("LockType", st);

  if (mLock == procmail_lockfile) {
    config.writeEntry("ProcmailLockFile", mProcmailLockFileName);
  }

}

//-----------------------------------------------------------------------------
void KMAcctLocal::setLocation(const QString& aLocation)
{
  mLocation = aLocation;
}

void
KMAcctLocal::setProcmailLockFileName(QString s)
{
  if (s && !s.isEmpty())
    mProcmailLockFileName = s;
  else
    mProcmailLockFileName = mLocation + ".lock";
}

<|endoftext|>


<commit_before><commit_msg>Create 1072 - Interval 2.cpp<commit_after><|endoftext|>


<commit_before><commit_msg>default value for tau_beta vector now has 2 elements for consistency<commit_after><|endoftext|>


<commit_before>//
// Name:	 canvas.cpp
// Purpose:	 Implements the canvas class for the wxWindows application.
//
// Copyright (c) 2001 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//

// For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"

#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif

#include "vtlib/vtlib.h"
#include "vtlib/core/TimeEngines.h"
#include "vtlib/core/TerrainScene.h"
#include "vtdata/vtLog.h"
#include "../Enviro.h"			// for g_App, GetTerrainScene
#include "canvas.h"
#include "frame.h"
#include "app.h"

DECLARE_APP(vtApp)

/*
 * vtGLCanvas implementation
 */
	BEGIN_EVENT_TABLE(vtGLCanvas, wxGLCanvas)
EVT_CLOSE(vtGLCanvas::OnClose)
EVT_SIZE(vtGLCanvas::OnSize)
EVT_PAINT(vtGLCanvas::OnPaint)
EVT_CHAR(vtGLCanvas::OnChar)
EVT_MOUSE_EVENTS(vtGLCanvas::OnMouseEvent)
EVT_ERASE_BACKGROUND(vtGLCanvas::OnEraseBackground)
END_EVENT_TABLE()

static vtGLCanvas *s_canvas = NULL;

vtGLCanvas::vtGLCanvas(wxWindow *parent, wxWindowID id,
	const wxPoint& pos, const wxSize& size, long style, const wxString& name, int* gl_attrib):
wxGLCanvas(parent, id, pos, size, style, name, gl_attrib)
{
	VTLOG("Constructing vtGLCanvas\n");
	parent->Show(TRUE);
	SetCurrent();

	m_StatusTimer.SetFrame((wxFrame *)parent);
	m_StatusTimer.Start(1000);

	m_bPainting = false;
	m_bRunning = true;
	m_bShowFrameRateChart = false;

	s_canvas = this;
}

vtGLCanvas::~vtGLCanvas(void)
{
	VTLOG("Deleting Canvas\n");
}

void EnableContinuousRendering(bool bTrue)
{
	VTLOG("EnableContinuousRendering %d\n", bTrue);
	if (!s_canvas)
		return;

	bool bNeedRefresh = (s_canvas->m_bRunning == false && bTrue == true);
	s_canvas->m_bRunning = bTrue;
	if (bNeedRefresh)
		s_canvas->Refresh(FALSE);
}

void vtGLCanvas::QueueRefresh(bool eraseBackground)
	// A Refresh routine we can call from inside OnPaint.
	//   (queues the events rather than dispatching them immediately).
{
	// With wxGTK, you can't do a Refresh() in OnPaint because it doesn't
	//   queue (post) a Refresh event for later.  Rather it dispatches
	//   (processes) the underlying events immediately via ProcessEvent
	//   (read, recursive call).  See the wxPostEvent docs and Refresh code
	//   for more details.
	if ( eraseBackground )
	{
		wxEraseEvent eevent( GetId() );
		eevent.SetEventObject( this );
		wxPostEvent( GetEventHandler(), eevent );
	}

	wxPaintEvent event( GetId() );
	event.SetEventObject( this );
	wxPostEvent( GetEventHandler(), event );
}

void StatusTimer::Notify()
{
	if (!m_pFrame || !m_pFrame->GetStatusBar()) return;

	vtScene *scene = vtGetScene();
	if (!scene) return;

	wxString str, str2;

	// get framerate
	float fps = scene->GetFrameRate();

	// only show 3 significant digits
	if (fps < 10)
		str.Printf(_T("fps %1.2f, "), fps);
	else if (fps < 80)
		str.Printf(_T("fps %2.1f, "), fps);
	else
		str.Printf(_T("fps %3.0f, "), fps);

	// get time of day
	TimeEngine *te = GetTerrainScene()->GetTimeEngine();
	if (te && te->GetEnabled())
	{
		int hr, min, sec;
		te->GetTime(hr, min, sec);

		str2.Printf(_T("time %02d:%02d:%02d, "), hr, min, sec);
		str += str2;
	}

	vtString vs;
	g_App.DescribeCoordinates(vs);
	str += wxString::FromAscii((const char *)vs);

	// get CLOD triangle counts, if appropriate
	g_App.DescribeCLOD(vs);
	str += wxString::FromAscii((const char *)vs);

	str += wxString::FromAscii((const char *)g_App.m_strMessage);

	m_pFrame->SetStatusText(str);
}

void vtGLCanvas::OnPaint( wxPaintEvent& event )
{
	vtScene *pScene = vtGetScene();

	if (!pScene->HasWinInfo())
	{
		VTLOG("First OnPaint message.\n");
#ifdef WIN32
		HWND handle = (HWND) GetHandle();
		pScene->SetWinInfo(handle, m_glContext);
#else
		pScene->SetWinInfo(NULL, NULL);
#endif
//		CreateScene();
	}

	// place the dc inside a scope, to delete it before the end of function
	if (1)
	{
		// This is a dummy, to avoid an endless succession of paint messages.
		// OnPaint handlers must always create a wxPaintDC.
		wxPaintDC dc(this);
#ifdef __WXMSW__
		if (!GetContext()) return;
#endif

		if (m_bPainting || !m_bRunning) return;

#if !VTLIB_PSM
		m_bPainting = true;

		// Render the Scene Graph
		vtGetScene()->DoUpdate();

		if (m_bShowFrameRateChart)
			vtGetScene()->DrawFrameRateChart();

		SwapBuffers();

#ifdef WIN32
		// Call Refresh again for continuous rendering,
		if (m_bRunning)
			Refresh(FALSE);
#else
		// Queue another refresh for continuous rendering.
		//   (Yield first so we don't starve out keyboard & mouse events.)
		//
		// FIXME: We may want to use a frame timer instead of immediate-
		//   redraw so we don't eat so much CPU on machines that can
		//   easily handle the frame rate.
		wxYield();
		QueueRefresh(FALSE);
#endif

		// update the status bar every 1/10 of a second
		static float last_stat = 0.0f;
		static vtString last_msg;
		float cur = vtGetTime();
		if (cur - last_stat > 0.1f || g_App.GetMessage() != last_msg)
		{
			last_msg = g_App.GetMessage();
			last_stat = cur;
			m_StatusTimer.Notify();
		}

		m_bPainting = false;
#endif // VTLIB_PSM
	}

	// Must allow some idle processing to occur - or the toolbars will not
	// update, and the close box will not respond!
	bool go = true;
	while (go)
	{
		go = wxGetApp().ProcessIdle();
	}
}

void vtGLCanvas::OnClose(wxCloseEvent& event)
{
	m_bRunning = false;
}

void vtGLCanvas::OnSize(wxSizeEvent& event)
{
  // Presumably this is a wxMSWism.
  // For wxGTK & wxMotif, all canvas resize events occur before the context
  //   is set.  So ignore this context check and grab the window width/height
  //   when we get it so it (and derived values such as aspect ratio and
  //   viewport parms) are computed correctly.
#ifdef __WXMSW__
	if (!GetContext()) return;
#endif

	SetCurrent();
	int width, height;
	GetClientSize(& width, & height);

	vtGetScene()->SetWindowSize(width, height);

	wxGLCanvas::OnSize(event);
}

void vtGLCanvas::OnChar(wxKeyEvent& event)
{
	long key = event.KeyCode();

	// pass the char to the frame for it to do "accelerator" shortcuts
	vtFrame *frame = (vtFrame*) GetParent();
	frame->OnChar(event);

	int flags = 0;

	if (event.ControlDown())
		flags |= VT_CONTROL;

	if (event.ShiftDown())
		flags |= VT_SHIFT;

	if (event.AltDown())
		flags |= VT_ALT;

	// pass the char to the vtlib Scene
	vtGetScene()->OnKey(key, flags);
}

void vtGLCanvas::OnMouseEvent(wxMouseEvent& event1)
{
	static bool bCapture = false;

	// turn WX mouse event into a VT mouse event
	vtMouseEvent event;
	wxEventType  ev = event1.GetEventType();
	if (ev == wxEVT_LEFT_DOWN) {
		event.type = VT_DOWN;
		event.button = VT_LEFT;
	} else if (ev == wxEVT_LEFT_UP) {
		event.type = VT_UP;
		event.button = VT_LEFT;
	} else if (ev == wxEVT_MIDDLE_DOWN) {
		event.type = VT_DOWN;
		event.button = VT_MIDDLE;
	} else if (ev == wxEVT_MIDDLE_UP) {
		event.type = VT_UP;
		event.button = VT_MIDDLE;
	} else if (ev == wxEVT_RIGHT_DOWN) {
		event.type = VT_DOWN;
		event.button = VT_RIGHT;
	} else if (ev == wxEVT_RIGHT_UP) {
		event.type = VT_UP;
		event.button = VT_RIGHT;
	} else if (ev == wxEVT_MOTION) {
		event.type = VT_MOVE;
		event.button = VT_NONE;
	} else {
		// ignored mouse events, such as wxEVT_LEAVE_WINDOW
		return;
	}

	if (ev == wxEVT_LEFT_DOWN || ev == wxEVT_MIDDLE_DOWN || ev == wxEVT_RIGHT_DOWN)
	{
//		VTLOG("DOWN: capture %d", bCapture);
		if (!bCapture)
		{
			CaptureMouse();
			bCapture = true;
//			VTLOG(" -> true");
		}
//		VTLOG("\n");
	}
	if (ev == wxEVT_LEFT_UP || ev == wxEVT_MIDDLE_UP || ev == wxEVT_RIGHT_UP)
	{
//		VTLOG("  UP: capture %d", bCapture);
		if (bCapture)
		{
			ReleaseMouse();
			bCapture = false;
//			VTLOG(" -> false");
		}
//		VTLOG("\n");
	}

	event.flags = 0;
	wxCoord xpos, ypos;
	event1.GetPosition(&xpos, &ypos);
	event.pos.Set(xpos, ypos);

	if (event1.ControlDown())
		event.flags |= VT_CONTROL;

	if (event1.ShiftDown())
		event.flags |= VT_SHIFT;

	if (event1.AltDown())
		event.flags |= VT_ALT;

	// inform Enviro app
	g_App.OnMouse(event);

	vtGetScene()->OnMouse(event);
}

void vtGLCanvas::OnEraseBackground(wxEraseEvent& event)
{
	// Do nothing, to avoid flashing.
}
<commit_msg>allow single refreshes even when not actively running (hope this don't break much)<commit_after>//
// Name:	 canvas.cpp
// Purpose:	 Implements the canvas class for the wxWindows application.
//
// Copyright (c) 2001 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//

// For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"

#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif

#include "vtlib/vtlib.h"
#include "vtlib/core/TimeEngines.h"
#include "vtlib/core/TerrainScene.h"
#include "vtdata/vtLog.h"
#include "../Enviro.h"			// for g_App, GetTerrainScene
#include "canvas.h"
#include "frame.h"
#include "app.h"

DECLARE_APP(vtApp)

/*
 * vtGLCanvas implementation
 */
	BEGIN_EVENT_TABLE(vtGLCanvas, wxGLCanvas)
EVT_CLOSE(vtGLCanvas::OnClose)
EVT_SIZE(vtGLCanvas::OnSize)
EVT_PAINT(vtGLCanvas::OnPaint)
EVT_CHAR(vtGLCanvas::OnChar)
EVT_MOUSE_EVENTS(vtGLCanvas::OnMouseEvent)
EVT_ERASE_BACKGROUND(vtGLCanvas::OnEraseBackground)
END_EVENT_TABLE()

static vtGLCanvas *s_canvas = NULL;

vtGLCanvas::vtGLCanvas(wxWindow *parent, wxWindowID id,
	const wxPoint& pos, const wxSize& size, long style, const wxString& name, int* gl_attrib):
wxGLCanvas(parent, id, pos, size, style, name, gl_attrib)
{
	VTLOG("Constructing vtGLCanvas\n");
	parent->Show(TRUE);
	SetCurrent();

	m_StatusTimer.SetFrame((wxFrame *)parent);
	m_StatusTimer.Start(1000);

	m_bPainting = false;
	m_bRunning = true;
	m_bShowFrameRateChart = false;

	s_canvas = this;
}

vtGLCanvas::~vtGLCanvas(void)
{
	VTLOG("Deleting Canvas\n");
}

void EnableContinuousRendering(bool bTrue)
{
	VTLOG("EnableContinuousRendering %d\n", bTrue);
	if (!s_canvas)
		return;

	bool bNeedRefresh = (s_canvas->m_bRunning == false && bTrue == true);
	s_canvas->m_bRunning = bTrue;
	if (bNeedRefresh)
		s_canvas->Refresh(FALSE);
}

void vtGLCanvas::QueueRefresh(bool eraseBackground)
	// A Refresh routine we can call from inside OnPaint.
	//   (queues the events rather than dispatching them immediately).
{
	// With wxGTK, you can't do a Refresh() in OnPaint because it doesn't
	//   queue (post) a Refresh event for later.  Rather it dispatches
	//   (processes) the underlying events immediately via ProcessEvent
	//   (read, recursive call).  See the wxPostEvent docs and Refresh code
	//   for more details.
	if ( eraseBackground )
	{
		wxEraseEvent eevent( GetId() );
		eevent.SetEventObject( this );
		wxPostEvent( GetEventHandler(), eevent );
	}

	wxPaintEvent event( GetId() );
	event.SetEventObject( this );
	wxPostEvent( GetEventHandler(), event );
}

void StatusTimer::Notify()
{
	if (!m_pFrame || !m_pFrame->GetStatusBar()) return;

	vtScene *scene = vtGetScene();
	if (!scene) return;

	wxString str, str2;

	// get framerate
	float fps = scene->GetFrameRate();

	// only show 3 significant digits
	if (fps < 10)
		str.Printf(_T("fps %1.2f, "), fps);
	else if (fps < 80)
		str.Printf(_T("fps %2.1f, "), fps);
	else
		str.Printf(_T("fps %3.0f, "), fps);

	// get time of day
	TimeEngine *te = GetTerrainScene()->GetTimeEngine();
	if (te && te->GetEnabled())
	{
		int hr, min, sec;
		te->GetTime(hr, min, sec);

		str2.Printf(_T("time %02d:%02d:%02d, "), hr, min, sec);
		str += str2;
	}

	vtString vs;
	g_App.DescribeCoordinates(vs);
	str += wxString::FromAscii((const char *)vs);

	// get CLOD triangle counts, if appropriate
	g_App.DescribeCLOD(vs);
	str += wxString::FromAscii((const char *)vs);

	str += wxString::FromAscii((const char *)g_App.m_strMessage);

	m_pFrame->SetStatusText(str);
}

void vtGLCanvas::OnPaint( wxPaintEvent& event )
{
	vtScene *pScene = vtGetScene();

	if (!pScene->HasWinInfo())
	{
		VTLOG("First OnPaint message.\n");
#ifdef WIN32
		HWND handle = (HWND) GetHandle();
		pScene->SetWinInfo(handle, m_glContext);
#else
		pScene->SetWinInfo(NULL, NULL);
#endif
//		CreateScene();
	}

	// place the dc inside a scope, to delete it before the end of function
	if (1)
	{
		// This is a dummy, to avoid an endless succession of paint messages.
		// OnPaint handlers must always create a wxPaintDC.
		wxPaintDC dc(this);
#ifdef __WXMSW__
		if (!GetContext()) return;
#endif

		if (m_bPainting) return;

#if !VTLIB_PSM
		m_bPainting = true;

		// Render the Scene Graph
		vtGetScene()->DoUpdate();

		if (m_bShowFrameRateChart)
			vtGetScene()->DrawFrameRateChart();

		SwapBuffers();

#ifdef WIN32
		// Call Refresh again for continuous rendering,
		if (m_bRunning)
			Refresh(FALSE);
#else
		// Queue another refresh for continuous rendering.
		//   (Yield first so we don't starve out keyboard & mouse events.)
		//
		// FIXME: We may want to use a frame timer instead of immediate-
		//   redraw so we don't eat so much CPU on machines that can
		//   easily handle the frame rate.
		wxYield();
		QueueRefresh(FALSE);
#endif

		// update the status bar every 1/10 of a second
		static float last_stat = 0.0f;
		static vtString last_msg;
		float cur = vtGetTime();
		if (cur - last_stat > 0.1f || g_App.GetMessage() != last_msg)
		{
			last_msg = g_App.GetMessage();
			last_stat = cur;
			m_StatusTimer.Notify();
		}

		m_bPainting = false;
#endif // VTLIB_PSM
	}

	// Must allow some idle processing to occur - or the toolbars will not
	// update, and the close box will not respond!
	bool go = true;
	while (go)
	{
		go = wxGetApp().ProcessIdle();
	}
}

void vtGLCanvas::OnClose(wxCloseEvent& event)
{
	m_bRunning = false;
}

void vtGLCanvas::OnSize(wxSizeEvent& event)
{
  // Presumably this is a wxMSWism.
  // For wxGTK & wxMotif, all canvas resize events occur before the context
  //   is set.  So ignore this context check and grab the window width/height
  //   when we get it so it (and derived values such as aspect ratio and
  //   viewport parms) are computed correctly.
#ifdef __WXMSW__
	if (!GetContext()) return;
#endif

	SetCurrent();
	int width, height;
	GetClientSize(& width, & height);

	vtGetScene()->SetWindowSize(width, height);

	wxGLCanvas::OnSize(event);
}

void vtGLCanvas::OnChar(wxKeyEvent& event)
{
	long key = event.KeyCode();

	// pass the char to the frame for it to do "accelerator" shortcuts
	vtFrame *frame = (vtFrame*) GetParent();
	frame->OnChar(event);

	int flags = 0;

	if (event.ControlDown())
		flags |= VT_CONTROL;

	if (event.ShiftDown())
		flags |= VT_SHIFT;

	if (event.AltDown())
		flags |= VT_ALT;

	// pass the char to the vtlib Scene
	vtGetScene()->OnKey(key, flags);
}

void vtGLCanvas::OnMouseEvent(wxMouseEvent& event1)
{
	static bool bCapture = false;

	// turn WX mouse event into a VT mouse event
	vtMouseEvent event;
	wxEventType  ev = event1.GetEventType();
	if (ev == wxEVT_LEFT_DOWN) {
		event.type = VT_DOWN;
		event.button = VT_LEFT;
	} else if (ev == wxEVT_LEFT_UP) {
		event.type = VT_UP;
		event.button = VT_LEFT;
	} else if (ev == wxEVT_MIDDLE_DOWN) {
		event.type = VT_DOWN;
		event.button = VT_MIDDLE;
	} else if (ev == wxEVT_MIDDLE_UP) {
		event.type = VT_UP;
		event.button = VT_MIDDLE;
	} else if (ev == wxEVT_RIGHT_DOWN) {
		event.type = VT_DOWN;
		event.button = VT_RIGHT;
	} else if (ev == wxEVT_RIGHT_UP) {
		event.type = VT_UP;
		event.button = VT_RIGHT;
	} else if (ev == wxEVT_MOTION) {
		event.type = VT_MOVE;
		event.button = VT_NONE;
	} else {
		// ignored mouse events, such as wxEVT_LEAVE_WINDOW
		return;
	}

	if (ev == wxEVT_LEFT_DOWN || ev == wxEVT_MIDDLE_DOWN || ev == wxEVT_RIGHT_DOWN)
	{
//		VTLOG("DOWN: capture %d", bCapture);
		if (!bCapture)
		{
			CaptureMouse();
			bCapture = true;
//			VTLOG(" -> true");
		}
//		VTLOG("\n");
	}
	if (ev == wxEVT_LEFT_UP || ev == wxEVT_MIDDLE_UP || ev == wxEVT_RIGHT_UP)
	{
//		VTLOG("  UP: capture %d", bCapture);
		if (bCapture)
		{
			ReleaseMouse();
			bCapture = false;
//			VTLOG(" -> false");
		}
//		VTLOG("\n");
	}

	event.flags = 0;
	wxCoord xpos, ypos;
	event1.GetPosition(&xpos, &ypos);
	event.pos.Set(xpos, ypos);

	if (event1.ControlDown())
		event.flags |= VT_CONTROL;

	if (event1.ShiftDown())
		event.flags |= VT_SHIFT;

	if (event1.AltDown())
		event.flags |= VT_ALT;

	// inform Enviro app
	g_App.OnMouse(event);

	vtGetScene()->OnMouse(event);
}

void vtGLCanvas::OnEraseBackground(wxEraseEvent& event)
{
	// Do nothing, to avoid flashing.
}
<|endoftext|>


<commit_before>//
// Helper.cpp - various helper functions used by the classes
//
// Copyright (c) 2001-2004 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//

#include "wx/wxprec.h"

#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif

#include "wx/progdlg.h"
#include "Frame.h"
#include "BuilderView.h"
#include "Helper.h"
#include "vtdata/vtLog.h"

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

static bool s_bOpen = false;
wxProgressDialog *g_pProg = NULL;

bool progress_callback(int amount)
{
	bool value = false;
	if (g_pProg)
		value = (g_pProg->Update(amount) == false);
	return value;
}

void OpenProgressDialog(const wxString &title, bool bCancellable)
{
	if (s_bOpen)
		return;

	BuilderView *pView = GetMainFrame()->GetView();

	// force the window to be wider by giving a dummy string
	wxString message = _T("___________________________________");
	int style = wxPD_AUTO_HIDE | wxPD_APP_MODAL;
	if (bCancellable)
		style |= wxPD_CAN_ABORT;

	s_bOpen = true;
	g_pProg = new wxProgressDialog(title, message, 100, pView, style);
	g_pProg->Show(true);
	g_pProg->Update(0, _T(" "));
}

void CloseProgressDialog()
{
	if (g_pProg)
	{
		g_pProg->Destroy();
		g_pProg = NULL;
		s_bOpen = false;
	}
}

void ResumeProgressDialog()
{
	if (g_pProg)
		g_pProg->Resume();
}

//
// returns true if the user pressed the "Cancel" button
//
bool UpdateProgressDialog(int amount, const wxString& newmsg)
{
	bool value = false;
	if (g_pProg)
		value = (g_pProg->Update(amount, newmsg) == false);
	return value;
}

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

void IncreaseRect(wxRect &rect, int adjust)
{
	rect.y -= adjust;
	rect.height += (adjust<<1);
	rect.x -= adjust;
	rect.width += (adjust<<1);
}

void DrawRectangle(wxDC* pDC, const wxRect &rect)
{
	int left = rect.x;
	int right = rect.x + rect.GetWidth();
	int top = rect.y;
	int bottom = rect.y + rect.GetHeight();
	wxPoint p[5];
	p[0].x = left;
	p[0].y = bottom;

	p[1].x = left;
	p[1].y = top;

	p[2].x = right;
	p[2].y = top;

	p[3].x = right;
	p[3].y = bottom;

	p[4].x = left;
	p[4].y = bottom;
	pDC->DrawLines(5, p);

	pDC->DrawLine(left, bottom, right, top);
	pDC->DrawLine(left, top, right, bottom);
}

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

int GuessZoneFromGeo(const DPoint2 &pos)
{
	int zone = (int) (((pos.x + 180.0) / 6.0) + 1.0);
	if (pos.y < 0)
		zone = -zone;
	return zone;
}

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

//
// Display a message to the user, and also send it to the log file.
//
void DisplayAndLog(const char *pFormat, ...)
{
	va_list va;
	va_start(va, pFormat);

	char ach[2048];
	vsprintf(ach, pFormat, va);

	wxString2 msg = ach;
	wxMessageBox(msg);

	strcat(ach, "\n");
	g_Log._Log(ach);
}

#if SUPPORT_WSTRING
//
// Also wide-character version of the same function.
//
void DisplayAndLog(const wchar_t *pFormat, ...)
{
//#ifdef UNICODE
//	// Try to translate the string
//	wxString2 trans = wxGetTranslation(pFormat);
//	pFormat = trans.c_str();
//#endif

	va_list va;
	va_start(va, pFormat);

	// Use wide characters
	wchar_t ach[2048];
#ifdef _MSC_VER
	vswprintf(ach, pFormat, va);
#else
	// apparently on non-MSVC platforms this takes 4 arguments (safer)
	vswprintf(ach, 2048, pFormat, va);
#endif

	wxString2 msg = ach;
	wxMessageBox(msg);

	g_Log._Log(ach);
	g_Log._Log("\n");
}
#endif // SUPPORT_WSTRING

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

#if WIN32

//
// Win32 allows us to do a real StrectBlt operation, although it still won't
// do a StretchBlt with a mask.
//
void wxDC2::StretchBlit(const wxBitmap &bmp,
						wxCoord x, wxCoord y,
						wxCoord width, wxCoord height,
						wxCoord src_x, wxCoord src_y,
						wxCoord src_width, wxCoord src_height)
{
	wxCHECK_RET( bmp.Ok(), _T("invalid bitmap in wxDC::DrawBitmap") );

	HDC cdc = ((HDC)GetHDC());
	HDC memdc = ::CreateCompatibleDC( cdc );
	HBITMAP hbitmap = (HBITMAP) bmp.GetHBITMAP( );

	COLORREF old_textground = ::GetTextColor(cdc);
	COLORREF old_background = ::GetBkColor(cdc);
	if (m_textForegroundColour.Ok())
	{
		::SetTextColor(cdc, m_textForegroundColour.GetPixel() );
	}
	if (m_textBackgroundColour.Ok())
	{
		::SetBkColor(cdc, m_textBackgroundColour.GetPixel() );
	}

	HGDIOBJ hOldBitmap = ::SelectObject( memdc, hbitmap );

//	int bwidth = bmp.GetWidth(), bheight = bmp.GetHeight();
	::StretchBlt( cdc, x, y, width, height, memdc, src_x, src_y, src_width, src_height, SRCCOPY);

	::SelectObject( memdc, hOldBitmap );
	::DeleteDC( memdc );

	::SetTextColor(cdc, old_textground);
	::SetBkColor(cdc, old_background);
}

#endif // WIN32

<commit_msg>added comment<commit_after>//
// Helper.cpp - various helper functions used by the classes
//
// Copyright (c) 2001-2004 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//

#include "wx/wxprec.h"

#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif

#include "wx/progdlg.h"
#include "Frame.h"
#include "BuilderView.h"
#include "Helper.h"
#include "vtdata/vtLog.h"

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

static bool s_bOpen = false;
wxProgressDialog *g_pProg = NULL;

bool progress_callback(int amount)
{
	bool value = false;
	// Update() returns false if the Cancel button has been pushed
	// but this functions return _true_ if user wants to cancel
	if (g_pProg)
		value = (g_pProg->Update(amount) == false);
	return value;
}

void OpenProgressDialog(const wxString &title, bool bCancellable)
{
	if (s_bOpen)
		return;

	BuilderView *pView = GetMainFrame()->GetView();

	// force the window to be wider by giving a dummy string
	wxString message = _T("___________________________________");
	int style = wxPD_AUTO_HIDE | wxPD_APP_MODAL;
	if (bCancellable)
		style |= wxPD_CAN_ABORT;

	s_bOpen = true;
	g_pProg = new wxProgressDialog(title, message, 100, pView, style);
	g_pProg->Show(true);
	g_pProg->Update(0, _T(" "));
}

void CloseProgressDialog()
{
	if (g_pProg)
	{
		g_pProg->Destroy();
		g_pProg = NULL;
		s_bOpen = false;
	}
}

void ResumeProgressDialog()
{
	if (g_pProg)
		g_pProg->Resume();
}

//
// returns true if the user pressed the "Cancel" button
//
bool UpdateProgressDialog(int amount, const wxString& newmsg)
{
	bool value = false;
	if (g_pProg)
		value = (g_pProg->Update(amount, newmsg) == false);
	return value;
}

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

void IncreaseRect(wxRect &rect, int adjust)
{
	rect.y -= adjust;
	rect.height += (adjust<<1);
	rect.x -= adjust;
	rect.width += (adjust<<1);
}

void DrawRectangle(wxDC* pDC, const wxRect &rect)
{
	int left = rect.x;
	int right = rect.x + rect.GetWidth();
	int top = rect.y;
	int bottom = rect.y + rect.GetHeight();
	wxPoint p[5];
	p[0].x = left;
	p[0].y = bottom;

	p[1].x = left;
	p[1].y = top;

	p[2].x = right;
	p[2].y = top;

	p[3].x = right;
	p[3].y = bottom;

	p[4].x = left;
	p[4].y = bottom;
	pDC->DrawLines(5, p);

	pDC->DrawLine(left, bottom, right, top);
	pDC->DrawLine(left, top, right, bottom);
}

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

int GuessZoneFromGeo(const DPoint2 &pos)
{
	int zone = (int) (((pos.x + 180.0) / 6.0) + 1.0);
	if (pos.y < 0)
		zone = -zone;
	return zone;
}

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

//
// Display a message to the user, and also send it to the log file.
//
void DisplayAndLog(const char *pFormat, ...)
{
	va_list va;
	va_start(va, pFormat);

	char ach[2048];
	vsprintf(ach, pFormat, va);

	wxString2 msg = ach;
	wxMessageBox(msg);

	strcat(ach, "\n");
	g_Log._Log(ach);
}

#if SUPPORT_WSTRING
//
// Also wide-character version of the same function.
//
void DisplayAndLog(const wchar_t *pFormat, ...)
{
//#ifdef UNICODE
//	// Try to translate the string
//	wxString2 trans = wxGetTranslation(pFormat);
//	pFormat = trans.c_str();
//#endif

	va_list va;
	va_start(va, pFormat);

	// Use wide characters
	wchar_t ach[2048];
#ifdef _MSC_VER
	vswprintf(ach, pFormat, va);
#else
	// apparently on non-MSVC platforms this takes 4 arguments (safer)
	vswprintf(ach, 2048, pFormat, va);
#endif

	wxString2 msg = ach;
	wxMessageBox(msg);

	g_Log._Log(ach);
	g_Log._Log("\n");
}
#endif // SUPPORT_WSTRING

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

#if WIN32

//
// Win32 allows us to do a real StrectBlt operation, although it still won't
// do a StretchBlt with a mask.
//
void wxDC2::StretchBlit(const wxBitmap &bmp,
						wxCoord x, wxCoord y,
						wxCoord width, wxCoord height,
						wxCoord src_x, wxCoord src_y,
						wxCoord src_width, wxCoord src_height)
{
	wxCHECK_RET( bmp.Ok(), _T("invalid bitmap in wxDC::DrawBitmap") );

	HDC cdc = ((HDC)GetHDC());
	HDC memdc = ::CreateCompatibleDC( cdc );
	HBITMAP hbitmap = (HBITMAP) bmp.GetHBITMAP( );

	COLORREF old_textground = ::GetTextColor(cdc);
	COLORREF old_background = ::GetBkColor(cdc);
	if (m_textForegroundColour.Ok())
	{
		::SetTextColor(cdc, m_textForegroundColour.GetPixel() );
	}
	if (m_textBackgroundColour.Ok())
	{
		::SetBkColor(cdc, m_textBackgroundColour.GetPixel() );
	}

	HGDIOBJ hOldBitmap = ::SelectObject( memdc, hbitmap );

//	int bwidth = bmp.GetWidth(), bheight = bmp.GetHeight();
	::StretchBlt( cdc, x, y, width, height, memdc, src_x, src_y, src_width, src_height, SRCCOPY);

	::SelectObject( memdc, hOldBitmap );
	::DeleteDC( memdc );

	::SetTextColor(cdc, old_textground);
	::SetBkColor(cdc, old_background);
}

#endif // WIN32

<|endoftext|>


<commit_before>//
// VegDlg.h
//
// Copyright (c) 2001 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//

#include <wx/wxprec.h>

#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif

#include "VegDlg.h"
#include "Frame.h"

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

BEGIN_EVENT_TABLE(PlantListCtrl, wxListCtrl)
	EVT_LIST_ITEM_SELECTED(WID_PSTABLE,	PlantListCtrl::OnSelect)
END_EVENT_TABLE()

void PlantListCtrl::OnSelect(wxListEvent &event)
{
	// Get index of that item
	int idx = event.GetIndex();

	// Clear all item data from the Appearance table on right.
	wxListCtrl *apps = GetMainFrame()->m_PlantListDlg->m_PATable;
	apps->DeleteAllItems();

	// Get species that was selected from left table.
	vtPlantSpecies* ps = GetMainFrame()->GetPlantList()->GetSpecies(idx);

	// Display appearance in right table of selected species from left table.
	for (int j = 0; j < ps->NumAppearances(); j++)
	{
		vtPlantAppearance* app = ps->GetAppearance(j);
		wxString str1;
		long item1;
		str1.Printf("%d", app->m_eType == AT_BILLBOARD);
		item1 = apps->InsertItem(j, str1, 0);
		str1 = app->m_filename;
		item1 = apps->SetItem(j, 1, str1);
		str1.Printf("%4.2f", app->m_width);
		item1 = apps->SetItem(j, 2, str1);
		str1.Printf("%4.2f", app->m_height);
		item1 = apps->SetItem(j, 3, str1);
		str1.Printf("%4.2f", app->m_shadow_radius);
		item1 = apps->SetItem(j, 4, str1);
		str1.Printf("%4.2f", app->m_shadow_darkness);
		item1 = apps->SetItem(j, 5, str1);
	}
}

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

void PlantListDlg::OnInitDialog(wxInitDialogEvent& event)
{
	// Setup Splitter Window.
	m_PSplitter = new wxSplitterWindow(this, WID_PSPLITTER, wxPoint(0,0), wxSize(950,400),
		wxSP_FULLSASH | wxSP_NOBORDER, "Plant List Dialog Splitter");

	int z = 0;

	// Setup left side with common name and max height per species.
	m_PSTable = new PlantListCtrl(m_PSplitter, WID_PSTABLE, wxPoint(0, 0), wxSize(400, 400),
		wxLC_REPORT | wxLC_ALIGN_TOP);
	m_PSTable->ClearAll();
	m_PSTable->SetSingleStyle(wxLC_REPORT);
	m_PSTable->InsertColumn(0, "SID");
	m_PSTable->SetColumnWidth(0, 30);
	m_PSTable->InsertColumn(1, "Common Name");
	m_PSTable->SetColumnWidth(1, 110);
	m_PSTable->InsertColumn(2, "Scientific Name");
	m_PSTable->SetColumnWidth(2, 150);
	m_PSTable->InsertColumn(3, "Max Height");
	m_PSTable->SetColumnWidth(3, 80);

	// Setup right side with each plant appearance's attributes.
	m_PATable = new wxListCtrl(m_PSplitter, WID_PATABLE, wxPoint(0, 0), wxSize(550, 400),
		wxLC_REPORT | wxLC_ALIGN_TOP);
	m_PATable->ClearAll();
	m_PATable->SetSingleStyle(wxLC_REPORT);
	m_PATable->InsertColumn(0, "Billboard");
	m_PATable->SetColumnWidth(0, 60);
	m_PATable->InsertColumn(1, "FileName");
	m_PATable->SetColumnWidth(1, 150);
	m_PATable->InsertColumn(2, "Width");
	m_PATable->SetColumnWidth(2, 60);
	m_PATable->InsertColumn(3, "Height");
	m_PATable->SetColumnWidth(3, 60);
	m_PATable->InsertColumn(4, "Shadow Radius");
	m_PATable->SetColumnWidth(4, 100);
	m_PATable->InsertColumn(5, "Shadow Darkness");
	m_PATable->SetColumnWidth(5, 100);

	// Initialize the splitter window.
	m_PATable->Show(FALSE);
	m_PSplitter->Initialize(m_PSTable);

	vtPlantList* pl = GetMainFrame()->GetPlantList();

	// Read data imported from plantlist file and display in tables.
	for (int i = 0; i < pl->NumSpecies(); i++)
	{
		// Display species and max height in left table.
		wxString str;
		long item;
		vtPlantSpecies *spe = pl->GetSpecies(i);

		str.Printf("%d", spe->GetSpecieID() );
        item = m_PSTable->InsertItem(i, str, 0);
		str.Printf("%s", spe->GetCommonName() );
        item = m_PSTable->SetItem(i, 1, str);
		str.Printf("%s", spe->GetSciName() );
        item = m_PSTable->SetItem(i, 2, str);
		str.Printf("%4.2f m", spe->GetMaxHeight() );
        item = m_PSTable->SetItem(i, 3, str);

		// Display plant appearances per species in right table.
		for (int j = 0; j < pl->GetSpecies(i)->NumAppearances(); j++)
		{
			vtPlantAppearance* app = spe->GetAppearance(j);
			wxString str1;
			long item1;

			str1.Printf("%d", app->m_eType == AT_BILLBOARD);
			item1 = m_PATable->InsertItem(j, str1, 0);
			str1 = app->m_filename;
			item1 = m_PATable->SetItem(j, 1, str1);
			str1.Printf("%4.2f", app->m_width);
			item1 = m_PATable->SetItem(j, 2, str1);
			str1.Printf("%4.2f", app->m_height);
			item1 = m_PATable->SetItem(j, 3, str1);
			str1.Printf("%4.2f", app->m_shadow_radius);
			item1 = m_PATable->SetItem(j, 4, str1);
			str1.Printf("%4.2f", app->m_shadow_darkness);
			item1 = m_PATable->SetItem(j, 5, str1);
		}
	}
	// Show all windows.
	m_PSTable->Show(TRUE);
	m_PATable->Show(TRUE);
	m_PSplitter->SplitVertically(m_PSTable, m_PATable, 400);
}

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

void BioRegionDlg::OnInitDialog(wxInitDialogEvent& event)
{
	// Create tree control window as child of dialog.
	int width, height;
	GetClientSize(&width, &height);
	m_BTree = new wxTreeCtrl(this, WID_BIOREGIONTREE, wxPoint(10, 10),
		wxSize(width - 20, height - 20), wxTR_EDIT_LABELS | wxTR_MULTIPLE);

	// Create root of tree.
	wxTreeItemId rootId;
	rootId = m_BTree->AddRoot("BioRegions");
	m_BTree->SetItemBold(rootId);

	vtBioRegion *br = GetMainFrame()->GetBioRegion();

	// Read data imported from bioregion file and display on tree.
	int numregions = br->m_Types.GetSize();
	for (int i = 0; i < numregions; i++)
	{
		// Display biotype as level 1 of tree.
		wxTreeItemId region;
		wxString bt;
		bt.Printf("Type %d", i+1);
		region = m_BTree->AppendItem(rootId, bt);

		int numspecies = br->m_Types[i]->m_Densities.GetSize();
		for (int j = 0; j < numspecies; j++)
		{
			// Display all species and it's density under each biotype as level 2 of tree.
			wxString s;
			s.Printf("%s (%1.4f /m^2)",
				(const char *) br->m_Types[i]->m_Densities[j]->m_common_name,
				br->m_Types[i]->m_Densities[j]->m_plant_per_m2);

			wxTreeItemId specie = m_BTree->AppendItem(region, s);
			m_BTree->Expand(specie);
		}

		m_BTree->Expand(region);
	}

	m_BTree->Expand(rootId);
	Show(TRUE);
}
<commit_msg>fixed displayed biotype numbers to match internal value<commit_after>//
// VegDlg.h
//
// Copyright (c) 2001 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//

#include <wx/wxprec.h>

#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif

#include "VegDlg.h"
#include "Frame.h"

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

BEGIN_EVENT_TABLE(PlantListCtrl, wxListCtrl)
	EVT_LIST_ITEM_SELECTED(WID_PSTABLE,	PlantListCtrl::OnSelect)
END_EVENT_TABLE()

void PlantListCtrl::OnSelect(wxListEvent &event)
{
	// Get index of that item
	int idx = event.GetIndex();

	// Clear all item data from the Appearance table on right.
	wxListCtrl *apps = GetMainFrame()->m_PlantListDlg->m_PATable;
	apps->DeleteAllItems();

	// Get species that was selected from left table.
	vtPlantSpecies* ps = GetMainFrame()->GetPlantList()->GetSpecies(idx);

	// Display appearance in right table of selected species from left table.
	for (int j = 0; j < ps->NumAppearances(); j++)
	{
		vtPlantAppearance* app = ps->GetAppearance(j);
		wxString str1;
		long item1;
		str1.Printf("%d", app->m_eType == AT_BILLBOARD);
		item1 = apps->InsertItem(j, str1, 0);
		str1 = app->m_filename;
		item1 = apps->SetItem(j, 1, str1);
		str1.Printf("%4.2f", app->m_width);
		item1 = apps->SetItem(j, 2, str1);
		str1.Printf("%4.2f", app->m_height);
		item1 = apps->SetItem(j, 3, str1);
		str1.Printf("%4.2f", app->m_shadow_radius);
		item1 = apps->SetItem(j, 4, str1);
		str1.Printf("%4.2f", app->m_shadow_darkness);
		item1 = apps->SetItem(j, 5, str1);
	}
}

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

void PlantListDlg::OnInitDialog(wxInitDialogEvent& event)
{
	// Setup Splitter Window.
	m_PSplitter = new wxSplitterWindow(this, WID_PSPLITTER, wxPoint(0,0), wxSize(950,400),
		wxSP_FULLSASH | wxSP_NOBORDER, "Plant List Dialog Splitter");

	int z = 0;

	// Setup left side with common name and max height per species.
	m_PSTable = new PlantListCtrl(m_PSplitter, WID_PSTABLE, wxPoint(0, 0), wxSize(400, 400),
		wxLC_REPORT | wxLC_ALIGN_TOP);
	m_PSTable->ClearAll();
	m_PSTable->SetSingleStyle(wxLC_REPORT);
	m_PSTable->InsertColumn(0, "SID");
	m_PSTable->SetColumnWidth(0, 30);
	m_PSTable->InsertColumn(1, "Common Name");
	m_PSTable->SetColumnWidth(1, 110);
	m_PSTable->InsertColumn(2, "Scientific Name");
	m_PSTable->SetColumnWidth(2, 150);
	m_PSTable->InsertColumn(3, "Max Height");
	m_PSTable->SetColumnWidth(3, 80);

	// Setup right side with each plant appearance's attributes.
	m_PATable = new wxListCtrl(m_PSplitter, WID_PATABLE, wxPoint(0, 0), wxSize(550, 400),
		wxLC_REPORT | wxLC_ALIGN_TOP);
	m_PATable->ClearAll();
	m_PATable->SetSingleStyle(wxLC_REPORT);
	m_PATable->InsertColumn(0, "Billboard");
	m_PATable->SetColumnWidth(0, 60);
	m_PATable->InsertColumn(1, "FileName");
	m_PATable->SetColumnWidth(1, 150);
	m_PATable->InsertColumn(2, "Width");
	m_PATable->SetColumnWidth(2, 60);
	m_PATable->InsertColumn(3, "Height");
	m_PATable->SetColumnWidth(3, 60);
	m_PATable->InsertColumn(4, "Shadow Radius");
	m_PATable->SetColumnWidth(4, 100);
	m_PATable->InsertColumn(5, "Shadow Darkness");
	m_PATable->SetColumnWidth(5, 100);

	// Initialize the splitter window.
	m_PATable->Show(FALSE);
	m_PSplitter->Initialize(m_PSTable);

	vtPlantList* pl = GetMainFrame()->GetPlantList();

	// Read data imported from plantlist file and display in tables.
	for (int i = 0; i < pl->NumSpecies(); i++)
	{
		// Display species and max height in left table.
		wxString str;
		long item;
		vtPlantSpecies *spe = pl->GetSpecies(i);

		str.Printf("%d", spe->GetSpecieID() );
        item = m_PSTable->InsertItem(i, str, 0);
		str.Printf("%s", spe->GetCommonName() );
        item = m_PSTable->SetItem(i, 1, str);
		str.Printf("%s", spe->GetSciName() );
        item = m_PSTable->SetItem(i, 2, str);
		str.Printf("%4.2f m", spe->GetMaxHeight() );
        item = m_PSTable->SetItem(i, 3, str);

		// Display plant appearances per species in right table.
		for (int j = 0; j < pl->GetSpecies(i)->NumAppearances(); j++)
		{
			vtPlantAppearance* app = spe->GetAppearance(j);
			wxString str1;
			long item1;

			str1.Printf("%d", app->m_eType == AT_BILLBOARD);
			item1 = m_PATable->InsertItem(j, str1, 0);
			str1 = app->m_filename;
			item1 = m_PATable->SetItem(j, 1, str1);
			str1.Printf("%4.2f", app->m_width);
			item1 = m_PATable->SetItem(j, 2, str1);
			str1.Printf("%4.2f", app->m_height);
			item1 = m_PATable->SetItem(j, 3, str1);
			str1.Printf("%4.2f", app->m_shadow_radius);
			item1 = m_PATable->SetItem(j, 4, str1);
			str1.Printf("%4.2f", app->m_shadow_darkness);
			item1 = m_PATable->SetItem(j, 5, str1);
		}
	}
	// Show all windows.
	m_PSTable->Show(TRUE);
	m_PATable->Show(TRUE);
	m_PSplitter->SplitVertically(m_PSTable, m_PATable, 400);
}

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

void BioRegionDlg::OnInitDialog(wxInitDialogEvent& event)
{
	// Create tree control window as child of dialog.
	int width, height;
	GetClientSize(&width, &height);
	m_BTree = new wxTreeCtrl(this, WID_BIOREGIONTREE, wxPoint(10, 10),
		wxSize(width - 20, height - 20), wxTR_EDIT_LABELS | wxTR_MULTIPLE);

	// Create root of tree.
	wxTreeItemId rootId;
	rootId = m_BTree->AddRoot("BioRegions");
	m_BTree->SetItemBold(rootId);

	vtBioRegion *br = GetMainFrame()->GetBioRegion();

	// Read data imported from bioregion file and display on tree.
	int numregions = br->m_Types.GetSize();
	for (int i = 0; i < numregions; i++)
	{
		// Display biotype as level 1 of tree.
		wxTreeItemId region;
		wxString bt;
		bt.Printf("Type %d", i);
		region = m_BTree->AppendItem(rootId, bt);

		int numspecies = br->m_Types[i]->m_Densities.GetSize();
		for (int j = 0; j < numspecies; j++)
		{
			// Display all species and it's density under each biotype as level 2 of tree.
			wxString s;
			s.Printf("%s (%1.4f /m^2)",
				(const char *) br->m_Types[i]->m_Densities[j]->m_common_name,
				br->m_Types[i]->m_Densities[j]->m_plant_per_m2);

			wxTreeItemId specie = m_BTree->AppendItem(region, s);
			m_BTree->Expand(specie);
		}

		m_BTree->Expand(region);
	}

	m_BTree->Expand(rootId);
	Show(TRUE);
}
<|endoftext|>


<commit_before><commit_msg>avoid possible problems with zero values in tone mapping algorithms (http://code.opencv.org/issues/4020)<commit_after><|endoftext|>


<commit_before>/*
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2010, Willow Garage, Inc.
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of Willow Garage, Inc. nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 * $Id$
 *
 */
// PCL
#include <boost/thread/thread.hpp>
#include <Eigen/Geometry>
#include <pcl/common/common.h>
#include <pcl/io/pcd_io.h>
#include <pcl/io/openni_grabber.h>
#include <cfloat>
#include <pcl/visualization/point_cloud_handlers.h>
#include <pcl/visualization/pcl_visualizer.h>
#include <pcl/visualization/histogram_visualizer.h>
#include <pcl/console/print.h>
#include <pcl/console/parse.h>
#include <pcl/console/time.h>

using pcl::console::print_color;
using pcl::console::print_error;
using pcl::console::print_error;
using pcl::console::print_warn;
using pcl::console::print_info;
using pcl::console::print_debug;
using pcl::console::print_value;
using pcl::console::print_highlight;
using pcl::console::TT_BRIGHT;
using pcl::console::TT_RED;
using pcl::console::TT_GREEN;
using pcl::console::TT_BLUE;

typedef pcl::visualization::PointCloudColorHandler<pcl::PointCloud<pcl::PointXYZ> > ColorHandler;
typedef ColorHandler::Ptr ColorHandlerPtr;
typedef ColorHandler::ConstPtr ColorHandlerConstPtr;

typedef pcl::visualization::PointCloudGeometryHandler<pcl::PointCloud<pcl::PointXYZ> > GeometryHandler;
typedef GeometryHandler::Ptr GeometryHandlerPtr;
typedef GeometryHandler::ConstPtr GeometryHandlerConstPtr;
boost::mutex mutex_;
pcl::PointCloud<pcl::PointXYZ>::ConstPtr g_cloud;
bool new_cloud = false;

#define NORMALS_SCALE 0.01
#define PC_SCALE 0.001

void
printHelp (int argc, char **argv)
{
  //print_error ("Syntax is: %s <file_name 1..N>.pcd <options>\n", argv[0]);
  print_error ("Syntax is: %s <options>\n", argv[0]);
  print_info ("  where options are:\n");
  print_info ("                     -dev device_id           = device to be used\n");
  print_info ("                                                maybe \"#n\", with n being the number of the device in device list.\n");
  print_info ("                                                maybe \"bus@addr\", with bus and addr being the usb bus and address where device is connected.\n");
  print_info ("                                                maybe \"serial\", with serial being the serial number of the device.\n");
  print_info ("                     -bc r,g,b                = background color\n");
  print_info ("                     -fc r,g,b                = foreground color\n");
  print_info ("                     -ps X                    = point size (");
  print_value ("1..64");
  print_info (") \n");
  print_info ("                     -opaque X                = rendered point cloud opacity (");
  print_value ("0..1");
  print_info (")\n");

  print_info ("                     -ax ");
  print_value ("n");
  print_info ("                    = enable on-screen display of ");
  print_color (stdout, TT_BRIGHT, TT_RED, "X");
  print_color (stdout, TT_BRIGHT, TT_GREEN, "Y");
  print_color (stdout, TT_BRIGHT, TT_BLUE, "Z");
  print_info (" axes and scale them to ");
  print_value ("n\n");
  print_info ("                     -ax_pos X,Y,Z            = if axes are enabled, set their X,Y,Z position in space (default ");
  print_value ("0,0,0");
  print_info (")\n");

  print_info ("\n");
  print_info ("                     -cam (*)                 = use given camera settings as initial view\n");
  print_info (stderr, " (*) [Clipping Range / Focal Point / Position / ViewUp / Distance / Window Size / Window Pos] or use a <filename.cam> that contains the same information.\n");

  print_info ("\n");
  print_info ("                     -multiview 0/1           = enable/disable auto-multi viewport rendering (default ");
  print_value ("disabled");
  print_info (")\n");
  print_info ("\n");

  print_info ("\n");
  print_info ("                     -normals 0/X             = disable/enable the display of every Xth point's surface normal as lines (default ");
  print_value ("disabled");
  print_info (")\n");
  print_info ("                     -normals_scale X         = resize the normal unit vector size to X (default ");
  print_value ("0.02");
  print_info (")\n");
  print_info ("\n");
  print_info ("                     -pc 0/X                  = disable/enable the display of every Xth point's principal curvatures as lines (default ");
  print_value ("disabled");
  print_info (")\n");
  print_info ("                     -pc_scale X              = resize the principal curvatures vectors size to X (default ");
  print_value ("0.02");
  print_info (")\n");
  print_info ("\n");

  print_info ("\n(Note: for multiple .pcd files, provide multiple -{fc,ps,opaque} parameters; they will be automatically assigned to the right file)\n");
}

// Create the PCLVisualizer object
boost::shared_ptr<pcl::visualization::PCLVisualizer> p;
ColorHandlerPtr color_handler;
GeometryHandlerPtr geometry_handler;
std::vector<double> fcolor_r, fcolor_b, fcolor_g;
bool fcolorparam = false;

struct EventHelper
{
  void cloud_cb (const pcl::PointCloud<pcl::PointXYZ>::ConstPtr & cloud)
  {
    if (mutex_.try_lock ())
    {
      g_cloud = cloud;
      new_cloud = true;
      mutex_.unlock ();
    }
  }
};

/* ---[ */
int
main (int argc, char** argv)
{
  srand (time (0));

  if (argc > 1)
  {
    for (int i = 1; i < argc; i++)
    {
      if (std::string (argv[i]) == "-h")
      {
        printHelp (argc, argv);
        return (-1);
      }
    }
  }

  // Command line parsing
  double bcolor[3] = {0, 0, 0};
  pcl::console::parse_3x_arguments (argc, argv, "-bc", bcolor[0], bcolor[1], bcolor[2]);

  fcolorparam = pcl::console::parse_multiple_3x_arguments (argc, argv, "-fc", fcolor_r, fcolor_g, fcolor_b);

  int psize = 0;
  pcl::console::parse_argument (argc, argv, "-ps", psize);

  double opaque;
  pcl::console::parse_argument (argc, argv, "-opaque", opaque);

  p.reset (new pcl::visualization::PCLVisualizer (argc, argv, "PCD viewer"));

  //  // Change the cloud rendered point size
  //  if (psize > 0)
  //    p->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, psize, "OpenNICloud");
  //
  //  // Change the cloud rendered opacity
  //  if (opaque >= 0)
  //    p->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_OPACITY, opaque, "OpenNICloud");

  p->setBackgroundColor (bcolor[0], bcolor[1], bcolor[2]);

  //boost::signals2::connection c = interface->registerCallback (boost::bind (&bla::blatestpointcloudrgb, *this, _1));
  //boost::function<void (boost::shared_ptr<pcl::PointCloud<pcl::PointXYZRGB> >)> f = boost::bind (&bla::blatestpointcloudrgb, this, _1);
  //boost::signals2::connection c =
  //  interface->registerCallback <void(boost::shared_ptr<pcl::PointCloud<pcl::PointXYZRGB> >)> (boost::bind (&bla::blatestpointcloudrgb, *this, _1).);

  // Read axes settings
  double axes = 0.0;
  pcl::console::parse_argument (argc, argv, "-ax", axes);
  if (axes != 0.0 && p)
  {
    double ax_x = 0.0, ax_y = 0.0, ax_z = 0.0;
    pcl::console::parse_3x_arguments (argc, argv, "-ax_pos", ax_x, ax_y, ax_z, false);
    // Draw XYZ axes if command-line enabled
    p->addCoordinateSystem (axes, ax_x, ax_y, ax_z);
  }

  std::string device_id = "";
  pcl::console::parse_argument (argc, argv, "-dev", device_id);

  pcl::Grabber* interface = new pcl::OpenNIGrabber (device_id);

  EventHelper h;
  boost::function<void(const pcl::PointCloud<pcl::PointXYZ>::ConstPtr&) > f = boost::bind (&EventHelper::cloud_cb, &h, _1);
  boost::signals2::connection c1 = interface->registerCallback (f);

  interface->start ();
  while (!p->wasStopped ())
  {
    p->spinOnce ();
    if (new_cloud && mutex_.try_lock ())
    {
      new_cloud = false;
      if (g_cloud)
      {
        p->removePointCloud ("OpenNICloud");
        p->addPointCloud (g_cloud, "OpenNICloud");
      }
      mutex_.unlock ();
    }
    else
      boost::this_thread::sleep (boost::posix_time::microseconds (1000));
  }

  interface->stop ();
}
/* ]--- */
<commit_msg>updated openni_viewer that uses @updatePointCloud@ instead of @removePointCloud@/@addPointCloud@<commit_after>/*
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2010, Willow Garage, Inc.
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of Willow Garage, Inc. nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 * $Id$
 *
 */
// PCL
#include <boost/thread/thread.hpp>
#include <Eigen/Geometry>
#include <pcl/common/common.h>
#define MEASURE_FUNCTION_TIME
#include <pcl/common/time.h> //fps calculations
#include <pcl/io/pcd_io.h>
#include <pcl/io/openni_grabber.h>
#include <cfloat>
#include <pcl/visualization/point_cloud_handlers.h>
#include <pcl/visualization/pcl_visualizer.h>
#include <pcl/visualization/histogram_visualizer.h>
#include <pcl/console/print.h>
#include <pcl/console/parse.h>
#include <pcl/console/time.h>

#define SHOW_FPS 1
#if SHOW_FPS
#define FPS_CALC(_WHAT_) \
do \
{ \
    static unsigned count = 0;\
    static double last = pcl::getTime ();\
    if (++count == 100) \
    { \
      double now = pcl::getTime (); \
      std::cout << "Average framerate("<< _WHAT_ << "): " << double(count)/double(now - last) << " Hz" <<  std::endl; \
      count = 0; \
      last = now; \
    } \
}while(false)
#else
#define FPS_CALC(_WHAT_) \
do \
{ \
}while(false)
#endif

using pcl::console::print_color;
using pcl::console::print_error;
using pcl::console::print_error;
using pcl::console::print_warn;
using pcl::console::print_info;
using pcl::console::print_debug;
using pcl::console::print_value;
using pcl::console::print_highlight;
using pcl::console::TT_BRIGHT;
using pcl::console::TT_RED;
using pcl::console::TT_GREEN;
using pcl::console::TT_BLUE;

boost::mutex mutex_;
pcl::PointCloud<pcl::PointXYZ>::ConstPtr g_cloud;
bool new_cloud = false;

void
printHelp (int argc, char **argv)
{
  //print_error ("Syntax is: %s <file_name 1..N>.pcd <options>\n", argv[0]);
  print_error ("Syntax is: %s <options>\n", argv[0]);
  print_info ("  where options are:\n");
  print_info ("                     -dev device_id           = device to be used\n");
  print_info ("                                                maybe \"#n\", with n being the number of the device in device list.\n");
  print_info ("                                                maybe \"bus@addr\", with bus and addr being the usb bus and address where device is connected.\n");
  print_info ("                                                maybe \"serial\", with serial being the serial number of the device.\n");
  print_info ("\n");
}

// Create the PCLVisualizer object
boost::shared_ptr<pcl::visualization::PCLVisualizer> p;

struct EventHelper
{
  void
  cloud_cb (const pcl::PointCloud<pcl::PointXYZ>::ConstPtr & cloud)
  {
    FPS_CALC ("callback");
    if (mutex_.try_lock ())
    {
      g_cloud = cloud;
      new_cloud = true;
      mutex_.unlock ();
    }
  }
};

/* ---[ */
int
main (int argc, char** argv)
{
  srand (time (0));

  if (argc > 1)
  {
    for (int i = 1; i < argc; i++)
    {
      if (std::string (argv[i]) == "-h")
      {
        printHelp (argc, argv);
        return (-1);
      }
    }
  }

  p.reset (new pcl::visualization::PCLVisualizer (argc, argv, "OpenNI Viewer"));

  std::string device_id = "";
  pcl::console::parse_argument (argc, argv, "-dev", device_id);

  pcl::Grabber* interface = new pcl::OpenNIGrabber (device_id);

  EventHelper h;
  boost::function<void(const pcl::PointCloud<pcl::PointXYZ>::ConstPtr&) > f = boost::bind (&EventHelper::cloud_cb, &h, _1);
  boost::signals2::connection c1 = interface->registerCallback (f);

  bool first = true;
  interface->start ();
  while (!p->wasStopped ())
  {
    p->spinOnce ();
    if (new_cloud && mutex_.try_lock ())
    {
      new_cloud = false;
      if (g_cloud)
      {
        FPS_CALC ("drawing");
        if (first)
        {
          p->addPointCloud (g_cloud, "OpenNICloud");
          first = false;
        }
        p->updatePointCloud (g_cloud, "OpenNICloud");
      }
      mutex_.unlock ();
    }
    else
      boost::this_thread::sleep (boost::posix_time::microseconds (1000));
  }

  interface->stop ();
}
/* ]--- */
<|endoftext|>


<commit_before>// Time:  O(nlogn)
// Space: O(n)

class Solution {
public:
    bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
        deque<int64_t> window_deq;
        multiset<int64_t> window;
        for (int i = 0; i < nums.size(); ++i) {
            // Only keep at most k elements.
            if (window.size() > k) {
                int num = window_deq.front();
                window_deq.pop_front();
                window.erase(window.find(num));
            }
            // Every search costs time: O(logn).
            const auto it = window.lower_bound(nums[i] - t);
            if (it == window.cend() || (*it - nums[i]) > t) {
                // Not found.
                window_deq.emplace_back(nums[i]);
                window.emplace(nums[i]);
            } else {
                return true;
            }
        }
        return false;
    }
};
<commit_msg>Update contains-duplicate-iii.cpp<commit_after>// Time:  O(nlogn)
// Space: O(n)

class Solution {
public:
    bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
        deque<int64_t> window;
        multiset<int64_t> bst;
        for (int i = 0; i < nums.size(); ++i) {
            // Only keep at most k elements.
            if (bst.size() > k) {
                int num = window.front();
                window.pop_front();
                bst.erase(bst.find(num));
            }
            // Every search costs time: O(logn).
            const auto it = bst.lower_bound(nums[i] - t);
            if (it == bst.cend() || (*it - nums[i]) > t) {
                // Not found.
                window.emplace_back(nums[i]);
                bst.emplace(nums[i]);
            } else {
                return true;
            }
        }
        return false;
    }
};
<|endoftext|>


<commit_before>// Copyright © 2011, Université catholique de Louvain
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// *  Redistributions of source code must retain the above copyright notice,
//    this list of conditions and the following disclaimer.
// *  Redistributions in binary form must reproduce the above copyright notice,
//    this list of conditions and the following disclaimer in the documentation
//    and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

#ifndef __MODCOMPILERSUPPORT_H
#define __MODCOMPILERSUPPORT_H

#include "../mozartcore.hh"

#ifndef MOZART_GENERATOR

namespace mozart {

namespace builtins {

////////////////////////////
// CompilerSupport module //
////////////////////////////

class ModCompilerSupport: public Module {
public:
  ModCompilerSupport(): Module("CompilerSupport") {}

  class NewCodeArea: public Builtin<NewCodeArea> {
  public:
    NewCodeArea(): Builtin("newCodeArea") {}

    OpResult operator()(VM vm, In byteCodeList, In XCount, In KsList,
                        Out result) {
      // Read byte code
      std::vector<ByteCode> byteCode;

      ozListForEach(vm, byteCodeList,
        [&] (nativeint elem) -> OpResult {
          if ((elem < std::numeric_limits<ByteCode>::min()) ||
              (elem > std::numeric_limits<ByteCode>::max())) {
            return raiseTypeError(vm, MOZART_STR("Byte code element"),
                                  build(vm, elem));
          } else {
            byteCode.push_back((ByteCode) elem);
            return OpResult::proceed();
          }
        },
        MOZART_STR("List of byte code elements")
      );

      // Read X count
      nativeint intXCount = 0;
      MOZART_GET_ARG(intXCount, XCount, MOZART_STR("positive integer"));

      // Read number of K registers
      size_t KCount = 0;
      MOZART_CHECK_OPRESULT(ozListLength(vm, KsList, KCount));

      // Create the code area
      result = CodeArea::build(vm, KCount, &byteCode.front(),
                               byteCode.size() * sizeof(ByteCode),
                               intXCount);

      // Fill the K registers
      ArrayInitializer KInitializer = result;
      size_t index = 0;

      ozListForEach(vm, KsList,
        [&] (UnstableNode& elem) -> OpResult {
          KInitializer.initElement(vm, index, elem);
          index++;
          return OpResult::proceed();
        },
        MOZART_STR("list")
      );

      return OpResult::proceed();
    }
  };

  class NewAbstraction: public Builtin<NewAbstraction> {
  public:
    NewAbstraction(): Builtin("newAbstraction") {}

    OpResult operator()(VM vm, In arity, In body, In GsList, Out result) {
      // Read arity
      nativeint intArity = 0;
      MOZART_GET_ARG(intArity, arity, MOZART_STR("positive integer"));

      // Check the type of the code area
      bool bodyIsCodeArea = false;
      MOZART_CHECK_OPRESULT(
        CodeAreaProvider(body).isCodeAreaProvider(vm, bodyIsCodeArea));
      if (!bodyIsCodeArea) {
        return raiseTypeError(vm, MOZART_STR("Code area"), body);
      }

      // Read number of G registers
      size_t GCount = 0;
      MOZART_CHECK_OPRESULT(ozListLength(vm, GsList, GCount));

      // Create the abstraction
      result = Abstraction::build(vm, GCount, intArity, body);

      // Fill the G registers
      ArrayInitializer GInitializer = result;
      size_t index = 0;

      ozListForEach(vm, GsList,
        [&] (UnstableNode& elem) -> OpResult {
          GInitializer.initElement(vm, index, elem);
          index++;
          return OpResult::proceed();
        },
        MOZART_STR("list")
      );

      return OpResult::proceed();
    }
  };

  class IsBuiltin: public Builtin<IsBuiltin> {
  public:
    IsBuiltin(): Builtin("isBuiltin") {}

    OpResult operator()(VM vm, In value, Out result) {
      bool boolResult = false;
      MOZART_CHECK_OPRESULT(BuiltinCallable(value).isBuiltin(vm, boolResult));

      result = Boolean::build(vm, boolResult);
      return OpResult::proceed();
    }
  };

  class GetBuiltinInfo: public Builtin<GetBuiltinInfo> {
  public:
    GetBuiltinInfo(): Builtin("getBuiltinInfo") {}

    OpResult operator()(VM vm, In value, Out result) {
      BaseBuiltin* builtin = nullptr;
      MOZART_CHECK_OPRESULT(BuiltinCallable(value).getBuiltin(vm, builtin));

      UnstableNode name = builtin->getNameAtom(vm);
      UnstableNode arity = build(vm, builtin->getArity());

      UnstableNode params = build(vm, vm->coreatoms.nil);
      for (size_t i = builtin->getArity(); i > 0; i--) {
        auto& paramInfo = builtin->getParams(i-1);
        UnstableNode param = buildRecord(
          vm, buildArity(vm, MOZART_STR("param"), MOZART_STR("kind")),
          paramInfo.kind == ParamInfo::Kind::pkIn ?
            MOZART_STR("in") : MOZART_STR("out"));
        params = buildCons(vm, std::move(param), std::move(params));
      }

      UnstableNode inlineAs;
      if (builtin->getInlineAs() < 0)
        inlineAs = build(vm, MOZART_STR("none"));
      else
        inlineAs = buildTuple(vm, MOZART_STR("some"), builtin->getInlineAs());

      result = buildRecord(
        vm, buildArity(vm,
                       MOZART_STR("builtin"),
                       MOZART_STR("arity"),
                       MOZART_STR("inlineAs"),
                       MOZART_STR("name"),
                       MOZART_STR("params")),
        std::move(arity), std::move(inlineAs), std::move(name),
        std::move(params));

      return OpResult::proceed();
    }
  };
};

}

}

#endif // MOZART_GENERATOR

#endif // __MODCOMPILERSUPPORT_H
<commit_msg>Added things needed by the compiler in CompilerSupport.<commit_after>// Copyright © 2011, Université catholique de Louvain
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// *  Redistributions of source code must retain the above copyright notice,
//    this list of conditions and the following disclaimer.
// *  Redistributions in binary form must reproduce the above copyright notice,
//    this list of conditions and the following disclaimer in the documentation
//    and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

#ifndef __MODCOMPILERSUPPORT_H
#define __MODCOMPILERSUPPORT_H

#include "../mozartcore.hh"

#ifndef MOZART_GENERATOR

namespace mozart {

namespace builtins {

////////////////////////////
// CompilerSupport module //
////////////////////////////

class ModCompilerSupport: public Module {
public:
  ModCompilerSupport(): Module("CompilerSupport") {}

  class FeatureLess: public Builtin<FeatureLess> {
  public:
    FeatureLess(): Builtin("featureLess") {}

    OpResult operator()(VM vm, In lhs, In rhs, Out result) {
      MOZART_REQUIRE_FEATURE(lhs);
      MOZART_REQUIRE_FEATURE(rhs);

      result = build(vm, compareFeatures(vm, lhs, rhs) < 0);
      return OpResult::proceed();
    }
  };

  class NewCodeArea: public Builtin<NewCodeArea> {
  public:
    NewCodeArea(): Builtin("newCodeArea") {}

    OpResult operator()(VM vm, In byteCodeList, In XCount, In KsList,
                        Out result) {
      // Read byte code
      std::vector<ByteCode> byteCode;

      ozListForEach(vm, byteCodeList,
        [&] (nativeint elem) -> OpResult {
          if ((elem < std::numeric_limits<ByteCode>::min()) ||
              (elem > std::numeric_limits<ByteCode>::max())) {
            return raiseTypeError(vm, MOZART_STR("Byte code element"),
                                  build(vm, elem));
          } else {
            byteCode.push_back((ByteCode) elem);
            return OpResult::proceed();
          }
        },
        MOZART_STR("List of byte code elements")
      );

      // Read X count
      nativeint intXCount = 0;
      MOZART_GET_ARG(intXCount, XCount, MOZART_STR("positive integer"));

      // Read number of K registers
      size_t KCount = 0;
      MOZART_CHECK_OPRESULT(ozListLength(vm, KsList, KCount));

      // Create the code area
      result = CodeArea::build(vm, KCount, &byteCode.front(),
                               byteCode.size() * sizeof(ByteCode),
                               intXCount);

      // Fill the K registers
      ArrayInitializer KInitializer = result;
      size_t index = 0;

      ozListForEach(vm, KsList,
        [&] (UnstableNode& elem) -> OpResult {
          KInitializer.initElement(vm, index, elem);
          index++;
          return OpResult::proceed();
        },
        MOZART_STR("list")
      );

      return OpResult::proceed();
    }
  };

  class NewAbstraction: public Builtin<NewAbstraction> {
  public:
    NewAbstraction(): Builtin("newAbstraction") {}

    OpResult operator()(VM vm, In arity, In body, In GsList, Out result) {
      // Read arity
      nativeint intArity = 0;
      MOZART_GET_ARG(intArity, arity, MOZART_STR("positive integer"));

      // Check the type of the code area
      bool bodyIsCodeArea = false;
      MOZART_CHECK_OPRESULT(
        CodeAreaProvider(body).isCodeAreaProvider(vm, bodyIsCodeArea));
      if (!bodyIsCodeArea) {
        return raiseTypeError(vm, MOZART_STR("Code area"), body);
      }

      // Read number of G registers
      size_t GCount = 0;
      MOZART_CHECK_OPRESULT(ozListLength(vm, GsList, GCount));

      // Create the abstraction
      result = Abstraction::build(vm, GCount, intArity, body);

      // Fill the G registers
      ArrayInitializer GInitializer = result;
      size_t index = 0;

      ozListForEach(vm, GsList,
        [&] (UnstableNode& elem) -> OpResult {
          GInitializer.initElement(vm, index, elem);
          index++;
          return OpResult::proceed();
        },
        MOZART_STR("list")
      );

      return OpResult::proceed();
    }
  };

  class IsBuiltin: public Builtin<IsBuiltin> {
  public:
    IsBuiltin(): Builtin("isBuiltin") {}

    OpResult operator()(VM vm, In value, Out result) {
      bool boolResult = false;
      MOZART_CHECK_OPRESULT(BuiltinCallable(value).isBuiltin(vm, boolResult));

      result = Boolean::build(vm, boolResult);
      return OpResult::proceed();
    }
  };

  class GetBuiltinInfo: public Builtin<GetBuiltinInfo> {
  public:
    GetBuiltinInfo(): Builtin("getBuiltinInfo") {}

    OpResult operator()(VM vm, In value, Out result) {
      BaseBuiltin* builtin = nullptr;
      MOZART_CHECK_OPRESULT(BuiltinCallable(value).getBuiltin(vm, builtin));

      UnstableNode name = builtin->getNameAtom(vm);
      UnstableNode arity = build(vm, builtin->getArity());

      UnstableNode params = build(vm, vm->coreatoms.nil);
      for (size_t i = builtin->getArity(); i > 0; i--) {
        auto& paramInfo = builtin->getParams(i-1);
        UnstableNode param = buildRecord(
          vm, buildArity(vm, MOZART_STR("param"), MOZART_STR("kind")),
          paramInfo.kind == ParamInfo::Kind::pkIn ?
            MOZART_STR("in") : MOZART_STR("out"));
        params = buildCons(vm, std::move(param), std::move(params));
      }

      UnstableNode inlineAs;
      if (builtin->getInlineAs() < 0)
        inlineAs = build(vm, MOZART_STR("none"));
      else
        inlineAs = buildTuple(vm, MOZART_STR("some"), builtin->getInlineAs());

      result = buildRecord(
        vm, buildArity(vm,
                       MOZART_STR("builtin"),
                       MOZART_STR("arity"),
                       MOZART_STR("inlineAs"),
                       MOZART_STR("name"),
                       MOZART_STR("params")),
        std::move(arity), std::move(inlineAs), std::move(name),
        std::move(params));

      return OpResult::proceed();
    }
  };

  class IsUniqueName: public Builtin<IsUniqueName> {
  public:
    IsUniqueName(): Builtin("isUniqueName") {}

    OpResult operator()(VM vm, In value, Out result) {
      if (value.isTransient())
        return OpResult::waitFor(vm, value);

      result = build(vm, value.is<UniqueName>());
      return OpResult::proceed();
    }
  };
};

}

}

#endif // MOZART_GENERATOR

#endif // __MODCOMPILERSUPPORT_H
<|endoftext|>


<commit_before>#include <iostream>

using namespace std;

int iterative_power_function(int m, int n){
	if(m < 0 || n < 0){
		cout << "Input not valid" << endl;
		return -1;
	}else{
		int product = 1;
		for(int x=0; x<n; x++){
			product *= m;
		}
	return product;
	}
}

int iterative_factorial_function(int n){
	if( n<=0){
		cout << "Input not valid" << endl;
		return -1;
	}else{
		int product = 1;
		for(int x = 1; x <= n; x++){
			product *= x;
		}
	return product;
	}
}

int main(){
	int temp;
	cin >> temp;
	cout << "BASIC CONDITIONAL STATEMENT" << endl;
	if(temp < 25){
		cout << "It is too cold" << endl;
	}else if(temp > 50){
		cout << "It is too warm" << endl;
	}else{
		cout << "The temperature is perfect" << endl;
	}

	cout << "NESTED CONDITIONAL STATEMENTS" << endl;
	if(temp >= 25){
		if(temp <= 50){
			cout << "The temperature is perfect" << endl;
		}else{
			cout << "the temperature is not perfect" << endl;
		}
	}else{
		cout << "The temperature is not perfect" << endl;
	}

	cout << "CONDITIONAL STATEMENTS WITH THE AND OPERATOR" << endl;
	if(temp >= 25 && temp <= 50){
		cout << "The temperature is perfect" << endl;
	}else{
		cout << "The temperature is not perfect" << endl;
	}

	cout << "CONDITIONAL STATEMENTS WITH THE OR OPERATOR" << endl;
	if(temp < 25 || temp > 50){
		cout << "The temperature is not perfect" << endl;
	}else{
		cout << "The temperature is perfect" << endl;
	}

	cout << "WHILE LOOP" << endl;
	if(temp < 25){
		cout << "It is too cold" << endl;
		int counter = temp;
		while(counter < 25){
			counter++;
			cout << "The temperature has been increased to " << counter << " degrees" << endl;
		}
		cout << "The temperature is now perfect";
	}else if(temp > 50){
		cout << "It is too warm" << endl;
		int counter = temp;
		while(counter >= 50){
			counter--;
			cout << "The temperature has been decreased to " << temp << " degrees" << endl;
		}
		cout << "The temperature is now perfect" << endl;
	}else{
		cout << "The temperature is perfect" << endl;
	}
	cout << "FOR LOOP" << endl;
	if(temp < 25){
		cout << "It is too cold" << endl;
		for(int counter = temp; counter < 25; ++counter){
			cout << "The temperature has been increased to " << counter << " degrees" << endl;
		}
		cout << "The temperature is now perfect";
	}else if(temp > 50){
		cout << "It is too warm" << endl;
		for(int counter = temp; counter >50; --counter){
			cout << "The temperature has been decreased to " << counter << " degrees" << endl;
		}
		cout << "The temperature is now perfect";
	}else{
		cout << "The temperature is perfect" << endl;
	}
	return 0;

}
<commit_msg>Update Sample.cpp<commit_after>#include <iostream>

using namespace std;
//Practice Problem 1
int iterative_power_function(int m, int n){
	if(m < 0 || n < 0){
		cout << "Input not valid" << endl;
		return -1;
	}else{
		int product = 1;
		for(int x=0; x<n; x++){
			product *= m;
		}
	return product;
	}
}
//Practice Problem 2
int iterative_factorial_function(int n){
	if( n<=0){
		cout << "Input not valid" << endl;
		return -1;
	}else{
		int product = 1;
		for(int x = 1; x <= n; x++){
			product *= x;
		}
	return product;
	}
}

int main(){
	int temp;
	cin >> temp;
	cout << "BASIC CONDITIONAL STATEMENT" << endl;
	if(temp < 25){
		cout << "It is too cold" << endl;
	}else if(temp > 50){
		cout << "It is too warm" << endl;
	}else{
		cout << "The temperature is perfect" << endl;
	}

	cout << "NESTED CONDITIONAL STATEMENTS" << endl;
	if(temp >= 25){
		if(temp <= 50){
			cout << "The temperature is perfect" << endl;
		}else{
			cout << "the temperature is not perfect" << endl;
		}
	}else{
		cout << "The temperature is not perfect" << endl;
	}

	cout << "CONDITIONAL STATEMENTS WITH THE AND OPERATOR" << endl;
	if(temp >= 25 && temp <= 50){
		cout << "The temperature is perfect" << endl;
	}else{
		cout << "The temperature is not perfect" << endl;
	}

	cout << "CONDITIONAL STATEMENTS WITH THE OR OPERATOR" << endl;
	if(temp < 25 || temp > 50){
		cout << "The temperature is not perfect" << endl;
	}else{
		cout << "The temperature is perfect" << endl;
	}

	cout << "WHILE LOOP" << endl;
	if(temp < 25){
		cout << "It is too cold" << endl;
		int counter = temp;
		while(counter < 25){
			counter++;
			cout << "The temperature has been increased to " << counter << " degrees" << endl;
		}
		cout << "The temperature is now perfect";
	}else if(temp > 50){
		cout << "It is too warm" << endl;
		int counter = temp;
		while(counter >= 50){
			counter--;
			cout << "The temperature has been decreased to " << temp << " degrees" << endl;
		}
		cout << "The temperature is now perfect" << endl;
	}else{
		cout << "The temperature is perfect" << endl;
	}
	cout << "FOR LOOP" << endl;
	if(temp < 25){
		cout << "It is too cold" << endl;
		for(int counter = temp; counter < 25; ++counter){
			cout << "The temperature has been increased to " << counter << " degrees" << endl;
		}
		cout << "The temperature is now perfect";
	}else if(temp > 50){
		cout << "It is too warm" << endl;
		for(int counter = temp; counter >50; --counter){
			cout << "The temperature has been decreased to " << counter << " degrees" << endl;
		}
		cout << "The temperature is now perfect";
	}else{
		cout << "The temperature is perfect" << endl;
	}
	return 0;

}
<|endoftext|>