<commit_before>/***************************************************************************
                          filter_ldif.cxx  -  description
                             -------------------
    begin                : Fri Dec 1, 2000
    copyright            : (C) 2000 by Oliver Strutynski
    email                : olistrut@gmx.de
 ***************************************************************************/

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

#include <iostream>
#include <stdlib.h>

#include <qdir.h>

#include <kfiledialog.h>
#include <klocale.h>

#include "filter_ldif.hxx"

filter_ldif::filter_ldif() : filter(i18n("Import Netscape LDIF Address Book 1(.LDIF)"),"Oliver Strutynski")
{}

filter_ldif::~filter_ldif()
{}

void filter_ldif::import(filterInfo *info) {
   QWidget *parent=info->parent();

   QString filename = KFileDialog::getOpenFileName( QDir::homeDirPath(),
		   	"*.ldif *.LDIF *.Ldif", parent);
   if (filename.isEmpty()) {
     info->alert(name(),i18n("No Addressbook chosen"));
     return;
   }

   QString from( i18n("Source: ") + "\t" + filename );
   QString to( i18n("Destination: ") + "\t" + i18n("the KAddressBook") );

   info->from(from);
   info->to(to);
   info->current(i18n("Currently converting .LDIF address file to Kab"));

   convert(filename, info);

   info->current(100.0);
   info->overall(100.0);
   info->current(i18n("Finished converting .LDIF address file to Kab"));
}

bool filter_ldif::convert(const QString &filename, filterInfo *info) {
   if (!kabStart(info))
	return false;

   QString caption( i18n("Import Netscape LDIF Personal Addressbook (.LDIF)") );

   QFile f(filename);
   if ( !f.open(IO_ReadOnly) ) {
	QString msg =  i18n("Can't open '%1' for reading").arg(filename);
	info->alert(caption,msg);
	return false;
   }

   QString empty;
   QString givenName, email, title, firstName, lastName, nickName,
	street, locality, state, zipCode, country, organization,
	department, phone, fax, mobile, homepage, comment;

   // Initializing code table for base64 decoding
   initCodeTable();

   QTextStream t( &f );
   QString s, fieldname;

   // We need this for calculating progress
   uint fileSize = f.size();
   uint bytesProcessed = 0;

   // Set to true if data currently read is part of
   // a list of names. Lists will be ignored.
   bool isGroup = false;

   while ( !t.eof() ) {
	s = t.readLine();
	bytesProcessed += s.length();

	// update progress information
    	info->current((float)bytesProcessed/fileSize*100);
    	info->overall((float)bytesProcessed/fileSize*100);

	if (s.isEmpty()) {
		// Newline: Write data
		if (!isGroup) {
  			kabAddress( info, i18n("Netscape Addressbook"),
				givenName, email, title, firstName, empty, lastName, nickName,
				street, locality, state, zipCode, country, organization,
				department, empty, empty, phone, fax, mobile, empty, homepage,
				empty, comment, empty);
			givenName = email = title = firstName = lastName = nickName =
			 street = locality = state = zipCode = country = organization =
			 department = phone = fax = mobile = homepage = comment = "";

   		} else {
			info->log(i18n("Warning: List data is being ignored."));
   		}

		isGroup = false;
		continue;
	}

	int position = s.find("::");
    	if (position != -1) {
    		// String is BASE64 encoded
    		fieldname = s.left(position);
    		s = decodeBase64(s.mid(position+3, s.length()-position-2));
    	} else {
    		position = s.find(":");
    		fieldname = s.left(position);
    		// Convert Utf8 string to unicode so special characters are preserved
		// We need this since we are reading normal strings from the file
		// which are not converted automatically
		s = QString::fromUtf8(s.mid(position+2, s.length()-position-2).latin1());
	}

	if (s.stripWhiteSpace().isEmpty())
		continue;

	if (fieldname == "givenname")
		{ firstName = s; continue; }

	if (fieldname == "xmozillanickname")
		{ nickName = s; continue; }

	if (fieldname == "sn")
		{ lastName = s;	continue; }

	if (fieldname == "mail")
		{ email = s; continue; }

	if (fieldname == "title")
		{ title = s; continue; }

	if (fieldname == "cn")
		{ givenName = s; continue; }

	if (fieldname == "o")
		{ organization = s; continue; }

	if (fieldname == "description")
		{ comment = s; continue; }

	if (fieldname == "homeurl")
		{ homepage = s;	continue; }

	if (fieldname == "homephone" || fieldname == "telephonenumber") {
		if (!phone.isEmpty()) info->log(i18n("Discarding Phone Number %1").arg(s));
  		phone = s;
		continue;
	}

	if (fieldname == "postalcode")
		{ zipCode = s;	continue; }

	if (fieldname == "facsimiletelephonenumber")
		{ fax = s; continue; }

	if (fieldname == "streetaddress")
		{ street = s; continue; }

	if (fieldname == "locality")
		{ locality = s; continue; }

	if (fieldname == "countryname")
		{ country = s; continue; }

	if (fieldname == "cellphone")
		{ mobile = s; continue; }

	if (fieldname == "st")
		{ state = s; continue; }

	if (fieldname == "ou")
		{ department = s; continue; }

	if (fieldname == "objectclass" && s == "groupOfNames")
			isGroup = true;

    } /* while !eof(f) */

    f.close();

    kabStop(info);
    return true;
}

/*
 * Decodes a BASE-64 encoded stream to recover the original data and compacts white space.
 * Code heavily based on java code written by Kevin Kelley (kelley@ruralnet.net)
 * published unter the GNU Library Public License
*/
QString filter_ldif::decodeBase64(QString input)
{
    QCString result;

    int tempLen = input.length();
    for(unsigned int i=0; i<input.length(); i++) {
        if(codes[ input[i].latin1() ] < 0) {
	   // std::cout << "Invalid character in base64 string: " <<
	   // input[i].latin1() << std::endl;
	   --tempLen; // ignore non-valid chars and padding
        }
    }

    // calculate required length:
    //  -- 3 bytes for every 4 valid base64 chars
    //  -- plus 2 bytes if there are 3 extra base64 chars,
    //     or plus 1 byte if there are 2 extra.
    int len = (tempLen / 4) * 3;
    if ((tempLen % 4) == 3) len += 2;
    if ((tempLen % 4) == 2) len += 1;

    int shift = 0; // # of excess bits stored in accum
    int accum = 0; // excess bits

    // we now loop over through the entire string
    for (unsigned int i=0; i<input.length(); i++) {
        int value = codes[ input[i].latin1() ];

        if ( value >= 0 ) {         // skip over non-code
            accum <<= 6;            // bits shift up by 6 each time thru
            shift += 6;             // loop, with new bits being put in
            accum |= value;         // at the bottom.
            if ( shift >= 8 ) {      // whenever there are 8 or more shifted in,
                shift -= 8;          // write them out (from the top, leaving any
                                    // excess at the bottom for next iteration.
                result += (char) ((accum >> shift) & 0xff);
            }
        }
    }

    // Remove any linefeeds, tabs and multiple space from decoded string and
    // convert to unicode.
    return QString::fromUtf8(result).simplifyWhiteSpace();
}

/* Initialize lookup */
void filter_ldif::initCodeTable() {
    // chars for 0..63
    for (int i=0; i<256; i++) codes[i] = -1;
    for (int i = 'A'; i <= 'Z'; i++) codes[i] = (int)(i - 'A');
    for (int i = 'a'; i <= 'z'; i++) codes[i] = (int)(26 + i - 'a');
    for (int i = '0'; i <= '9'; i++) codes[i] = (int)(52 + i - '0');
    codes['+'] = 62;
    codes['/'] = 63;
}

<commit_msg>Don't be picky when the server doesn't return lowercase fiednames<commit_after>/***************************************************************************
                          filter_ldif.cxx  -  description
                             -------------------
    begin                : Fri Dec 1, 2000
    copyright            : (C) 2000 by Oliver Strutynski
    email                : olistrut@gmx.de
 ***************************************************************************/

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

#include <iostream>
#include <stdlib.h>

#include <qdir.h>

#include <kfiledialog.h>
#include <klocale.h>

#include "filter_ldif.hxx"

filter_ldif::filter_ldif() : filter(i18n("Import Netscape LDIF Address Book 1(.LDIF)"),"Oliver Strutynski")
{}

filter_ldif::~filter_ldif()
{}

void filter_ldif::import(filterInfo *info) {
   QWidget *parent=info->parent();

   QString filename = KFileDialog::getOpenFileName( QDir::homeDirPath(),
		   	"*.ldif *.LDIF *.Ldif", parent);
   if (filename.isEmpty()) {
     info->alert(name(),i18n("No Addressbook chosen"));
     return;
   }

   QString from( i18n("Source: ") + "\t" + filename );
   QString to( i18n("Destination: ") + "\t" + i18n("the KAddressBook") );

   info->from(from);
   info->to(to);
   info->current(i18n("Currently converting .LDIF address file to Kab"));

   convert(filename, info);

   info->current(100.0);
   info->overall(100.0);
   info->current(i18n("Finished converting .LDIF address file to Kab"));
}

bool filter_ldif::convert(const QString &filename, filterInfo *info) {
   if (!kabStart(info))
	return false;

   QString caption( i18n("Import Netscape LDIF Personal Addressbook (.LDIF)") );

   QFile f(filename);
   if ( !f.open(IO_ReadOnly) ) {
	QString msg =  i18n("Can't open '%1' for reading").arg(filename);
	info->alert(caption,msg);
	return false;
   }

   QString empty;
   QString givenName, email, title, firstName, lastName, nickName,
	street, locality, state, zipCode, country, organization,
	department, phone, fax, mobile, homepage, comment;

   // Initializing code table for base64 decoding
   initCodeTable();

   QTextStream t( &f );
   QString s, fieldname;

   // We need this for calculating progress
   uint fileSize = f.size();
   uint bytesProcessed = 0;

   // Set to true if data currently read is part of
   // a list of names. Lists will be ignored.
   bool isGroup = false;

   while ( !t.eof() ) {
	s = t.readLine();
	bytesProcessed += s.length();

	// update progress information
    	info->current((float)bytesProcessed/fileSize*100);
    	info->overall((float)bytesProcessed/fileSize*100);

	if (s.isEmpty()) {
		// Newline: Write data
		if (!isGroup) {
  			kabAddress( info, i18n("Netscape Addressbook"),
				givenName, email, title, firstName, empty, lastName, nickName,
				street, locality, state, zipCode, country, organization,
				department, empty, empty, phone, fax, mobile, empty, homepage,
				empty, comment, empty);
			givenName = email = title = firstName = lastName = nickName =
			 street = locality = state = zipCode = country = organization =
			 department = phone = fax = mobile = homepage = comment = "";

   		} else {
			info->log(i18n("Warning: List data is being ignored."));
   		}

		isGroup = false;
		continue;
	}

	int position = s.find("::");
    	if (position != -1) {
    		// String is BASE64 encoded
    		fieldname = s.left(position).lower();
    		s = decodeBase64(s.mid(position+3, s.length()-position-2));
    	} else {
    		position = s.find(":");
    		fieldname = s.left(position).lower();
    		// Convert Utf8 string to unicode so special characters are preserved
		// We need this since we are reading normal strings from the file
		// which are not converted automatically
		s = QString::fromUtf8(s.mid(position+2, s.length()-position-2).latin1());
	}

	if (s.stripWhiteSpace().isEmpty())
		continue;

	if (fieldname == "givenname")
		{ firstName = s; continue; }

	if (fieldname == "xmozillanickname")
		{ nickName = s; continue; }

	if (fieldname == "sn")
		{ lastName = s;	continue; }

	if (fieldname == "mail")
		{ email = s; continue; }

	if (fieldname == "title")
		{ title = s; continue; }

	if (fieldname == "cn")
		{ givenName = s; continue; }

	if (fieldname == "o")
		{ organization = s; continue; }

	if (fieldname == "description")
		{ comment = s; continue; }

	if (fieldname == "homeurl")
		{ homepage = s;	continue; }

	if (fieldname == "homephone" || fieldname == "telephonenumber") {
		if (!phone.isEmpty()) info->log(i18n("Discarding Phone Number %1").arg(s));
  		phone = s;
		continue;
	}

	if (fieldname == "postalcode")
		{ zipCode = s;	continue; }

	if (fieldname == "facsimiletelephonenumber")
		{ fax = s; continue; }

	if (fieldname == "streetaddress")
		{ street = s; continue; }

	if (fieldname == "locality")
		{ locality = s; continue; }

	if (fieldname == "countryname")
		{ country = s; continue; }

	if (fieldname == "cellphone")
		{ mobile = s; continue; }

	if (fieldname == "st")
		{ state = s; continue; }

	if (fieldname == "ou")
		{ department = s; continue; }

	if (fieldname == "objectclass" && s == "groupOfNames")
			isGroup = true;

    } /* while !eof(f) */

    f.close();

    kabStop(info);
    return true;
}

