<commit_before>/*  -*- c++ -*-
    kregexp3.cpp

    This file is part of libkdenetwork.
    Copyright (c) 2001 Marc Mutz <mutz@kde.org>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License,
    version 2, as published by the Free Software Foundation.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this library; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

    In addition, as a special exception, the copyright holders give
    permission to link the code of this library with any edition of
    the Qt library by Trolltech AS, Norway (or with modified versions
    of Qt that use the same license as Qt), and distribute linked
    combinations including the two.  You must obey the GNU General
    Public License in all respects for all of the code used other than
    Qt.  If you modify this file, you may extend this exception to
    your version of the file, but you are not obligated to do so.  If
    you do not wish to do so, delete this exception statement from
    your version.
*/

#include "kregexp3.h"

// #define DEBUG_KREGEXP3

#ifdef DEBUG_KREGEXP3
#include <kdebug.h>
#endif

QString KRegExp3::replace( const QString & str,
			   const QString & replacementStr,
			   int start, bool global )
{
  int oldpos, pos;

  //-------- parsing the replacementStr into
  //-------- literal parts and backreferences:
  QStringList     literalStrs;
  QValueList<int> backRefs;

  // Due to LTS: The regexp in unquoted form and with spaces:
  // \\ (\d) | \$ (\d) | \$ \{ (\d+) \}
  QRegExp rx( "\\\\(\\d)|\\$(\\d)|\\$\\{(\\d+)\\}" );
  QRegExp bbrx("\\\\");
  QRegExp brx("\\");

#ifdef DEBUG_KREGEXP3
  kdDebug() << "Analyzing replacementStr: \"" + replacementStr + "\"" << endl;
#endif

  oldpos = 0;
  pos = 0;
  while ( true ) {
    pos = rx.search( replacementStr, pos );

#ifdef DEBUG_KREGEXP3
    kdDebug() << QString("  Found match at pos %1").arg(pos) << endl;
#endif

    if ( pos < 0 ) {
      literalStrs << replacementStr.mid( oldpos )
	.replace( bbrx, "\\" )
	.replace( brx, "" );
#ifdef DEBUG_KREGEXP3
      kdDebug() << "  No more matches. Last literal is \"" + literalStrs.last() + "\"" << endl;
#endif
      break;
    } else {
      literalStrs << replacementStr.mid( oldpos, pos-oldpos )
	.replace( bbrx, "\\" )
	.replace( brx, "" );
#ifdef DEBUG_KREGEXP3
      kdDebug() << QString("  Inserting \"") + literalStrs.last() + "\" as literal." << endl;
      kdDebug() << "    Searching for corresponding digit(s):" << endl;
#endif
      for ( int i = 1 ; i < 4 ; i++ )
	if ( !rx.cap(i).isEmpty() ) {
	  backRefs << rx.cap(i).toInt();
#ifdef DEBUG_KREGEXP3
	  kdDebug() << QString("      Found %1 at position %2 in the capturedTexts.")
            .arg(backRefs.last()).arg(i) << endl;
#endif
	  break;
	}
      pos += rx.matchedLength();
#ifdef DEBUG_KREGEXP3
      kdDebug() << QString("  Setting new pos to %1.").arg(pos) << endl;
#endif
      oldpos = pos;
    }
  }

#ifdef DEBUG_KREGEXP3
  kdDebug() << "Finished the analysis of replacementStr!" << endl;
#endif
  Q_ASSERT( literalStrs.count() == backRefs.count() + 1 );

  //-------- actual construction of the
  //-------- resulting QString
  QString result = "";
  oldpos = 0;
  pos = start;

  QStringList::Iterator sIt;
  QValueList<int>::Iterator iIt;

  if ( start < 0 )
    start += str.length();

#ifdef DEBUG_KREGEXP3
  kdDebug() << "Constructing the resultant string starts now:" << endl;
#endif

  while ( pos < str.length() ) {
    pos = search( str, pos );

#ifdef DEBUG_KREGEXP3
    kdDebug() << QString("  Found match at pos %1").arg(pos) << endl;
#endif

    if ( pos < 0 ) {
      result += str.mid( oldpos );
#ifdef DEBUG_KREGEXP3
      kdDebug() << "   No more matches. Adding trailing part from str:" << endl;
      kdDebug() << "    result == \"" + result + "\"" << endl;
#endif
      break;
    } else {
      result += str.mid( oldpos, pos-oldpos );
#ifdef DEBUG_KREGEXP3
      kdDebug() << "   Adding unchanged part from str:" << endl;
      kdDebug() << "    result == \"" + result + "\"" << endl;
#endif
      for ( sIt = literalStrs.begin(), iIt = backRefs.begin() ;
            iIt != backRefs.end() ; ++sIt, ++iIt ) {
	result += (*sIt);
#ifdef DEBUG_KREGEXP3
	kdDebug() << "   Adding literal replacement part:" << endl;
	kdDebug() << "    result == \"" + result + "\"" << endl;
#endif
	result += cap( (*iIt) );
#ifdef DEBUG_KREGEXP3
	kdDebug() << "   Adding captured string:" << endl;
	kdDebug() << "    result == \"" + result + "\"" << endl;
#endif
      }
      result += (*sIt);
#ifdef DEBUG_KREGEXP3
      kdDebug() << "   Adding literal replacement part:" << endl;
      kdDebug() << "    result == \"" + result + "\"" << endl;
#endif
    }
    pos += matchedLength();
#ifdef DEBUG_KREGEXP3
    kdDebug() << QString("  Setting new pos to %1.").arg(pos) << endl;
#endif
    oldpos = pos;

    if ( !global ) {
      // only replace the first occurrence, so stop here:
      result += str.mid( oldpos );
      break;
    }
  }

  return result;
}
<commit_msg>--warning<commit_after>/*  -*- c++ -*-
    kregexp3.cpp

    This file is part of libkdenetwork.
    Copyright (c) 2001 Marc Mutz <mutz@kde.org>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License,
    version 2, as published by the Free Software Foundation.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this library; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

    In addition, as a special exception, the copyright holders give
    permission to link the code of this library with any edition of
    the Qt library by Trolltech AS, Norway (or with modified versions
    of Qt that use the same license as Qt), and distribute linked
    combinations including the two.  You must obey the GNU General
    Public License in all respects for all of the code used other than
    Qt.  If you modify this file, you may extend this exception to
    your version of the file, but you are not obligated to do so.  If
    you do not wish to do so, delete this exception statement from
    your version.
*/

#include "kregexp3.h"

// #define DEBUG_KREGEXP3

#ifdef DEBUG_KREGEXP3
#include <kdebug.h>
#endif

QString KRegExp3::replace( const QString & str,
			   const QString & replacementStr,
			   int start, bool global )
{
  int oldpos, pos;

  //-------- parsing the replacementStr into
  //-------- literal parts and backreferences:
  QStringList     literalStrs;
  QValueList<int> backRefs;

  // Due to LTS: The regexp in unquoted form and with spaces:
  // \\ (\d) | \$ (\d) | \$ \{ (\d+) \}
  QRegExp rx( "\\\\(\\d)|\\$(\\d)|\\$\\{(\\d+)\\}" );
  QRegExp bbrx("\\\\");
  QRegExp brx("\\");

#ifdef DEBUG_KREGEXP3
  kdDebug() << "Analyzing replacementStr: \"" + replacementStr + "\"" << endl;
#endif

  oldpos = 0;
  pos = 0;
  while ( true ) {
    pos = rx.search( replacementStr, pos );

#ifdef DEBUG_KREGEXP3
    kdDebug() << QString("  Found match at pos %1").arg(pos) << endl;
#endif

    if ( pos < 0 ) {
      literalStrs << replacementStr.mid( oldpos )
	.replace( bbrx, "\\" )
	.replace( brx, "" );
#ifdef DEBUG_KREGEXP3
      kdDebug() << "  No more matches. Last literal is \"" + literalStrs.last() + "\"" << endl;
#endif
      break;
    } else {
      literalStrs << replacementStr.mid( oldpos, pos-oldpos )
	.replace( bbrx, "\\" )
	.replace( brx, "" );
#ifdef DEBUG_KREGEXP3
      kdDebug() << QString("  Inserting \"") + literalStrs.last() + "\" as literal." << endl;
      kdDebug() << "    Searching for corresponding digit(s):" << endl;
#endif
      for ( int i = 1 ; i < 4 ; i++ )
	if ( !rx.cap(i).isEmpty() ) {
	  backRefs << rx.cap(i).toInt();
#ifdef DEBUG_KREGEXP3
	  kdDebug() << QString("      Found %1 at position %2 in the capturedTexts.")
            .arg(backRefs.last()).arg(i) << endl;
#endif
	  break;
	}
      pos += rx.matchedLength();
#ifdef DEBUG_KREGEXP3
      kdDebug() << QString("  Setting new pos to %1.").arg(pos) << endl;
#endif
      oldpos = pos;
    }
  }

#ifdef DEBUG_KREGEXP3
  kdDebug() << "Finished the analysis of replacementStr!" << endl;
#endif
  Q_ASSERT( literalStrs.count() == backRefs.count() + 1 );

  //-------- actual construction of the
  //-------- resulting QString
  QString result = "";
  oldpos = 0;
  pos = start;

  QStringList::Iterator sIt;
  QValueList<int>::Iterator iIt;

  if ( start < 0 )
    start += str.length();

#ifdef DEBUG_KREGEXP3
  kdDebug() << "Constructing the resultant string starts now:" << endl;
#endif

  while ( pos < (int)str.length() ) {
    pos = search( str, pos );

#ifdef DEBUG_KREGEXP3
    kdDebug() << QString("  Found match at pos %1").arg(pos) << endl;
#endif

    if ( pos < 0 ) {
      result += str.mid( oldpos );
#ifdef DEBUG_KREGEXP3
      kdDebug() << "   No more matches. Adding trailing part from str:" << endl;
      kdDebug() << "    result == \"" + result + "\"" << endl;
#endif
      break;
    } else {
      result += str.mid( oldpos, pos-oldpos );
#ifdef DEBUG_KREGEXP3
      kdDebug() << "   Adding unchanged part from str:" << endl;
      kdDebug() << "    result == \"" + result + "\"" << endl;
#endif
      for ( sIt = literalStrs.begin(), iIt = backRefs.begin() ;
            iIt != backRefs.end() ; ++sIt, ++iIt ) {
	result += (*sIt);
#ifdef DEBUG_KREGEXP3
	kdDebug() << "   Adding literal replacement part:" << endl;
	kdDebug() << "    result == \"" + result + "\"" << endl;
#endif
	result += cap( (*iIt) );
#ifdef DEBUG_KREGEXP3
	kdDebug() << "   Adding captured string:" << endl;
	kdDebug() << "    result == \"" + result + "\"" << endl;
#endif
      }
      result += (*sIt);
#ifdef DEBUG_KREGEXP3
      kdDebug() << "   Adding literal replacement part:" << endl;
      kdDebug() << "    result == \"" + result + "\"" << endl;
#endif
    }
    pos += matchedLength();
#ifdef DEBUG_KREGEXP3
    kdDebug() << QString("  Setting new pos to %1.").arg(pos) << endl;
#endif
    oldpos = pos;

    if ( !global ) {
      // only replace the first occurrence, so stop here:
      result += str.mid( oldpos );
      break;
    }
  }

  return result;
}
<|endoftext|>


