<commit_before>/*
 * Distributed under the OSI-approved Apache License, Version 2.0.  See
 * accompanying file Copyright.txt for details.
 *
 * CompressMGARD.cpp :
 *
 *  Created on: Aug 3, 2018
 *      Author: William F Godoy godoywf@ornl.gov
 */

#include "CompressMGARD.h"

#include <cstring> //std::memcpy

#include <mgard_api.h>

#include "adios2/helper/adiosFunctions.h"

namespace adios2
{
namespace core
{
namespace compress
{

CompressMGARD::CompressMGARD(const Params &parameters, const bool debugMode)
: Operator("mgard", parameters, debugMode)
{
}

size_t CompressMGARD::Compress(const void *dataIn, const Dims &dimensions,
                               const size_t elementSize, const std::string type,
                               void *bufferOut, const Params &parameters,
                               Params &info) const
{
    const size_t ndims = dimensions.size();
    if (m_DebugMode)
    {
        if (ndims > 3)
        {
            throw std::invalid_argument(
                "ERROR: ADIOS2 MGARD compression: no more "
                "than 3-dimensions is supported.\n");
        }
    }

    // set type
    int mgardType = -1;
    if (type == helper::GetType<double>())
    {
        mgardType = 1;
    }
    else
    {
        if (m_DebugMode)
        {
            throw std::invalid_argument(
                "ERROR: ADIOS2 operator "
                "MGARD only supports double precision, in call to Put\n");
        }
    }

    int r[3];
    r[0] = 0;
    r[1] = 0;
    r[2] = 0;

    for (size_t i = 0; i < ndims; i++)
    {
        r[ndims - i - 1] = static_cast<int>(dimensions[i]);
    }

    // Parameters
    bool hasTolerance = false;
    double tolerance;
    auto itAccuracy = parameters.find("accuracy");
    if (itAccuracy != parameters.end())
    {
        tolerance = std::stod(itAccuracy->second);
        hasTolerance = true;
    }
    auto itTolerance = parameters.find("tolerance");
    if (itTolerance != parameters.end())
    {
        tolerance = std::stod(itTolerance->second);
        hasTolerance = true;
    }
    if (!hasTolerance)
    {
        throw std::invalid_argument("ERROR: missing mandatory parameter "
                                    "tolerance for MGARD compression "
                                    "operator\n");
    }

    int sizeOut = 0;
    unsigned char *dataOutPtr =
        mgard_compress(mgardType, const_cast<double *>(static_cast<const double *>(dataIn)), sizeOut, r[0],
                       r[1], r[2], tolerance, 0.0);

    const size_t sizeOutT = static_cast<size_t>(sizeOut);
    std::memcpy(bufferOut, dataOutPtr, sizeOutT);

    return sizeOutT;
}

size_t CompressMGARD::Decompress(const void *bufferIn, const size_t sizeIn,
                                 void *dataOut, const Dims &dimensions,
                                 const std::string type,
                                 const Params & /*parameters*/) const
{
    int mgardType = -1;
    size_t elementSize = 0;

    if (type == helper::GetType<double>())
    {
        mgardType = 1;
        elementSize = 8;
    }
    else
    {
        if (m_DebugMode)
        {
            throw std::invalid_argument(
                "ERROR: ADIOS2 operator "
                "MGARD only supports double precision, in call to Get\n");
        }
    }

    const size_t ndims = dimensions.size();
    int r[3];
    r[0] = 0;
    r[1] = 0;
    r[2] = 0;

    for (size_t i = 0; i < ndims; i++)
    {
        r[ndims - i - 1] = static_cast<int>(dimensions[i]);
    }

    void *dataPtr = mgard_decompress(
        mgardType,
        reinterpret_cast<unsigned char *>(const_cast<void *>(bufferIn)),
        static_cast<int>(sizeIn), r[0], r[1], r[2], 0);

    const size_t dataSizeBytes = helper::GetTotalSize(dimensions) * elementSize;
    std::memcpy(dataOut, dataPtr, dataSizeBytes);

    return static_cast<size_t>(dataSizeBytes);
}

} // end namespace compress
} // end namespace core
} // end namespace adios2
<commit_msg>Format compliance.<commit_after>/*
 * Distributed under the OSI-approved Apache License, Version 2.0.  See
 * accompanying file Copyright.txt for details.
 *
 * CompressMGARD.cpp :
 *
 *  Created on: Aug 3, 2018
 *      Author: William F Godoy godoywf@ornl.gov
 */

#include "CompressMGARD.h"

#include <cstring> //std::memcpy

#include <mgard_api.h>

#include "adios2/helper/adiosFunctions.h"

namespace adios2
{
namespace core
{
namespace compress
{

CompressMGARD::CompressMGARD(const Params &parameters, const bool debugMode)
: Operator("mgard", parameters, debugMode)
{
}

size_t CompressMGARD::Compress(const void *dataIn, const Dims &dimensions,
                               const size_t elementSize, const std::string type,
                               void *bufferOut, const Params &parameters,
                               Params &info) const
{
    const size_t ndims = dimensions.size();
    if (m_DebugMode)
    {
        if (ndims > 3)
        {
            throw std::invalid_argument(
                "ERROR: ADIOS2 MGARD compression: no more "
                "than 3-dimensions is supported.\n");
        }
    }

    // set type
    int mgardType = -1;
    if (type == helper::GetType<double>())
    {
        mgardType = 1;
    }
    else
    {
        if (m_DebugMode)
        {
            throw std::invalid_argument(
                "ERROR: ADIOS2 operator "
                "MGARD only supports double precision, in call to Put\n");
        }
    }

    int r[3];
    r[0] = 0;
    r[1] = 0;
    r[2] = 0;

    for (size_t i = 0; i < ndims; i++)
    {
        r[ndims - i - 1] = static_cast<int>(dimensions[i]);
    }

    // Parameters
    bool hasTolerance = false;
    double tolerance;
    auto itAccuracy = parameters.find("accuracy");
    if (itAccuracy != parameters.end())
    {
        tolerance = std::stod(itAccuracy->second);
        hasTolerance = true;
    }
    auto itTolerance = parameters.find("tolerance");
    if (itTolerance != parameters.end())
    {
        tolerance = std::stod(itTolerance->second);
        hasTolerance = true;
    }
    if (!hasTolerance)
    {
        throw std::invalid_argument("ERROR: missing mandatory parameter "
                                    "tolerance for MGARD compression "
                                    "operator\n");
    }

    int sizeOut = 0;
    unsigned char *dataOutPtr = mgard_compress(
        mgardType, const_cast<double *>(static_cast<const double *>(dataIn)),
	sizeOut, r[0], r[1], r[2], tolerance, 0.0);

    const size_t sizeOutT = static_cast<size_t>(sizeOut);
    std::memcpy(bufferOut, dataOutPtr, sizeOutT);

    return sizeOutT;
}

size_t CompressMGARD::Decompress(const void *bufferIn, const size_t sizeIn,
                                 void *dataOut, const Dims &dimensions,
                                 const std::string type,
                                 const Params & /*parameters*/) const
{
    int mgardType = -1;
    size_t elementSize = 0;

    if (type == helper::GetType<double>())
    {
        mgardType = 1;
        elementSize = 8;
    }
    else
    {
        if (m_DebugMode)
        {
            throw std::invalid_argument(
                "ERROR: ADIOS2 operator "
                "MGARD only supports double precision, in call to Get\n");
        }
    }

    const size_t ndims = dimensions.size();
    int r[3];
    r[0] = 0;
    r[1] = 0;
    r[2] = 0;

    for (size_t i = 0; i < ndims; i++)
    {
        r[ndims - i - 1] = static_cast<int>(dimensions[i]);
    }

    void *dataPtr = mgard_decompress(
        mgardType,
        reinterpret_cast<unsigned char *>(const_cast<void *>(bufferIn)),
        static_cast<int>(sizeIn), r[0], r[1], r[2], 0);

    const size_t dataSizeBytes = helper::GetTotalSize(dimensions) * elementSize;
    std::memcpy(dataOut, dataPtr, dataSizeBytes);

    return static_cast<size_t>(dataSizeBytes);
}

} // end namespace compress
} // end namespace core
} // end namespace adios2
<|endoftext|>