/*
 * Decodes a BASE-64 encoded stream to recover the original data and compacts white space.
 * Code heavily based on java code written by Kevin Kelley (kelley@ruralnet.net)
 * published unter the GNU Library Public License
*/
QString filter_ldif::decodeBase64(QString input)
{
    QCString result;

    int tempLen = input.length();
    for(unsigned int i=0; i<input.length(); i++) {
        if(codes[ input[i].latin1() ] < 0) {
	   // std::cout << "Invalid character in base64 string: " <<
	   // input[i].latin1() << std::endl;
	   --tempLen; // ignore non-valid chars and padding
        }
    }

    // calculate required length:
    //  -- 3 bytes for every 4 valid base64 chars
    //  -- plus 2 bytes if there are 3 extra base64 chars,
    //     or plus 1 byte if there are 2 extra.
    int len = (tempLen / 4) * 3;
    if ((tempLen % 4) == 3) len += 2;
    if ((tempLen % 4) == 2) len += 1;

    int shift = 0; // # of excess bits stored in accum
    int accum = 0; // excess bits

    // we now loop over through the entire string
    for (unsigned int i=0; i<input.length(); i++) {
        int value = codes[ input[i].latin1() ];

        if ( value >= 0 ) {         // skip over non-code
            accum <<= 6;            // bits shift up by 6 each time thru
            shift += 6;             // loop, with new bits being put in
            accum |= value;         // at the bottom.
            if ( shift >= 8 ) {      // whenever there are 8 or more shifted in,
                shift -= 8;          // write them out (from the top, leaving any
                                    // excess at the bottom for next iteration.
                result += (char) ((accum >> shift) & 0xff);
            }
        }
    }

    // Remove any linefeeds, tabs and multiple space from decoded string and
    // convert to unicode.
    return QString::fromUtf8(result).simplifyWhiteSpace();
}

/* Initialize lookup */
void filter_ldif::initCodeTable() {
    // chars for 0..63
    for (int i=0; i<256; i++) codes[i] = -1;
    for (int i = 'A'; i <= 'Z'; i++) codes[i] = (int)(i - 'A');
    for (int i = 'a'; i <= 'z'; i++) codes[i] = (int)(26 + i - 'a');
    for (int i = '0'; i <= '9'; i++) codes[i] = (int)(52 + i - '0');
    codes['+'] = 62;
    codes['/'] = 63;
}

<|endoftext|>


<commit_before>/*
    This file is part of KOrganizer.

    Copyright © 2007 Loïc Corbasson <loic.corbasson@gmail.com>

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

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

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

    As a special exception, permission is given to link this program
    with any edition of Qt, and distribute the resulting executable,
    without including the source code for Qt in the source distribution.
*/

#include <KApplication>
#include <KAboutData>
#include <KMessageBox>
#include <KCmdLineArgs>
#include <KLocale>
#include <KGlobal>
#include <KDebug>

#include "theme.h"

int main ( int argc, char **argv )
{
  KAboutData aboutData("korganizer",
                        0,
                        ki18n("KOrganizer Theming Stub"),
                        "0.001",
                        ki18n("DO NOT USE - Stub doing various things with KOrganizer themes"),
                        KAboutData::License_GPL,
                        ki18n("© 2007 Loïc Corbasson"),
                        ki18n(""),
                        "http://blog.loic.corbasson.fr/",
                        "loic.corbasson@gmail.com");

  KCmdLineArgs::init( argc, argv, &aboutData );

  KCmdLineOptions options;
  options.add("+[url]", ki18n("Theme to use"));
  KCmdLineArgs::addCmdLineOptions(options);

  KApplication app( false );   // no GUI

  KCmdLineArgs* args = KCmdLineArgs::parsedArgs();
  if (args->count() > 0) {
    for (int i = 0; i < args->count(); ++i) {
      KOrg::Theme::useThemeFrom( args->url(i) );
    }
  }
  args->clear();

}
<commit_msg>I don't think many translators will find a different translation for nothing<commit_after>/*
    This file is part of KOrganizer.

    Copyright © 2007 Loïc Corbasson <loic.corbasson@gmail.com>

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

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

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

    As a special exception, permission is given to link this program
    with any edition of Qt, and distribute the resulting executable,
    without including the source code for Qt in the source distribution.
*/

#include <KApplication>
#include <KAboutData>
#include <KMessageBox>
#include <KCmdLineArgs>
#include <KLocale>
#include <KGlobal>
#include <KDebug>

#include "theme.h"

int main ( int argc, char **argv )
{
  KAboutData aboutData("korganizer",
                        0,
                        ki18n("KOrganizer Theming Stub"),
                        "0.001",
                        ki18n("DO NOT USE - Stub doing various things with KOrganizer themes"),
                        KAboutData::License_GPL,
                        ki18n("© 2007 Loïc Corbasson"),
                        "",
                        "http://blog.loic.corbasson.fr/",
                        "loic.corbasson@gmail.com");

  KCmdLineArgs::init( argc, argv, &aboutData );

  KCmdLineOptions options;
  options.add("+[url]", ki18n("Theme to use"));
  KCmdLineArgs::addCmdLineOptions(options);

  KApplication app( false );   // no GUI

  KCmdLineArgs* args = KCmdLineArgs::parsedArgs();
  if (args->count() > 0) {
    for (int i = 0; i < args->count(); ++i) {
      KOrg::Theme::useThemeFrom( args->url(i) );
    }
  }
  args->clear();

}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2004, Mart Kelder (mart.kde@hccnet.nl)
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "keditlistboxman.h"

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

#include <qmap.h>
#include <qlistview.h>
#include <qstring.h>

KEditListBoxManager::KEditListBoxManager(	QWidget *parent, const char *name,
						bool checkAtEntering, KEditListBox::Buttons buttons )
	: KEditListBox( parent, name, checkAtEntering, buttons ),
	_config( 0 ),
	_groupName( 0 ),
	_subGroupName( 0 ),
	_prevCount( 0 )
{
	init();
}

KEditListBoxManager::KEditListBoxManager(	const QString& title, QWidget *parent,
						const char *name, bool checkAtEntering,
						KEditListBox::Buttons buttons)
	: KEditListBox( title, parent, name, checkAtEntering, buttons ),
	_config( 0 ),
	_groupName( 0 ),
	_subGroupName( 0 ),
	_prevCount( 0 )
{
	init();
}

KEditListBoxManager::KEditListBoxManager(	const QString& title,
						const KEditListBox::CustomEditor &customEditor,
						QWidget *parent, const char *name,
						bool checkAtEntering, KEditListBox::Buttons buttons )
	: KEditListBox( title, customEditor, parent, name, checkAtEntering, buttons ),
	_config( 0 ),
	_groupName( 0 ),
	_subGroupName( 0 ),
	_prevCount( 0 )
{
	init();
}

KEditListBoxManager::~KEditListBoxManager()
{
	delete _groupName;
}

void KEditListBoxManager::setConfig( KConfig* config )
{
	_config = config;
	if( _groupName )
		readNames();
}

void KEditListBoxManager::setGroupName( const QString& name )
{
	if( _groupName )
		*_groupName = name;
	else
		_groupName = new QString( name );

	if( _config )
		readNames();
}

void KEditListBoxManager::setSubGroupName( const QString& name )
{
	if( _subGroupName )
		*_subGroupName = name;
	else
		_subGroupName = new QString( name );

	if( _config && _groupName )
		readNames();
}

void KEditListBoxManager::init()
{
	connect( this, SIGNAL( changed() ), this, SLOT( slotChanged() ) );
	connect( this, SIGNAL( added( const QString& ) ), this, SLOT( slotAdded( const QString& ) ) );
	connect( this, SIGNAL( removed( const QString& ) ), this, SLOT( slotRemoved( const QString& ) ) );

	connect( this->listView(), SIGNAL( doubleClicked( const QModelIndex&) ), this, SLOT( slotActivated( const QModelIndex& ) ) );
	connect( this->listView(), SIGNAL( returnPressed( const QModelIndex& ) ), this, SLOT( slotActivated( const QModelIndex& ) ) );
}

void KEditListBoxManager::readNames()
{
	int number = 0;

	this->clear();
	while( _config->hasGroup( _groupName->arg( number ) ) )
	{
		_config->setGroup( _groupName->arg( number ) );
		this->insertItem( _config->readEntry( "name", QString() ) );
		++number;
	}

	_prevCount = this->count();
}

void KEditListBoxManager::slotChanged()
{
	/* Three thing could be hapened:
	 * 1. the text is changed;
	 * 2. the item has moved up;
	 * 3. the item has moved down.
	 */

	//_prevCount is invariant under all of these operation
	//if _prevCount is changed, is wasn't one of those operations.

	if( _prevCount != this->count() )
		return;

	 if( !_config || !_groupName )
	 	return;

	//First check if the item was moved up

	_config->setGroup( _groupName->arg( this->currentItem() ) );

	if( this->currentItem() > 0 && this->text( this->currentItem() - 1 ) == _config->readEntry( "name", QString() ) )
		changeItem( this->currentItem() - 1, this->currentItem() ); //moved down
	else if( this->currentItem() < this->count() - 1 &&
		 this->text( this->currentItem() + 1 ) == _config->readEntry( "name", QString() ) )
		changeItem( this->currentItem(), this->currentItem() + 1 );  //moved up
	else if( this->currentText() != _config->readEntry( "name", QString() ) )
		changedText(); //changed
}