<commit_before>/*
 * Summary: Exceptions for the C++ interface
 *
 * Copy: See Copyright for the status of this software.
 *
 */

/**
 * @file
 * @brief Exception declarations
 */

#ifndef LIBMEMACHED_EXCEPTION_HPP
#define LIBMEMACHED_EXCEPTION_HPP

#include <stdexcept>

namespace memcache
{
  class Exception : public std::runtime_error
  {
  public:
    Exception(const std::string& msg, bool in_errno)
      :
        std::runtime_error(msg),
        errno(in_errno)
    {}

    Exception(const char *msg, bool in_errno)
      :
        std::runtime_error(msg),
        errno(in_errno) {}

    virtual ~Exception() throw() {}

    int getErrno() const
    {
      return errno;
    }

  private:
    int errno;
  };

  class Warning : public Exception
  {
  public:
    Warning(const std::string& msg, bool errno) : Exception(msg, errno) {}
    Warning(const char *msg, bool errno) : Exception(msg, errno) {}
  };

  class Error : public Exception
  {
  public:
    Error(const std::string& msg, bool errno) : Exception(msg, errno) {}
    Error(const char *msg, bool errno) : Exception(msg, errno) {}
    virtual ~Error() throw() {}
  };

} /* namespace libmemcached */

#endif /* LIBMEMACHED_EXCEPTION_HPP */
<commit_msg>Correcting mistake I made in exceptions header file.<commit_after>/*
 * Summary: Exceptions for the C++ interface
 *
 * Copy: See Copyright for the status of this software.
 *
 */

/**
 * @file
 * @brief Exception declarations
 */

#ifndef LIBMEMACHED_EXCEPTION_HPP
#define LIBMEMACHED_EXCEPTION_HPP

#include <stdexcept>

namespace memcache
{
  class Exception : public std::runtime_error
  {
  public:
    Exception(const std::string& msg, bool in_errno)
      :
        std::runtime_error(msg),
        errno(in_errno)
    {}

    Exception(const char *msg, bool in_errno)
      :
        std::runtime_error(msg),
        errno(in_errno) {}

    virtual ~Exception() throw() {}

    int getErrno() const
    {
      return errno;
    }

  private:
    int errno;
  };

  class Warning : public Exception
  {
  public:
    Warning(const std::string& msg, bool in_errno) : Exception(msg, in_errno) {}
    Warning(const char *msg, bool in_errno) : Exception(msg, in_errno) {}
  };

  class Error : public Exception
  {
  public:
    Error(const std::string& msg, bool in_errno) : Exception(msg, in_errno) {}
    Error(const char *msg, bool in_errno) : Exception(msg, in_errno) {}
    virtual ~Error() throw() {}
  };

} /* namespace libmemcached */

#endif /* LIBMEMACHED_EXCEPTION_HPP */
<|endoftext|>


<commit_before>#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/wdt.h>
#define F_CPU 1000000L
#include <util/delay.h>
#include <common.hpp>
#include <am2302.hpp>
#include <sensor.hpp>
#include <vcc.hpp>
#include <interrupt/WATCHDOG.hpp>
#include <interrupt/PCINT0.hpp>

typedef AM2302< Pin<Port<B>, 1> > Tsensor1;
typedef Pin<Port<B>, 0> LED;

unsigned char id;

static unsigned char read_eeprom(int addr)
{
	loop_until_bit_is_clear(EECR, EEPE);

	EEAR = addr;

	EECR |= _BV(EERE);

	return EEDR;
}

void send()
{
	union {
		struct {
			unsigned char len;
			unsigned char id;
			unsigned char data[0];
		};
		unsigned char raw[16];
	} data;

	VCC vccreader;
	unsigned char* dp = data.data;

	short hum, temp;
	if (Tsensor1::read(hum, temp)) {
		dp += SensorValue<Humidity>::encode(hum, dp);
		dp += SensorValue<Temperature>::encode(temp, dp);
	}

	int voltage = vccreader.read_voltage();
	dp += SensorValue<Power>::encode(voltage, dp);

	data.len = dp - data.data + 1;
	data.id = id;

	radio::select();
	radio::write_txfifo(data.raw, data.len + 1);
	radio::select();
	radio::wcmd<radio::STX>();
	radio::release();
}

static void loop();

static void radio_off()
{
	GIMSK &= ~_BV(PCIE0);

	radio::select();
	radio::wcmd<radio::SPWD>();
	radio::release();

	wdt_reset();
	WDTCSR = _BV(WDIE) | _BV(WDP3) | _BV(WDP0);
	WATCHDOGInterrupt::set(loop);

	LED::clear();
}

#define P_TIMEOUTS 3

static void loop()
{
	static unsigned char counter = 0;

	counter++;

	if (counter == P_TIMEOUTS) {
		short thum, ttemp;
		Tsensor1::read(thum, ttemp);
		WDTCSR = _BV(WDIE) | _BV(WDP3);
	} else if (counter == P_TIMEOUTS+1) {
		LED::set();
		counter = 0;
		send();
		WDTCSR = _BV(WDP2) | _BV(WDP0) | _BV(WDIE);
		WATCHDOGInterrupt::set(radio_off);

		GIMSK |= _BV(PCIE0);

		set_sleep_mode(SLEEP_MODE_PWR_DOWN);
		sleep_mode();
		PCINT0Interrupt::pending();
	}
}

int main()
{
	id = read_eeprom(511);

	radio::setup();
	radio_reset();
	radio::select();
	radio::set<radio::IOCFG1>(0x06);
	radio::release();

	LED::mode(OUTPUT);

	sei();

	PCMSK0 |= _BV(radio::USI::DI::pin);
	PCINT0Interrupt::set(radio_off);

	radio_off();

	for (;;) {
		set_sleep_mode(SLEEP_MODE_PWR_DOWN);
		sleep_mode();
		WATCHDOGInterrupt::pending();
	}
}
<commit_msg>TX start reorganized<commit_after>#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/wdt.h>
#define F_CPU 1000000L
#include <util/delay.h>
#include <common.hpp>
#include <am2302.hpp>
#include <sensor.hpp>
#include <vcc.hpp>
#include <interrupt/WATCHDOG.hpp>
#include <interrupt/PCINT0.hpp>

typedef AM2302< Pin<Port<B>, 1> > Tsensor1;
typedef Pin<Port<B>, 0> LED;

unsigned char id;

static unsigned char read_eeprom(int addr)
{
	loop_until_bit_is_clear(EECR, EEPE);

	EEAR = addr;

	EECR |= _BV(EERE);

	return EEDR;
}

void send()
{
	union {
		struct {
			unsigned char len;
			unsigned char id;
			unsigned char data[0];
		};
		unsigned char raw[16];
	} data;

	VCC vccreader;
	unsigned char* dp = data.data;

	short hum, temp;
	if (Tsensor1::read(hum, temp)) {
		dp += SensorValue<Humidity>::encode(hum, dp);
		dp += SensorValue<Temperature>::encode(temp, dp);
	}

	int voltage = vccreader.read_voltage();
	dp += SensorValue<Power>::encode(voltage, dp);

	data.len = dp - data.data + 1;
	data.id = id;

	radio::select();
	radio::wcmd<radio::STX>();
	radio::write_txfifo(data.raw, data.len + 1);
}

static void loop();

static void radio_off()
{
	GIMSK &= ~_BV(PCIE0);

	radio::select();
	radio::wcmd<radio::SPWD>();
	radio::release();

	wdt_reset();
	WDTCSR = _BV(WDIE) | _BV(WDP3) | _BV(WDP0);
	WATCHDOGInterrupt::set(loop);

	LED::clear();
}

#define P_TIMEOUTS 3

static void loop()
{
	static unsigned char counter = 0;

	counter++;

	if (counter == P_TIMEOUTS) {
		short thum, ttemp;
		Tsensor1::read(thum, ttemp);
		WDTCSR = _BV(WDIE) | _BV(WDP3);
	} else if (counter == P_TIMEOUTS+1) {
		LED::set();
		counter = 0;
		send();
		WDTCSR = _BV(WDP2) | _BV(WDP0) | _BV(WDIE);
		WATCHDOGInterrupt::set(radio_off);

		GIMSK |= _BV(PCIE0);

		set_sleep_mode(SLEEP_MODE_PWR_DOWN);
		sleep_mode();
		PCINT0Interrupt::pending();
	}
}

int main()
{
	id = read_eeprom(511);

	radio::setup();
	radio_reset();
	radio::select();
	radio::set<radio::IOCFG1>(0x06);
	radio::release();

	LED::mode(OUTPUT);

	sei();

	PCMSK0 |= _BV(radio::USI::DI::pin);
	PCINT0Interrupt::set(radio_off);

	radio_off();

	for (;;) {
		set_sleep_mode(SLEEP_MODE_PWR_DOWN);
		sleep_mode();
		WATCHDOGInterrupt::pending();
	}
}
<|endoftext|>


<commit_before>

#include "cssysdef.h"
#include "csengine/csanim2d.h"
#include "igraph3d.h"

csAnimation2D::~csAnimation2D() {
  for (int i=0;i<Frames.Length();i++) {
    csPixmap *p=GetFrame(i);
    delete p;
  }
}

csPixmap *csAnimation2D::GetFrameByTime(unsigned long time) {
  time%=GetTotalTime();
  int n=0;
  while (time>=FrameTime) {time-=FrameTime;n++;}
  return GetFrame(n);
}

void csAnimation2D::Draw(iGraphics3D *G3D,int x,int y,unsigned long time) {
  csPixmap *spr=GetFrameByTime(time);
  spr->Draw(G3D,x,y);
}