<commit_before>/*
    kopeteonlinestatus.cpp - Kopete Online Status

    Copyright (c) 2002-2003 by Olivier Goffart       <ogoffart@tiscalinet.be>
    Copyright (c) 2003      by Martijn Klingens      <klingens@kde.org>

    Kopete    (c) 2002-2003 by the Kopete developers <kopete-devel@kde.org>

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

#include <qpainter.h>

#include <klocale.h>
#include <kiconloader.h>
#include <kdebug.h>

#include "kopetecontactlistview.h"
#include "kopetegroupviewitem.h"
#include "kopetegroup.h"
#include "kopeteonlinestatus.h"
#include "kopeteprefs.h"
#include "kopetemetacontactlvi.h"
#include "kopetemetacontact.h"

using namespace Kopete::UI;

class KopeteGroupViewItem::Private
{
public:
	ListView::ImageComponent *image;
	ListView::TextComponent *name;
	ListView::TextComponent *count;
};

KopeteGroupViewItem::KopeteGroupViewItem( KopeteGroup *group_, QListView *parent, const char *name )
: Kopete::UI::ListView::Item( parent, group_, name )
{
	m_group = group_;
	initLVI();
}

KopeteGroupViewItem::KopeteGroupViewItem( KopeteGroup *group_, QListViewItem *parent, const char *name )
 : Kopete::UI::ListView::Item( parent, group_, name )
{
	m_group = group_;
	initLVI();
}

KopeteGroupViewItem::~KopeteGroupViewItem()
{
	delete d;
}

void KopeteGroupViewItem::initLVI()
{
	d = new Private;

	using namespace ListView;
	Component *hbox = new BoxComponent( this, BoxComponent::Horizontal );
	d->image = new ImageComponent( hbox );
	d->name = new TextComponent( hbox );
	d->count = new TextComponent( hbox );

	connect( m_group, SIGNAL( renamed( KopeteGroup*, const QString& ) ),
		this, SLOT( refreshDisplayName() ) );

	connect( KopetePrefs::prefs(), SIGNAL( contactListAppearanceChanged() ),
		SLOT( slotConfigChanged() ) );

	connect( m_group, SIGNAL( iconAppearanceChanged() ), SLOT( updateIcon() ) );

	refreshDisplayName();
	slotConfigChanged();
}

KopeteGroup* KopeteGroupViewItem::group() const
{
	return m_group;
}

void KopeteGroupViewItem::slotConfigChanged()
{
	updateVisibility();

	d->name->setColor( KopetePrefs::prefs()->contactListGroupNameColor() );

	QFont font = listView()->font();
	if ( KopetePrefs::prefs()->contactListUseCustomFonts() )
		font = KopetePrefs::prefs()->contactListCustomNormalFont();
	d->name->setFont( font );

	d->count->setFont( KopetePrefs::prefs()->contactListSmallFont() );
}

void KopeteGroupViewItem::refreshDisplayName()
{
	totalMemberCount = 0;
	onlineMemberCount = 0;

	for ( QListViewItem *lvi = firstChild(); lvi; lvi = lvi->nextSibling() )
	{
		if ( KopeteMetaContactLVI *kc = dynamic_cast<KopeteMetaContactLVI*>( lvi ) )
		{
			totalMemberCount++;
			if ( kc->metaContact()->isOnline() )
				onlineMemberCount++;
		}
	}

	d->name->setText( m_group->displayName() );
	d->count->setText( i18n( "(NUMBER OF ONLINE CONTACTS/NUMBER OF CONTACTS IN GROUP)", "(%1/%2)" )
	                  .arg( QString::number( onlineMemberCount ), QString::number( totalMemberCount ) ) );

	updateVisibility();

	// Sorting in this slot is extremely expensive as it's called dozens of times and
	// the sorting itself is rather slow. Therefore we call delayedSort, which tries
	// to group multiple sort requests into one.
	if ( KopeteContactListView *lv = dynamic_cast<KopeteContactListView *>( listView() ) )
		lv->delayedSort();
	else
		listView()->sort();
}

QString KopeteGroupViewItem::key( int, bool ) const
{
	//Groups are placed after topLevel contact.
	//Exepted Temporary group which is the first group
	if ( group()->type() != KopeteGroup::Normal )
		return "0" + d->name->text();
	return "M" + d->name->text();
}

void KopeteGroupViewItem::startRename( int col )
{
	kdDebug(14000) << k_funcinfo << endl;
	if ( col != 0 ) return;
	refreshDisplayName();
	setText( 0, d->name->text() );
	setRenameEnabled( 0, true );
	KListViewItem::startRename( 0 );
/*
	KListView *lv = static_cast<KListView*>( listView() );
	lv->rename( this, 0 );*/
}

void KopeteGroupViewItem::okRename( int col )
{
	kdDebug(14000) << k_funcinfo << endl;
	KListViewItem::okRename(col);
	if ( col == 0 )
		group()->setDisplayName(text(0));
	setText( col, QString::null );
	refreshDisplayName();
}

void KopeteGroupViewItem::cancelRename( int col )
{
	kdDebug(14000) << k_funcinfo << endl;
	KListViewItem::cancelRename(col);
	setText( col, QString::null );
}

void KopeteGroupViewItem::updateVisibility()
{
	int visibleUsers = onlineMemberCount;
	if ( KopetePrefs::prefs()->showOffline() )
		visibleUsers = totalMemberCount;

	bool visible = KopetePrefs::prefs()->showEmptyGroups() || ( visibleUsers > 0 );

	if ( isVisible() != visible )
	{
		setTargetVisibility( visible );
		if ( visible )
		{
			// When calling setVisible(true) EVERY child item will be shown,
			// even if they should be hidden.
			// We just re-update the visibility of all child items
			for ( QListViewItem *lvi = firstChild(); lvi; lvi = lvi->nextSibling() )
			{
				if ( KopeteMetaContactLVI *kmc = dynamic_cast<KopeteMetaContactLVI *>( lvi ) )
					kmc->updateVisibility();
			}
		}
	}
}

void KopeteGroupViewItem::updateIcon()
{
	// TODO: clever caching
	if ( isOpen() )
	{
		if ( group()->useCustomIcon() )
			open = SmallIcon( group()->icon( KopetePluginDataObject::Open ) );
		else
			open = SmallIcon( "folder_green_open" );

		d->image->setPixmap( open );
	}
	else
	{
		if ( group()->useCustomIcon() )
			closed = SmallIcon( group()->icon( KopetePluginDataObject::Closed ) );
		else
			closed = SmallIcon( "folder_green" );

		d->image->setPixmap( closed );
	}
}

#include "kopetegroupviewitem.moc"
// vim: set noet ts=4 sts=4 sw=4:
<commit_msg>Update the icon anytime the config changes. Also takes care of 84637.<commit_after>/*
    kopeteonlinestatus.cpp - Kopete Online Status

    Copyright (c) 2002-2003 by Olivier Goffart       <ogoffart@tiscalinet.be>
    Copyright (c) 2003      by Martijn Klingens      <klingens@kde.org>

    Kopete    (c) 2002-2003 by the Kopete developers <kopete-devel@kde.org>

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

#include <qpainter.h>

#include <klocale.h>
#include <kiconloader.h>
#include <kdebug.h>

#include "kopetecontactlistview.h"
#include "kopetegroupviewitem.h"
#include "kopetegroup.h"
#include "kopeteonlinestatus.h"
#include "kopeteprefs.h"
#include "kopetemetacontactlvi.h"
#include "kopetemetacontact.h"

using namespace Kopete::UI;

class KopeteGroupViewItem::Private
{
public:
	ListView::ImageComponent *image;
	ListView::TextComponent *name;
	ListView::TextComponent *count;
};

KopeteGroupViewItem::KopeteGroupViewItem( KopeteGroup *group_, QListView *parent, const char *name )
: Kopete::UI::ListView::Item( parent, group_, name )
{
	m_group = group_;
	initLVI();
}

KopeteGroupViewItem::KopeteGroupViewItem( KopeteGroup *group_, QListViewItem *parent, const char *name )
 : Kopete::UI::ListView::Item( parent, group_, name )
{
	m_group = group_;
	initLVI();
}

KopeteGroupViewItem::~KopeteGroupViewItem()
{
	delete d;
}

void KopeteGroupViewItem::initLVI()
{
	d = new Private;

	using namespace ListView;
	Component *hbox = new BoxComponent( this, BoxComponent::Horizontal );
	d->image = new ImageComponent( hbox );
	d->name = new TextComponent( hbox );
	d->count = new TextComponent( hbox );

	connect( m_group, SIGNAL( renamed( KopeteGroup*, const QString& ) ),
		this, SLOT( refreshDisplayName() ) );

	connect( KopetePrefs::prefs(), SIGNAL( contactListAppearanceChanged() ),
		SLOT( slotConfigChanged() ) );

	connect( m_group, SIGNAL( iconAppearanceChanged() ), SLOT( updateIcon() ) );

	refreshDisplayName();
	slotConfigChanged();
}

KopeteGroup* KopeteGroupViewItem::group() const
{
	return m_group;
}

void KopeteGroupViewItem::slotConfigChanged()
{
	updateIcon();
	updateVisibility();

	d->name->setColor( KopetePrefs::prefs()->contactListGroupNameColor() );

	QFont font = listView()->font();
	if ( KopetePrefs::prefs()->contactListUseCustomFonts() )
		font = KopetePrefs::prefs()->contactListCustomNormalFont();
	d->name->setFont( font );

	d->count->setFont( KopetePrefs::prefs()->contactListSmallFont() );
}

void KopeteGroupViewItem::refreshDisplayName()
{
	totalMemberCount = 0;
	onlineMemberCount = 0;

	for ( QListViewItem *lvi = firstChild(); lvi; lvi = lvi->nextSibling() )
	{
		if ( KopeteMetaContactLVI *kc = dynamic_cast<KopeteMetaContactLVI*>( lvi ) )
		{
			totalMemberCount++;
			if ( kc->metaContact()->isOnline() )
				onlineMemberCount++;
		}
	}

	d->name->setText( m_group->displayName() );
	d->count->setText( i18n( "(NUMBER OF ONLINE CONTACTS/NUMBER OF CONTACTS IN GROUP)", "(%1/%2)" )
	                  .arg( QString::number( onlineMemberCount ), QString::number( totalMemberCount ) ) );

	updateVisibility();

	// Sorting in this slot is extremely expensive as it's called dozens of times and
	// the sorting itself is rather slow. Therefore we call delayedSort, which tries
	// to group multiple sort requests into one.
	if ( KopeteContactListView *lv = dynamic_cast<KopeteContactListView *>( listView() ) )
		lv->delayedSort();
	else
		listView()->sort();
}

QString KopeteGroupViewItem::key( int, bool ) const
{
	//Groups are placed after topLevel contact.
	//Exepted Temporary group which is the first group
	if ( group()->type() != KopeteGroup::Normal )
		return "0" + d->name->text();
	return "M" + d->name->text();
}

void KopeteGroupViewItem::startRename( int col )
{
	kdDebug(14000) << k_funcinfo << endl;
	if ( col != 0 ) return;
	refreshDisplayName();
	setText( 0, d->name->text() );
	setRenameEnabled( 0, true );
	KListViewItem::startRename( 0 );
/*
	KListView *lv = static_cast<KListView*>( listView() );
	lv->rename( this, 0 );*/
}

void KopeteGroupViewItem::okRename( int col )
{
	kdDebug(14000) << k_funcinfo << endl;
	KListViewItem::okRename(col);
	if ( col == 0 )
		group()->setDisplayName(text(0));
	setText( col, QString::null );
	refreshDisplayName();
}

void KopeteGroupViewItem::cancelRename( int col )
{
	kdDebug(14000) << k_funcinfo << endl;
	KListViewItem::cancelRename(col);
	setText( col, QString::null );
}