void KEditListBoxManager::slotAdded( const QString& name )
{
	//Update _prevCount
	_prevCount = this->count();

	if( !_config || !_groupName )
	 	return;

	int number = 0;
	while( _config->hasGroup( _groupName->arg( number ) ) )
		++number;

	_config->setGroup( _groupName->arg( number ) );
	_config->writeEntry( "name", name );

	emit setDefaults( name, number, _config );
}

void KEditListBoxManager::slotRemoved( const QString& name )
{
	//Update prevCount
	_prevCount = this->count();

	if( !_config || !_groupName )
	 	return;

	//First: search the item number.
	int number = 0;
	int subnumber = 0;
	while( true )
	{
		if( !_config->hasGroup( _groupName->arg( number ) ) )
		{
			number = -1; //not found
			break;
		}
		_config->setGroup( _groupName->arg( number ) );
		if( name == _config->readEntry( "name", QString() ) )
			break; //found

		++number; //Try next group
	}

	if( number < 0 ) //failure
		return; //do nothing

	_config->deleteGroup( _groupName->arg( number ), KConfig::NLS );
	emit elementDeleted( number );
	while( _subGroupName && _config->hasGroup( _subGroupName->arg( number ).arg( subnumber ) ) )
	{
		_config->deleteGroup( _subGroupName->arg( number ).arg( subnumber ) );
		++subnumber;
	}

	//rotate groups
	while( _config->hasGroup( _groupName->arg( number + 1 ) ) )
	{
		moveItem( number + 1, number );

		++number;
	}
}

void KEditListBoxManager::slotActivated( const QModelIndex& item )
{
	emit activated( item );
}

void KEditListBoxManager::moveItem( int src, int dest )
{
	QMap<QString, QString> *srcList = new QMap<QString, QString >;
	QMap<QString, QString>::iterator it;
	int subnumber = 0;

	*srcList = _config->entryMap( _groupName->arg( src ) );
	_config->deleteGroup( _groupName->arg( src ) );

	_config->setGroup( _groupName->arg( dest ) );
	for( it = srcList->begin(); it != srcList->end(); ++it )
		_config->writeEntry( it.key(), it.value() );

	while( _subGroupName && _config->hasGroup( _subGroupName->arg( src ).arg( subnumber ) ) )
	{
		_config->deleteGroup( _subGroupName->arg( dest ).arg( subnumber ) );
		_config->setGroup( _subGroupName->arg( dest ).arg( subnumber ) );
		for( it = srcList->begin(); it != srcList->end(); ++it )
			_config->writeEntry( it.key(), it.value() );

		++subnumber;
	}

	emit elementsSwapped( src, dest );

	delete srcList;
}

void KEditListBoxManager::changeItem( int first, int last )
{
	QMap<QString, QString> *firstList = new QMap<QString, QString >;
	QMap<QString, QString> *lastList = new QMap<QString, QString >;
	QMap<QString, QString>::iterator it;
	int subnumber = 0;

	*firstList = _config->entryMap( _groupName->arg( first ) );
	*lastList = _config->entryMap( _groupName->arg( last ) );
	_config->deleteGroup( _groupName->arg( first ) );
	_config->deleteGroup( _groupName->arg( last ) );

	_config->setGroup( _groupName->arg( last ) );
	for( it = firstList->begin(); it != firstList->end(); ++it )
		_config->writeEntry( it.key(), it.value() );

	_config->setGroup( _groupName->arg( first ) );
	for( it = lastList->begin(); it != lastList->end(); ++it )
		_config->writeEntry( it.key(), it.value() );

	while( _subGroupName && (
		_config->hasGroup( _subGroupName->arg( first ).arg( subnumber ) ) ||
		_config->hasGroup( _subGroupName->arg( last ).arg( subnumber ) ) ) )
	{
		*firstList = _config->entryMap( _subGroupName->arg( first ).arg( subnumber ) );
		*lastList = _config->entryMap( _subGroupName->arg( last ).arg( subnumber ) );
		_config->deleteGroup( _subGroupName->arg( first ).arg( subnumber ) );
		_config->deleteGroup( _subGroupName->arg( last ).arg( subnumber ) );

		_config->setGroup( _subGroupName->arg( last ).arg( subnumber ) );
		for( it = firstList->begin(); it != firstList->end(); ++it )
			_config->writeEntry( it.key(), it.value() );

		_config->setGroup( _subGroupName->arg( first ).arg( subnumber ) );
		for( it = lastList->begin(); it != lastList->end(); ++it )
			_config->writeEntry( it.key(), it.value() );

		++subnumber;
	}

	emit elementsSwapped( first, last );

	delete firstList;
	delete lastList;
}

void KEditListBoxManager::changedText()
{
	_config->setGroup( _groupName->arg( this->currentItem() ) );
	_config->writeEntry( "name", this->currentText() );
}

#include "keditlistboxman.moc"
<commit_msg>fix crash (CID 1357)<commit_after>/*
 * Copyright (C) 2004, Mart Kelder (mart.kde@hccnet.nl)
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "keditlistboxman.h"

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

#include <qmap.h>
#include <qlistview.h>
#include <qstring.h>

KEditListBoxManager::KEditListBoxManager(	QWidget *parent, const char *name,
						bool checkAtEntering, KEditListBox::Buttons buttons )
	: KEditListBox( parent, name, checkAtEntering, buttons ),
	_config( 0 ),
	_groupName( 0 ),
	_subGroupName( 0 ),
	_prevCount( 0 )
{
	init();
}

KEditListBoxManager::KEditListBoxManager(	const QString& title, QWidget *parent,
						const char *name, bool checkAtEntering,
						KEditListBox::Buttons buttons)
	: KEditListBox( title, parent, name, checkAtEntering, buttons ),
	_config( 0 ),
	_groupName( 0 ),
	_subGroupName( 0 ),
	_prevCount( 0 )
{
	init();
}

KEditListBoxManager::KEditListBoxManager(	const QString& title,
						const KEditListBox::CustomEditor &customEditor,
						QWidget *parent, const char *name,
						bool checkAtEntering, KEditListBox::Buttons buttons )
	: KEditListBox( title, customEditor, parent, name, checkAtEntering, buttons ),
	_config( 0 ),
	_groupName( 0 ),
	_subGroupName( 0 ),
	_prevCount( 0 )
{
	init();
}

KEditListBoxManager::~KEditListBoxManager()
{
	delete _groupName;
}

void KEditListBoxManager::setConfig( KConfig* config )
{
	_config = config;
	if( _groupName )
		readNames();
}

void KEditListBoxManager::setGroupName( const QString& name )
{
	if( _groupName )
		*_groupName = name;
	else
		_groupName = new QString( name );

	if( _config )
		readNames();
}

void KEditListBoxManager::setSubGroupName( const QString& name )
{
	if( _subGroupName )
		*_subGroupName = name;
	else
		_subGroupName = new QString( name );

	if( _config && _groupName )
		readNames();
}

void KEditListBoxManager::init()
{
	connect( this, SIGNAL( changed() ), this, SLOT( slotChanged() ) );
	connect( this, SIGNAL( added( const QString& ) ), this, SLOT( slotAdded( const QString& ) ) );
	connect( this, SIGNAL( removed( const QString& ) ), this, SLOT( slotRemoved( const QString& ) ) );

	connect( this->listView(), SIGNAL( doubleClicked( const QModelIndex&) ), this, SLOT( slotActivated( const QModelIndex& ) ) );
	connect( this->listView(), SIGNAL( returnPressed( const QModelIndex& ) ), this, SLOT( slotActivated( const QModelIndex& ) ) );
}

void KEditListBoxManager::readNames()
{
	int number = 0;

	this->clear();
	while( _config->hasGroup( _groupName->arg( number ) ) )
	{
		_config->setGroup( _groupName->arg( number ) );
		this->insertItem( _config->readEntry( "name", QString() ) );
		++number;
	}

	_prevCount = this->count();
}

void KEditListBoxManager::slotChanged()
{
	/* Three thing could be hapened:
	 * 1. the text is changed;
	 * 2. the item has moved up;
	 * 3. the item has moved down.
	 */

	//_prevCount is invariant under all of these operation
	//if _prevCount is changed, is wasn't one of those operations.

	if( _prevCount != this->count() )
		return;

	 if( !_config || !_groupName )
	 	return;

	//First check if the item was moved up

	_config->setGroup( _groupName->arg( this->currentItem() ) );

        int ci = currentItem();
	if( ci > 0 && this->text( ci - 1 ) == _config->readEntry( "name", QString() ) )
		changeItem( ci - 1, ci ); //moved down
	else if( ci >= 0 && ci < this->count() - 1 &&
		 this->text( ci + 1 ) == _config->readEntry( "name", QString() ) )
		changeItem( ci, ci + 1 );  //moved up
	else if( this->currentText() != _config->readEntry( "name", QString() ) )
		changedText(); //changed
}

void KEditListBoxManager::slotAdded( const QString& name )
{
	//Update _prevCount
	_prevCount = this->count();

	if( !_config || !_groupName )
	 	return;

	int number = 0;
	while( _config->hasGroup( _groupName->arg( number ) ) )
		++number;

	_config->setGroup( _groupName->arg( number ) );
	_config->writeEntry( "name", name );

	emit setDefaults( name, number, _config );
}

void KEditListBoxManager::slotRemoved( const QString& name )
{
	//Update prevCount
	_prevCount = this->count();

	if( !_config || !_groupName )
	 	return;

	//First: search the item number.
	int number = 0;
	int subnumber = 0;
	while( true )
	{
		if( !_config->hasGroup( _groupName->arg( number ) ) )
		{
			number = -1; //not found
			break;
		}
		_config->setGroup( _groupName->arg( number ) );
		if( name == _config->readEntry( "name", QString() ) )
			break; //found

		++number; //Try next group
	}

	if( number < 0 ) //failure
		return; //do nothing

	_config->deleteGroup( _groupName->arg( number ), KConfig::NLS );
	emit elementDeleted( number );
	while( _subGroupName && _config->hasGroup( _subGroupName->arg( number ).arg( subnumber ) ) )
	{
		_config->deleteGroup( _subGroupName->arg( number ).arg( subnumber ) );
		++subnumber;
	}

	//rotate groups
	while( _config->hasGroup( _groupName->arg( number + 1 ) ) )
	{
		moveItem( number + 1, number );

		++number;
	}
}

void KEditListBoxManager::slotActivated( const QModelIndex& item )
{
	emit activated( item );
}