void csAnimation2D::DrawAlign(iGraphics3D *G3D, int x, int y, int alnx,
        int alny, unsigned long time) {
  csPixmap *spr=GetFrameByTime(time);
  spr->DrawAlign(G3D,x,y,alnx,alny);
}

void csAnimation2D::DrawScaled(iGraphics3D *G3D,int x,int y,int w2,int h2,
        unsigned long time) {
  csPixmap *spr=GetFrameByTime(time);
  spr->DrawScaled(G3D,x,y,w2,h2);
}

void csAnimation2D::DrawScaledAlign(iGraphics3D *G3D, int x, int y, int w2,
        int h2, int alnx, int alny, unsigned long time) {
  csPixmap *spr=GetFrameByTime(time);
  spr->DrawScaledAlign(G3D, x, y, w2, h2, alnx, alny);
}
<commit_msg>added a missing copyright message<commit_after>/*
    Copyright (C) 2000 by Jorrit Tyberghein

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public
    License along with this library; if not, write to the Free
    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include "cssysdef.h"
#include "csengine/csanim2d.h"
#include "igraph3d.h"

csAnimation2D::~csAnimation2D() {
  for (int i=0;i<Frames.Length();i++) {
    csPixmap *p=GetFrame(i);
    delete p;
  }
}

csPixmap *csAnimation2D::GetFrameByTime(unsigned long time) {
  time%=GetTotalTime();
  int n=0;
  while (time>=FrameTime) {time-=FrameTime;n++;}
  return GetFrame(n);
}

void csAnimation2D::Draw(iGraphics3D *G3D,int x,int y,unsigned long time) {
  csPixmap *spr=GetFrameByTime(time);
  spr->Draw(G3D,x,y);
}

void csAnimation2D::DrawAlign(iGraphics3D *G3D, int x, int y, int alnx,
        int alny, unsigned long time) {
  csPixmap *spr=GetFrameByTime(time);
  spr->DrawAlign(G3D,x,y,alnx,alny);
}

void csAnimation2D::DrawScaled(iGraphics3D *G3D,int x,int y,int w2,int h2,
        unsigned long time) {
  csPixmap *spr=GetFrameByTime(time);
  spr->DrawScaled(G3D,x,y,w2,h2);
}

void csAnimation2D::DrawScaledAlign(iGraphics3D *G3D, int x, int y, int w2,
        int h2, int alnx, int alny, unsigned long time) {
  csPixmap *spr=GetFrameByTime(time);
  spr->DrawScaledAlign(G3D, x, y, w2, h2, alnx, alny);
}
<|endoftext|>


<commit_before>/* -*- mode: C++; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
/** \file examples/charpoly.C
\brief Characteristic polynomial of matrix over Z or Zp.
 \ingroup examples
*/

// Warning : example under development.
// integer computation must be completed
#include <iostream>
#include <iomanip>
#include "Matio.h"

#include "linbox/field/modular-double.h"
#include "linbox/field/unparametric.h"
#include "linbox/blackbox/sparse.h"
#include "linbox/blackbox/blas-blackbox.h"
using namespace std;

#include "linbox/solutions/charpoly.h"
#include "linbox/ring/givaro-polynomial.h"
#include "linbox/element/givaro-polynomial.h"
using namespace LinBox;

template <class Field, class Polynomial>
std::ostream& printPolynomial (std::ostream& out, const Field &F, const Polynomial &v)
{
	for (int i = v.size () - 1; i >= 0; i--) {
		F.write (out, v[i]);
		if (i > 0)
			out << " X^" << i << " + ";
	}
	return out;
}
template <class Field, class Polynomial>
std::ostream& prettyprintIntegerPolynomial (std::ostream& out, const Field &F, const Polynomial &v)
{
  size_t n = v.size()-1;
  if (n == 0) {
    F.write(out, v[0]);
  } else {
    if(v[n] != 0) {
      if (v[n] != 1) F.write(out, v[n]) << '*';
      out << 'X';
      if (n > 1) out << '^' << n;
      for (int i = n - 1; i > 0; i--) {
	  if (v[i] != 0) {
	    if (v[i] >0) out << " + ";
	    if (v[i] != 1) F.write (out, v[i]) << '*';
	    out << 'X';
	    if (i > 1) out << '^' << i;
	  }
      }
      if (v[0] != 0) {
	if (v[0] >0) out << " + ";
	F.write(out, v[0]);
      }
    }
  }
  return out;
}
template <class Field, class Factors, class Exponents>
std::ostream& printFactorization (std::ostream& out, const Field &F, const Factors &f, const Exponents& exp)
{
  typename Factors::const_iterator itf = f.begin();
  typename Exponents::const_iterator ite = exp.begin();
  for ( ; itf != f.end(); ++itf, ++ite) {
    prettyprintIntegerPolynomial(out << '(', F, *(*itf)) << ')';
    if (*ite > 1) out << '^' << *ite;
    out << endl;
  }
  return out;
}

int main (int argc, char **argv)
{
	cout<<setprecision(8);
	cerr<<setprecision(8);
	if (argc < 2 || argc > 3) {
		cerr << "Usage: charpoly <matrix-file-in-SMS-format> [<p>]" << endl;
		return -1;
	}

	ifstream input (argv[1]);
	if (!input) { cerr << "Error opening matrix file " << argv[1] << endl; return -1; }

	if (argc == 2) {

		PID_integer ZZ;
		DenseMatrix<PID_integer > A (ZZ);
		A.read (input);
		typedef GivPolynomialRing<PID_integer,Dense> IntPolRing;
		IntPolRing::Element c_A;
		charpoly (c_A, A);

		cout << "Characteristic Polynomial is ";
		printPolynomial (cout, ZZ, c_A) << endl;

#ifdef __LINBOX_HAVE_NTL
		cout << "Do you want a factorization (y/n) ? ";
		char tmp;
		cin >> tmp;
		if (tmp == 'y' || tmp == 'Y') {
                  commentator.start("Integer Polynomial factorization by NTL", "NTLfac");
		  vector<IntPolRing::Element*> intFactors;
		  vector<unsigned long> exp;
		  IntPolRing IPD(ZZ);
		  IPD.factor (intFactors, exp, c_A);
                  commentator.stop("done", NULL, "NTLfac");
		  printFactorization(cout << intFactors.size() << " integer polynomial factors:" << endl, ZZ, intFactors, exp) << endl;
		}
#endif
	}
	if (argc == 3) {

		typedef Modular<double> Field;
		double q = atof(argv[2]);
		Field F(q);
		DenseMatrix<Field> B (F);
		B.read (input);
		cout << "B is " << B.rowdim() << " by " << B.coldim() << endl;
		GivPolynomial<Field::Element> c_B;
		charpoly (c_B, B);
		cout << "Characteristic Polynomial is ";
		printPolynomial (cout, F, c_B) << endl;
	}

	return 0;
}
<commit_msg>added timings<commit_after>/* -*- mode: C++; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
/** \file examples/charpoly.C
\brief Characteristic polynomial of matrix over Z or Zp.
 \ingroup examples
*/

// Warning : example under development.
// integer computation must be completed
#include <iostream>
#include <iomanip>
#include "Matio.h"

#include "linbox/util/timer.h"
#include "linbox/field/modular-double.h"
#include "linbox/field/unparametric.h"
#include "linbox/blackbox/sparse.h"
#include "linbox/blackbox/blas-blackbox.h"
using namespace std;

#include "linbox/solutions/charpoly.h"
#include "linbox/ring/givaro-polynomial.h"
#include "linbox/element/givaro-polynomial.h"
using namespace LinBox;

template <class Field, class Polynomial>
std::ostream& printPolynomial (std::ostream& out, const Field &F, const Polynomial &v)
{
	for (int i = v.size () - 1; i >= 0; i--) {
		F.write (out, v[i]);
		if (i > 0)
			out << " X^" << i << " + ";
	}
	return out;
}
template <class Field, class Polynomial>
std::ostream& prettyprintIntegerPolynomial (std::ostream& out, const Field &F, const Polynomial &v)
{
  size_t n = v.size()-1;
  if (n == 0) {
    F.write(out, v[0]);
  } else {
    if(v[n] != 0) {
      if (v[n] != 1) F.write(out, v[n]) << '*';
      out << 'X';
      if (n > 1) out << '^' << n;
      for (int i = n - 1; i > 0; i--) {
	  if (v[i] != 0) {
	    if (v[i] >0) out << " + ";
	    if (v[i] != 1) F.write (out, v[i]) << '*';
	    out << 'X';
	    if (i > 1) out << '^' << i;
	  }
      }
      if (v[0] != 0) {
	if (v[0] >0) out << " + ";
	F.write(out, v[0]);
      }
    }
  }
  return out;
}
template <class Field, class Factors, class Exponents>
std::ostream& printFactorization (std::ostream& out, const Field &F, const Factors &f, const Exponents& exp)
{
  typename Factors::const_iterator itf = f.begin();
  typename Exponents::const_iterator ite = exp.begin();
  for ( ; itf != f.end(); ++itf, ++ite) {
    prettyprintIntegerPolynomial(out << '(', F, *(*itf)) << ')';
    if (*ite > 1) out << '^' << *ite;
    out << endl;
  }
  return out;
}

int main (int argc, char **argv)
{
	commentator.setMaxDetailLevel(-1);
 	cout<<setprecision(8);
	cerr<<setprecision(8);
	if (argc < 2 || argc > 3) {
		cerr << "Usage: charpoly <matrix-file-in-SMS-format> [<p>]" << endl;
		return -1;
	}

	ifstream input (argv[1]);
	if (!input) { cerr << "Error opening matrix file " << argv[1] << endl; return -1; }

	if (argc == 2) {

		PID_integer ZZ;
		DenseMatrix<PID_integer > A (ZZ);
		A.read (input);
		typedef GivPolynomialRing<PID_integer,Dense> IntPolRing;
		IntPolRing::Element c_A;

                Timer tim; tim.clear();tim.start();
                charpoly (c_A, A);
                tim.stop();

		cout << "Characteristic Polynomial is ";
		printPolynomial (cout, ZZ, c_A) << endl;
                cout << tim << endl;

#ifdef __LINBOX_HAVE_NTL
		cout << "Do you want a factorization (y/n) ? ";
		char tmp;
		cin >> tmp;
		if (tmp == 'y' || tmp == 'Y') {
                  commentator.start("Integer Polynomial factorization by NTL", "NTLfac");
		  vector<IntPolRing::Element*> intFactors;
		  vector<unsigned long> exp;
		  IntPolRing IPD(ZZ);
                  tim.start();
		  IPD.factor (intFactors, exp, c_A);
                  tim.stop();
                  commentator.stop("done", NULL, "NTLfac");
		  printFactorization(cout << intFactors.size() << " integer polynomial factors:" << endl, ZZ, intFactors, exp) << endl;
                  cout << tim << endl;

		}
#endif
	}
	if (argc == 3) {

		typedef Modular<double> Field;
		double q = atof(argv[2]);
		Field F(q);
		DenseMatrix<Field> B (F);
		B.read (input);
		cout << "B is " << B.rowdim() << " by " << B.coldim() << endl;
		GivPolynomial<Field::Element> c_B;
		charpoly (c_B, B);
		cout << "Characteristic Polynomial is ";
		printPolynomial (cout, F, c_B) << endl;
	}

	return 0;
}
<|endoftext|>