void KopeteGroupViewItem::updateVisibility()
{
	int visibleUsers = onlineMemberCount;
	if ( KopetePrefs::prefs()->showOffline() )
		visibleUsers = totalMemberCount;

	bool visible = KopetePrefs::prefs()->showEmptyGroups() || ( visibleUsers > 0 );

	if ( isVisible() != visible )
	{
		setTargetVisibility( visible );
		if ( visible )
		{
			// When calling setVisible(true) EVERY child item will be shown,
			// even if they should be hidden.
			// We just re-update the visibility of all child items
			for ( QListViewItem *lvi = firstChild(); lvi; lvi = lvi->nextSibling() )
			{
				if ( KopeteMetaContactLVI *kmc = dynamic_cast<KopeteMetaContactLVI *>( lvi ) )
					kmc->updateVisibility();
			}
		}
	}
}

void KopeteGroupViewItem::updateIcon()
{
	// TODO: clever caching
	if ( isOpen() )
	{
		if ( group()->useCustomIcon() )
			open = SmallIcon( group()->icon( KopetePluginDataObject::Open ) );
		else
			open = SmallIcon( "folder_green_open" );

		d->image->setPixmap( open );
	}
	else
	{
		if ( group()->useCustomIcon() )
			closed = SmallIcon( group()->icon( KopetePluginDataObject::Closed ) );
		else
			closed = SmallIcon( "folder_green" );

		d->image->setPixmap( closed );
	}
}

#include "kopetegroupviewitem.moc"
// vim: set noet ts=4 sts=4 sw=4:
<|endoftext|>


<commit_before>#include "Fit/Fitter.h"
#include "Math/WrappedMultiTF1.h"
#include "TH1.h"
#include "TMath.h"
#include "TRandom.h"
#include "TROOT.h"

#include<iostream>
#include<chrono>

constexpr int paramSize = 6;

bool compareResult(double v1, double v2, std::string s = "", double tol = 0.01)
{
   // compare v1 with reference v2
   //  // give 1% tolerance
   if (std::abs(v1 - v2) < tol * std::abs(v2)) return true;
   std::cerr << s << " Failed comparison of fit results \t logl = " << v1 << "   it should be = " << v2 << std::endl;
   return false;
}

//Functor for a Higgs Fit normalized with analytical integral
template<class T>
class Func {
public:

   Func()
   {
      params.resize(paramSize);
   }
   T operator()(const T *data, const Double_t *p)
   {
      bool changed = false;
      for (unsigned i = 0; i < params.size(); i++) {
         R__LOCKGUARD(gROOTMutex);
         if (p[i] != params[i])
            if (!changed) {
               changed = true;
            }

      }

      if (changed) {
         R__LOCKGUARD(gROOTMutex);
         for (unsigned i = 0; i < paramSize; i++) {
            params[i] = p[i];
         }
         auto funcInt1 = [&](double x) {
            return 50.*TMath::Sqrt(TMath::Pi()) * exp((p[4] * p[4]) / (4 * p[5])) * TMath::Erf((0.5 * p[4] + p[5] * 0.01 * x) / (TMath::Sqrt(p[5])))
                   / (TMath::Sqrt(p[5]));
         };
         auto funcInt2 = [&](double x) {
            return -p[3] * TMath::Sqrt(TMath::Pi() / 2.) * TMath::Erf((p[2] - x) / (TMath::Sqrt(2.) * p[3]));
         };
         integral1 = funcInt1(200) - funcInt1(100);
         integral2 = funcInt2(200) - funcInt2(100);
      }

      auto f1 = params[0] * exp(-(*data + (-p[2])) * (*data + (-p[2])) / (2.*p[3] * p[3]));

      auto f2 = (1 - params[0]) * exp(-(params[4] * (*data * (0.01)) +
                                        params[5] * ((*data) * (0.01)) * ((*data) * (0.01))));

      f1 /= integral2 != 0 ? integral2 : 1;
      f2 /= integral1 != 0 ? integral1 : 1;
      return f1 + f2;
   }

private:

   double integral1 = 1.;
   double integral2 = 1.;
   std::vector<double> params;
};

//Test class with functions for each of the cases
class TestVector {
public:
   TestVector(unsigned nPoints)
   {
      fSeq =  new TF1("fseq", Func<double>(), 100, 200, paramSize);
      wfSeq =  new ROOT::Math::WrappedMultiTF1Templ<double>(*fSeq);

#ifdef R__HAS_VECCORE
      fVec = new TF1("fvCore", Func<ROOT::Double_v>(), 100, 200, paramSize);
      wfVec =  new ROOT::Math::WrappedMultiTF1Templ<ROOT::Double_v>(*fVec);
#endif

      dataSB = new ROOT::Fit::UnBinData(nPoints);

      fSeq->SetParameters(p);
      if (!filledData) {
         for (unsigned i = 0; i < nPoints; ++i) {
            double x = fSeq->GetRandom();
            dataSB->Add(x);
         }
         filledData = true;
      }
      fitter.Config().MinimizerOptions().SetPrintLevel(3);
      fitter.Config().SetMinimizer("Minuit2", "Migrad");
      fitter.Config().MinimizerOptions().SetTolerance(10);
   }

   double testFitSeq()
   {
      std::cout << "\n////////////////////////////SEQUENTIAL TEST////////////////////////////" << std::endl << std::endl;
      fSeq->SetParameters(p);
      fitter.SetFunction(*wfSeq, false);
      fitter.Config().ParSettings(0).SetLimits(0, 1);
      fitter.Config().ParSettings(1).Fix();
      fitter.Config().ParSettings(3).SetLowerLimit(0);
      fitter.Config().ParSettings(4).SetLowerLimit(0);
      fitter.Config().ParSettings(5).SetLowerLimit(0);
      // save the parameter settings for the other fits
      paramSettings = fitter.Config().ParamsSettings();
      start = std::chrono::system_clock::now();
      bool ret = fitter.Fit(*dataSB);
      end =  std::chrono::system_clock::now();
      duration = end - start;
      std::cout << std::endl << "Time for the sequential test: " << duration.count() << std::endl;
      return  ret;
   }

   double testMTFit()
   {
      std::cout << "\n///////////////////////////////MT TEST////////////////////////////" << std::endl << std::endl;
      fSeq->SetParameters(p);
      fitter.SetFunction(*wfSeq, false);
      fitter.Config().ParamsSettings() = paramSettings;
      start = std::chrono::system_clock::now();
      bool ret = fitter.Fit(*dataSB, 0, ROOT::Fit::ExecutionPolicy::kMultithread);
      end =  std::chrono::system_clock::now();
      duration = end - start;
      std::cout << "Time for the parallel test: " << duration.count() << std::endl;
      return ret;
   }

   double testMPFit()
   {
      std::cout << "\n///////////////////////////////MP TEST////////////////////////////\n\n";
      fSeq->SetParameters(p);
      fitter.SetFunction(*wfSeq, false);
      fitter.Config().ParamsSettings() = paramSettings;
      start = std::chrono::system_clock::now();
      bool ret = fitter.Fit(*dataSB, 0, ROOT::Fit::ExecutionPolicy::kMultiprocess);
      end =  std::chrono::system_clock::now();
      duration = end - start;
      std::cout << "Time for the multiprocess test:" << duration.count() << std::endl;
      return ret;
   }

#ifdef R__HAS_VECCORE
   double testFitVec()
   {
      std::cout << "\n////////////////////////////VECTOR TEST////////////////////////////" << std::endl << std::endl;
      fVec->SetParameters(p);
      fitter.SetFunction(*wfVec);
      fitter.Config().ParamsSettings() = paramSettings;
      start = std::chrono::system_clock::now();
      bool ret = fitter.Fit(*dataSB);
      end =  std::chrono::system_clock::now();
      duration = end - start;
      std::cout << "Time for the vectorized test: " << duration.count() << std::endl;
      return ret;
   }

   double testMTFitVec()
   {
      std::cout << "\n///////////////////////////////MT+VEC TEST////////////////////////////\n\n";
      fVec->SetParameters(p);
      fitter.SetFunction(*wfVec);
      fitter.Config().ParSettings(0).SetLimits(0, 1);
      start = std::chrono::system_clock::now();
      bool ret = fitter.Fit(*dataSB, 0, ROOT::Fit::ExecutionPolicy::kMultithread);
      end =  std::chrono::system_clock::now();
      duration = end - start;
      std::cout << "Time for the parallel+vectorized test: " << duration.count() << std::endl;
      return ret;
   }

   double testMPFitVec()
   {
      std::cout << "\n///////////////////////////////MP+VEC TEST////////////////////////////\n\n";
      fVec->SetParameters(p);
      fitter.SetFunction(*wfVec);
      fitter.Config().ParamsSettings() = paramSettings;
      start = std::chrono::system_clock::now();
      bool ret = fitter.Fit(*dataSB, 0, ROOT::Fit::ExecutionPolicy::kMultiprocess);
      end =  std::chrono::system_clock::now();
      duration = end - start;
      std::cout << "Time for the multiprocess+vectorized test:" << duration.count() << std::endl;
      return ret;
   }
#endif
   const ROOT::Fit::Fitter &GetFitter()
   {
      return fitter;
   }

private:
   TF1 *fSeq;
   ROOT::Math::WrappedMultiTF1Templ<double> *wfSeq;
#ifdef R__HAS_VECCORE
   TF1 *fVec;
   ROOT::Math::WrappedMultiTF1Templ<ROOT::Double_v> *wfVec;
#endif
   std::chrono::time_point<std::chrono::system_clock> start, end;
   std::chrono::duration<double> duration;
   ROOT::Fit::Fitter fitter;
   ROOT::Fit::UnBinData *dataSB;
   std::vector<ROOT::Fit::ParameterSettings> paramSettings;
   bool filledData = false;
   double p[paramSize] = {0.1, 1000., 130., 2., 3.5, 1.5};
};