void KEditListBoxManager::moveItem( int src, int dest )
{
	QMap<QString, QString> *srcList = new QMap<QString, QString >;
	QMap<QString, QString>::iterator it;
	int subnumber = 0;

	*srcList = _config->entryMap( _groupName->arg( src ) );
	_config->deleteGroup( _groupName->arg( src ) );

	_config->setGroup( _groupName->arg( dest ) );
	for( it = srcList->begin(); it != srcList->end(); ++it )
		_config->writeEntry( it.key(), it.value() );

	while( _subGroupName && _config->hasGroup( _subGroupName->arg( src ).arg( subnumber ) ) )
	{
		_config->deleteGroup( _subGroupName->arg( dest ).arg( subnumber ) );
		_config->setGroup( _subGroupName->arg( dest ).arg( subnumber ) );
		for( it = srcList->begin(); it != srcList->end(); ++it )
			_config->writeEntry( it.key(), it.value() );

		++subnumber;
	}

	emit elementsSwapped( src, dest );

	delete srcList;
}

void KEditListBoxManager::changeItem( int first, int last )
{
	QMap<QString, QString> *firstList = new QMap<QString, QString >;
	QMap<QString, QString> *lastList = new QMap<QString, QString >;
	QMap<QString, QString>::iterator it;
	int subnumber = 0;

	*firstList = _config->entryMap( _groupName->arg( first ) );
	*lastList = _config->entryMap( _groupName->arg( last ) );
	_config->deleteGroup( _groupName->arg( first ) );
	_config->deleteGroup( _groupName->arg( last ) );

	_config->setGroup( _groupName->arg( last ) );
	for( it = firstList->begin(); it != firstList->end(); ++it )
		_config->writeEntry( it.key(), it.value() );

	_config->setGroup( _groupName->arg( first ) );
	for( it = lastList->begin(); it != lastList->end(); ++it )
		_config->writeEntry( it.key(), it.value() );

	while( _subGroupName && (
		_config->hasGroup( _subGroupName->arg( first ).arg( subnumber ) ) ||
		_config->hasGroup( _subGroupName->arg( last ).arg( subnumber ) ) ) )
	{
		*firstList = _config->entryMap( _subGroupName->arg( first ).arg( subnumber ) );
		*lastList = _config->entryMap( _subGroupName->arg( last ).arg( subnumber ) );
		_config->deleteGroup( _subGroupName->arg( first ).arg( subnumber ) );
		_config->deleteGroup( _subGroupName->arg( last ).arg( subnumber ) );

		_config->setGroup( _subGroupName->arg( last ).arg( subnumber ) );
		for( it = firstList->begin(); it != firstList->end(); ++it )
			_config->writeEntry( it.key(), it.value() );

		_config->setGroup( _subGroupName->arg( first ).arg( subnumber ) );
		for( it = lastList->begin(); it != lastList->end(); ++it )
			_config->writeEntry( it.key(), it.value() );

		++subnumber;
	}

	emit elementsSwapped( first, last );

	delete firstList;
	delete lastList;
}

void KEditListBoxManager::changedText()
{
	_config->setGroup( _groupName->arg( this->currentItem() ) );
	_config->writeEntry( "name", this->currentText() );
}

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


<commit_before>/*
 * CvTypesIo.hpp
 *
 *  Created on: May 20, 2013
 *      Author: link
 */

#ifndef CVTYPESIO_HPP_
#define CVTYPESIO_HPP_

#include <opencv2/core/core.hpp>

void operator>>(const cv::FileNode &node, cv::Size &size);

void operator>>(const cv::FileNode &node,
        cv::TermCriteria &termCrit);
template<class T>
void operator>>(const cv::FileNode &node,
        cv::Point_<T> &point){
        node[0]>>point.x;
        node[1]>>point.y;
}

cv::FileStorage &operator<<(cv::FileStorage &fs,
        const cv::TermCriteria &termCrit);

#endif /* CVTYPESIO_HPP_ */
<commit_msg>Added doxygen dosumentation to CvTypesIo<commit_after>/*
 * CvTypesIo.hpp
 *
 *  Created on: May 20, 2013
 *      Author: link
 */

#ifndef CVTYPESIO_HPP_
#define CVTYPESIO_HPP_

#include <opencv2/core/core.hpp>

/// Operator enabling to use cv::Size with OpenCV persistence
/// functionality (reading)

/**
 * Function provides a way to read a cv::Size value from
 * OpenCV text file.
 * @param[in] node - file node in which the size value is stored
 * @param[out] size - value read
 */
void operator>>(const cv::FileNode &node, cv::Size &size);

/// Operator enabling to use cv::TermCriteria with OpenCV persistence
/// functionality (reading)

/**
 * Function provides a way to read a cv::TermCriteria value from
 * OpenCV text file.
 * @param[in] node - file node in which the termCrit value is stored
 * @param[out] termCrit - value read
 */
void operator>>(const cv::FileNode &node,
        cv::TermCriteria &termCrit);

/// Operator enabling to use cv::Point_<T> with OpenCV persistence
/// functionality (reading)

/**
 * Function provides a way to read a cv::Point_<T> value from
 * OpenCV text file.
 * @param[in] node - file node in which the size value is stored
 * @param[out] point - value read
 */
template<class T>
void operator>>(const cv::FileNode &node,
        cv::Point_<T> &point){
        node[0]>>point.x;
        node[1]>>point.y;
}

/// Operator enabling to use cv::TermCriteria with OpenCV persistence
/// functionality (writing)

/**
 * Function provides a way to store a cv::TermCriteria value in
 * OpenCV text file.
 * @param[in] fs - file storage in which the size value is stored
 * @param[in] termCrit - value to be stored
 * @return fs file storage to enable chain calls.
 */

cv::FileStorage &operator<<(cv::FileStorage &fs,
        const cv::TermCriteria &termCrit);

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


<commit_before>/*
 * safe_queue.hpp
 *
 *  Created on: 2014-11-11
 *      Author: joseph
 */

#ifndef SAFE_QUEUE_HPP_
#define SAFE_QUEUE_HPP_

#include <queue>
#include <boost/thread/condition_variable.hpp>

//#include <pthread.h>
//#include <semaphore.h>

template <typename T >
class SafeQueue {

private:
	std::queue<T > values;
	boost::condition_variable m_cond;       // The condition to wait for
	boost::mutex mtx_;
	//pthread_mutex_t access_lock;
	//sem_t access_resource;
	bool stop_waiting;
	//pthread_cond_t empty_wait;

public:

	SafeQueue()// : sem_(0)
	{
		//pthread_mutex_init(&access_lock, NULL);
		//sem_init(&access_resource, 0, 0);
		stop_waiting = false;
		//pthread_cond_init(&empty_wait, 0);
		//pthread_cond_signal(&self_adapt_wait);
	}

	~SafeQueue() {
		//pthread_mutex_destroy(&access_lock);
		//sem_destroy(&access_resource);
		//pthread_cond_destroy(&empty_wait);
	}

	bool empty() {
		boost::unique_lock<boost::mutex> lock(mtx_);
		//pthread_mutex_lock(&access_lock);
		bool e = values.empty();
		//pthread_mutex_unlock(&access_lock);
		return e;
	}

	/* Didnt really need this
	typename std::queue<T >::size_type size() const {
		pthread_mutex_lock(&access_lock);
		auto s = values.size();
		pthread_mutex_unlock(&access_lock);
		return s;
	}*/

	/*
	T waitToPop() {
		boost::unique_lock<boost::mutex> guard(mtx_);
		//sem_wait(&access_resource);
		//if(stop_waiting) {
		//	return T ();
		//}
		//TODO add in exit conidtion
		return pop();
	}*/

	/**
	 * Retrieves the next value from the queue. The value is also removed.
	 * If the wait is to true the thread will sleep until the next value is
	 * available.
	 *
	 * @param result The next value in the queue.
	 * @param wait Whether the pop will wait for a value if the queue is empty.
	 * Default is to wait for the a value if the queue is empty.
	 *
	 * @return Whether the next value was retrieved or not.
	 *
	 */
	bool pop(T& result, bool wait=true) {

		boost::unique_lock<boost::mutex> lock(mtx_);

		while (values.size()==0 && !stop_waiting) {

			if(!wait) {
				// Queue is empty.
				return false;
			}

			m_cond.wait(lock);
		}

		// Exit the queue is finished
		if (stop_waiting) {
			return false;
		}

		//T val = values.front();
		result = values.front();
		values.pop();
		//pthread_mutex_unlock(&access_lock);
		return true;
	}

	/**
	 * Retrieve the next amount of items from the queue. If the queue does not
	 * have enough values the thread will wait.
	 *
	 * This method can be potentially dangerous since values may be left on
	 * the queue and never worked on if the the amount left on is less than the
	 * desired amount
	 *
	 * @param amount The number of items to retrieve from the front the queue.
	 * @param results The output vector of the values retrieved.
	 *
	 * @return Returns true if the number of values are within the results
	 * vector and false otherwise.
	 *
	 */
	bool pop(unsigned int amount, std::vector<T > &results) {
		boost::unique_lock<boost::mutex> lock(mtx_);

		// Initial design, can deadlock if no more values are added.
		while (values.size() < amount && !stop_waiting) {
			m_cond.wait(lock);
		}

		if(stop_waiting) {
			return false;
		}

		// Pop amount of values from the queue
		for(unsigned int i = 0; i < amount; i++) {

			results.push_back(values.front());
			values.pop();
		}
		return true;
	}

	/**
	 * Retrieves the next amount of items or less from the queue. If the queue
	 * is empty the thread will wait. Otherwise up to the amount of elements
	 * will be returned
	 *
	 * @param amount The number of items to retrieve from the front the queue.
	 * @param results The output vector of the values retrieved.
	 *
	 * @return Returns true if some number of values are within the results
	 * vector and false otherwise.
	 */
	bool popUpTO(unsigned int amount, std::vector<T > &results) {
		boost::unique_lock<boost::mutex> lock(mtx_);

		// Initial design, can deadlock if no more values are added.
		while (values.size()==0 && !stop_waiting) {
			m_cond.wait(lock);
		}

		if(stop_waiting) {
			return false;
		}

		// pop off upto amount of values from the queue
		for(unsigned int i = 0; i < amount || i < values.size(); i++) {

			results.push_back(values.front());
			values.pop();
		}
		return true;
	}

	/**
	 * Simple push of a single value into the queue.
	 *
	 * @param The value to add to the queue.
	 *
	 */
	void push(T &val) {
		//pthread_mutex_lock(&access_lock);
		boost::unique_lock<boost::mutex> guard(mtx_);
		values.push(val);
		m_cond.notify_one();
		//sem_.post();
		//pthread_mutex_unlock(&access_lock);

		// Identify that more jobs are available
		//sem_post(&access_resource);
	}

	/**
	 * Push a set of values into the queue.
	 * This is implemented to increase performance for a push that involves a
	 * large sum of entries which can be accomplished faster than fighting
	 * other threads for access to the mutex several times.
	 *
	 * @param entries The list of values to push into the queue.
	 */
	void push(std::vector<T > &entries) {
		boost::unique_lock<boost::mutex> guard(mtx_);

		for(unsigned int i = 0; i < entries.size(); i++) {
			values.push(entries[i]);
			m_cond.notify_one();
		}
	}