<commit_before>/* linbox/tests/test-common.C
 * Copyright (C) 2001, 2002 Bradford Hovinen
 *
 * Written by Bradford Hovinen <hovinen@cis.udel.edu>
 *
 * ========LICENCE========
 * This file is part of the library LinBox.
 *
  * LinBox 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
 * ========LICENCE========
 */

/*! @file  tests/test-common.C
 * @ingroup tests
 * @brief  no doc
 */

#ifndef __LINBOX_test_common_C
#define __LINBOX_test_common_C

#include "linbox-config.h"

#include <iostream>
#include <fstream>

#include <cmath>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <list>

#include "linbox/util/commentator.h"
#include "linbox/field/archetype.h"

#include "test-common.h"

bool isPower (LinBox::integer n, LinBox::integer m)
{
	return (n == 1) || (((n % m) == 0) && isPower (n/m, m));
}

inline double incompleteGamma (double a, double x, double tol)
{
	double xa_ex = pow (x, a) * exp (-x);
	double pi = 1.0;
	double xn = 1.0;
	double sigma = 0.0;
	double last_sigma;

	int n = 0;

	do {
		pi *= a + n;
		last_sigma = sigma;
		sigma += xn / pi;
		xn *= x;
		++n;
	} while (abs (sigma - last_sigma) >= tol) ;

	return sigma * xa_ex;
}

double chiSquaredCDF (double chi_sqr, double df)
{
	return incompleteGamma (df / 2.0, chi_sqr / 2.0, 1e-10) / exp (gamma (df / 2.0));
}
#endif // __LINBOX_test_common_C

// vim:sts=8:sw=8:ts=8:noet:sr:cino=>s,f0,{0,g0,(0,:0,t0,+0,=s
// Local Variables:
// mode: C++
// tab-width: 8
// indent-tabs-mode: nil
// c-basic-offset: 8
// End:

<commit_msg>gamma is deprecated --> lgamma instead<commit_after>/* linbox/tests/test-common.C
 * Copyright (C) 2001, 2002 Bradford Hovinen
 *
 * Written by Bradford Hovinen <hovinen@cis.udel.edu>
 *
 * ========LICENCE========
 * This file is part of the library LinBox.
 *
  * LinBox 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
 * ========LICENCE========
 */

/*! @file  tests/test-common.C
 * @ingroup tests
 * @brief  no doc
 */

#ifndef __LINBOX_test_common_C
#define __LINBOX_test_common_C

#include "linbox-config.h"

#include <iostream>
#include <fstream>

#include <cmath>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <list>

#include "linbox/util/commentator.h"
#include "linbox/field/archetype.h"

#include "test-common.h"

bool isPower (LinBox::integer n, LinBox::integer m)
{
	return (n == 1) || (((n % m) == 0) && isPower (n/m, m));
}

inline double incompleteGamma (double a, double x, double tol)
{
	double xa_ex = pow (x, a) * exp (-x);
	double pi = 1.0;
	double xn = 1.0;
	double sigma = 0.0;
	double last_sigma;

	int n = 0;

	do {
		pi *= a + n;
		last_sigma = sigma;
		sigma += xn / pi;
		xn *= x;
		++n;
	} while (abs (sigma - last_sigma) >= tol) ;

	return sigma * xa_ex;
}

double chiSquaredCDF (double chi_sqr, double df)
{
	return incompleteGamma (df / 2.0, chi_sqr / 2.0, 1e-10) / exp (lgamma (df / 2.0));
}
#endif // __LINBOX_test_common_C

// vim:sts=8:sw=8:ts=8:noet:sr:cino=>s,f0,{0,g0,(0,:0,t0,+0,=s
// Local Variables:
// mode: C++
// tab-width: 8
// indent-tabs-mode: nil
// c-basic-offset: 8
// End:

<|endoftext|>


<commit_before>/****************************************************************************

This file is part of the QtMediaHub project on http://www.gitorious.org.

Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).*
All rights reserved.

Contact:  Nokia Corporation (qt-info@nokia.com)**

You may use this file under the terms of the BSD license as follows:

"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 Nokia Corporation and its Subsidiary(-ies) nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."

****************************************************************************/

#include "staticservicebrowsermodel.h"
#include <QtGui>

StaticServiceBrowserModel::StaticServiceBrowserModel(QWidget *parent)
    : QAbstractListModel(parent)
{
    QHash<int, QByteArray> roleNames = QAbstractListModel::roleNames();
    roleNames[Qt::DisplayRole] = "display";
    roleNames[AddressRole] = "address";
    roleNames[PortRole] = "port";
    setRoleNames(roleNames);

    QString servicesFile = QDesktopServices::storageLocation(QDesktopServices::DataLocation) + "/services.conf";
    if (QFile::exists(servicesFile)) {
        initModelFromFile(servicesFile);
    } else {
        initModelFromFile(":/services.conf");
    }
    save();
}

StaticServiceBrowserModel::~StaticServiceBrowserModel()
{
}

void StaticServiceBrowserModel::initModelFromFile(const QString &fileName)
{
    QFile file(fileName);
    if (!file.open(QFile::ReadOnly)) {
        qWarning("Failed to open static services file");
        return;
    }

    QTextStream stream(&file);
    while (!stream.atEnd()) {
        QString hostName;
        stream >> hostName;
        if (hostName.startsWith('#') || hostName.isEmpty()) {
            stream.readLine();
            continue;
        }
        QString ip, port;
        stream >> ip >> port;

        addService(hostName, ip, port);
    }
}

void StaticServiceBrowserModel::addService(const QString &hostName, const QString &ip, const QString &port)
{
    QStringList list;
    list << hostName << ip << port;

    int start = m_model.count()-1 < 0 ? 0 : m_model.count()-1;
    int end = m_model.count() < 0 ? 1 : m_model.count();

    emit beginInsertRows(QModelIndex(), start, end);
    m_model.append(list);
    emit endInsertRows();

    save();
}

void StaticServiceBrowserModel::save()
{
    QString servicesFileName = QDesktopServices::storageLocation(QDesktopServices::DataLocation) + "/services.conf";
    QFile file(servicesFileName);
    file.open(QFile::WriteOnly);
    QTextStream stream(&file);
    stream << "# Static configuration file auto-created by qmh remotecontrol" << endl;
    for (int i = 0; i < m_model.count(); i++) {
        QString hostName = m_model.at(i).at(0);
        QString ip = m_model.at(i).at(1);
        QString port = m_model.at(i).at(2);
        stream << hostName << " " << ip << " " << port << endl;
    }
}

QVariant StaticServiceBrowserModel::data(const QModelIndex &index, int role) const
{
    QVariant rv;

    if (!index.isValid())
        return rv;

    if (0 <= index.row() && index.row() < m_model.count()) {
        if (role == Qt::DisplayRole)
            return m_model.at(index.row()).at(0);
        else if (role == StaticServiceBrowserModel::AddressRole)
            return m_model.at(index.row()).at(1);
        else if (role == StaticServiceBrowserModel::PortRole)
            return m_model.at(index.row()).at(2);
    }

    return rv;
}
<commit_msg>Fix beginInsertRows<commit_after>/****************************************************************************

This file is part of the QtMediaHub project on http://www.gitorious.org.

Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).*
All rights reserved.

Contact:  Nokia Corporation (qt-info@nokia.com)**

You may use this file under the terms of the BSD license as follows:

"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 Nokia Corporation and its Subsidiary(-ies) nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."

****************************************************************************/

#include "staticservicebrowsermodel.h"
#include <QtGui>

StaticServiceBrowserModel::StaticServiceBrowserModel(QWidget *parent)
    : QAbstractListModel(parent)
{
    QHash<int, QByteArray> roleNames = QAbstractListModel::roleNames();
    roleNames[Qt::DisplayRole] = "display";
    roleNames[AddressRole] = "address";
    roleNames[PortRole] = "port";
    setRoleNames(roleNames);

    QString servicesFile = QDesktopServices::storageLocation(QDesktopServices::DataLocation) + "/services.conf";
    if (QFile::exists(servicesFile)) {
        initModelFromFile(servicesFile);
    } else {
        initModelFromFile(":/services.conf");
    }
    save();
}

StaticServiceBrowserModel::~StaticServiceBrowserModel()
{
}

void StaticServiceBrowserModel::initModelFromFile(const QString &fileName)
{
    QFile file(fileName);
    if (!file.open(QFile::ReadOnly)) {
        qWarning("Failed to open static services file");
        return;
    }

    QTextStream stream(&file);
    while (!stream.atEnd()) {
        QString hostName;
        stream >> hostName;
        if (hostName.startsWith('#') || hostName.isEmpty()) {
            stream.readLine();
            continue;
        }
        QString ip, port;
        stream >> ip >> port;

        addService(hostName, ip, port);
    }
}

void StaticServiceBrowserModel::addService(const QString &hostName, const QString &ip, const QString &port)
{
    QStringList list;
    list << hostName << ip << port;

    emit beginInsertRows(QModelIndex(), m_model.count(), m_model.count());
    m_model.append(list);
    emit endInsertRows();

    save();
}

void StaticServiceBrowserModel::save()
{
    QString servicesFileName = QDesktopServices::storageLocation(QDesktopServices::DataLocation) + "/services.conf";
    QFile file(servicesFileName);
    file.open(QFile::WriteOnly);
    QTextStream stream(&file);
    stream << "# Static configuration file auto-created by qmh remotecontrol" << endl;
    for (int i = 0; i < m_model.count(); i++) {
        QString hostName = m_model.at(i).at(0);
        QString ip = m_model.at(i).at(1);
        QString port = m_model.at(i).at(2);
        stream << hostName << " " << ip << " " << port << endl;
    }
}