int main()
{
   TestVector test(200000);

   //Sequential
   if (!test.testFitSeq()) {
      Error("testLogLExecPolicy", "Fit failed!");
      return -1;
   }

// #if defined(R__USE_IMT) || defined(R__HAS_VECCORE)
//#ifdef R__HAS_VECCORE
   auto seq = test.GetFitter().Result().MinFcnValue();
//#endif

#ifdef R__USE_IMT
   //Multithreaded
   if (!test.testMTFit()) {
      Error("testLogLExecPolicy", "Multithreaded Fit failed!");
      return -1;
   }
   auto seqMT = test.GetFitter().Result().MinFcnValue();
   if (!compareResult(seqMT, seq, "Mutithreaded LogL Fit: "))
      return 1;
#endif

#ifdef R__HAS_VECCORE
   //Vectorized
   if (!test.testFitVec()) {
      Error("testLogLExecPolicy", "Vectorized Fit failed!");
      return -1;
   }
   auto vec = test.GetFitter().Result().MinFcnValue();
   if (!compareResult(vec, seq, "vectorized LogL Fit: "))
      return 2;
#endif

#if defined(R__USE_IMT) && defined(R__HAS_VECCORE)
   //Multithreaded and vectorized
   if (!test.testMTFitVec()) {
      Error("testLogLExecPolicy", "Multithreaded + vectorized Fit failed!");
      return -1;
   }
   auto vecMT = test.GetFitter().Result().MinFcnValue();
   if (!compareResult(vecMT, seq, "Mutithreaded + vectorized LogL Fit: "))
      return 3;
#endif
   return 0;
}
<commit_msg>Set correctly the fit parameters settings for all the different tests (2)<commit_after>#include "Fit/Fitter.h"
#include "Math/WrappedMultiTF1.h"
#include "TH1.h"
#include "TMath.h"
#include "TRandom.h"
#include "TROOT.h"

#include<iostream>
#include<chrono>

constexpr int paramSize = 6;

bool compareResult(double v1, double v2, std::string s = "", double tol = 0.01)
{
   // compare v1 with reference v2
   //  // give 1% tolerance
   if (std::abs(v1 - v2) < tol * std::abs(v2)) return true;
   std::cerr << s << " Failed comparison of fit results \t logl = " << v1 << "   it should be = " << v2 << std::endl;
   return false;
}

//Functor for a Higgs Fit normalized with analytical integral
template<class T>
class Func {
public:

   Func()
   {
      params.resize(paramSize);
   }
   T operator()(const T *data, const Double_t *p)
   {
      bool changed = false;
      for (unsigned i = 0; i < params.size(); i++) {
         R__LOCKGUARD(gROOTMutex);
         if (p[i] != params[i])
            if (!changed) {
               changed = true;
            }

      }

      if (changed) {
         R__LOCKGUARD(gROOTMutex);
         for (unsigned i = 0; i < paramSize; i++) {
            params[i] = p[i];
         }
         auto funcInt1 = [&](double x) {
            return 50.*TMath::Sqrt(TMath::Pi()) * exp((p[4] * p[4]) / (4 * p[5])) * TMath::Erf((0.5 * p[4] + p[5] * 0.01 * x) / (TMath::Sqrt(p[5])))
                   / (TMath::Sqrt(p[5]));
         };
         auto funcInt2 = [&](double x) {
            return -p[3] * TMath::Sqrt(TMath::Pi() / 2.) * TMath::Erf((p[2] - x) / (TMath::Sqrt(2.) * p[3]));
         };
         integral1 = funcInt1(200) - funcInt1(100);
         integral2 = funcInt2(200) - funcInt2(100);
      }

      auto f1 = params[0] * exp(-(*data + (-p[2])) * (*data + (-p[2])) / (2.*p[3] * p[3]));

      auto f2 = (1 - params[0]) * exp(-(params[4] * (*data * (0.01)) +
                                        params[5] * ((*data) * (0.01)) * ((*data) * (0.01))));

      f1 /= integral2 != 0 ? integral2 : 1;
      f2 /= integral1 != 0 ? integral1 : 1;
      return f1 + f2;
   }

private:

   double integral1 = 1.;
   double integral2 = 1.;
   std::vector<double> params;
};

//Test class with functions for each of the cases
class TestVector {
public:
   TestVector(unsigned nPoints)
   {
      fSeq =  new TF1("fseq", Func<double>(), 100, 200, paramSize);
      wfSeq =  new ROOT::Math::WrappedMultiTF1Templ<double>(*fSeq);

#ifdef R__HAS_VECCORE
      fVec = new TF1("fvCore", Func<ROOT::Double_v>(), 100, 200, paramSize);
      wfVec =  new ROOT::Math::WrappedMultiTF1Templ<ROOT::Double_v>(*fVec);
#endif

      dataSB = new ROOT::Fit::UnBinData(nPoints);

      fSeq->SetParameters(p);
      if (!filledData) {
         for (unsigned i = 0; i < nPoints; ++i) {
            double x = fSeq->GetRandom();
            dataSB->Add(x);
         }
         filledData = true;
      }
      fitter.Config().MinimizerOptions().SetPrintLevel(3);
      fitter.Config().SetMinimizer("Minuit2", "Migrad");
      fitter.Config().MinimizerOptions().SetTolerance(10);
   }

   double testFitSeq()
   {
      std::cout << "\n////////////////////////////SEQUENTIAL TEST////////////////////////////" << std::endl << std::endl;
      fSeq->SetParameters(p);
      fitter.SetFunction(*wfSeq, false);
      fitter.Config().ParSettings(0).SetLimits(0, 1);
      fitter.Config().ParSettings(1).Fix();
      fitter.Config().ParSettings(3).SetLowerLimit(0);
      fitter.Config().ParSettings(4).SetLowerLimit(0);
      fitter.Config().ParSettings(5).SetLowerLimit(0);
      // save the parameter settings for the other fits
      paramSettings = fitter.Config().ParamsSettings();
      start = std::chrono::system_clock::now();
      bool ret = fitter.Fit(*dataSB);
      end =  std::chrono::system_clock::now();
      duration = end - start;
      std::cout << std::endl << "Time for the sequential test: " << duration.count() << std::endl;
      return  ret;
   }

   double testMTFit()
   {
      std::cout << "\n///////////////////////////////MT TEST////////////////////////////" << std::endl << std::endl;
      fSeq->SetParameters(p);
      fitter.SetFunction(*wfSeq, false);
      fitter.Config().ParamsSettings() = paramSettings;
      start = std::chrono::system_clock::now();
      bool ret = fitter.Fit(*dataSB, 0, ROOT::Fit::ExecutionPolicy::kMultithread);
      end =  std::chrono::system_clock::now();
      duration = end - start;
      std::cout << "Time for the parallel test: " << duration.count() << std::endl;
      return ret;
   }

   double testMPFit()
   {
      std::cout << "\n///////////////////////////////MP TEST////////////////////////////\n\n";
      fSeq->SetParameters(p);
      fitter.SetFunction(*wfSeq, false);
      fitter.Config().ParamsSettings() = paramSettings;
      start = std::chrono::system_clock::now();
      bool ret = fitter.Fit(*dataSB, 0, ROOT::Fit::ExecutionPolicy::kMultiprocess);
      end =  std::chrono::system_clock::now();
      duration = end - start;
      std::cout << "Time for the multiprocess test:" << duration.count() << std::endl;
      return ret;
   }

#ifdef R__HAS_VECCORE
   double testFitVec()
   {
      std::cout << "\n////////////////////////////VECTOR TEST////////////////////////////" << std::endl << std::endl;
      fVec->SetParameters(p);
      fitter.SetFunction(*wfVec);
      fitter.Config().ParamsSettings() = paramSettings;
      start = std::chrono::system_clock::now();
      bool ret = fitter.Fit(*dataSB);
      end =  std::chrono::system_clock::now();
      duration = end - start;
      std::cout << "Time for the vectorized test: " << duration.count() << std::endl;
      return ret;
   }

   double testMTFitVec()
   {
      std::cout << "\n///////////////////////////////MT+VEC TEST////////////////////////////\n\n";
      fVec->SetParameters(p);
      fitter.SetFunction(*wfVec);
      fitter.Config().ParamsSettings() = paramSettings;
      start = std::chrono::system_clock::now();
      bool ret = fitter.Fit(*dataSB, 0, ROOT::Fit::ExecutionPolicy::kMultithread);
      end =  std::chrono::system_clock::now();
      duration = end - start;
      std::cout << "Time for the parallel+vectorized test: " << duration.count() << std::endl;
      return ret;
   }

   double testMPFitVec()
   {
      std::cout << "\n///////////////////////////////MP+VEC TEST////////////////////////////\n\n";
      fVec->SetParameters(p);
      fitter.SetFunction(*wfVec);
      fitter.Config().ParamsSettings() = paramSettings;
      start = std::chrono::system_clock::now();
      bool ret = fitter.Fit(*dataSB, 0, ROOT::Fit::ExecutionPolicy::kMultiprocess);
      end =  std::chrono::system_clock::now();
      duration = end - start;
      std::cout << "Time for the multiprocess+vectorized test:" << duration.count() << std::endl;
      return ret;
   }
#endif
   const ROOT::Fit::Fitter &GetFitter()
   {
      return fitter;
   }

private:
   TF1 *fSeq;
   ROOT::Math::WrappedMultiTF1Templ<double> *wfSeq;
#ifdef R__HAS_VECCORE
   TF1 *fVec;
   ROOT::Math::WrappedMultiTF1Templ<ROOT::Double_v> *wfVec;
#endif
   std::chrono::time_point<std::chrono::system_clock> start, end;
   std::chrono::duration<double> duration;
   ROOT::Fit::Fitter fitter;
   ROOT::Fit::UnBinData *dataSB;
   std::vector<ROOT::Fit::ParameterSettings> paramSettings;
   bool filledData = false;
   double p[paramSize] = {0.1, 1000., 130., 2., 3.5, 1.5};
};

int main()
{
   TestVector test(200000);

   //Sequential
   if (!test.testFitSeq()) {
      Error("testLogLExecPolicy", "Fit failed!");
      return -1;
   }

// #if defined(R__USE_IMT) || defined(R__HAS_VECCORE)
//#ifdef R__HAS_VECCORE
   auto seq = test.GetFitter().Result().MinFcnValue();
//#endif

#ifdef R__USE_IMT
   //Multithreaded
   if (!test.testMTFit()) {
      Error("testLogLExecPolicy", "Multithreaded Fit failed!");
      return -1;
   }
   auto seqMT = test.GetFitter().Result().MinFcnValue();
   if (!compareResult(seqMT, seq, "Mutithreaded LogL Fit: "))
      return 1;
#endif

#ifdef R__HAS_VECCORE
   //Vectorized
   if (!test.testFitVec()) {
      Error("testLogLExecPolicy", "Vectorized Fit failed!");
      return -1;
   }
   auto vec = test.GetFitter().Result().MinFcnValue();
   if (!compareResult(vec, seq, "vectorized LogL Fit: "))
      return 2;
#endif

#if defined(R__USE_IMT) && defined(R__HAS_VECCORE)
   //Multithreaded and vectorized
   if (!test.testMTFitVec()) {
      Error("testLogLExecPolicy", "Multithreaded + vectorized Fit failed!");
      return -1;
   }
   auto vecMT = test.GetFitter().Result().MinFcnValue();
   if (!compareResult(vecMT, seq, "Mutithreaded + vectorized LogL Fit: "))
      return 3;
#endif
   return 0;
}
<|endoftext|>