	/**
	 * Notify all waiting threads to wake up and return false. This method
	 * essentially is a nice way of stopping the threads that are waiting for
	 * pop.
	 */
	void finish() {

		boost::unique_lock<boost::mutex> lock(mtx_);
		this->stop_waiting = true;
		m_cond.notify_all();
	}

};

#endif /* SAFE_QUEUE_HPP_ */
<commit_msg>ADDED: pop all method for safe queue.<commit_after>/*
 * safe_queue.hpp
 *
 *  Created on: 2014-11-11
 *      Author: joseph
 */

#ifndef SAFE_QUEUE_HPP_
#define SAFE_QUEUE_HPP_

#include <queue>
#include <boost/thread/condition_variable.hpp>

//#include <pthread.h>
//#include <semaphore.h>

template <typename T >
class SafeQueue {

private:
	std::queue<T > values;
	boost::condition_variable m_cond;       // The condition to wait for
	boost::mutex mtx_;
	//pthread_mutex_t access_lock;
	//sem_t access_resource;
	bool stop_waiting;
	//pthread_cond_t empty_wait;

public:

	SafeQueue()// : sem_(0)
	{
		//pthread_mutex_init(&access_lock, NULL);
		//sem_init(&access_resource, 0, 0);
		stop_waiting = false;
		//pthread_cond_init(&empty_wait, 0);
		//pthread_cond_signal(&self_adapt_wait);
	}

	~SafeQueue() {
		//pthread_mutex_destroy(&access_lock);
		//sem_destroy(&access_resource);
		//pthread_cond_destroy(&empty_wait);
	}

	bool empty() {
		boost::unique_lock<boost::mutex> lock(mtx_);
		//pthread_mutex_lock(&access_lock);
		bool e = values.empty();
		//pthread_mutex_unlock(&access_lock);
		return e;
	}

	/* Didnt really need this
	typename std::queue<T >::size_type size() const {
		pthread_mutex_lock(&access_lock);
		auto s = values.size();
		pthread_mutex_unlock(&access_lock);
		return s;
	}*/

	/*
	T waitToPop() {
		boost::unique_lock<boost::mutex> guard(mtx_);
		//sem_wait(&access_resource);
		//if(stop_waiting) {
		//	return T ();
		//}
		//TODO add in exit conidtion
		return pop();
	}*/

	/**
	 * Retrieves the next value from the queue. The value is also removed.
	 * If the wait is to true the thread will sleep until the next value is
	 * available.
	 *
	 * @param result The next value in the queue.
	 * @param wait Whether the pop will wait for a value if the queue is empty.
	 * Default is to wait for the a value if the queue is empty.
	 *
	 * @return Whether the next value was retrieved or not.
	 *
	 */
	bool pop(T& result, bool wait=true) {

		boost::unique_lock<boost::mutex> lock(mtx_);

		while (values.size()==0 && !stop_waiting) {

			if(!wait) {
				// Queue is empty.
				return false;
			}

			m_cond.wait(lock);
		}

		// Exit the queue is finished
		if (stop_waiting) {
			return false;
		}

		//T val = values.front();
		result = values.front();
		values.pop();
		//pthread_mutex_unlock(&access_lock);
		return true;
	}

	/**
	 * Retrieve the next amount of items from the queue. If the queue does not
	 * have enough values the thread will wait.
	 *
	 * This method can be potentially dangerous since values may be left on
	 * the queue and never worked on if the the amount left on is less than the
	 * desired amount
	 *
	 * @param amount The number of items to retrieve from the front the queue.
	 * @param results The output vector of the values retrieved.
	 *
	 * @return Returns true if the number of values are within the results
	 * vector and false otherwise.
	 *
	 */
	bool pop(unsigned int amount, std::vector<T > &results) {
		boost::unique_lock<boost::mutex> lock(mtx_);

		// Initial design, can deadlock if no more values are added.
		while (values.size() < amount && !stop_waiting) {
			m_cond.wait(lock);
		}

		if(stop_waiting) {
			return false;
		}

		// Pop amount of values from the queue
		for(unsigned int i = 0; i < amount; i++) {

			results.push_back(values.front());
			values.pop();
		}
		return true;
	}

	/**
	 * Retrieves the next amount of items or less from the queue. If the queue
	 * is empty the thread will wait. Otherwise up to the amount of elements
	 * will be returned
	 *
	 * @param amount The number of items to retrieve from the front the queue.
	 * @param results The output vector of the values retrieved.
	 *
	 * @return Returns true if some number of values are within the results
	 * vector and false otherwise.
	 */
	bool popUpTO(unsigned int amount, std::vector<T > &results) {
		boost::unique_lock<boost::mutex> lock(mtx_);

		// Initial design, can deadlock if no more values are added.
		while (values.size()==0 && !stop_waiting) {
			m_cond.wait(lock);
		}

		if(stop_waiting) {
			return false;
		}

		// pop off upto amount of values from the queue
		for(unsigned int i = 0; i < amount || i < values.size(); i++) {

			results.push_back(values.front());
			values.pop();
		}
		return true;
	}

	/**
	 * Retrieve all the values within the queue. If no values are within the
	 * queue the thread will wait until there are some values within the queue.
	 *
	 * @param results All the values currently within the queue.
	 *
	 * @return Returns true if values were successfully retrieved and false if
	 * the queue's finish method has been called.
	 */
	bool popAll(std::vector<T > &results, bool wait=true) {
		boost::unique_lock<boost::mutex> lock(mtx_);

		// Initial design, can deadlock if no more values are added.
		while (values.size()==0 && !stop_waiting) {

			if(!wait) {
				// Queue is empty.
				return false;
			}

			m_cond.wait(lock);
		}

		if(stop_waiting) {
			return false;
		}

		// pop off all the available values within the queue.
		while(values.size() != 0) {

			results.push_back(values.front());
			values.pop();
		}
		return true;
	}

	/**
	 * Simple push of a single value into the queue.
	 *
	 * @param The value to add to the queue.
	 *
	 */
	void push(T &val) {
		//pthread_mutex_lock(&access_lock);
		boost::unique_lock<boost::mutex> guard(mtx_);
		values.push(val);
		m_cond.notify_one();
		//sem_.post();
		//pthread_mutex_unlock(&access_lock);

		// Identify that more jobs are available
		//sem_post(&access_resource);
	}

	/**
	 * Push a set of values into the queue.
	 * This is implemented to increase performance for a push that involves a
	 * large sum of entries which can be accomplished faster than fighting
	 * other threads for access to the mutex several times.
	 *
	 * @param entries The list of values to push into the queue.
	 */
	void push(std::vector<T > &entries) {
		boost::unique_lock<boost::mutex> guard(mtx_);

		for(unsigned int i = 0; i < entries.size(); i++) {
			values.push(entries[i]);
			m_cond.notify_one();
		}
	}

	/**
	 * Notify all waiting threads to wake up and return false. This method
	 * essentially is a nice way of stopping the threads that are waiting for
	 * pop.
	 */
	void finish() {

		boost::unique_lock<boost::mutex> lock(mtx_);
		this->stop_waiting = true;
		m_cond.notify_all();
	}

};

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


<commit_before>#ifndef ALX_EVENT_HPP
#define ALX_EVENT_HPP

#include <cassert>
#include "Joystick.hpp"
#include "Display.hpp"
#include "Timer.hpp"

namespace alx {

/**
    An allegro event.
 */
class Event {
public:
    /**
        default constructor.
     */
    Event() {
    }

    /**
        constructor from event struct.
     */
    Event(const ALLEGRO_EVENT &event) :m_object(event) {
    }

    /**
        If the event is a user event, then it is automatically unrefd.
     */
    ~Event() {
        if (_isUserEvent(m_object.type)) al_unref_user_event(&m_object.user);
    }

    /**
        Returns true if the event is a user one.
        @return true if user event, false otherwise.
     */
    bool isUserEvent() const {
        return _isUserEvent(m_object.type);
    }

    int getType() const {
        return m_object.type;
    }

    EventSource getEventSource() const {
        return EventSource(m_object.any.source, false);
    }

    double getTimestamp() const {
        return m_object.any.timestamp;
    }

    Display getDisplay() const {
        return Display(m_object.display.source, false);
    }

    int getDisplayX() const {
        return m_object.display.x;
    }

    int getDisplayY() const {
        return m_object.display.y;
    }

    int getDisplayWidth() const {
        return m_object.display.width;
    }

    int getDisplayHeight() const {
        return m_object.display.height;
    }

    int getDisplayOrientation() const {
        return m_object.display.orientation;
    }

    Joystick getJoystick() const {
        return Joystick(m_object.joystick.source, false);
    }

    Joystick getJoystickId() const {
        return Joystick(m_object.joystick.id, false);
    }

    int getJoystickStick() const {
        return m_object.joystick.stick;
    }

    int getJoystickAxis() const {
        return m_object.joystick.axis;
    }

    float getJoystickPos() const {
        return m_object.joystick.pos;
    }

    int getJoystickButton() const {
        return m_object.joystick.button;
    }

    Display getKeyboardDisplay() const {
        return Display(m_object.keyboard.display, false);
    }

    int getKeyboardKeycode() const {
        return m_object.keyboard.keycode;
    }

    int getKeyboardUnicodeCharacter() const {
        return m_object.keyboard.unichar;
    }

    int getKeyboardModifiers() const {
        return m_object.keyboard.modifiers;
    }

    bool getKeyboardRepeat() const {
        return m_object.keyboard.repeat;
    }

    Display getMouseDisplay() const {
        return Display(m_object.mouse.display, false);
    }

    int getMouseX() const {
        return m_object.mouse.x;
    }

    int getMouseY() const {
        return m_object.mouse.y;
    }

    int getMouseZ() const {
        return m_object.mouse.z;
    }

    int getMouseW() const {
        return m_object.mouse.w;
    }

    int getMouseDX() const {
        return m_object.mouse.dx;
    }

    int getMouseDY() const {
        return m_object.mouse.dy;
    }

    int getMouseDZ() const {
        return m_object.mouse.dz;
    }

    int getMouseDW() const {
        return m_object.mouse.dw;
    }

    float getMousePressure() const {
        return m_object.mouse.pressure;
    }

    Timer getTimer() const {
        return Timer(m_object.timer.source, false);
    }

    int64_t getTimerCount() const {
        return m_object.timer.count;
    }

    double getTimerError() const {
        return m_object.timer.error;
    }

    intptr_t getUserData1() const {
        return m_object.user.data1;
    }

    intptr_t getUserData2() const {
        return m_object.user.data2;
    }

    intptr_t getUserData3() const {
        return m_object.user.data3;
    }

    intptr_t getUserData4() const {
        return m_object.user.data4;
    }

private:
    //allegro event
    ALLEGRO_EVENT m_object;

    friend class UserEventSource;

    //check if the type represents an Allegro event or a user type event.
    static bool _isUserEvent(int type);
};

} //namespace alx

#endif //ALX_EVENT_HPP
<commit_msg>Documented the Event class members.<commit_after>#ifndef ALX_EVENT_HPP
#define ALX_EVENT_HPP