QVariant StaticServiceBrowserModel::data(const QModelIndex &index, int role) const
{
    QVariant rv;

    if (!index.isValid())
        return rv;

    if (0 <= index.row() && index.row() < m_model.count()) {
        if (role == Qt::DisplayRole)
            return m_model.at(index.row()).at(0);
        else if (role == StaticServiceBrowserModel::AddressRole)
            return m_model.at(index.row()).at(1);
        else if (role == StaticServiceBrowserModel::PortRole)
            return m_model.at(index.row()).at(2);
    }

    return rv;
}
<|endoftext|>


<commit_before>#include "Ucodei.h"
#include "Label.h"
#include "UcodeiStack.h"
#include "ArithmeticLogicUnit.h"
#include "Interpret.h"

Interpret::Interpret() : sysStack(STACKSIZE), memStack(STACKSIZE)
{
  arBase = 4;
  tcycle = 0;
  exeCount = 0 ;
}

int Interpret::findAddr(int n)
{
  int temp;

  if (!instrBuf[n].value1)
    errmsg("findAddr()", "Lexical level is zero ...");
  else if (instrBuf[n].value2 < 1)
    errmsg("findAddr()", "Negative offset ...");

  for (temp = arBase; instrBuf[n].value1 != sysStack[temp+3]; temp = sysStack[temp]) {
    if ((temp > STACKSIZE) || (temp < 0 ))
      cout << "Lexical level :  " << instrBuf[n].value1 << ' '
           << "Offset        :  " << instrBuf[n].value2 << '\n';
  }

  return (temp + instrBuf[n].value2 + 3);
}

void Interpret::predefinedProc(int procIndex)
{
  int data, temp;

  // read
  if (procIndex == READPROC) {
    /*
    char dataFileName[20];
    static ifstream dataFile;
    static int readFirst = TRUE;
    if (readFirst) {
      cout << "\nEnter Data File Name : ";
      cin >> dataFileName;
      dataFile.open(dataFileName, ios::in);
      if (dataFileName == NULL)
        errmsg("checkPredefined()", "Data file open error ...");
      readFirst = FALSE;
    }
    dataFile >> data;
    */
    cin >> data;
    temp = memStack.pop();
    sysStack[temp] = data;
    //sysStack.spSet(sysStack.top()-4);
  } else if (procIndex == WRITEPROC) { // write
    //temp = memStack[memStack.pop()];
    temp = memStack.pop();
    cout << ' ' << temp;
    outputFile << ' ' << temp;
    //sysStack.spSet(sysStack.top()-4);
  } else if (procIndex == LFPROC) { // lf : line feed
    outputFile.put('\n');
    cout << "\n";
  }
}

void Interpret::statistic()
{
  int i, opcode;

  outputFile << "\n\n   **********************\n\n";
  outputFile << "\n\n\n                 " << "#### Statistics ####\n";
  outputFile << "\n\n    ****  Static Instruction Counts  ****\n\n\n";
  for (i=0, opcode = notop ; opcode <= none; opcode++) {
    if ( staticCnt[opcode] != 0) {
      outputFile.width(5);
      outputFile.setf(ios::left, ios::adjustfield);
      outputFile << opcodeName[opcode] <<  "  =  " ;
      outputFile.width(5);
      outputFile.setf(ios::left, ios::adjustfield);
      outputFile <<  staticCnt[opcode] << "   ";
      i++;
      if (i % 4 == 0) outputFile.put('\n');
    }
  }
  outputFile << "\n\n\n  ****  Dynamic instruction counts  ****\n\n\n";
  for (i=0, opcode = notop ; opcode <= none; opcode++) {
    if (dynamicCnt[opcode] != 0) {
      outputFile.width(5);
      outputFile.setf(ios::left, ios::adjustfield);
      outputFile << opcodeName[opcode] << "  =  " ;
      outputFile.width(8);
      outputFile.setf(ios::left, ios::adjustfield);
      outputFile << dynamicCnt[opcode] << "  " ;
      i++;
      if ( i % 4 == 0) outputFile << "\n";
    }
  }
  outputFile << "\n\n Executable instruction count  =   " << exeCount;
  outputFile << "\n\n Total execution cycle         =   " << tcycle;
  outputFile << "\n";
}

void Interpret::execute(int startAddr)
{
  int parms;
  int temp, temp1;
  int pc;
  // int returnAddress;

  pc = startAddr;
  cout << " == Executing ...  ==\n";
  cout << " == Result         ==\n";
  while (pc >= 0) {
    // Instruction Register
    Instruction ir = instrBuf[pc];

    // 명령어당 사용량
    // 디버깅용 총 사이클수(소모된 클럭수) 측정용
    dynamicCnt[ir.opcode]++;
    if (executable[ir.opcode]) exeCount++;
    tcycle = opcodeCycle[ir.opcode];

    //cout << opcodeName[ir.opcode] << "  = " << memStack.top() << endl;
    // instruction execution
    switch(ir.opcode) {
      case call:
        if ((temp = ir.value1) < 0) {
          // call assembly functions
          predefinedProc(temp);
          // jump return address
          //memStack.restore();
          //pc = memStack.pop();
        } else {
          // return base address
          memStack.push(pc + 1);
          //memStack.store();
          // 이 부분이 실제로 함수 코드로 점프하는 부분
          pc = ir.value1 - 1;
          arBase = sysStack.top() + 1;
          /*
          // param : func parameter stack pointer
          // set up param value in `ldp` inst
          sysStack[parms+2] = pc + 1; // return base address

          // linked list 방식으로 관리중인 before pointer 셋팅
          sysStack[parms+1] = arBase; // func stack information
          arBase = parms; // next func call index

          // 이 부분이 실제로 함수 코드로 점프하는 부분
          pc = ir.value1 - 1; // pc = func code address
          */
        }
        break;
      case proc:
        // value 1: block number(base)
        // value 2: static level => lexical level (static chain)
        // 함수에서 사용 할 메모리 공간 확보
        sysStack.spSet(arBase + 3);
        // 함수에서 사용하는 메모리 공간의 고유 키값 셋팅 : block number
        // 만약 이 값이 서로 같은 함수가 존재한다면 서로의 공간을 공유한다.
        sysStack[arBase+3] = ir.value1;

        /*
        // lexical level : innerBlock 을 처리하기위한 용도로 현재 쓰이진 않음
        for (temp = sysStack[arBase+1];
             sysStack[temp+3] != ir.value2 -1;
             temp = sysStack[temp]);
        // innerBlock 을 처리하기 위한 부모 Block Address
        // 이 또한 내부적으로 linked list 자료구조를 사용
        sysStack[arBase] = temp;
        */
        break;
      /*
      case ldp:
        // 함수 정보 저장용 공간 4칸 확보
        parms = sysStack.top() + 1;
        sysStack.spSet(sysStack.top()+4);
        break;
      */
      case retv:
        temp = memStack.pop();
      case ret:
        /*
        sysStack.spSet(arBase - 1);
        if (ir.opcode == retv)
          sysStack.push(temp);
        pc = sysStack[arBase+2] - 1;
        arBase = sysStack[arBase+1];
        */
        //memStack.restore();
        pc = memStack.pop();
        if (ir.opcode == retv)
          memStack.push(temp);
        break;
      /*
      case stp:
        returnAddress = sysStack[arBase+2] - 1;
        sysStack.spSet(arBase - 1);
        arBase = sysStack[arBase  1];
        break;
      case ret:
        pc = returnAddress;
        break;
      */
      case sym:
        // 함수에서 사용할 메모리 공간 확보
        sysStack.spSet(sysStack.top() + ir.value2);
        //ir.value1 // block number
        //ir.value2 // size
        break;

      // Arithmetic Logical Unit
      case add:
      case sub:
      case divop:
      case modop:
      case mult:
      case andop:
      case orop:
        alu.setReg2(memStack.pop());
        alu.setReg1(memStack.pop());
        memStack.push(alu.execute(ir.opcode));
        break;
      case neg:
      case notop:
      case incop:
      case decop:
        alu.setReg1(memStack.pop());
        memStack.push(alu.execute(ir.opcode));
        break;

      case lod:
        memStack.push(sysStack[findAddr(pc)]);
        break;
      case lda:
        memStack.push(findAddr(pc));
        break;
      case str:
        sysStack[findAddr(pc)] = memStack.pop();
        break;
      case ldi:
        if ((memStack.top() <= 0) || (memStack.top() > STACKSIZE))
          errmsg("execute()", "Illegal ldi instruction ...");
        temp = memStack.pop();
        memStack.push(sysStack[temp]);
        break;
      case sti:
        temp = memStack.pop();
        sysStack[memStack.pop()] = temp;
        break;

      case ldc:
        memStack.push(ir.value1);
        break;
      case gt:
        temp = memStack.pop();
        memStack.push(memStack.pop()>temp);
        break;
      case lt:
        temp = memStack.pop();
        memStack.push(memStack.pop()<temp);
        break;
      case ge:
        temp = memStack.pop();
        memStack.push(memStack.pop()>=temp);
        break;
      case le:
        temp = memStack.pop();
        memStack.push(memStack.pop()<=temp);
        break;
      case eq:
        temp = memStack.pop();
        memStack.push(memStack.pop()==temp);
        break;
      case ne:
        temp = memStack.pop();
        memStack.push(memStack.pop()!=temp);
        break;
      case ujp:
        pc = ir.value1 - 1;
        break;
      case tjp:
        if (memStack.pop()) pc = ir.value1 - 1;
        break;
      case fjp:
        if (!memStack.pop()) pc = ir.value1 - 1;
        break;
      case endop:
        pc = -2;
        break;
      case bgn:
        sysStack.spSet(sysStack.top() + ir.value1);
        break;
      case nop:
        break;
    }
    pc++;
  }
  cout << '\n';
  statistic();
}<commit_msg>remove instruction of ldp and old unneeded<commit_after>#include "Ucodei.h"
#include "Label.h"
#include "UcodeiStack.h"
#include "ArithmeticLogicUnit.h"
#include "Interpret.h"

Interpret::Interpret() : sysStack(STACKSIZE), memStack(STACKSIZE)
{
  arBase = 4;
  tcycle = 0;
  exeCount = 0 ;
}

int Interpret::findAddr(int n)
{
  int temp;

  if (!instrBuf[n].value1)
    errmsg("findAddr()", "Lexical level is zero ...");
  else if (instrBuf[n].value2 < 1)
    errmsg("findAddr()", "Negative offset ...");

  for (temp = arBase; instrBuf[n].value1 != sysStack[temp+3]; temp = sysStack[temp]) {
    if ((temp > STACKSIZE) || (temp < 0 ))
      cout << "Lexical level :  " << instrBuf[n].value1 << ' '
           << "Offset        :  " << instrBuf[n].value2 << '\n';
  }

  return (temp + instrBuf[n].value2 + 3);
}