<commit_before>/**
 * The MIT License (MIT)
 *
 * Copyright (c) 2015 Nathan Osman
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 **/

#include <QFont>

#include "../util/platform.h"
#include "aboutdialog.h"
#include "config.h"

const QString Credits =
    "<meta name='qrichtext' content='1'/>"
    "

Created by:	"
    "Nathan Osman
"
    "
	Matthew Jump
"
    "
	Daniel San
"
    "
";

const QString License =
    "The MIT License (MIT)\n\n"

    "Permission is hereby granted, free of charge, to any person obtaining a copy "
    "of this software and associated documentation files (the \"Software\"), to "
    "deal in the Software without restriction, including without limitation the "
    "rights to use, copy, modify, merge, publish, distribute, sublicense, and/or "
    "sell copies of the Software, and to permit persons to whom the Software is "
    "furnished to do so, subject to the following conditions:\n\n"

    "The above copyright notice and this permission notice shall be included in "
    "all copies or substantial portions of the Software.\n\n"

    "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR "
    "IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, "
    "FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE "
    "AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER "
    "LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING "
    "FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS "
    "IN THE SOFTWARE.";

AboutDialog::AboutDialog()
{
    setupUi(this);

    layout()->setAlignment(logo, Qt::AlignHCenter);
    logo->load(QString(":/img/logo.svg"));

    QFont font = lblProjectTitle->font();
    font.setBold(true);
    lblProjectTitle->setFont(font);
    lblProjectTitle->setText(PROJECT_NAME);

    lblVersion->setText(QString("Version %1 - %2 %3").arg(PROJECT_VERSION)
            .arg(Platform::operatingSystemFriendlyName())
            .arg(Platform::architectureName()));
    lblDescription->setText(PROJECT_DESCRIPTION);

    QString websiteTxt("%1");
    lblWebsite->setText(websiteTxt.arg(PROJECT_WEBSITE));
    lblCopyright->setText(QString("Copyright (c) 2016 - %1").arg(PROJECT_AUTHOR));

    textBrowser->hide();
}

void AboutDialog::onCreditsOrLicenceClicked(bool checked)
{
    if (sender()->objectName() == "btnLicense") {
        textBrowser->setText(License);
        btnCredits->setChecked(false);
    } else if (sender()->objectName() == "btnCredits") {
        textBrowser->setText(Credits);
        btnLicense->setChecked(false);
    }

    textBrowser->setVisible(checked);
    wdtContent->setVisible(!checked);
}
<commit_msg>Added Edity to list of translators.<commit_after>/**
 * The MIT License (MIT)
 *
 * Copyright (c) 2015 Nathan Osman
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 **/

#include <QFont>

#include "../util/platform.h"
#include "aboutdialog.h"
#include "config.h"

const QString Credits =
    "<meta name='qrichtext' content='1'/>"
    "

Created by: 	"
    "Nathan Osman
"
    "Matthew Jump
"
    "Daniel San
"
    "

Translated by: 	"
    "Edity (Korean)	"
    "
";

const QString License =
    "The MIT License (MIT)\n\n"

    "Permission is hereby granted, free of charge, to any person obtaining a copy "
    "of this software and associated documentation files (the \"Software\"), to "
    "deal in the Software without restriction, including without limitation the "
    "rights to use, copy, modify, merge, publish, distribute, sublicense, and/or "
    "sell copies of the Software, and to permit persons to whom the Software is "
    "furnished to do so, subject to the following conditions:\n\n"

    "The above copyright notice and this permission notice shall be included in "
    "all copies or substantial portions of the Software.\n\n"

    "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR "
    "IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, "
    "FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE "
    "AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER "
    "LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING "
    "FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS "
    "IN THE SOFTWARE.";

AboutDialog::AboutDialog()
{
    setupUi(this);

    layout()->setAlignment(logo, Qt::AlignHCenter);
    logo->load(QString(":/img/logo.svg"));

    QFont font = lblProjectTitle->font();
    font.setBold(true);
    lblProjectTitle->setFont(font);
    lblProjectTitle->setText(PROJECT_NAME);

    lblVersion->setText(QString("Version %1 - %2 %3").arg(PROJECT_VERSION)
            .arg(Platform::operatingSystemFriendlyName())
            .arg(Platform::architectureName()));
    lblDescription->setText(PROJECT_DESCRIPTION);

    QString websiteTxt("%1");
    lblWebsite->setText(websiteTxt.arg(PROJECT_WEBSITE));
    lblCopyright->setText(QString("Copyright (c) 2016 - %1").arg(PROJECT_AUTHOR));

    textBrowser->hide();
}

void AboutDialog::onCreditsOrLicenceClicked(bool checked)
{
    if (sender()->objectName() == "btnLicense") {
        textBrowser->setText(License);
        btnCredits->setChecked(false);
    } else if (sender()->objectName() == "btnCredits") {
        textBrowser->setText(Credits);
        btnLicense->setChecked(false);
    }

    textBrowser->setVisible(checked);
    wdtContent->setVisible(!checked);
}
<|endoftext|>


<commit_before>#include "Atm_player.hpp"

/* Add optional parameters for the state machine to begin()
 * Add extra initialization code
 */

Atm_player& Atm_player::begin( int pin /* = - 1 */ ) {
  // clang-format off
  const static state_t state_table[] PROGMEM = {
    /*             ON_ENTER    ON_LOOP  ON_EXIT  EVT_START  EVT_STOP  EVT_TOGGLE  EVT_TIMER  EVT_EOPAT  EVT_REPEAT   ELSE */
    /*   IDLE */   ENT_IDLE, ATM_SLEEP,      -1,     START,       -1,      START,        -1,        -1,         -1,    -1,
    /*  START */  ENT_START,        -1,      -1,        -1,       -1,         -1,        -1,        -1,         -1, SOUND,
    /*  SOUND */  ENT_SOUND,        -1,      -1,        -1,     IDLE,       IDLE,     QUIET,        -1,         -1,    -1,
    /*  QUIET */  ENT_QUIET,        -1,      -1,        -1,     IDLE,       IDLE,      NEXT,        -1,         -1,    -1,
    /*   NEXT */   ENT_NEXT,        -1,      -1,        -1,     IDLE,       IDLE,        -1,    REPEAT,         -1, SOUND,
    /* REPEAT */ ENT_REPEAT,        -1,      -1,        -1,     IDLE,       IDLE,        -1,        -1,     FINISH, START,
    /* FINISH */ ENT_FINISH,        -1,      -1,        -1,     IDLE,         -1,        -1,        -1,       IDLE, START,
  };
  // clang-format on
  Machine::begin( state_table, ELSE );
  Atm_player::pin = pin;
  speed( 100 );
  pitch( 100 );
  repeat( 1 );
  play( 880, 50 );
  return *this;
}

/* Add C++ code for each event (input)
 * The code must return 1 if the event should be triggered
 */

int Atm_player::event( int id ) {
  switch ( id ) {
    case EVT_START:
      return 0;
    case EVT_TIMER:
      return timer.expired( this );
    case EVT_EOPAT:
      if ( patternwidth == 32 ) {
        return ( step * 3 * sizeof( uint32_t ) ) >= patternsize;
      } else {
        return ( step * 3 * sizeof( int ) ) >= patternsize;
      }
    case EVT_REPEAT:
      return counter_repeat.expired();
  }
  return 0;
}

/* Add C++ code for each action
 * This generates the 'output' for the state machine
 */

void Atm_player::action( int id ) {
  switch ( id ) {
    case ENT_FINISH:
      push( connectors, ON_FINISH, 0, 0, 0 );
      return;
    case ENT_IDLE:
#ifdef _VARIANT_ARDUINO_DUE_X_
      if ( pin >= 0 ) noTone( pin );  // Tone takes up 7 bytes extra SRAM
#endif
      counter_repeat.set( repeatCount );
      return;
    case ENT_START:
      step = 0;
      counter_repeat.decrement();
      return;
    case ENT_SOUND:
      if ( patternwidth == 32 ) {
        uint32_t v = pattern32[step * 3] * (uint32_t)pitchFactor;
        push( connectors, ON_NOTE, true, v & 0xFFFF, v >> 16 & 0xFFFF );
#ifdef _VARIANT_ARDUINO_DUE_X_
        if ( pin >= 0 ) tone( pin, pattern32[step * 3] * pitchFactor );
#endif
        timer.set( pattern32[step * 3 + 1] * speedFactor );
      } else {
        push( connectors, ON_NOTE, true, pattern16[step * 3] * pitchFactor, 1 );
#ifdef _VARIANT_ARDUINO_DUE_X_
        if ( pin >= 0 ) tone( pin, pattern16[step * 3] * pitchFactor );
#endif
        timer.set( pattern16[step * 3 + 1] * speedFactor );
      }
      return;
    case ENT_QUIET:
      if ( patternwidth == 32 ) {
        uint32_t v = pattern32[step * 3] * (uint32_t)pitchFactor;
        push( connectors, ON_NOTE, false, v & 0xFFFF, v >> 16 & 0xFFFF );
#ifdef _VARIANT_ARDUINO_DUE_X_
        if ( pin >= 0 ) noTone( pin );
#endif
        timer.set( pattern32[step * 3 + 2] * speedFactor );
      } else {
        push( connectors, ON_NOTE, false, pattern16[step * 3] * pitchFactor, 0 );
#ifdef _VARIANT_ARDUINO_DUE_X_
        if ( pin >= 0 ) noTone( pin );
#endif
        timer.set( pattern16[step * 3 + 2] * speedFactor );
      }
      return;
    case ENT_NEXT:
      step++;
      return;
    case ENT_REPEAT:
      return;
  }
}