#include <cassert>
#include "Joystick.hpp"
#include "Display.hpp"
#include "Timer.hpp"

namespace alx {

/**
    An allegro event.
 */
class Event {
public:
    /**
        default constructor.
     */
    Event() {
    }

    /**
        constructor from event struct.
     */
    Event(const ALLEGRO_EVENT &event) :m_object(event) {
    }

    /**
        If the event is a user event, then it is automatically unrefd.
     */
    ~Event() {
        if (_isUserEvent(m_object.type)) al_unref_user_event(&m_object.user);
    }

    /**
        Returns true if the event is a user one.
        @return true if user event, false otherwise.
     */
    bool isUserEvent() const {
        return _isUserEvent(m_object.type);
    }

    /**
        Returns the type of the event.
        @return the type of the event.
     */
    int getType() const {
        return m_object.type;
    }

    /**
        Returns the event source.
        @return the event source.
     */
    EventSource getEventSource() const {
        return EventSource(m_object.any.source, false);
    }

    /**
        Returns the timestamp.
        @return the timestamp.
     */
    double getTimestamp() const {
        return m_object.any.timestamp;
    }

    /**
        Returns the display.
        @return the display.
     */
    Display getDisplay() const {
        return Display(m_object.display.source, false);
    }

    /**
        Returns the display x.
        @return the display x.
     */
    int getDisplayX() const {
        return m_object.display.x;
    }

    /**
        Returns the display y.
        @return the display y.
     */
    int getDisplayY() const {
        return m_object.display.y;
    }

    /**
        Returns the display width.
        @return the display width.
     */
    int getDisplayWidth() const {
        return m_object.display.width;
    }

    /**
        Returns the display height.
        @return the display height.
     */
    int getDisplayHeight() const {
        return m_object.display.height;
    }

    /**
        Returns the display orientation.
        @return the display orientation.
     */
    int getDisplayOrientation() const {
        return m_object.display.orientation;
    }

    /**
        Returns the joystick.
        @return the joystick.
     */
    Joystick getJoystick() const {
        return Joystick(m_object.joystick.source, false);
    }

    /**
        Returns the joystick id.
        @return the joystick id.
     */
    Joystick getJoystickId() const {
        return Joystick(m_object.joystick.id, false);
    }

    /**
        Returns the joystick stick.
        @return the joystick stick.
     */
    int getJoystickStick() const {
        return m_object.joystick.stick;
    }

    /**
        Returns the joystick axis.
        @return the joystick axis.
     */
    int getJoystickAxis() const {
        return m_object.joystick.axis;
    }

    /**
        Returns the joystick position.
        @return the joystick position.
     */
    float getJoystickPos() const {
        return m_object.joystick.pos;
    }

    /**
        Returns the joystick button.
        @return the joystick button.
     */
    int getJoystickButton() const {
        return m_object.joystick.button;
    }

    /**
        Returns the keyboard display.
        @return the keyboard display.
     */
    Display getKeyboardDisplay() const {
        return Display(m_object.keyboard.display, false);
    }

    /**
        Returns the keyboard keycode.
        @return the keyboard keycode.
     */
    int getKeyboardKeycode() const {
        return m_object.keyboard.keycode;
    }

    /**
        Returns the keyboard unicode character.
        @return the keyboard unicode character.
     */
    int getKeyboardCharacter() const {
        return m_object.keyboard.unichar;
    }

    /**
        Returns the keyboard modifiers.
        @return the keyboard modifiers.
     */
    int getKeyboardModifiers() const {
        return m_object.keyboard.modifiers;
    }

    /**
        Returns the keyboard repeat flag.
        @return the keyboard repeat flag.
     */
    bool getKeyboardRepeat() const {
        return m_object.keyboard.repeat;
    }

    /**
        Returns the mouse display.
        @return the mouse display.
     */
    Display getMouseDisplay() const {
        return Display(m_object.mouse.display, false);
    }

    /**
        Returns the mouse x.
        @return the mouse x.
     */
    int getMouseX() const {
        return m_object.mouse.x;
    }

    /**
        Returns the mouse y.
        @return the mouse y.
     */
    int getMouseY() const {
        return m_object.mouse.y;
    }

    /**
        Returns the mouse z.
        @return the mouse z.
     */
    int getMouseZ() const {
        return m_object.mouse.z;
    }

    /**
        Returns the mouse w.
        @return the mouse w.
     */
    int getMouseW() const {
        return m_object.mouse.w;
    }

    /**
        Returns the mouse dx.
        @return the mouse dx.
     */
    int getMouseDX() const {
        return m_object.mouse.dx;
    }

    /**
        Returns the mouse dy.
        @return the mouse dy.
     */
    int getMouseDY() const {
        return m_object.mouse.dy;
    }

    /**
        Returns the mouse dz.
        @return the mouse dz.
     */
    int getMouseDZ() const {
        return m_object.mouse.dz;
    }

    /**
        Returns the mouse dw.
        @return the mouse dw.
     */
    int getMouseDW() const {
        return m_object.mouse.dw;
    }

    /**
        Returns the mouse pressure.
        @return the mouse pressure.
     */
    float getMousePressure() const {
        return m_object.mouse.pressure;
    }

    /**
        Returns the timer.
        @return the timer.
     */
    Timer getTimer() const {
        return Timer(m_object.timer.source, false);
    }

    /**
        Returns the timer count.
        @return the timer count.
     */
    int64_t getTimerCount() const {
        return m_object.timer.count;
    }

    /**
        Returns the timer error.
        @return the timer error.
     */
    double getTimerError() const {
        return m_object.timer.error;
    }

    /**
        Returns the user data field 1.
        @return the user data field 1.
     */
    intptr_t getUserData1() const {
        return m_object.user.data1;
    }

    /**
        Returns the user data field 2.
        @return the user data field 2.
     */
    intptr_t getUserData2() const {
        return m_object.user.data2;
    }

    /**
        Returns the user data field 3.
        @return the user data field 3.
     */
    intptr_t getUserData3() const {
        return m_object.user.data3;
    }

    /**
        Returns the user data field 4.
        @return the user data field 4.
     */
    intptr_t getUserData4() const {
        return m_object.user.data4;
    }

private:
    //allegro event
    ALLEGRO_EVENT m_object;

    friend class UserEventSource;

    //check if the type represents an Allegro event or a user type event.
    static bool _isUserEvent(int type);
};

} //namespace alx

#endif //ALX_EVENT_HPP
<|endoftext|>


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

  Program:   Visualization Library
  Module:    Mat4x4.hh
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

This file is part of the Visualization Library. No part of this file or its
contents may be copied, reproduced or altered in any way without the express
written consent of the authors.

Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994

=========================================================================*/
#ifndef __vlMatrix4x4_hh
#define __vlMatrix4x4_hh

#include "Object.hh"

class vlMatrix4x4 : public vlObject
{
 public:
  float Element[4][4];
  //  A 4 x 4 matrix.
  vlMatrix4x4 ();
  void operator= (float element);
  void operator= (vlMatrix4x4& source);
  float *operator[](const unsigned int i) const {return &(Element[i][0]);};

  //  Calculate the inverse of in and
  //  return it in out.
  void Invert (vlMatrix4x4 in,vlMatrix4x4 & out);
  void Invert (void) { Invert(*this,*this);};

  //  Calculate the transpose of in and
  //  return it in out.
  void Transpose (vlMatrix4x4 in,vlMatrix4x4 & out);
  void Transpose (void) { Transpose(*this,*this);};

  void VectorMultiply(float in[4], float out[4]);
  void Adjoint (vlMatrix4x4 & in,vlMatrix4x4 & out);
  float Determinant (vlMatrix4x4 & in);
  char *GetClassName () {return "vlMatrix4x4";};
  void PrintSelf (ostream& os, vlIndent indent);
};
#endif
<commit_msg>fixed prototype<commit_after>/*=========================================================================

  Program:   Visualization Library
  Module:    Mat4x4.hh
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

This file is part of the Visualization Library. No part of this file or its
contents may be copied, reproduced or altered in any way without the express
written consent of the authors.

Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994

=========================================================================*/
#ifndef __vlMatrix4x4_hh
#define __vlMatrix4x4_hh

#include "Object.hh"

class vlMatrix4x4 : public vlObject
{
 public:
  float Element[4][4];
  //  A 4 x 4 matrix.
  vlMatrix4x4 ();
  void operator= (float element);
  void operator= (vlMatrix4x4& source);
  float *operator[](const unsigned int i) {return &(Element[i][0]);};

  //  Calculate the inverse of in and
  //  return it in out.
  void Invert (vlMatrix4x4 in,vlMatrix4x4 & out);
  void Invert (void) { Invert(*this,*this);};

  //  Calculate the transpose of in and
  //  return it in out.
  void Transpose (vlMatrix4x4 in,vlMatrix4x4 & out);
  void Transpose (void) { Transpose(*this,*this);};

  void VectorMultiply(float in[4], float out[4]);
  void Adjoint (vlMatrix4x4 & in,vlMatrix4x4 & out);
  float Determinant (vlMatrix4x4 & in);
  char *GetClassName () {return "vlMatrix4x4";};
  void PrintSelf (ostream& os, vlIndent indent);
};
#endif
<|endoftext|>


<commit_before>//
// Copyright (C) 2013
// Alessio Sclocco <a.sclocco@vu.nl>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//

#include <ctime>
#include <cmath>
#include <string>
using std::string;
#include <chrono>
using std::chrono::duration_cast;
using std::chrono::duration;
using std::chrono::high_resolution_clock;

#ifndef TIMER_HPP
#define TIMER_HPP

namespace isa {
namespace utils {

class Timer {
public:
	Timer(string name);

	void start();
	void stop();
	void reset();

	inline unsigned int getNrRuns() const;
	inline double getTotalTime() const;
	inline double getLastRunTime() const;
	inline double getAverageTime() const;
	inline double getStdDev() const;

private:
	string name;
	high_resolution_clock::time_point starting;
	unsigned int nrRuns;
	double totalTime;
	double time;
	double average;
	double variance;
};

// Implementation

Timer::Timer(string name) : name(name), starting(high_resolution_clock::time_point()), nrRuns(0), totalTime(0.0), time(0.0), average(0.0), variance(0.0) {}

void Timer::start() {
	starting = high_resolution_clock::now();
}

void Timer::stop() {
	time = (duration_cast< duration< double > >(high_resolution_clock::now() - starting)).count();
	totalTime += time;
	nrRuns++;

	if ( nrRuns == 1 ) {
		average = time;
		variance = 0.0;
	} else {
		double oldAverage = average;

		average = oldAverage + ((time - oldAverage) / nrRuns);
		variance += ((time - oldAverage) * (time - average));
	}
}

void Timer::reset() {
	starting = high_resolution_clock::time_point();
	nrRuns = 0;
	totalTime = 0.0;
	time = 0.0;
	average = 0.0;
	variance = 0.0;
}

inline unsigned int Timer::getNrRuns() const {
	return nrRuns;
}

inline double Timer::getTotalTime() const {
	return totalTime;
}

inline double Timer::getLastRunTime() const {
	return time;
}

inline double Timer::getAverageTime() const {
	return average;
}

inline double Timer::getStdDev() const {
	return sqrt(variance / nrRuns);
}

} // utils
} // isa