void Interpret::predefinedProc(int procIndex)
{
  int data, temp;

  // read
  if (procIndex == READPROC) {
    cin >> data;
    temp = memStack.pop();
    sysStack[temp] = data;
  } else if (procIndex == WRITEPROC) { // write
    temp = memStack.pop();
    cout << ' ' << temp;
    outputFile << ' ' << temp;
  } else if (procIndex == LFPROC) { // lf : line feed
    outputFile.put('\n');
    cout << "\n";
  }
}

void Interpret::statistic()
{
  int i, opcode;

  outputFile << "\n\n   **********************\n\n";
  outputFile << "\n\n\n                 " << "#### Statistics ####\n";
  outputFile << "\n\n    ****  Static Instruction Counts  ****\n\n\n";
  for (i=0, opcode = notop ; opcode <= none; opcode++) {
    if ( staticCnt[opcode] != 0) {
      outputFile.width(5);
      outputFile.setf(ios::left, ios::adjustfield);
      outputFile << opcodeName[opcode] <<  "  =  " ;
      outputFile.width(5);
      outputFile.setf(ios::left, ios::adjustfield);
      outputFile <<  staticCnt[opcode] << "   ";
      i++;
      if (i % 4 == 0) outputFile.put('\n');
    }
  }
  outputFile << "\n\n\n  ****  Dynamic instruction counts  ****\n\n\n";
  for (i=0, opcode = notop ; opcode <= none; opcode++) {
    if (dynamicCnt[opcode] != 0) {
      outputFile.width(5);
      outputFile.setf(ios::left, ios::adjustfield);
      outputFile << opcodeName[opcode] << "  =  " ;
      outputFile.width(8);
      outputFile.setf(ios::left, ios::adjustfield);
      outputFile << dynamicCnt[opcode] << "  " ;
      i++;
      if ( i % 4 == 0) outputFile << "\n";
    }
  }
  outputFile << "\n\n Executable instruction count  =   " << exeCount;
  outputFile << "\n\n Total execution cycle         =   " << tcycle;
  outputFile << "\n";
}

void Interpret::execute(int startAddr)
{
  int parms;
  int temp, temp1;
  int pc;
  // int returnAddress;

  pc = startAddr;
  cout << " == Executing ...  ==\n";
  cout << " == Result         ==\n";
  while (pc >= 0) {
    // Instruction Register
    Instruction ir = instrBuf[pc];

    // 명령어당 사용량
    // 디버깅용 총 사이클수(소모된 클럭수) 측정용
    dynamicCnt[ir.opcode]++;
    if (executable[ir.opcode]) exeCount++;
    tcycle = opcodeCycle[ir.opcode];

    //cout << opcodeName[ir.opcode] << "  = " << memStack.top() << endl;
    // instruction execution
    switch(ir.opcode) {
      case call:
        if ((temp = ir.value1) < 0) {
          // call assembly functions
          predefinedProc(temp);
          // jump return address
          //memStack.restore();
          //pc = memStack.pop();
        } else {
          // return base address
          memStack.push(pc + 1);
          //memStack.store();
          // 이 부분이 실제로 함수 코드로 점프하는 부분
          pc = ir.value1 - 1;
          arBase = sysStack.top() + 1;
        }
        break;
      case proc:
        // value 1: block number(base)
        // value 2: static level => lexical level (static chain)
        // 함수에서 사용 할 메모리 공간 확보
        sysStack.spSet(arBase + 3);
        // 함수에서 사용하는 메모리 공간의 고유 키값 셋팅 : block number
        // 만약 이 값이 서로 같은 함수가 존재한다면 서로의 공간을 공유한다.
        sysStack[arBase+3] = ir.value1;
        break;
      case retv:
        temp = memStack.pop();
      case ret:
        //memStack.restore();
        pc = memStack.pop();
        if (ir.opcode == retv)
          memStack.push(temp);
        break;
      case sym:
        // 함수에서 사용할 메모리 공간 확보
        sysStack.spSet(sysStack.top() + ir.value2);
        //ir.value1 // block number
        //ir.value2 // size
        break;

      // Arithmetic Logical Unit
      case add:
      case sub:
      case divop:
      case modop:
      case mult:
      case andop:
      case orop:
        alu.setReg2(memStack.pop());
        alu.setReg1(memStack.pop());
        memStack.push(alu.execute(ir.opcode));
        break;
      case neg:
      case notop:
      case incop:
      case decop:
        alu.setReg1(memStack.pop());
        memStack.push(alu.execute(ir.opcode));
        break;

      case lod:
        memStack.push(sysStack[findAddr(pc)]);
        break;
      case lda:
        memStack.push(findAddr(pc));
        break;
      case str:
        sysStack[findAddr(pc)] = memStack.pop();
        break;
      case ldi:
        if ((memStack.top() <= 0) || (memStack.top() > STACKSIZE))
          errmsg("execute()", "Illegal ldi instruction ...");
        temp = memStack.pop();
        memStack.push(sysStack[temp]);
        break;
      case sti:
        temp = memStack.pop();
        sysStack[memStack.pop()] = temp;
        break;

      case ldc:
        memStack.push(ir.value1);
        break;
      case gt:
        temp = memStack.pop();
        memStack.push(memStack.pop()>temp);
        break;
      case lt:
        temp = memStack.pop();
        memStack.push(memStack.pop()<temp);
        break;
      case ge:
        temp = memStack.pop();
        memStack.push(memStack.pop()>=temp);
        break;
      case le:
        temp = memStack.pop();
        memStack.push(memStack.pop()<=temp);
        break;
      case eq:
        temp = memStack.pop();
        memStack.push(memStack.pop()==temp);
        break;
      case ne:
        temp = memStack.pop();
        memStack.push(memStack.pop()!=temp);
        break;
      case ujp:
        pc = ir.value1 - 1;
        break;
      case tjp:
        if (memStack.pop()) pc = ir.value1 - 1;
        break;
      case fjp:
        if (!memStack.pop()) pc = ir.value1 - 1;
        break;

      case endop:
        pc = -2;
        break;
      case bgn:
        sysStack.spSet(sysStack.top() + ir.value1);
        break;
      case nop:
        break;
    }
    pc++;
  }
  cout << '\n';
  statistic();
}<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include <stdio.h>

#include <string>

#include "after_initialization_fixture.h"
#include "test/testsupport/fileutils.h"

namespace webrtc {
namespace {

const int16_t kLimiterHeadroom = 29204;  // == -1 dbFS
const int16_t kInt16Max = 0x7fff;
const int kSampleRateHz = 16000;
const int kTestDurationMs = 3000;
const int kSkipOutputMs = 500;

}  // namespace

class MixingTest : public AfterInitializationFixture {
 protected:
  MixingTest()
    : input_filename_(test::OutputPath() + "mixing_test_input.pcm"),
      output_filename_(test::OutputPath() + "mixing_test_output.pcm") {
  }

  // Creates and mixes |num_remote_streams| which play a file "as microphone"
  // with |num_local_streams| which play a file "locally", using a constant
  // amplitude of |input_value|. The local streams manifest as "anonymous"
  // mixing participants, meaning they will be mixed regardless of the number
  // of participants. (A stream is a VoiceEngine "channel").
  //
  // The mixed output is verified to always fall between |max_output_value| and
  // |min_output_value|, after a startup phase.
  //
  // |num_remote_streams_using_mono| of the remote streams use mono, with the
  // remainder using stereo.
  void RunMixingTest(int num_remote_streams,
                     int num_local_streams,
                     int num_remote_streams_using_mono,
                     int16_t input_value,
                     int16_t max_output_value,
                     int16_t min_output_value) {
    ASSERT_LE(num_remote_streams_using_mono, num_remote_streams);

    GenerateInputFile(input_value);

    std::vector<int> local_streams(num_local_streams);
    for (size_t i = 0; i < local_streams.size(); ++i) {
      local_streams[i] = voe_base_->CreateChannel();
      EXPECT_NE(-1, local_streams[i]);
    }
    StartLocalStreams(local_streams);
    TEST_LOG("Playing %d local streams.\n", num_local_streams);

    std::vector<int> remote_streams(num_remote_streams);
    for (size_t i = 0; i < remote_streams.size(); ++i) {
      remote_streams[i] = voe_base_->CreateChannel();
      EXPECT_NE(-1, remote_streams[i]);
    }
    StartRemoteStreams(remote_streams, num_remote_streams_using_mono);
    TEST_LOG("Playing %d remote streams.\n", num_remote_streams);

    // Start recording the mixed output and wait.
    EXPECT_EQ(0, voe_file_->StartRecordingPlayout(-1 /* record meeting */,
        output_filename_.c_str()));
    Sleep(kTestDurationMs);
    EXPECT_EQ(0, voe_file_->StopRecordingPlayout(-1));

    StopLocalStreams(local_streams);
    StopRemoteStreams(remote_streams);

    VerifyMixedOutput(max_output_value, min_output_value);
  }

 private:
  // Generate input file with constant values equal to |input_value|. The file
  // will be one second longer than the duration of the test.
  void GenerateInputFile(int16_t input_value) {
    FILE* input_file = fopen(input_filename_.c_str(), "wb");
    ASSERT_TRUE(input_file != NULL);
    for (int i = 0; i < kSampleRateHz / 1000 * (kTestDurationMs + 1000); i++) {
      ASSERT_EQ(1u, fwrite(&input_value, sizeof(input_value), 1, input_file));
    }
    ASSERT_EQ(0, fclose(input_file));
  }

  void VerifyMixedOutput(int16_t max_output_value, int16_t min_output_value) {
    // Verify the mixed output.
    FILE* output_file = fopen(output_filename_.c_str(), "rb");
    ASSERT_TRUE(output_file != NULL);
    int16_t output_value = 0;
    // Skip the first segment to avoid initialization and ramping-in effects.
    EXPECT_EQ(0, fseek(output_file, sizeof(output_value) *
                       kSampleRateHz / 1000 * kSkipOutputMs, SEEK_SET));
    int samples_read = 0;
    while (fread(&output_value, sizeof(output_value), 1, output_file) == 1) {
      samples_read++;
      std::ostringstream trace_stream;
      trace_stream << samples_read << " samples read";
      SCOPED_TRACE(trace_stream.str());
      EXPECT_LE(output_value, max_output_value);
      EXPECT_GE(output_value, min_output_value);
    }
    // Ensure the recording length is close to the duration of the test.
    // We have to use a relaxed tolerance here due to filesystem flakiness on
    // the bots.
    ASSERT_GE((samples_read * 1000.0) / kSampleRateHz,
              0.7 * (kTestDurationMs - kSkipOutputMs));
    // Ensure we read the entire file.
    ASSERT_NE(0, feof(output_file));
    ASSERT_EQ(0, fclose(output_file));
  }