/* How many times to repeat the pattern
 *
 */

Atm_player& Atm_player::repeat( uint16_t v /* = -1 */) {
  counter_repeat.set( repeatCount = v );
  return *this;
}

Atm_player& Atm_player::speed( float v ) {
  speedFactor = 100 / v;
  return *this;
}

Atm_player& Atm_player::pitch( float v ) {
  pitchFactor = v / 100;
  return *this;
}

Atm_player& Atm_player::start( void ) {
  trigger( EVT_START );
  return *this;
}

Atm_player& Atm_player::stop( void ) {
  trigger( EVT_STOP );
  return *this;
}

Atm_player& Atm_player::toggle( void ) {
  trigger( EVT_TOGGLE );
  return *this;
}

/* Sets the pattern and pattern length (in bytes)
 *
 */

Atm_player& Atm_player::play( int* pat, int patsize ) {
  patternwidth = 16;
  pattern16 = pat;
  patternsize = patsize;
  counter_repeat.set( repeatCount );
  step = 0;
  return *this;
}

Atm_player& Atm_player::play( uint32_t* pat, int patsize ) {
  patternwidth = 32;
  pattern32 = pat;
  patternsize = patsize;
  counter_repeat.set( repeatCount );
  step = 0;
  return *this;
}

Atm_player& Atm_player::play( int freq, int period, int pause /* = 0 */ ) {
  patternwidth = 16;
  stub[0] = freq;
  stub[1] = period;
  stub[2] = pause;
  pattern16 = stub;
  patternsize = 3 * sizeof( int );
  step = 0;
  return *this;
}

/* Optionally override the default trigger() method
 * Control what triggers your machine can and cannot process
 */

Atm_player& Atm_player::trigger( int event ) {
  Machine::trigger( event );
  return *this;
}

/* Optionally override the default state() method
 * Control what the machine returns when another process requests its state()
 */

int Atm_player::state( void ) {
  return Machine::state();
}

/* Nothing customizable below this line
 ************************************************************************************************
*/

/* onFinish() push connector variants ( slots 1, autostore 0, broadcast 0 )
 *
 * Usage in action() handler: push( connectors, ON_FINISH, 0, v, up)
 */

Atm_player& Atm_player::onFinish( Machine& machine, int event ) {
  onPush( connectors, ON_FINISH, 0, 1, 1, machine, event );
  return *this;
}
Atm_player& Atm_player::onFinish( atm_cb_push_t callback, int idx ) {
  onPush( connectors, ON_FINISH, 0, 1, 1, callback, idx );
  return *this;
}

/* onNote() push connector variants ( slots 2, autostore 0, broadcast 0 )
 *
 * Usage in action() handler: push( connectors, ON_NOTE, sub, v, up)
 */

Atm_player& Atm_player::onNote( Machine& machine, int event ) {
  onPush( connectors, ON_NOTE, 0, 2, 1, machine, event );
  return *this;
}
Atm_player& Atm_player::onNote( atm_cb_push_t callback, int idx ) {
  onPush( connectors, ON_NOTE, 0, 2, 1, callback, idx );
  return *this;
}
Atm_player& Atm_player::onNote( int sub, Machine& machine, int event ) {
  onPush( connectors, ON_NOTE, sub, 2, 0, machine, event );
  return *this;
}
Atm_player& Atm_player::onNote( int sub, atm_cb_push_t callback, int idx ) {
  onPush( connectors, ON_NOTE, sub, 2, 0, callback, idx );
  return *this;
}

/* State trace method
 * Sets the symbol table and the default logging method for serial monitoring
 */