#endif // TIMER_HPP

<commit_msg>Timer is now using the new Stats class.<commit_after>//
// Copyright (C) 2013
// Alessio Sclocco <a.sclocco@vu.nl>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//

#include <ctime>
#include <string>
using std::string;
#include <chrono>
using std::chrono::duration_cast;
using std::chrono::duration;
using std::chrono::high_resolution_clock;

#include <Stats.hpp>

#ifndef TIMER_HPP
#define TIMER_HPP

namespace isa {
namespace utils {

class Timer {
public:
	Timer(string name);

	void start();
	void stop();
	void reset();

	inline unsigned int getNrRuns() const;
	inline double getTotalTime() const;
	inline double getLastRunTime() const;
	inline double getAverageTime() const;
	inline double getStdDev() const;

private:
	Stats< double > stats;
	string name;
	high_resolution_clock::time_point starting;
	double totalTime;
	double time;
};

// Implementation

Timer::Timer(string name) : stats(Stats< double >()) name(name), starting(high_resolution_clock::time_point()), totalTime(0.0), time(0.0) {}

void Timer::start() {
	starting = high_resolution_clock::now();
}

void Timer::stop() {
	time = (duration_cast< duration< double > >(high_resolution_clock::now() - starting)).count();
	totalTime += time;
	stats.addElement(time);
}

void Timer::reset() {
	starting = high_resolution_clock::time_point();
	totalTime = 0.0;
	time = 0.0;
}

inline unsigned int Timer::getNrRuns() const {
	return stats.getNrElements();
}

inline double Timer::getTotalTime() const {
	return totalTime;
}

inline double Timer::getLastRunTime() const {
	return time;
}

inline double Timer::getAverageTime() const {
	return stats.getAverage();
}

inline double Timer::getStdDev() const {
	return stats.getStdDev();
}

} // utils
} // isa

#endif // TIMER_HPP

<|endoftext|>


<commit_before>///
/// @file  imath.hpp
/// @brief Integer math functions used in primesum.
///
/// Copyright (C) 2017 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#ifndef IMATH_HPP
#define IMATH_HPP

#include <isqrt.hpp>

#include <stdint.h>
#include <algorithm>
#include <cassert>
#include <cmath>
#include <vector>

namespace primesum {

inline int64_t isquare(int64_t x)
{
  return x * x;
}

template <typename A, typename B>
inline A ceil_div(A a, B b)
{
  assert(b > 0);
  return (A) ((a + b - 1) / b);
}

template <typename T>
inline T number_of_bits(T)
{
  return (T) (sizeof(T) * 8);
}

template <typename T>
inline T next_power_of_2(T x)
{
  if (x == 0)
    return 1;

  x--;
  for (T i = 1; i < number_of_bits(x); i += i)
    x |= (x >> i);

  return ++x;
}

template <typename T>
inline T prev_power_of_2(T x)
{
  for (T i = 1; i < number_of_bits(x); i += i)
    x |= (x >> i);

  return x - (x >> 1);
}

template <typename T>
inline int ilog(T x)
{
  return (int) std::log((double) x);
}

/// Raise to power
template <typename T>
inline T ipow(T x, int n)
{
  T r = 1;
  for (int i = 0; i < n; i++)
    r *= x;

  return r;
}

/// Integer nth root
template <int N, typename T>
inline T iroot(T x)
{
  if (N == 0)
    return 0;

  T r = (T) std::pow((double) x, 1.0 / N);

  // fix root too large
  for (; r > 0 && ipow(r, N - 1) > x / r; r--);

  // fix root too small
  for (; ipow(r + 1, N - 1) <= x / (r + 1); r++);

  return r;
}

/// Count the number of primes <= x using binary search.
/// @pre primes[1] = 2, primes[3] = 3, ...
/// @pre x <= primes.back()
///
template <typename T1, typename T2>
inline T2 pi_bsearch(const std::vector<T1>& primes, T2 x)
{
  assert(primes[0] == 0);
  return (T2) (std::upper_bound(primes.begin() + 1, primes.end(), x) - (primes.begin() + 1));
}

template <typename T1, typename T2, typename T3>
inline T2 in_between(T1 min, T2 x, T3 max)
{
  if (x < min)
    return (T2) min;
  if (x > max)
    return (T2) max;

  return x;
}

} // namespace

#endif
<commit_msg>Improve number_of_bits()<commit_after>///
/// @file  imath.hpp
/// @brief Integer math functions used in primesum.
///
/// Copyright (C) 2018 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#ifndef IMATH_HPP
#define IMATH_HPP

#include <isqrt.hpp>

#include <stdint.h>
#include <algorithm>
#include <cassert>
#include <climits>
#include <cmath>
#include <vector>

namespace primesum {

inline int64_t isquare(int64_t x)
{
  return x * x;
}

template <typename A, typename B>
inline A ceil_div(A a, B b)
{
  assert(b > 0);
  return (A) ((a + b - 1) / b);
}

template <typename T>
inline T number_of_bits(T)
{
  static_assert(sizeof(uint64_t) * CHAR_BIT == 64, "number_of_bits() is broken");
  return (T) (sizeof(T) * CHAR_BIT);
}

template <typename T>
inline T next_power_of_2(T x)
{
  if (x == 0)
    return 1;

  x--;
  for (T i = 1; i < number_of_bits(x); i += i)
    x |= (x >> i);

  return ++x;
}

template <typename T>
inline T prev_power_of_2(T x)
{
  for (T i = 1; i < number_of_bits(x); i += i)
    x |= (x >> i);

  return x - (x >> 1);
}

template <typename T>
inline int ilog(T x)
{
  return (int) std::log((double) x);
}

/// Raise to power
template <typename T>
inline T ipow(T x, int n)
{
  T r = 1;
  for (int i = 0; i < n; i++)
    r *= x;

  return r;
}

/// Integer nth root
template <int N, typename T>
inline T iroot(T x)
{
  if (N == 0)
    return 0;

  T r = (T) std::pow((double) x, 1.0 / N);

  // fix root too large
  for (; r > 0 && ipow(r, N - 1) > x / r; r--);

  // fix root too small
  for (; ipow(r + 1, N - 1) <= x / (r + 1); r++);

  return r;
}

/// Count the number of primes <= x using binary search.
/// @pre primes[1] = 2, primes[3] = 3, ...
/// @pre x <= primes.back()
///
template <typename T1, typename T2>
inline T2 pi_bsearch(const std::vector<T1>& primes, T2 x)
{
  assert(primes[0] == 0);
  return (T2) (std::upper_bound(primes.begin() + 1, primes.end(), x) - (primes.begin() + 1));
}

template <typename T1, typename T2, typename T3>
inline T2 in_between(T1 min, T2 x, T3 max)
{
  if (x < min)
    return (T2) min;
  if (x > max)
    return (T2) max;

  return x;
}

} // namespace

#endif
<|endoftext|>


<commit_before><commit_msg>LOJ 3057<commit_after><|endoftext|>


<commit_before><commit_msg>Skip 16+ and 18+ images<commit_after><|endoftext|>


<commit_before>// PThreads
#include <pthread.h>

// Intel intrinsics
#include <immintrin.h>

// STL
#include <functional>
#include <iostream>

// xsync
#include "lock.hpp"

namespace xsync {

/*
 * Provides an RAII style wrapper for transactional execution.
 */
template <typename LockType>
class XScope {
public:

    XScope(LockType& fallback) : fallback_(fallback), cb_registered_(false) { enter(); }
    ~XScope() { exit(); }

    // The next few functions need to be specialized for each of the locktypes
    // passing a non-specialized lock will result in additional aborts
    inline bool isFallbackLocked() {
        return false;
    }

    // These need to be specialized if the LockType is not a BasicLockable
    inline void lockFallback() { fallback_.lock();  }
    inline void unlockFallback() { fallback_.unlock(); }

    void enter(int nretries = 3) {
        unsigned int xact_status;

        std::cout << isFallbackLocked() << std::endl;

        for (int attempt = 0; attempt <= nretries; ++attempt) {
            xact_status = _xbegin();

            if (xact_status == _XBEGIN_STARTED) {

                if (!isFallbackLocked()) {
                    // No other threads are executing the critical section non-transactionally,
                    // so we can execute the critical section
                    return;
                } else {
                    // explicit abort since the lock is held
                    _xabort(0xFF);
                }

            } else {
                // We have aborted
                if ((xact_status & _XABORT_EXPLICIT) && _XABORT_CODE(xact_status) == 0xFF) {
                    // We aborted because the lock was held
                    // wait until the lock is free and then retry
                    lockFallback();
                    unlockFallback();

                } else if (!(xact_status & _XABORT_RETRY)) {
                    // If the retry bit is not set, take fallback
                    break;
                }
            }
        }
        // Take fallback
        lockFallback();
    }

    void exit() {
        if (_xtest()) {
            _xend();
        } else {
            unlockFallback();
        }

        // Execute callback
        if (cb_registered_) cb_();
    }

    // Callback must not throw an exception since it is executed in the destructor
    void registerCommitCallback(const std::function<void()> &callback) {
        cb_registered_ = true;
        cb_ = callback;
    }

private:
    //friend class XCondVar;
    std::function<void()> cb_;
    bool cb_registered_;
    LockType &fallback_;
};

// These are lock-specific hacks to check the state without modifying memory.
// Usually this state is private (for good reason), but we need to access it

// template<>
// bool XScope<spinlock_t>::isFallbackLocked() {
//     return *(reinterpret_cast<int*>(&fallback_)) == 0;
//}

template<>
bool XScope<pthread_mutex_t>::isFallbackLocked() {
    return fallback_.__data.__lock != 0;
}

template<>
inline void XScope<pthread_mutex_t>::lockFallback() {
    pthread_mutex_lock(&fallback_);
}

template<>
inline void XScope<pthread_mutex_t>::unlockFallback() {
    pthread_mutex_unlock(&fallback_);
}

} // namespace xsync
<commit_msg>remove io<commit_after>// PThreads
#include <pthread.h>

// Intel intrinsics
#include <immintrin.h>

// STL
#include <functional>
#include <iostream>

// xsync
#include "lock.hpp"

namespace xsync {

/*
 * Provides an RAII style wrapper for transactional execution.
 */
template <typename LockType>
class XScope {
public:

    XScope(LockType& fallback) : fallback_(fallback), cb_registered_(false) { enter(); }
    ~XScope() { exit(); }

    // The next few functions need to be specialized for each of the locktypes
    // passing a non-specialized lock will result in additional aborts
    inline bool isFallbackLocked() {
        return false;
    }

    // These need to be specialized if the LockType is not a BasicLockable
    inline void lockFallback() { fallback_.lock();  }
    inline void unlockFallback() { fallback_.unlock(); }