  // Start up local streams ("anonymous" participants).
  void StartLocalStreams(const std::vector<int>& streams) {
    for (size_t i = 0; i < streams.size(); ++i) {
      EXPECT_EQ(0, voe_base_->StartPlayout(streams[i]));
      EXPECT_EQ(0, voe_file_->StartPlayingFileLocally(streams[i],
          input_filename_.c_str(), true));
    }
  }

  void StopLocalStreams(const std::vector<int>& streams) {
    for (size_t i = 0; i < streams.size(); ++i) {
      EXPECT_EQ(0, voe_base_->StopPlayout(streams[i]));
      EXPECT_EQ(0, voe_base_->DeleteChannel(streams[i]));
    }
  }

  // Start up remote streams ("normal" participants).
  void StartRemoteStreams(const std::vector<int>& streams,
                          int num_remote_streams_using_mono) {
    // Use L16 at 16kHz to minimize distortion (file recording is 16kHz and
    // resampling will cause distortion).
    CodecInst codec_inst;
    strcpy(codec_inst.plname, "L16");
    codec_inst.channels = 1;
    codec_inst.plfreq = kSampleRateHz;
    codec_inst.pltype = 105;
    codec_inst.pacsize = codec_inst.plfreq / 100;
    codec_inst.rate = codec_inst.plfreq * sizeof(int16_t) * 8;  // 8 bits/byte.

    for (int i = 0; i < num_remote_streams_using_mono; ++i) {
      StartRemoteStream(streams[i], codec_inst, 1234 + 2 * i);
    }

    // The remainder of the streams will use stereo.
    codec_inst.channels = 2;
    codec_inst.pltype++;
    for (size_t i = num_remote_streams_using_mono; i < streams.size(); ++i) {
      StartRemoteStream(streams[i], codec_inst, 1234 + 2 * i);
    }
  }

  // Start up a single remote stream.
  void StartRemoteStream(int stream, const CodecInst& codec_inst, int port) {
    EXPECT_EQ(0, voe_codec_->SetRecPayloadType(stream, codec_inst));
    EXPECT_EQ(0, voe_base_->SetLocalReceiver(stream, port));
    EXPECT_EQ(0, voe_base_->SetSendDestination(stream, port, "127.0.0.1"));
    EXPECT_EQ(0, voe_base_->StartReceive(stream));
    EXPECT_EQ(0, voe_base_->StartPlayout(stream));
    EXPECT_EQ(0, voe_codec_->SetSendCodec(stream, codec_inst));
    EXPECT_EQ(0, voe_base_->StartSend(stream));
    EXPECT_EQ(0, voe_file_->StartPlayingFileAsMicrophone(stream,
        input_filename_.c_str(), true));
  }

  void StopRemoteStreams(const std::vector<int>& streams) {
    for (size_t i = 0; i < streams.size(); ++i) {
      EXPECT_EQ(0, voe_base_->StopSend(streams[i]));
      EXPECT_EQ(0, voe_base_->StopPlayout(streams[i]));
      EXPECT_EQ(0, voe_base_->StopReceive(streams[i]));
      EXPECT_EQ(0, voe_base_->DeleteChannel(streams[i]));
    }
  }

  const std::string input_filename_;
  const std::string output_filename_;
};

// These tests assume a maximum of three mixed participants. We typically allow
// a +/- 15% range around the expected output level to account for distortion
// from coding and processing in the loopback chain.
TEST_F(MixingTest, FourChannelsWithOnlyThreeMixed) {
  const int16_t kInputValue = 1000;
  const int16_t kExpectedOutput = kInputValue * 3;
  RunMixingTest(4, 0, 4, kInputValue, 1.15 * kExpectedOutput,
                0.85 * kExpectedOutput);
}

// Ensure the mixing saturation protection is working. We can do this because
// the mixing limiter is given some headroom, so the expected output is less
// than full scale.
TEST_F(MixingTest, VerifySaturationProtection) {
  const int16_t kInputValue = 20000;
  const int16_t kExpectedOutput = kLimiterHeadroom;
  // If this isn't satisfied, we're not testing anything.
  ASSERT_GT(kInputValue * 3, kInt16Max);
  ASSERT_LT(1.1 * kExpectedOutput, kInt16Max);
  RunMixingTest(3, 0, 3, kInputValue, 1.15 * kExpectedOutput,
               0.85 * kExpectedOutput);
}

TEST_F(MixingTest, SaturationProtectionHasNoEffectOnOneChannel) {
  const int16_t kInputValue = kInt16Max;
  const int16_t kExpectedOutput = kInt16Max;
  // If this isn't satisfied, we're not testing anything.
  ASSERT_GT(0.95 * kExpectedOutput, kLimiterHeadroom);
  // Tighter constraints are required here to properly test this.
  RunMixingTest(1, 0, 1, kInputValue, kExpectedOutput,
                0.95 * kExpectedOutput);
}

TEST_F(MixingTest, VerifyAnonymousAndNormalParticipantMixing) {
  const int16_t kInputValue = 1000;
  const int16_t kExpectedOutput = kInputValue * 2;
  RunMixingTest(1, 1, 1, kInputValue, 1.15 * kExpectedOutput,
                0.85 * kExpectedOutput);
}

TEST_F(MixingTest, AnonymousParticipantsAreAlwaysMixed) {
  const int16_t kInputValue = 1000;
  const int16_t kExpectedOutput = kInputValue * 4;
  RunMixingTest(3, 1, 3, kInputValue, 1.15 * kExpectedOutput,
                0.85 * kExpectedOutput);
}

TEST_F(MixingTest, VerifyStereoAndMonoMixing) {
  const int16_t kInputValue = 1000;
  const int16_t kExpectedOutput = kInputValue * 2;
  RunMixingTest(2, 0, 1, kInputValue, 1.15 * kExpectedOutput,
                0.85 * kExpectedOutput);
}

}  // namespace webrtc
<commit_msg>Fix implicit conversion error in mixing test.<commit_after>/*
 *  Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include <stdio.h>

#include <string>

#include "after_initialization_fixture.h"
#include "test/testsupport/fileutils.h"

namespace webrtc {
namespace {

const int16_t kLimiterHeadroom = 29204;  // == -1 dbFS
const int16_t kInt16Max = 0x7fff;
const int kSampleRateHz = 16000;
const int kTestDurationMs = 3000;
const int kSkipOutputMs = 500;

}  // namespace

class MixingTest : public AfterInitializationFixture {
 protected:
  MixingTest()
    : input_filename_(test::OutputPath() + "mixing_test_input.pcm"),
      output_filename_(test::OutputPath() + "mixing_test_output.pcm") {
  }

  // Creates and mixes |num_remote_streams| which play a file "as microphone"
  // with |num_local_streams| which play a file "locally", using a constant
  // amplitude of |input_value|. The local streams manifest as "anonymous"
  // mixing participants, meaning they will be mixed regardless of the number
  // of participants. (A stream is a VoiceEngine "channel").
  //
  // The mixed output is verified to always fall between |max_output_value| and
  // |min_output_value|, after a startup phase.
  //
  // |num_remote_streams_using_mono| of the remote streams use mono, with the
  // remainder using stereo.
  void RunMixingTest(int num_remote_streams,
                     int num_local_streams,
                     int num_remote_streams_using_mono,
                     int16_t input_value,
                     int16_t max_output_value,
                     int16_t min_output_value) {
    ASSERT_LE(num_remote_streams_using_mono, num_remote_streams);

    GenerateInputFile(input_value);

    std::vector<int> local_streams(num_local_streams);
    for (size_t i = 0; i < local_streams.size(); ++i) {
      local_streams[i] = voe_base_->CreateChannel();
      EXPECT_NE(-1, local_streams[i]);
    }
    StartLocalStreams(local_streams);
    TEST_LOG("Playing %d local streams.\n", num_local_streams);

    std::vector<int> remote_streams(num_remote_streams);
    for (size_t i = 0; i < remote_streams.size(); ++i) {
      remote_streams[i] = voe_base_->CreateChannel();
      EXPECT_NE(-1, remote_streams[i]);
    }
    StartRemoteStreams(remote_streams, num_remote_streams_using_mono);
    TEST_LOG("Playing %d remote streams.\n", num_remote_streams);

    // Start recording the mixed output and wait.
    EXPECT_EQ(0, voe_file_->StartRecordingPlayout(-1 /* record meeting */,
        output_filename_.c_str()));
    Sleep(kTestDurationMs);
    EXPECT_EQ(0, voe_file_->StopRecordingPlayout(-1));

    StopLocalStreams(local_streams);
    StopRemoteStreams(remote_streams);

    VerifyMixedOutput(max_output_value, min_output_value);
  }

 private:
  // Generate input file with constant values equal to |input_value|. The file
  // will be one second longer than the duration of the test.
  void GenerateInputFile(int16_t input_value) {
    FILE* input_file = fopen(input_filename_.c_str(), "wb");
    ASSERT_TRUE(input_file != NULL);
    for (int i = 0; i < kSampleRateHz / 1000 * (kTestDurationMs + 1000); i++) {
      ASSERT_EQ(1u, fwrite(&input_value, sizeof(input_value), 1, input_file));
    }
    ASSERT_EQ(0, fclose(input_file));
  }

  void VerifyMixedOutput(int16_t max_output_value, int16_t min_output_value) {
    // Verify the mixed output.
    FILE* output_file = fopen(output_filename_.c_str(), "rb");
    ASSERT_TRUE(output_file != NULL);
    int16_t output_value = 0;
    // Skip the first segment to avoid initialization and ramping-in effects.
    EXPECT_EQ(0, fseek(output_file, sizeof(output_value) *
                       kSampleRateHz / 1000 * kSkipOutputMs, SEEK_SET));
    int samples_read = 0;
    while (fread(&output_value, sizeof(output_value), 1, output_file) == 1) {
      samples_read++;
      std::ostringstream trace_stream;
      trace_stream << samples_read << " samples read";
      SCOPED_TRACE(trace_stream.str());
      EXPECT_LE(output_value, max_output_value);
      EXPECT_GE(output_value, min_output_value);
    }
    // Ensure the recording length is close to the duration of the test.
    // We have to use a relaxed tolerance here due to filesystem flakiness on
    // the bots.
    ASSERT_GE((samples_read * 1000.0) / kSampleRateHz,
              0.7 * (kTestDurationMs - kSkipOutputMs));
    // Ensure we read the entire file.
    ASSERT_NE(0, feof(output_file));
    ASSERT_EQ(0, fclose(output_file));
  }

  // Start up local streams ("anonymous" participants).
  void StartLocalStreams(const std::vector<int>& streams) {
    for (size_t i = 0; i < streams.size(); ++i) {
      EXPECT_EQ(0, voe_base_->StartPlayout(streams[i]));
      EXPECT_EQ(0, voe_file_->StartPlayingFileLocally(streams[i],
          input_filename_.c_str(), true));
    }
  }

  void StopLocalStreams(const std::vector<int>& streams) {
    for (size_t i = 0; i < streams.size(); ++i) {
      EXPECT_EQ(0, voe_base_->StopPlayout(streams[i]));
      EXPECT_EQ(0, voe_base_->DeleteChannel(streams[i]));
    }
  }

  // Start up remote streams ("normal" participants).
  void StartRemoteStreams(const std::vector<int>& streams,
                          int num_remote_streams_using_mono) {
    // Use L16 at 16kHz to minimize distortion (file recording is 16kHz and
    // resampling will cause distortion).
    CodecInst codec_inst;
    strcpy(codec_inst.plname, "L16");
    codec_inst.channels = 1;
    codec_inst.plfreq = kSampleRateHz;
    codec_inst.pltype = 105;
    codec_inst.pacsize = codec_inst.plfreq / 100;
    codec_inst.rate = codec_inst.plfreq * sizeof(int16_t) * 8;  // 8 bits/byte.

    for (int i = 0; i < num_remote_streams_using_mono; ++i) {
      StartRemoteStream(streams[i], codec_inst, 1234 + 2 * i);
    }

    // The remainder of the streams will use stereo.
    codec_inst.channels = 2;
    codec_inst.pltype++;
    for (size_t i = num_remote_streams_using_mono; i < streams.size(); ++i) {
      StartRemoteStream(streams[i], codec_inst, 1234 + 2 * i);
    }
  }

  // Start up a single remote stream.
  void StartRemoteStream(int stream, const CodecInst& codec_inst, int port) {
    EXPECT_EQ(0, voe_codec_->SetRecPayloadType(stream, codec_inst));
    EXPECT_EQ(0, voe_base_->SetLocalReceiver(stream, port));
    EXPECT_EQ(0, voe_base_->SetSendDestination(stream, port, "127.0.0.1"));
    EXPECT_EQ(0, voe_base_->StartReceive(stream));
    EXPECT_EQ(0, voe_base_->StartPlayout(stream));
    EXPECT_EQ(0, voe_codec_->SetSendCodec(stream, codec_inst));
    EXPECT_EQ(0, voe_base_->StartSend(stream));
    EXPECT_EQ(0, voe_file_->StartPlayingFileAsMicrophone(stream,
        input_filename_.c_str(), true));
  }

  void StopRemoteStreams(const std::vector<int>& streams) {
    for (size_t i = 0; i < streams.size(); ++i) {
      EXPECT_EQ(0, voe_base_->StopSend(streams[i]));
      EXPECT_EQ(0, voe_base_->StopPlayout(streams[i]));
      EXPECT_EQ(0, voe_base_->StopReceive(streams[i]));
      EXPECT_EQ(0, voe_base_->DeleteChannel(streams[i]));
    }
  }

  const std::string input_filename_;
  const std::string output_filename_;
};