Atm_player& Atm_player::trace( Stream& stream ) {
  Machine::setTrace( &stream, atm_serial_debug::trace,
                     "PLAYER\0EVT_START\0EVT_STOP\0EVT_TOGGLE\0EVT_TIMER\0EVT_EOPAT\0EVT_REPEAT\0ELSE\0IDLE\0START\0SOUND\0QUIET\0NEXT\0REPEAT\0FINISH" );
  return *this;
}
<commit_msg>Fixed tone ifdefs into ifndefs (issue #41)<commit_after>#include "Atm_player.hpp"

/* Add optional parameters for the state machine to begin()
 * Add extra initialization code
 */

Atm_player& Atm_player::begin( int pin /* = - 1 */ ) {
  // clang-format off
  const static state_t state_table[] PROGMEM = {
    /*             ON_ENTER    ON_LOOP  ON_EXIT  EVT_START  EVT_STOP  EVT_TOGGLE  EVT_TIMER  EVT_EOPAT  EVT_REPEAT   ELSE */
    /*   IDLE */   ENT_IDLE, ATM_SLEEP,      -1,     START,       -1,      START,        -1,        -1,         -1,    -1,
    /*  START */  ENT_START,        -1,      -1,        -1,       -1,         -1,        -1,        -1,         -1, SOUND,
    /*  SOUND */  ENT_SOUND,        -1,      -1,        -1,     IDLE,       IDLE,     QUIET,        -1,         -1,    -1,
    /*  QUIET */  ENT_QUIET,        -1,      -1,        -1,     IDLE,       IDLE,      NEXT,        -1,         -1,    -1,
    /*   NEXT */   ENT_NEXT,        -1,      -1,        -1,     IDLE,       IDLE,        -1,    REPEAT,         -1, SOUND,
    /* REPEAT */ ENT_REPEAT,        -1,      -1,        -1,     IDLE,       IDLE,        -1,        -1,     FINISH, START,
    /* FINISH */ ENT_FINISH,        -1,      -1,        -1,     IDLE,         -1,        -1,        -1,       IDLE, START,
  };
  // clang-format on
  Machine::begin( state_table, ELSE );
  Atm_player::pin = pin;
  speed( 100 );
  pitch( 100 );
  repeat( 1 );
  play( 880, 50 );
  return *this;
}

/* Add C++ code for each event (input)
 * The code must return 1 if the event should be triggered
 */

int Atm_player::event( int id ) {
  switch ( id ) {
    case EVT_START:
      return 0;
    case EVT_TIMER:
      return timer.expired( this );
    case EVT_EOPAT:
      if ( patternwidth == 32 ) {
        return ( step * 3 * sizeof( uint32_t ) ) >= patternsize;
      } else {
        return ( step * 3 * sizeof( int ) ) >= patternsize;
      }
    case EVT_REPEAT:
      return counter_repeat.expired();
  }
  return 0;
}

/* Add C++ code for each action
 * This generates the 'output' for the state machine
 */

void Atm_player::action( int id ) {
  switch ( id ) {
    case ENT_FINISH:
      push( connectors, ON_FINISH, 0, 0, 0 );
      return;
    case ENT_IDLE:
#ifndef _VARIANT_ARDUINO_DUE_X_
      if ( pin >= 0 ) noTone( pin );  // Tone takes up 7 bytes extra SRAM
#endif
      counter_repeat.set( repeatCount );
      return;
    case ENT_START:
      step = 0;
      counter_repeat.decrement();
      return;
    case ENT_SOUND:
      if ( patternwidth == 32 ) {
        uint32_t v = pattern32[step * 3] * (uint32_t)pitchFactor;
        push( connectors, ON_NOTE, true, v & 0xFFFF, v >> 16 & 0xFFFF );
#ifndef _VARIANT_ARDUINO_DUE_X_
        if ( pin >= 0 ) tone( pin, pattern32[step * 3] * pitchFactor );
#endif
        timer.set( pattern32[step * 3 + 1] * speedFactor );
      } else {
        push( connectors, ON_NOTE, true, pattern16[step * 3] * pitchFactor, 1 );
#ifndef _VARIANT_ARDUINO_DUE_X_
        if ( pin >= 0 ) tone( pin, pattern16[step * 3] * pitchFactor );
#endif
        timer.set( pattern16[step * 3 + 1] * speedFactor );
      }
      return;
    case ENT_QUIET:
      if ( patternwidth == 32 ) {
        uint32_t v = pattern32[step * 3] * (uint32_t)pitchFactor;
        push( connectors, ON_NOTE, false, v & 0xFFFF, v >> 16 & 0xFFFF );
#ifndef _VARIANT_ARDUINO_DUE_X_
        if ( pin >= 0 ) noTone( pin );
#endif
        timer.set( pattern32[step * 3 + 2] * speedFactor );
      } else {
        push( connectors, ON_NOTE, false, pattern16[step * 3] * pitchFactor, 0 );
#ifndef _VARIANT_ARDUINO_DUE_X_
        if ( pin >= 0 ) noTone( pin );
#endif
        timer.set( pattern16[step * 3 + 2] * speedFactor );
      }
      return;
    case ENT_NEXT:
      step++;
      return;
    case ENT_REPEAT:
      return;
  }
}

/* How many times to repeat the pattern
 *
 */

Atm_player& Atm_player::repeat( uint16_t v /* = -1 */) {
  counter_repeat.set( repeatCount = v );
  return *this;
}

Atm_player& Atm_player::speed( float v ) {
  speedFactor = 100 / v;
  return *this;
}

Atm_player& Atm_player::pitch( float v ) {
  pitchFactor = v / 100;
  return *this;
}

Atm_player& Atm_player::start( void ) {
  trigger( EVT_START );
  return *this;
}

Atm_player& Atm_player::stop( void ) {
  trigger( EVT_STOP );
  return *this;
}

Atm_player& Atm_player::toggle( void ) {
  trigger( EVT_TOGGLE );
  return *this;
}

/* Sets the pattern and pattern length (in bytes)
 *
 */

Atm_player& Atm_player::play( int* pat, int patsize ) {
  patternwidth = 16;
  pattern16 = pat;
  patternsize = patsize;
  counter_repeat.set( repeatCount );
  step = 0;
  return *this;
}

Atm_player& Atm_player::play( uint32_t* pat, int patsize ) {
  patternwidth = 32;
  pattern32 = pat;
  patternsize = patsize;
  counter_repeat.set( repeatCount );
  step = 0;
  return *this;
}

Atm_player& Atm_player::play( int freq, int period, int pause /* = 0 */ ) {
  patternwidth = 16;
  stub[0] = freq;
  stub[1] = period;
  stub[2] = pause;
  pattern16 = stub;
  patternsize = 3 * sizeof( int );
  step = 0;
  return *this;
}

/* Optionally override the default trigger() method
 * Control what triggers your machine can and cannot process
 */

Atm_player& Atm_player::trigger( int event ) {
  Machine::trigger( event );
  return *this;
}

/* Optionally override the default state() method
 * Control what the machine returns when another process requests its state()
 */

int Atm_player::state( void ) {
  return Machine::state();
}

/* Nothing customizable below this line
 ************************************************************************************************
*/

/* onFinish() push connector variants ( slots 1, autostore 0, broadcast 0 )
 *
 * Usage in action() handler: push( connectors, ON_FINISH, 0, v, up)
 */

Atm_player& Atm_player::onFinish( Machine& machine, int event ) {
  onPush( connectors, ON_FINISH, 0, 1, 1, machine, event );
  return *this;
}
Atm_player& Atm_player::onFinish( atm_cb_push_t callback, int idx ) {
  onPush( connectors, ON_FINISH, 0, 1, 1, callback, idx );
  return *this;
}

/* onNote() push connector variants ( slots 2, autostore 0, broadcast 0 )
 *
 * Usage in action() handler: push( connectors, ON_NOTE, sub, v, up)
 */

Atm_player& Atm_player::onNote( Machine& machine, int event ) {
  onPush( connectors, ON_NOTE, 0, 2, 1, machine, event );
  return *this;
}
Atm_player& Atm_player::onNote( atm_cb_push_t callback, int idx ) {
  onPush( connectors, ON_NOTE, 0, 2, 1, callback, idx );
  return *this;
}
Atm_player& Atm_player::onNote( int sub, Machine& machine, int event ) {
  onPush( connectors, ON_NOTE, sub, 2, 0, machine, event );
  return *this;
}
Atm_player& Atm_player::onNote( int sub, atm_cb_push_t callback, int idx ) {
  onPush( connectors, ON_NOTE, sub, 2, 0, callback, idx );
  return *this;
}

/* State trace method
 * Sets the symbol table and the default logging method for serial monitoring
 */

Atm_player& Atm_player::trace( Stream& stream ) {
  Machine::setTrace( &stream, atm_serial_debug::trace,
                     "PLAYER\0EVT_START\0EVT_STOP\0EVT_TOGGLE\0EVT_TIMER\0EVT_EOPAT\0EVT_REPEAT\0ELSE\0IDLE\0START\0SOUND\0QUIET\0NEXT\0REPEAT\0FINISH" );
  return *this;
}
<|endoftext|>


<commit_before>//===--- ConstantFolding.cpp - Utils for SIL constant folding -------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#include "swift/SILOptimizer/Utils/ConstantFolding.h"

using namespace swift;

APInt swift::constantFoldBitOperation(APInt lhs, APInt rhs, BuiltinValueKind ID) {
  switch (ID) {
    default: llvm_unreachable("Not all cases are covered!");
    case BuiltinValueKind::And:
      return lhs.And(rhs);
    case BuiltinValueKind::AShr:
      return lhs.ashr(rhs);
    case BuiltinValueKind::LShr:
      return lhs.lshr(rhs);
    case BuiltinValueKind::Or:
      return lhs.Or(rhs);
    case BuiltinValueKind::Shl:
      return lhs.shl(rhs);
    case BuiltinValueKind::Xor:
      return lhs.Xor(rhs);
  }
}

APInt swift::constantFoldComparison(APInt lhs, APInt rhs, BuiltinValueKind ID) {
  bool result;
  switch (ID) {
    default: llvm_unreachable("Invalid integer compare kind");
    case BuiltinValueKind::ICMP_EQ:  result = lhs == rhs; break;
    case BuiltinValueKind::ICMP_NE:  result = lhs != rhs; break;
    case BuiltinValueKind::ICMP_SLT: result = lhs.slt(rhs); break;
    case BuiltinValueKind::ICMP_SGT: result = lhs.sgt(rhs); break;
    case BuiltinValueKind::ICMP_SLE: result = lhs.sle(rhs); break;
    case BuiltinValueKind::ICMP_SGE: result = lhs.sge(rhs); break;
    case BuiltinValueKind::ICMP_ULT: result = lhs.ult(rhs); break;
    case BuiltinValueKind::ICMP_UGT: result = lhs.ugt(rhs); break;
    case BuiltinValueKind::ICMP_ULE: result = lhs.ule(rhs); break;
    case BuiltinValueKind::ICMP_UGE: result = lhs.uge(rhs); break;
  }
  return APInt(1, result);
}

APInt swift::constantFoldBinaryWithOverflow(APInt lhs, APInt rhs,
                                            bool &Overflow,
                                            llvm::Intrinsic::ID ID) {
  switch (ID) {
    default: llvm_unreachable("Invalid case");
    case llvm::Intrinsic::sadd_with_overflow:
      return lhs.sadd_ov(rhs, Overflow);
    case llvm::Intrinsic::uadd_with_overflow:
      return lhs.uadd_ov(rhs, Overflow);
    case llvm::Intrinsic::ssub_with_overflow:
      return lhs.ssub_ov(rhs, Overflow);
    case llvm::Intrinsic::usub_with_overflow:
      return lhs.usub_ov(rhs, Overflow);
    case llvm::Intrinsic::smul_with_overflow:
      return lhs.smul_ov(rhs, Overflow);
    case llvm::Intrinsic::umul_with_overflow:
      return lhs.umul_ov(rhs, Overflow);
  }
}

APInt swift::constantFoldDiv(APInt lhs, APInt rhs, bool &Overflow,
                             BuiltinValueKind ID) {
  assert(rhs != 0 && "division by zero");
  switch (ID) {
    default : llvm_unreachable("Invalid case");
    case BuiltinValueKind::SDiv:
      return lhs.sdiv_ov(rhs, Overflow);
    case BuiltinValueKind::SRem:
      // Check for overflow
      lhs.sdiv_ov(rhs, Overflow);
      return lhs.srem(rhs);
    case BuiltinValueKind::UDiv:
      Overflow = false;
      return lhs.udiv(rhs);
    case BuiltinValueKind::URem:
      Overflow = false;
      return lhs.urem(rhs);
  }
}

APInt swift::constantFoldCast(APInt val, const BuiltinInfo &BI) {
  // Get the cast result.
  Type SrcTy = BI.Types[0];
  Type DestTy = BI.Types.size() == 2 ? BI.Types[1] : Type();
  uint32_t SrcBitWidth =
  SrcTy->castTo<BuiltinIntegerType>()->getGreatestWidth();
  uint32_t DestBitWidth =
  DestTy->castTo<BuiltinIntegerType>()->getGreatestWidth();

  APInt CastResV;
  if (SrcBitWidth == DestBitWidth) {
    return val;
  } else switch (BI.ID) {
    default : llvm_unreachable("Invalid case.");
    case BuiltinValueKind::Trunc:
    case BuiltinValueKind::TruncOrBitCast:
      return val.trunc(DestBitWidth);
    case BuiltinValueKind::ZExt:
    case BuiltinValueKind::ZExtOrBitCast:
      return val.zext(DestBitWidth);
      break;
    case BuiltinValueKind::SExt:
    case BuiltinValueKind::SExtOrBitCast:
      return val.sext(DestBitWidth);
  }
}
<commit_msg>Adjust for SVN r297121<commit_after>//===--- ConstantFolding.cpp - Utils for SIL constant folding -------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#include "swift/SILOptimizer/Utils/ConstantFolding.h"

using namespace swift;

APInt swift::constantFoldBitOperation(APInt lhs, APInt rhs, BuiltinValueKind ID) {
  switch (ID) {
    default: llvm_unreachable("Not all cases are covered!");
    case BuiltinValueKind::And:
      return lhs & rhs;
    case BuiltinValueKind::AShr:
      return lhs.ashr(rhs);
    case BuiltinValueKind::LShr:
      return lhs.lshr(rhs);
    case BuiltinValueKind::Or:
      return lhs | rhs;
    case BuiltinValueKind::Shl:
      return lhs.shl(rhs);
    case BuiltinValueKind::Xor:
      return lhs ^ rhs;
  }
}

APInt swift::constantFoldComparison(APInt lhs, APInt rhs, BuiltinValueKind ID) {
  bool result;
  switch (ID) {
    default: llvm_unreachable("Invalid integer compare kind");
    case BuiltinValueKind::ICMP_EQ:  result = lhs == rhs; break;
    case BuiltinValueKind::ICMP_NE:  result = lhs != rhs; break;
    case BuiltinValueKind::ICMP_SLT: result = lhs.slt(rhs); break;
    case BuiltinValueKind::ICMP_SGT: result = lhs.sgt(rhs); break;
    case BuiltinValueKind::ICMP_SLE: result = lhs.sle(rhs); break;
    case BuiltinValueKind::ICMP_SGE: result = lhs.sge(rhs); break;
    case BuiltinValueKind::ICMP_ULT: result = lhs.ult(rhs); break;
    case BuiltinValueKind::ICMP_UGT: result = lhs.ugt(rhs); break;
    case BuiltinValueKind::ICMP_ULE: result = lhs.ule(rhs); break;
    case BuiltinValueKind::ICMP_UGE: result = lhs.uge(rhs); break;
  }
  return APInt(1, result);
}

APInt swift::constantFoldBinaryWithOverflow(APInt lhs, APInt rhs,
                                            bool &Overflow,
                                            llvm::Intrinsic::ID ID) {
  switch (ID) {
    default: llvm_unreachable("Invalid case");
    case llvm::Intrinsic::sadd_with_overflow:
      return lhs.sadd_ov(rhs, Overflow);
    case llvm::Intrinsic::uadd_with_overflow:
      return lhs.uadd_ov(rhs, Overflow);
    case llvm::Intrinsic::ssub_with_overflow:
      return lhs.ssub_ov(rhs, Overflow);
    case llvm::Intrinsic::usub_with_overflow:
      return lhs.usub_ov(rhs, Overflow);
    case llvm::Intrinsic::smul_with_overflow:
      return lhs.smul_ov(rhs, Overflow);
    case llvm::Intrinsic::umul_with_overflow:
      return lhs.umul_ov(rhs, Overflow);
  }
}

APInt swift::constantFoldDiv(APInt lhs, APInt rhs, bool &Overflow,
                             BuiltinValueKind ID) {
  assert(rhs != 0 && "division by zero");
  switch (ID) {
    default : llvm_unreachable("Invalid case");
    case BuiltinValueKind::SDiv:
      return lhs.sdiv_ov(rhs, Overflow);
    case BuiltinValueKind::SRem:
      // Check for overflow
      lhs.sdiv_ov(rhs, Overflow);
      return lhs.srem(rhs);
    case BuiltinValueKind::UDiv:
      Overflow = false;
      return lhs.udiv(rhs);
    case BuiltinValueKind::URem:
      Overflow = false;
      return lhs.urem(rhs);
  }
}

APInt swift::constantFoldCast(APInt val, const BuiltinInfo &BI) {
  // Get the cast result.
  Type SrcTy = BI.Types[0];
  Type DestTy = BI.Types.size() == 2 ? BI.Types[1] : Type();
  uint32_t SrcBitWidth =
  SrcTy->castTo<BuiltinIntegerType>()->getGreatestWidth();
  uint32_t DestBitWidth =
  DestTy->castTo<BuiltinIntegerType>()->getGreatestWidth();

  APInt CastResV;
  if (SrcBitWidth == DestBitWidth) {
    return val;
  } else switch (BI.ID) {
    default : llvm_unreachable("Invalid case.");
    case BuiltinValueKind::Trunc:
    case BuiltinValueKind::TruncOrBitCast:
      return val.trunc(DestBitWidth);
    case BuiltinValueKind::ZExt:
    case BuiltinValueKind::ZExtOrBitCast:
      return val.zext(DestBitWidth);
      break;
    case BuiltinValueKind::SExt:
    case BuiltinValueKind::SExtOrBitCast:
      return val.sext(DestBitWidth);
  }
}
<|endoftext|>


<commit_before>#pragma once

#include <stack>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/lexical_cast.hpp>

#include <karl/price_normalization.hpp>

#include <karl/util/log.hpp>

#include <karl/storage/storage.hpp>
#include <karl/storage/storage_read_fusion.hpp>
#include <karl/storage/storage_write_fusion.hpp>

#include <supermarx/util/guard.hpp>

#include <supermarx/data/tagalias.hpp>
#include <supermarx/data/tagcategoryalias.hpp>

#include "sql.cc"

#include <karl/storage/query_gen.hpp>
#include <karl/storage/table_repository.hpp>

namespace supermarx
{

enum class statement : uint8_t
{
	absorb_productclass_product,
	absorb_productclass_delete_tag_productclass,
	absorb_productclass_tag_productclass,
	absorb_productclass_delete,

	update_product,
	absorb_tag,
	absorb_tagcategory,
	bind_tag,
	update_tag_set_parent,

	update_product_image_citation,

	invalidate_productdetails,
};

inline std::string conv(statement rhs)
{
	return std::string("PREP_STATEMENT") + boost::lexical_cast<std::string>(static_cast<uint32_t>(rhs));
}

id_t read_id(pqxx::result& result, std::string const& key = "id")
{
	for(auto row : result)
		return row[key].as<id_t>();

	throw std::logic_error("Storage backend did not return a single row for `read_id`");
}

template<typename T>
static inline T read_first_result(pqxx::result const& result)
{
	for(auto row : result)
		return read_result<T>(row);

	throw storage::not_found_error();
}

template<typename T, typename ARG>
static inline T fetch_simple_first(pqxx::connection& conn, statement stmt, ARG const& arg)
{
	pqxx::work txn(conn);
	pqxx::result result(txn.prepared(conv(stmt))(arg).exec());
	return read_first_result<T>(result);
}

template<typename T, typename ARG>
static inline T fetch_simple_first(pqxx::connection& conn, std::string const& q, ARG const& arg)
{
	pqxx::work txn(conn);
	pqxx::result result(txn.parameterized(q)(arg).exec());
	return read_first_result<T>(result);
}

template<typename T, typename U>
static inline reference<T> fetch_id(pqxx::work& txn, statement stmt, U const& x)
{
	pqxx::prepare::invocation invo(txn.prepared(conv(stmt)));
	write_invo<U>(invo, x);
	pqxx::result result(invo.exec());
	return reference<T>(read_id(result));
}

template<typename T>
static inline pqxx::result write(pqxx::transaction_base& txn, statement stmt, T const& x)
{
	pqxx::prepare::invocation invo(txn.prepared(conv(stmt)));
	write_invo<T>(invo, x);
	pqxx::result result(invo.exec());
	return result;
}

template<typename T>
static inline reference<T> write_with_id(pqxx::transaction_base& txn, statement stmt, T const& x)
{
	pqxx::result result(write(txn, stmt, x));
	return reference<T>(read_id(result));
}

template<typename T>
static inline reference<T> write_with_id(pqxx::transaction_base& txn, T const& x)
{
	static std::string q = query_gen::simple_insert_with_id<T>(table_repository::lookup<T>());
	auto invo(txn.parameterized(q));
	write_invo<T>(invo, x);
	pqxx::result result(invo.exec());
	return reference<T>(read_id(result));
}

template<typename T>
static inline pqxx::result write(pqxx::transaction_base& txn, T const& x)
{
	static std::string q = query_gen::simple_insert<T>(table_repository::lookup<T>());
	auto invo(txn.parameterized(q));
	write_invo<T>(invo, x);
	return invo.exec();
}

template<typename T>
static inline pqxx::result write_simple(pqxx::connection& conn, T const& x)
{
	pqxx::work txn(conn);
	pqxx::result result(write(txn, x));
	txn.commit();
	return result;
}

template<typename T>
static inline reference<T> write_simple_with_id(pqxx::connection& conn, T const& x)
{
	pqxx::result result(write_simple(conn, x));
	return reference<T>(read_id(result));
}

void lock_products_read(pqxx::transaction_base& txn)
{
	txn.exec("lock table product in access share mode");
}

void lock_products_write(pqxx::transaction_base& txn)
{
	txn.exec("lock table product in access exclusive mode");
}

}
<commit_msg>Fixed write_simple_with_id<commit_after>#pragma once

#include <stack>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/lexical_cast.hpp>

#include <karl/price_normalization.hpp>

#include <karl/util/log.hpp>

#include <karl/storage/storage.hpp>
#include <karl/storage/storage_read_fusion.hpp>
#include <karl/storage/storage_write_fusion.hpp>

#include <supermarx/util/guard.hpp>

#include <supermarx/data/tagalias.hpp>
#include <supermarx/data/tagcategoryalias.hpp>

#include "sql.cc"

#include <karl/storage/query_gen.hpp>
#include <karl/storage/table_repository.hpp>

namespace supermarx
{

enum class statement : uint8_t
{
	absorb_productclass_product,
	absorb_productclass_delete_tag_productclass,
	absorb_productclass_tag_productclass,
	absorb_productclass_delete,

	update_product,
	absorb_tag,
	absorb_tagcategory,
	bind_tag,
	update_tag_set_parent,

	update_product_image_citation,

	invalidate_productdetails,
};

inline std::string conv(statement rhs)
{
	return std::string("PREP_STATEMENT") + boost::lexical_cast<std::string>(static_cast<uint32_t>(rhs));
}

id_t read_id(pqxx::result& result, std::string const& key = "id")
{
	for(auto row : result)
		return row[key].as<id_t>();

	throw std::logic_error("Storage backend did not return a single row for `read_id`");
}

template<typename T>
static inline T read_first_result(pqxx::result const& result)
{
	for(auto row : result)
		return read_result<T>(row);

	throw storage::not_found_error();
}

template<typename T, typename ARG>
static inline T fetch_simple_first(pqxx::connection& conn, statement stmt, ARG const& arg)
{
	pqxx::work txn(conn);
	pqxx::result result(txn.prepared(conv(stmt))(arg).exec());
	return read_first_result<T>(result);
}

template<typename T, typename ARG>
static inline T fetch_simple_first(pqxx::connection& conn, std::string const& q, ARG const& arg)
{
	pqxx::work txn(conn);
	pqxx::result result(txn.parameterized(q)(arg).exec());
	return read_first_result<T>(result);
}

template<typename T, typename U>
static inline reference<T> fetch_id(pqxx::work& txn, statement stmt, U const& x)
{
	pqxx::prepare::invocation invo(txn.prepared(conv(stmt)));
	write_invo<U>(invo, x);
	pqxx::result result(invo.exec());
	return reference<T>(read_id(result));
}

template<typename T>
static inline pqxx::result write(pqxx::transaction_base& txn, statement stmt, T const& x)
{
	pqxx::prepare::invocation invo(txn.prepared(conv(stmt)));
	write_invo<T>(invo, x);
	pqxx::result result(invo.exec());
	return result;
}

template<typename T>
static inline reference<T> write_with_id(pqxx::transaction_base& txn, statement stmt, T const& x)
{
	pqxx::result result(write(txn, stmt, x));
	return reference<T>(read_id(result));
}

template<typename T>
static inline reference<T> write_with_id(pqxx::transaction_base& txn, T const& x)
{
	static std::string q = query_gen::simple_insert_with_id<T>(table_repository::lookup<T>());
	auto invo(txn.parameterized(q));
	write_invo<T>(invo, x);
	pqxx::result result(invo.exec());
	return reference<T>(read_id(result));
}

template<typename T>
static inline pqxx::result write(pqxx::transaction_base& txn, T const& x)
{
	static std::string q = query_gen::simple_insert<T>(table_repository::lookup<T>());
	auto invo(txn.parameterized(q));
	write_invo<T>(invo, x);
	return invo.exec();
}

template<typename T>
static inline pqxx::result write_simple(pqxx::connection& conn, T const& x)
{
	pqxx::work txn(conn);
	pqxx::result result(write(txn, x));
	txn.commit();
	return result;
}

template<typename T>
static inline reference<T> write_simple_with_id(pqxx::connection& conn, T const& x)
{
	pqxx::work txn(conn);
	reference<T> result(write_with_id(txn, x));
	txn.commit();
	return result;
}

void lock_products_read(pqxx::transaction_base& txn)
{
	txn.exec("lock table product in access share mode");
}

void lock_products_write(pqxx::transaction_base& txn)
{
	txn.exec("lock table product in access exclusive mode");
}

}
<|endoftext|>