    void enter(int nretries = 3) {
        unsigned int xact_status;

        for (int attempt = 0; attempt <= nretries; ++attempt) {
            xact_status = _xbegin();

            if (xact_status == _XBEGIN_STARTED) {

                if (!isFallbackLocked()) {
                    // No other threads are executing the critical section non-transactionally,
                    // so we can execute the critical section
                    return;
                } else {
                    // explicit abort since the lock is held
                    _xabort(0xFF);
                }

            } else {
                // We have aborted
                if ((xact_status & _XABORT_EXPLICIT) && _XABORT_CODE(xact_status) == 0xFF) {
                    // We aborted because the lock was held
                    // wait until the lock is free and then retry
                    lockFallback();
                    unlockFallback();

                } else if (!(xact_status & _XABORT_RETRY)) {
                    // If the retry bit is not set, take fallback
                    break;
                }
            }
        }
        // Take fallback
        lockFallback();
    }

    void exit() {
        if (_xtest()) {
            _xend();
        } else {
            unlockFallback();
        }

        // Execute callback
        if (cb_registered_) cb_();
    }

    // Callback must not throw an exception since it is executed in the destructor
    void registerCommitCallback(const std::function<void()> &callback) {
        cb_registered_ = true;
        cb_ = callback;
    }

private:
    //friend class XCondVar;
    std::function<void()> cb_;
    bool cb_registered_;
    LockType &fallback_;
};

// These are lock-specific hacks to check the state without modifying memory.
// Usually this state is private (for good reason), but we need to access it

// template<>
// bool XScope<spinlock_t>::isFallbackLocked() {
//     return *(reinterpret_cast<int*>(&fallback_)) == 0;
//}

template<>
bool XScope<pthread_mutex_t>::isFallbackLocked() {
    return fallback_.__data.__lock != 0;
}

template<>
inline void XScope<pthread_mutex_t>::lockFallback() {
    pthread_mutex_lock(&fallback_);
}

template<>
inline void XScope<pthread_mutex_t>::unlockFallback() {
    pthread_mutex_unlock(&fallback_);
}

} // namespace xsync
<|endoftext|>


<commit_before>#include <iostream>

template <typename T>
class stack
{
public:
	stack();
	stack(stack const &);
	~stack();
	size_t count() const;
	auto push(T const &) -> void;
	T pop();
	auto operator=(stack const & right)->stack &;
private:
	T *array_;
	size_t array_size_;
	size_t count_;
};
template<typename T>
auto newcopy(const T * item, size_t size, size_t count) -> T*
{
	T * buff = new T[size];
	std::copy(item, item + count, buff);
	return buff;
}
template <typename T>
size_t stack<T>::count() const
{
	std::cout << count_;
	return count_;
}
template <typename T>
stack<T>::stack()
{
	array_size_ = 0;
	array_ = new T[array_size_];
	count_ = 0;
}

template<typename T>
stack<T>::stack(stack const & other) :array_size_(other.array_size_), count_(other.count_), array_(newcopy(other.array_, other.array_size_, other.count_))
{

}

template <typename T>
stack<T>::~stack()
{
	delete[] array_;
}

template<typename T>
void stack<T>::push(T const &item)
{
	if (count_ == array_size_)
	{
		size_t size = array_size_ * 2 + (array_size_ == 0);
		delete[] array_;
		array_ = newcopy(array_, size, array_size_);
		array_size_ = size;
	}
	array_[count_] = item;
	++count_;
}
template<typename T>
T stack<T>::pop()
{
	if (count_ == 0)
	{
		throw std::logic_error("Stack is empty!");
	}
	return array_[--count_];
}
template<typename T>
auto stack<T>::operator=(stack const & right) -> stack & {
	if (this != &right) {
		delete[] array_;
		newcopy(right.array_, right.array_size_, right.count_);
	}
	return *this;
}
<commit_msg>Update stack.cpp<commit_after>#include <iostream>

template <typename T>
class stack
{
public:
	stack();							//noexcept
	stack(stack const &);						//strong
	~stack();							//noexcept
	size_t count() const;						//noexcept
	auto push(T const &) -> void;					//strong
	T pop();							//basic
	auto operator=(stack const & right)->stack &;			//strong
private:
	T *array_;
	size_t array_size_;
	size_t count_;
};
template<typename T>
auto newcopy(const T * item, size_t size, size_t count) -> T*		//strong
{
	T * buff = new T[size];
	std::copy(item, item + count, buff);
	return buff;
}
template <typename T>
size_t stack<T>::count() const
{
	std::cout << count_;
	return count_;
}
template <typename T>
stack<T>::stack()
{
	array_size_ = 0;
	array_ = new T[array_size_];
	count_ = 0;
}

template<typename T>
stack<T>::stack(stack const & other) :array_size_(other.array_size_), count_(other.count_), array_(newcopy(other.array_, other.array_size_, other.count_))
{

}

template <typename T>
stack<T>::~stack()
{
	delete[] array_;
}

template<typename T>
void stack<T>::push(T const &item)
{
	if (count_ == array_size_)
	{
		size_t size = array_size_ * 2 + (array_size_ == 0);
		delete[] array_;
		array_ = newcopy(array_, size, array_size_);
		array_size_ = size;
	}
	array_[count_] = item;
	++count_;
}
template<typename T>
T stack<T>::pop()
{
	if (count_ == 0)
	{
		throw std::logic_error("Stack is empty!");
	}
	return array_[--count_];
}
template<typename T>
auto stack<T>::operator=(stack const & right) -> stack & {
	if (this != &right) {
		delete[] array_;
		newcopy(right.array_, right.array_size_, right.count_);
	}
	return *this;
}
<|endoftext|>


<commit_before>#include <iostream>

template <typename T>
class stack
{
public:
	stack();									//noexcept
	stack(stack const &);								//strong
	~stack();									//noexcept
	size_t count() const;								//noexcept
	auto push(T const &) -> void;							//strong
	void pop();									//basic
	const T& top() const;								//strong
	auto operator=(stack const & right)->stack &;					//strong
private:
	T *array_;
	size_t array_size_;
	size_t count_;
};
template<typename T>
auto newcopy(const T * item, size_t size, size_t count) -> T* 				//strong
{
	T * buff = new T[size];
	try
	{
		std::copy(item, item + count, buff);
	}
	catch (...)
	{
		delete[] buff;
		throw;
	}
	return buff;
}
template <typename T>
size_t stack<T>::count() const
{
	std::cout << count_;
	return count_;
}
template <typename T>
stack<T>::stack()
{
	array_size_ = 0;
	array_ = new T[array_size_];
	count_ = 0;
}

template<typename T>
stack<T>::stack(stack const & other) :array_size_(other.array_size_), count_(other.count_), array_(newcopy(other.array_, other.array_size_, other.count_))
{

}

template <typename T>
stack<T>::~stack()
{
	delete[] array_;
}

template<typename T>
void stack<T>::push(T const &item)
{
	if (count_ == array_size_)
	{
		size_t size = array_size_ * 2 + (array_size_ == 0);
		delete[] array_;
		array_ = newcopy(array_, size, array_size_);
		array_size_ = size;
	}
	array_[count_] = item;
	++count_;
}
template<typename T>
void stack<T>::pop()
{
	if (count_ == 0)
	{
		throw std::logic_error("Stack is empty!");
	}
	else
	{
		count_--;
	}
}

template<typename T>
const T& stack<T>::top()
{
	if (count_ == 0)
	{
		throw ("Stack is empty!");
	}
	return array_[count_ - 1];
}

template<typename T>
auto stack<T>::operator=(stack const & right) -> stack &
{
	if (this != &right)
	{
		delete[] array_;
		newcopy(right.array_, right.array_size_, right.count_);
	}
	return *this;
}
<commit_msg>Update stack.cpp<commit_after>#ifndef stack_cpp
#define stack_cpp
#pragma once
#include <iostream>

template <typename T>
class stack
{
public:
	stack();									//noexcept
	stack(stack const &);								//strong
	~stack();									//noexcept
	size_t count() const;								//noexcept
	auto push(T const &) -> void;							//strong
	void pop();									//basic
	const T& top() const;								//strong
	auto operator=(stack const & right)->stack &;					//strong
private:
	T *array_;
	size_t array_size_;
	size_t count_;
};
template<typename T>
auto newcopy(const T * item, size_t size, size_t count) -> T* 				//strong
{
	T * buff = new T[size];
	try
	{
		std::copy(item, item + count, buff);
	}
	catch (...)
	{
		delete[] buff;
		throw;
	}
	return buff;
}
template <typename T>
size_t stack<T>::count() const
{
	return count_;
}
template <typename T>
stack<T>::stack()
{
	array_size_ = 0;
	array_ = new T[array_size_];
	count_ = 0;
}

template<typename T>
stack<T>::stack(stack const & other) :array_size_(other.array_size_), count_(other.count_), array_(newcopy(other.array_, other.array_size_, other.count_))
{

}

template <typename T>
stack<T>::~stack()
{
	delete[] array_;
}

template<typename T>
void stack<T>::push(T const &item)
{
	if (count_ == array_size_)
	{
		size_t size = array_size_ * 2 + (array_size_ == 0);
		delete[] array_;
		array_ = newcopy(array_, size, array_size_);
		array_size_ = size;
	}
	array_[count_] = item;
	++count_;
}
template<typename T>
void stack<T>::pop()
{
	if (count_ == 0)
	{
		throw std::logic_error("Stack is empty!");
	}
	else
	{
		count_--;
	}
}

template<typename T>
const T& stack<T>::top()
{
	if (count_ == 0)
	{
		throw ("Stack is empty!");
	}
	return array_[count_ - 1];
}

template<typename T>
auto stack<T>::operator=(stack const & right) -> stack &
{
	if (this != &right)
	{
		delete[] array_;
		newcopy(right.array_, right.array_size_, right.count_);
	}
	return *this;
}
#endif
<|endoftext|>


<commit_before>//
// Class for performing common math operations (e.g., dot, cross products)
//
#ifndef __vlMath_hh
#define __vlMath_hh

#include <math.h>

class vlMath
{
public:
  vlMath();
  float Pi() {return 3.14159265358979;};
  float Dot(float x[3], float y[3])
    {return x[0]*y[0] + x[1]*y[1] + x[2]*y[2];};
  float Norm(float x[3])
    {return sqrt(x[0]*x[0] + x[1]*x[1] + x[2]*x[2]);};
  void RandomSeed(long s);
  float Random();
private:
  long Seed;
};

#endif
<commit_msg>*** empty log message ***<commit_after>//
// Class for performing common math operations (e.g., dot, cross products)
//
#ifndef __vlMath_hh
#define __vlMath_hh

#include <math.h>

class vlMath
{
public:
  vlMath();
  float Pi() {return 3.14159265358979;};
  float DegreesToRadians() {return 0.018977369;};
  float Dot(float x[3], float y[3])
    {return x[0]*y[0] + x[1]*y[1] + x[2]*y[2];};
  float Norm(float x[3])
    {return sqrt(x[0]*x[0] + x[1]*x[1] + x[2]*x[2]);};
  void RandomSeed(long s);
  float Random();
private:
  long Seed;
};

#endif
<|endoftext|>