// These tests assume a maximum of three mixed participants. We typically allow
// a +/- 15% range around the expected output level to account for distortion
// from coding and processing in the loopback chain.
TEST_F(MixingTest, FourChannelsWithOnlyThreeMixed) {
  const int16_t kInputValue = 1000;
  const int16_t kExpectedOutput = kInputValue * 3;
  RunMixingTest(4, 0, 4, kInputValue,
                static_cast<int16_t>(1.15 * kExpectedOutput),
                static_cast<int16_t>(0.85 * kExpectedOutput));
}

// Ensure the mixing saturation protection is working. We can do this because
// the mixing limiter is given some headroom, so the expected output is less
// than full scale.
TEST_F(MixingTest, VerifySaturationProtection) {
  const int16_t kInputValue = 20000;
  const int16_t kExpectedOutput = kLimiterHeadroom;
  // If this isn't satisfied, we're not testing anything.
  ASSERT_GT(kInputValue * 3, kInt16Max);
  ASSERT_LT(1.1 * kExpectedOutput, kInt16Max);
  RunMixingTest(3, 0, 3, kInputValue,
                static_cast<int16_t>(1.15 * kExpectedOutput),
                static_cast<int16_t>(0.85 * kExpectedOutput));
}

TEST_F(MixingTest, SaturationProtectionHasNoEffectOnOneChannel) {
  const int16_t kInputValue = kInt16Max;
  const int16_t kExpectedOutput = kInt16Max;
  // If this isn't satisfied, we're not testing anything.
  ASSERT_GT(0.95 * kExpectedOutput, kLimiterHeadroom);
  // Tighter constraints are required here to properly test this.
  RunMixingTest(1, 0, 1, kInputValue, kExpectedOutput,
                static_cast<int16_t>(0.95 * kExpectedOutput));
}

TEST_F(MixingTest, VerifyAnonymousAndNormalParticipantMixing) {
  const int16_t kInputValue = 1000;
  const int16_t kExpectedOutput = kInputValue * 2;
  RunMixingTest(1, 1, 1, kInputValue,
                static_cast<int16_t>(1.15 * kExpectedOutput),
                static_cast<int16_t>(0.85 * kExpectedOutput));
}

TEST_F(MixingTest, AnonymousParticipantsAreAlwaysMixed) {
  const int16_t kInputValue = 1000;
  const int16_t kExpectedOutput = kInputValue * 4;
  RunMixingTest(3, 1, 3, kInputValue,
                static_cast<int16_t>(1.15 * kExpectedOutput),
                static_cast<int16_t>(0.85 * kExpectedOutput));
}

TEST_F(MixingTest, VerifyStereoAndMonoMixing) {
  const int16_t kInputValue = 1000;
  const int16_t kExpectedOutput = kInputValue * 2;
  RunMixingTest(2, 0, 1, kInputValue,
                static_cast<int16_t>(1.15 * kExpectedOutput),
                static_cast<int16_t>(0.85 * kExpectedOutput));
}

}  // namespace webrtc
<|endoftext|>


<commit_before>#pragma once

#include "handle.hpp"
#include "error.hpp"

namespace uvpp
{

    class Signal : public handle<uv_signal_t>
    {
    public:
    	Signal():
            handle<uv_signal_t>()
        {
            uv_signal_init(uv_default_loop(), get());
        }

        Signal(loop& l):
            handle<uv_signal_t>()
        {
            uv_signal_init(l.get(), get());
        }

        error start(int signum, std::function<void(int signum)> callback) {
			callbacks::store(get()->data, internal::uv_cid_signal, callback);
        	return error(uv_signal_start(get(),
        		[](uv_signal_t* handle, int signum){
        			callbacks::invoke<decltype(callback)>(handle->data, internal::uv_cid_signal, signum);
        		},
                        signum));
        }

        error stop() {
			return error(uv_signal_stop(get()));
        }
    };
}    <commit_msg>NL at the end of file<commit_after>#pragma once

#include "handle.hpp"
#include "error.hpp"

namespace uvpp
{

    class Signal : public handle<uv_signal_t>
    {
    public:
    	Signal():
            handle<uv_signal_t>()
        {
            uv_signal_init(uv_default_loop(), get());
        }

        Signal(loop& l):
            handle<uv_signal_t>()
        {
            uv_signal_init(l.get(), get());
        }

        error start(int signum, std::function<void(int signum)> callback) {
			callbacks::store(get()->data, internal::uv_cid_signal, callback);
        	return error(uv_signal_start(get(),
        		[](uv_signal_t* handle, int signum){
        			callbacks::invoke<decltype(callback)>(handle->data, internal::uv_cid_signal, signum);
        		},
                        signum));
        }

        error stop() {
			return error(uv_signal_stop(get()));
        }
    };
}
<|endoftext|>


<commit_before><commit_msg>Fix event generation for layout tests. Key codes are 'A'..'Z' so we must ensure that the values used are they.<commit_after><|endoftext|>


<commit_before>/*
 * Copyright 2007-2018 Content Management AG
 * All rights reserved.
 *
 * author: Max Kellermann <mk@cm4all.com>
 *
 * 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
 * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "ZeroIstream.hxx"
#include "istream.hxx"
#include "New.hxx"

#include <limits.h>

static uint8_t zero_buffer[1024];

class ZeroIstream final : public Istream {
public:
    explicit ZeroIstream(struct pool &_pool):Istream(_pool) {}

    /* virtual methods from class Istream */

    off_t _GetAvailable(bool partial) noexcept override {
        return partial
            ? INT_MAX
            : -1;
    }

    off_t _Skip(off_t length) noexcept override {
        Consumed(length);
        return length;
    }

    void _Read() noexcept override {
        InvokeData(zero_buffer, sizeof(zero_buffer));
    }
};

UnusedIstreamPtr
istream_zero_new(struct pool &pool) noexcept
{
    return NewIstreamPtr<ZeroIstream>(pool);
}
<commit_msg>istream/zero: make the buffer `constexpr`<commit_after>/*
 * Copyright 2007-2018 Content Management AG
 * All rights reserved.
 *
 * author: Max Kellermann <mk@cm4all.com>
 *
 * 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
 * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "ZeroIstream.hxx"
#include "istream.hxx"
#include "New.hxx"

#include <limits.h>

static constexpr uint8_t zero_buffer[1024]{};

class ZeroIstream final : public Istream {
public:
    explicit ZeroIstream(struct pool &_pool):Istream(_pool) {}

    /* virtual methods from class Istream */

    off_t _GetAvailable(bool partial) noexcept override {
        return partial
            ? INT_MAX
            : -1;
    }

    off_t _Skip(off_t length) noexcept override {
        Consumed(length);
        return length;
    }

    void _Read() noexcept override {
        InvokeData(zero_buffer, sizeof(zero_buffer));
    }
};

UnusedIstreamPtr
istream_zero_new(struct pool &pool) noexcept
{
    return NewIstreamPtr<ZeroIstream>(pool);
}
<|endoftext|>