<commit_before>/* Copyright 2014 CyberTech Labs Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. */

#include "backgroundWidget.h"

#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
	#include <QtGui/QApplication>
#else
	#include <QtWidgets/QApplication>
#endif

#include "lazyMainWidget.h"
#include "lazyMainWidgetWrapper.h"
#include <QScreen>

using namespace trikGui;

BackgroundWidget::BackgroundWidget(
		const QString &configPath
		, QWidget *parent)
	: QWidget(parent)
	, mController(configPath)
	, mBatteryIndicator(mController.brick())
	, mWiFiIndicator(mController)
	, mGamepadIndicator(mController)
	, mMailboxIndicator("://resources/mailboxConnected.png", mController.mailbox()->isConnected())
	, mCommunicatorIndicator("://resources/communicatorConnected.png", mController.communicatorConnectionStatus())
	, mStartWidget(mController)
	, mRunningWidget(mController)
{
	setFixedSize(qApp->primaryScreen()->availableSize());
	mMainLayout.setSpacing(10);

	mBatteryIndicator.setStyleSheet("font: 12px");

	mStatusBarLayout.addWidget(&mBatteryIndicator);
	mStatusBarLayout.addStretch();
	mStatusBarLayout.addWidget(&mGamepadIndicator);
	mStatusBarLayout.addWidget(&mMailboxIndicator);
	mStatusBarLayout.addWidget(&mCommunicatorIndicator);
	mStatusBarLayout.addWidget(&mWiFiIndicator);
	addMainWidget(mStartWidget);
	mBrickDisplayWidgetWrapper.reset(new LazyMainWidgetWrapper(mController.brick().graphicsWidget()));
	addLazyWidget(*mBrickDisplayWidgetWrapper);
	mMainWidgetsLayout.addWidget(&mRunningWidget);

	mMainLayout.setContentsMargins(mDefaultMargins);
	mMainLayout.addLayout(&mStatusBarLayout);
	mMainLayout.addLayout(&mMainWidgetsLayout);

	setLayout(&mMainLayout);

	connect(&mMainWidgetsLayout, SIGNAL(currentChanged(int)), this, SLOT(renewFocus()));
	connect(&mMainWidgetsLayout, SIGNAL(widgetRemoved(int)), this, SLOT(updateStack(int)));

	connect(&mController, SIGNAL(brickStopped()), this, SLOT(refresh()));
	connect(&mController, SIGNAL(showRunningWidget(QString, int)), this, SLOT(showRunningWidget(QString, int)));
	connect(&mController, SIGNAL(showError(QString, int)), this, SLOT(showError(QString, int)));
	connect(&mController, SIGNAL(hideRunningWidget(int)), this, SLOT(hideRunningWidget(int)));
	connect(&mController, SIGNAL(hideGraphicsWidget()), this, SLOT(hideGraphicsWidget()));
	connect(&mController, SIGNAL(hideScriptWidgets()), this, SLOT(hideScriptWidgets()));

	connect(&mController, SIGNAL(communicatorStatusChanged(bool)), &mCommunicatorIndicator, SLOT(changeStatus(bool)));
	connect(&mController, SIGNAL(mailboxStatusChanged(bool)), &mMailboxIndicator, SLOT(changeStatus(bool)));

	connect(&mRunningWidget, SIGNAL(hideMe(int)), this, SLOT(hideRunningWidget(int)));
}

BackgroundWidget::~BackgroundWidget()
{
	// Disconnect is needed here because QWidget destructor will trigger widgetRemoved signal which will be caught
	// here by partially deleted object and everything will crash.
	disconnect(&mMainWidgetsLayout, 0, 0, 0);
}

void BackgroundWidget::resetWidgetLayout(MainWidget &widget)
{
	// If the widget has layout, remove its margins because main widgets layout has its own margins.
	QLayout *layout = widget.layout();
	if (layout != nullptr) {
		layout->setContentsMargins(0, 0, 0, 0);
	}
}

void BackgroundWidget::addMainWidget(MainWidget &widget)
{
	resetWidgetLayout(widget);

	mMainWidgetIndex.push(mMainWidgetsLayout.addWidget(&widget));
	mMainWidgetsLayout.setCurrentIndex(mMainWidgetIndex.top());

	connect(&widget, SIGNAL(newWidget(MainWidget &)), this, SLOT(addMainWidget(MainWidget &)));
}

void BackgroundWidget::addRunningWidget(MainWidget &widget)
{
	resetWidgetLayout(widget);
	mMainWidgetsLayout.addWidget(&widget);
}

void BackgroundWidget::addLazyWidget(LazyMainWidget &widget)
{
	resetWidgetLayout(widget);
	mMainWidgetsLayout.addWidget(&widget);

	connect(&widget, SIGNAL(showMe(MainWidget &)), this, SLOT(showMainWidget(MainWidget &)));
	connect(&widget, SIGNAL(hideMe()), this, SLOT(hideGraphicsWidget()));
}

void BackgroundWidget::showMainWidget(MainWidget &widget)
{
	if (&widget == mBrickDisplayWidgetWrapper.data()) {
		expandMainWidget();
	}

	const int index = mMainWidgetsLayout.indexOf(&widget);
	if (index >= 0) {
		mMainWidgetsLayout.setCurrentIndex(index);
	}
}

void BackgroundWidget::showRunningWidget(const QString &fileName, int scriptId)
{
	mRunningWidget.setProgram(fileName, scriptId);
	mMainWidgetsLayout.setCurrentWidget(&mRunningWidget);
	mRunningWidget.grabKeyboard();
}

void BackgroundWidget::hideRunningWidget(int scriptId)
{
	if (mRunningWidget.scriptId() == scriptId) {
		mMainWidgetsLayout.setCurrentIndex(mMainWidgetIndex.top());
		mRunningWidget.releaseKeyboard();
	}
}

void BackgroundWidget::showError(const QString &error, int scriptId)
{
	if (mRunningWidget.scriptId() == scriptId) {
		mRunningWidget.showError(error, scriptId);
		mMainWidgetsLayout.setCurrentWidget(&mRunningWidget);
	}
}

void BackgroundWidget::hideGraphicsWidget()
{
	if (mMainWidgetsLayout.currentWidget() == mBrickDisplayWidgetWrapper.data()) {
		unexpandMainWidget();
		mMainWidgetsLayout.setCurrentWidget(&mRunningWidget);
	}
}

void BackgroundWidget::hideScriptWidgets()
{
	mMainWidgetsLayout.setCurrentIndex(mMainWidgetIndex.top());
	mRunningWidget.releaseKeyboard();
}

void BackgroundWidget::renewFocus()
{
	// When current widget in main widgets layout changed, we should set focus properly.

	MainWidget *currentWidget = dynamic_cast<MainWidget *>(mMainWidgetsLayout.currentWidget());

	if (currentWidget != nullptr) {
		currentWidget->renewFocus();
	}
}

void BackgroundWidget::refresh()
{
	for (const auto widget : QApplication::allWidgets()) {
		widget->update();
	}
}

void BackgroundWidget::updateStack(int removedWidget)
{
	if (mMainWidgetIndex.top() == removedWidget) {
		mMainWidgetIndex.pop();
		mMainWidgetsLayout.setCurrentIndex(mMainWidgetIndex.top());
	}
}

void BackgroundWidget::expandMainWidget()
{
	mMainLayout.setContentsMargins(0, 0, 0, 0);
	QMargins margins = mDefaultMargins;
	margins.setBottom(0);
	mStatusBarLayout.setContentsMargins(margins);
}

void BackgroundWidget::unexpandMainWidget()
{
	mMainLayout.setContentsMargins(mDefaultMargins);
	mStatusBarLayout.setContentsMargins(0, 0, 0, 0);
}
<commit_msg>fixed SIGNAL/SLOT to &method<commit_after>/* Copyright 2014 CyberTech Labs Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. */

#include "backgroundWidget.h"

#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
	#include <QtGui/QApplication>
#else
	#include <QtWidgets/QApplication>
#endif

#include "lazyMainWidget.h"
#include "lazyMainWidgetWrapper.h"
#include <QScreen>

using namespace trikGui;

BackgroundWidget::BackgroundWidget(
		const QString &configPath
		, QWidget *parent)
	: QWidget(parent)
	, mController(configPath)
	, mBatteryIndicator(mController.brick())
	, mWiFiIndicator(mController)
	, mGamepadIndicator(mController)
	, mMailboxIndicator("://resources/mailboxConnected.png", mController.mailbox()->isConnected())
	, mCommunicatorIndicator("://resources/communicatorConnected.png", mController.communicatorConnectionStatus())
	, mStartWidget(mController)
	, mRunningWidget(mController)
{
	setFixedSize(qApp->primaryScreen()->availableSize());
	mMainLayout.setSpacing(10);

	mBatteryIndicator.setStyleSheet("font: 12px");

	mStatusBarLayout.addWidget(&mBatteryIndicator);
	mStatusBarLayout.addStretch();
	mStatusBarLayout.addWidget(&mGamepadIndicator);
	mStatusBarLayout.addWidget(&mMailboxIndicator);
	mStatusBarLayout.addWidget(&mCommunicatorIndicator);
	mStatusBarLayout.addWidget(&mWiFiIndicator);
	addMainWidget(mStartWidget);
	mBrickDisplayWidgetWrapper.reset(new LazyMainWidgetWrapper(mController.brick().graphicsWidget()));
	addLazyWidget(*mBrickDisplayWidgetWrapper);
	mMainWidgetsLayout.addWidget(&mRunningWidget);

	mMainLayout.setContentsMargins(mDefaultMargins);
	mMainLayout.addLayout(&mStatusBarLayout);
	mMainLayout.addLayout(&mMainWidgetsLayout);

	setLayout(&mMainLayout);

	connect(&mMainWidgetsLayout, &QStackedLayout::currentChanged, this, &BackgroundWidget::renewFocus);
	connect(&mMainWidgetsLayout, &QStackedLayout::widgetRemoved, this, &BackgroundWidget::updateStack);

	connect(&mController, &Controller::brickStopped, this, &BackgroundWidget::refresh);
	connect(&mController, &Controller::showRunningWidget, this, &BackgroundWidget::showRunningWidget);
	connect(&mController, &Controller::showError, this, &BackgroundWidget::showError);
	connect(&mController, &Controller::hideRunningWidget, this, &BackgroundWidget::hideRunningWidget);
	connect(&mController, &Controller::hideGraphicsWidget, this, &BackgroundWidget::hideGraphicsWidget);
	connect(&mController, &Controller::hideScriptWidgets, this, &BackgroundWidget::hideScriptWidgets);
	connect(&mController, &Controller::communicatorStatusChanged, &mCommunicatorIndicator, &OpenSocketIndicator::changeStatus);
	connect(&mController, &Controller::mailboxStatusChanged, &mMailboxIndicator, &OpenSocketIndicator::changeStatus);

	connect(&mRunningWidget, &RunningWidget::hideMe, this, &BackgroundWidget::hideRunningWidget);
}

BackgroundWidget::~BackgroundWidget()
{
	// Disconnect is needed here because QWidget destructor will trigger widgetRemoved signal which will be caught
	// here by partially deleted object and everything will crash.
	disconnect(&mMainWidgetsLayout, 0, 0, 0);
}

void BackgroundWidget::resetWidgetLayout(MainWidget &widget)
{
	// If the widget has layout, remove its margins because main widgets layout has its own margins.
	QLayout *layout = widget.layout();
	if (layout != nullptr) {
		layout->setContentsMargins(0, 0, 0, 0);
	}
}

void BackgroundWidget::addMainWidget(MainWidget &widget)
{
	resetWidgetLayout(widget);

	mMainWidgetIndex.push(mMainWidgetsLayout.addWidget(&widget));
	mMainWidgetsLayout.setCurrentIndex(mMainWidgetIndex.top());

	connect(&widget, &MainWidget::newWidget, this, &BackgroundWidget::addMainWidget);
}

void BackgroundWidget::addRunningWidget(MainWidget &widget)
{
	resetWidgetLayout(widget);
	mMainWidgetsLayout.addWidget(&widget);
}

void BackgroundWidget::addLazyWidget(LazyMainWidget &widget)
{
	resetWidgetLayout(widget);
	mMainWidgetsLayout.addWidget(&widget);

	connect(&widget, &LazyMainWidget::showMe, this, &BackgroundWidget::showMainWidget);
	connect(&widget, &LazyMainWidget::hideMe, this, &BackgroundWidget::hideGraphicsWidget);
}

void BackgroundWidget::showMainWidget(MainWidget &widget)
{
	if (&widget == mBrickDisplayWidgetWrapper.data()) {
		expandMainWidget();
	}

	const int index = mMainWidgetsLayout.indexOf(&widget);
	if (index >= 0) {
		mMainWidgetsLayout.setCurrentIndex(index);
	}
}

void BackgroundWidget::showRunningWidget(const QString &fileName, int scriptId)
{
	mRunningWidget.setProgram(fileName, scriptId);
	mMainWidgetsLayout.setCurrentWidget(&mRunningWidget);
	mRunningWidget.grabKeyboard();
}

void BackgroundWidget::hideRunningWidget(int scriptId)
{
	if (mRunningWidget.scriptId() == scriptId) {
		mMainWidgetsLayout.setCurrentIndex(mMainWidgetIndex.top());
		mRunningWidget.releaseKeyboard();
	}
}

void BackgroundWidget::showError(const QString &error, int scriptId)
{
	if (mRunningWidget.scriptId() == scriptId) {
		mRunningWidget.showError(error, scriptId);
		mMainWidgetsLayout.setCurrentWidget(&mRunningWidget);
	}
}

void BackgroundWidget::hideGraphicsWidget()
{
	if (mMainWidgetsLayout.currentWidget() == mBrickDisplayWidgetWrapper.data()) {
		unexpandMainWidget();
		mMainWidgetsLayout.setCurrentWidget(&mRunningWidget);
	}
}

void BackgroundWidget::hideScriptWidgets()
{
	mMainWidgetsLayout.setCurrentIndex(mMainWidgetIndex.top());
	mRunningWidget.releaseKeyboard();
}

void BackgroundWidget::renewFocus()
{
	// When current widget in main widgets layout changed, we should set focus properly.

	MainWidget *currentWidget = dynamic_cast<MainWidget *>(mMainWidgetsLayout.currentWidget());

	if (currentWidget != nullptr) {
		currentWidget->renewFocus();
	}
}

void BackgroundWidget::refresh()
{
	for (const auto widget : QApplication::allWidgets()) {
		widget->update();
	}
}

void BackgroundWidget::updateStack(int removedWidget)
{
	if (mMainWidgetIndex.top() == removedWidget) {
		mMainWidgetIndex.pop();
		mMainWidgetsLayout.setCurrentIndex(mMainWidgetIndex.top());
	}
}

void BackgroundWidget::expandMainWidget()
{
	mMainLayout.setContentsMargins(0, 0, 0, 0);
	QMargins margins = mDefaultMargins;
	margins.setBottom(0);
	mStatusBarLayout.setContentsMargins(margins);
}

void BackgroundWidget::unexpandMainWidget()
{
	mMainLayout.setContentsMargins(mDefaultMargins);
	mStatusBarLayout.setContentsMargins(0, 0, 0, 0);
}
<|endoftext|>


<commit_before>/// \file
/// \ingroup tutorial_spectrum
/// \notebook
///
/// This macro fits the source spectrum using the AWMI algorithm
/// from the "TSpectrumFit" class ("TSpectrum" class is used to find peaks).
///
/// To try this macro, in a ROOT (5 or 6) prompt, do:
///
/// ~~~{.cpp}
///  root > .x FitAwmi.C
/// ~~~
///
/// or:
///
/// ~~~{.cpp}
///  root > .x FitAwmi.C++
///  root > FitAwmi(); // re-run with another random set of peaks
/// ~~~
///
/// \macro_image
/// \macro_output
/// \macro_code
///
/// \author Silesius Anonymus

#include "TROOT.h"
#include "TMath.h"
#include "TRandom.h"
#include "TH1.h"
#include "TF1.h"
#include "TCanvas.h"
#include "TSpectrum.h"
#include "TSpectrumFit.h"
#include "TPolyMarker.h"
#include "TList.h"

#include <iostream>

TH1F *FitAwmi_Create_Spectrum(void) {
   Int_t nbins = 1000;
   Double_t xmin = -10., xmax = 10.;
   delete gROOT->FindObject("h"); // prevent "memory leak"
   TH1F *h = new TH1F("h", "simulated spectrum", nbins, xmin, xmax);
   h->SetStats(kFALSE);
   TF1 f("f", "TMath::Gaus(x, [0], [1], 1)", xmin, xmax);
   // f.SetParNames("mean", "sigma");
   gRandom->SetSeed(0); // make it really random
   // create well separated peaks with exactly known means and areas
   // note: TSpectrumFit assumes that all peaks have the same sigma
   Double_t sigma = (xmax - xmin) / Double_t(nbins) * Int_t(gRandom->Uniform(2., 6.));
   Int_t npeaks = 0;
   while (xmax > (xmin + 6. * sigma)) {
      npeaks++;
      xmin += 3. * sigma; // "mean"
      f.SetParameters(xmin, sigma);
      Double_t area = 1. * Int_t(gRandom->Uniform(1., 11.));
      h->Add(&f, area, ""); // "" ... or ... "I"
      std::cout << "created "
                << xmin << " "
                << (area / sigma / TMath::Sqrt(TMath::TwoPi())) << " "
                << area << std::endl;
      xmin += 3. * sigma;
   }
   std::cout << "the total number of created peaks = " << npeaks
             << " with sigma = " << sigma << std::endl;
   return h;
}

void FitAwmi(void) {

   TH1F *h = FitAwmi_Create_Spectrum();

   TCanvas *cFit = ((TCanvas *)(gROOT->GetListOfCanvases()->FindObject("cFit")));
   if (!cFit) cFit = new TCanvas("cFit", "cFit", 10, 10, 1000, 700);
   else cFit->Clear();
   h->Draw("L");
   Int_t i, nfound, bin;
   Int_t nbins = h->GetNbinsX();

   Double_t *source = new Double_t[nbins];
   Double_t *dest = new Double_t[nbins];

   for (i = 0; i < nbins; i++) source[i] = h->GetBinContent(i + 1);
   TSpectrum *s = new TSpectrum(); // note: default maxpositions = 100
   // searching for candidate peaks positions
   nfound = s->SearchHighRes(source, dest, nbins, 2., 2., kFALSE, 10000, kFALSE, 0);
   // filling in the initial estimates of the input parameters
   Bool_t *FixPos = new Bool_t[nfound];
   Bool_t *FixAmp = new Bool_t[nfound];
   for(i = 0; i < nfound; i++) FixAmp[i] = FixPos[i] = kFALSE;

   Double_t *Pos, *Amp = new Double_t[nfound]; // ROOT 6

   Pos = s->GetPositionX(); // 0 ... (nbins - 1)
   for (i = 0; i < nfound; i++) {
      bin = 1 + Int_t(Pos[i] + 0.5); // the "nearest" bin
      Amp[i] = h->GetBinContent(bin);
   }
   TSpectrumFit *pfit = new TSpectrumFit(nfound);
   pfit->SetFitParameters(0, (nbins - 1), 1000, 0.1, pfit->kFitOptimChiCounts,
                          pfit->kFitAlphaHalving, pfit->kFitPower2,
                          pfit->kFitTaylorOrderFirst);
   pfit->SetPeakParameters(2., kFALSE, Pos, FixPos, Amp, FixAmp);
   // pfit->SetBackgroundParameters(source[0], kFALSE, 0., kFALSE, 0., kFALSE);
   pfit->FitAwmi(source);
   Double_t *Positions = pfit->GetPositions();
   Double_t *PositionsErrors = pfit->GetPositionsErrors();
   Double_t *Amplitudes = pfit->GetAmplitudes();
   Double_t *AmplitudesErrors = pfit->GetAmplitudesErrors();
   Double_t *Areas = pfit->GetAreas();
   Double_t *AreasErrors = pfit->GetAreasErrors();
   delete gROOT->FindObject("d"); // prevent "memory leak"
   TH1F *d = new TH1F(*h); d->SetNameTitle("d", ""); d->Reset("M");
   for (i = 0; i < nbins; i++) d->SetBinContent(i + 1, source[i]);
   Double_t x1 = d->GetBinCenter(1), dx = d->GetBinWidth(1);
   Double_t sigma, sigmaErr;
   pfit->GetSigma(sigma, sigmaErr);

   // current TSpectrumFit needs a sqrt(2) correction factor for sigma
   sigma /= TMath::Sqrt2(); sigmaErr /= TMath::Sqrt2();
   // convert "bin numbers" into "x-axis values"
   sigma *= dx; sigmaErr *= dx;

   std::cout << "the total number of found peaks = " << nfound
             << " with sigma = " << sigma << " (+-" << sigmaErr << ")"
             << std::endl;
   std::cout << "fit chi^2 = " << pfit->GetChi() << std::endl;
   for (i = 0; i < nfound; i++) {
      bin = 1 + Int_t(Positions[i] + 0.5); // the "nearest" bin
      Pos[i] = d->GetBinCenter(bin);
      Amp[i] = d->GetBinContent(bin);

      // convert "bin numbers" into "x-axis values"
      Positions[i] = x1 + Positions[i] * dx;
      PositionsErrors[i] *= dx;
      Areas[i] *= dx;
      AreasErrors[i] *= dx;

      std::cout << "found "
                << Positions[i] << " (+-" << PositionsErrors[i] << ") "
                << Amplitudes[i] << " (+-" << AmplitudesErrors[i] << ") "
                << Areas[i] << " (+-" << AreasErrors[i] << ")"
                << std::endl;
   }
   d->SetLineColor(kRed); d->SetLineWidth(1);
   d->Draw("SAME L");
   TPolyMarker *pm = ((TPolyMarker*)(h->GetListOfFunctions()->FindObject("TPolyMarker")));
   if (pm) {
      h->GetListOfFunctions()->Remove(pm);
      delete pm;
   }
   pm = new TPolyMarker(nfound, Pos, Amp);
   h->GetListOfFunctions()->Add(pm);
   pm->SetMarkerStyle(23);
   pm->SetMarkerColor(kRed);
   pm->SetMarkerSize(1);
   // cleanup
   delete pfit;
   delete [] Amp;
   delete [] FixAmp;
   delete [] FixPos;
   delete s;
   delete [] dest;
   delete [] source;
   return;
}<commit_msg>Wile changed his mind and asked to remove the author name (with was useless anyway as it was anonymous).<commit_after>/// \file
/// \ingroup tutorial_spectrum
/// \notebook
///
/// This macro fits the source spectrum using the AWMI algorithm
/// from the "TSpectrumFit" class ("TSpectrum" class is used to find peaks).
///
/// To try this macro, in a ROOT (5 or 6) prompt, do:
///
/// ~~~{.cpp}
///  root > .x FitAwmi.C
/// ~~~
///
/// or:
///
/// ~~~{.cpp}
///  root > .x FitAwmi.C++
///  root > FitAwmi(); // re-run with another random set of peaks
/// ~~~
///
/// \macro_image
/// \macro_output
/// \macro_code
///
/// \author

#include "TROOT.h"
#include "TMath.h"
#include "TRandom.h"
#include "TH1.h"
#include "TF1.h"
#include "TCanvas.h"
#include "TSpectrum.h"
#include "TSpectrumFit.h"
#include "TPolyMarker.h"
#include "TList.h"

#include <iostream>

TH1F *FitAwmi_Create_Spectrum(void) {
   Int_t nbins = 1000;
   Double_t xmin = -10., xmax = 10.;
   delete gROOT->FindObject("h"); // prevent "memory leak"
   TH1F *h = new TH1F("h", "simulated spectrum", nbins, xmin, xmax);
   h->SetStats(kFALSE);
   TF1 f("f", "TMath::Gaus(x, [0], [1], 1)", xmin, xmax);
   // f.SetParNames("mean", "sigma");
   gRandom->SetSeed(0); // make it really random
   // create well separated peaks with exactly known means and areas
   // note: TSpectrumFit assumes that all peaks have the same sigma
   Double_t sigma = (xmax - xmin) / Double_t(nbins) * Int_t(gRandom->Uniform(2., 6.));
   Int_t npeaks = 0;
   while (xmax > (xmin + 6. * sigma)) {
      npeaks++;
      xmin += 3. * sigma; // "mean"
      f.SetParameters(xmin, sigma);
      Double_t area = 1. * Int_t(gRandom->Uniform(1., 11.));
      h->Add(&f, area, ""); // "" ... or ... "I"
      std::cout << "created "
                << xmin << " "
                << (area / sigma / TMath::Sqrt(TMath::TwoPi())) << " "
                << area << std::endl;
      xmin += 3. * sigma;
   }
   std::cout << "the total number of created peaks = " << npeaks
             << " with sigma = " << sigma << std::endl;
   return h;
}

void FitAwmi(void) {

   TH1F *h = FitAwmi_Create_Spectrum();

   TCanvas *cFit = ((TCanvas *)(gROOT->GetListOfCanvases()->FindObject("cFit")));
   if (!cFit) cFit = new TCanvas("cFit", "cFit", 10, 10, 1000, 700);
   else cFit->Clear();
   h->Draw("L");
   Int_t i, nfound, bin;
   Int_t nbins = h->GetNbinsX();

   Double_t *source = new Double_t[nbins];
   Double_t *dest = new Double_t[nbins];

   for (i = 0; i < nbins; i++) source[i] = h->GetBinContent(i + 1);
   TSpectrum *s = new TSpectrum(); // note: default maxpositions = 100
   // searching for candidate peaks positions
   nfound = s->SearchHighRes(source, dest, nbins, 2., 2., kFALSE, 10000, kFALSE, 0);
   // filling in the initial estimates of the input parameters
   Bool_t *FixPos = new Bool_t[nfound];
   Bool_t *FixAmp = new Bool_t[nfound];
   for(i = 0; i < nfound; i++) FixAmp[i] = FixPos[i] = kFALSE;

   Double_t *Pos, *Amp = new Double_t[nfound]; // ROOT 6

   Pos = s->GetPositionX(); // 0 ... (nbins - 1)
   for (i = 0; i < nfound; i++) {
      bin = 1 + Int_t(Pos[i] + 0.5); // the "nearest" bin
      Amp[i] = h->GetBinContent(bin);
   }
   TSpectrumFit *pfit = new TSpectrumFit(nfound);
   pfit->SetFitParameters(0, (nbins - 1), 1000, 0.1, pfit->kFitOptimChiCounts,
                          pfit->kFitAlphaHalving, pfit->kFitPower2,
                          pfit->kFitTaylorOrderFirst);
   pfit->SetPeakParameters(2., kFALSE, Pos, FixPos, Amp, FixAmp);
   // pfit->SetBackgroundParameters(source[0], kFALSE, 0., kFALSE, 0., kFALSE);
   pfit->FitAwmi(source);
   Double_t *Positions = pfit->GetPositions();
   Double_t *PositionsErrors = pfit->GetPositionsErrors();
   Double_t *Amplitudes = pfit->GetAmplitudes();
   Double_t *AmplitudesErrors = pfit->GetAmplitudesErrors();
   Double_t *Areas = pfit->GetAreas();
   Double_t *AreasErrors = pfit->GetAreasErrors();
   delete gROOT->FindObject("d"); // prevent "memory leak"
   TH1F *d = new TH1F(*h); d->SetNameTitle("d", ""); d->Reset("M");
   for (i = 0; i < nbins; i++) d->SetBinContent(i + 1, source[i]);
   Double_t x1 = d->GetBinCenter(1), dx = d->GetBinWidth(1);
   Double_t sigma, sigmaErr;
   pfit->GetSigma(sigma, sigmaErr);

   // current TSpectrumFit needs a sqrt(2) correction factor for sigma
   sigma /= TMath::Sqrt2(); sigmaErr /= TMath::Sqrt2();
   // convert "bin numbers" into "x-axis values"
   sigma *= dx; sigmaErr *= dx;

   std::cout << "the total number of found peaks = " << nfound
             << " with sigma = " << sigma << " (+-" << sigmaErr << ")"
             << std::endl;
   std::cout << "fit chi^2 = " << pfit->GetChi() << std::endl;
   for (i = 0; i < nfound; i++) {
      bin = 1 + Int_t(Positions[i] + 0.5); // the "nearest" bin
      Pos[i] = d->GetBinCenter(bin);
      Amp[i] = d->GetBinContent(bin);

      // convert "bin numbers" into "x-axis values"
      Positions[i] = x1 + Positions[i] * dx;
      PositionsErrors[i] *= dx;
      Areas[i] *= dx;
      AreasErrors[i] *= dx;

      std::cout << "found "
                << Positions[i] << " (+-" << PositionsErrors[i] << ") "
                << Amplitudes[i] << " (+-" << AmplitudesErrors[i] << ") "
                << Areas[i] << " (+-" << AreasErrors[i] << ")"
                << std::endl;
   }
   d->SetLineColor(kRed); d->SetLineWidth(1);
   d->Draw("SAME L");
   TPolyMarker *pm = ((TPolyMarker*)(h->GetListOfFunctions()->FindObject("TPolyMarker")));
   if (pm) {
      h->GetListOfFunctions()->Remove(pm);
      delete pm;
   }
   pm = new TPolyMarker(nfound, Pos, Amp);
   h->GetListOfFunctions()->Add(pm);
   pm->SetMarkerStyle(23);
   pm->SetMarkerColor(kRed);
   pm->SetMarkerSize(1);
   // cleanup
   delete pfit;
   delete [] Amp;
   delete [] FixAmp;
   delete [] FixPos;
   delete s;
   delete [] dest;
   delete [] source;
   return;
}<|endoftext|>


<commit_before>#include "extensions/filters/network/common/redis/client_impl.h"

namespace Envoy {
namespace Extensions {
namespace NetworkFilters {
namespace Common {
namespace Redis {
namespace Client {

ConfigImpl::ConfigImpl(
    const envoy::config::filter::network::redis_proxy::v2::RedisProxy::ConnPoolSettings& config)
    : op_timeout_(PROTOBUF_GET_MS_REQUIRED(config, op_timeout)),
      enable_hashtagging_(config.enable_hashtagging()),
      enable_redirection_(config.enable_redirection()),
      max_buffer_size_before_flush_(
          config.max_buffer_size_before_flush()), // This is a scalar, so default is zero.
      buffer_flush_timeout_(PROTOBUF_GET_MS_OR_DEFAULT(
          config, buffer_flush_timeout,
          3)) // Default timeout is 3ms. If max_buffer_size_before_flush is zero, this is not used
              // as the buffer is flushed on each request immediately.
{}

ClientPtr ClientImpl::create(Upstream::HostConstSharedPtr host, Event::Dispatcher& dispatcher,
                             EncoderPtr&& encoder, DecoderFactory& decoder_factory,
                             const Config& config) {

  std::unique_ptr<ClientImpl> client(
      new ClientImpl(host, dispatcher, std::move(encoder), decoder_factory, config));
  client->connection_ = host->createConnection(dispatcher, nullptr, nullptr).connection_;
  client->connection_->addConnectionCallbacks(*client);
  client->connection_->addReadFilter(Network::ReadFilterSharedPtr{new UpstreamReadFilter(*client)});
  client->connection_->connect();
  client->connection_->noDelay(true);
  return std::move(client);
}

ClientImpl::ClientImpl(Upstream::HostConstSharedPtr host, Event::Dispatcher& dispatcher,
                       EncoderPtr&& encoder, DecoderFactory& decoder_factory, const Config& config)
    : host_(host), encoder_(std::move(encoder)), decoder_(decoder_factory.create(*this)),
      config_(config),
      connect_or_op_timer_(dispatcher.createTimer([this]() -> void { onConnectOrOpTimeout(); })),
      flush_timer_(dispatcher.createTimer([this]() -> void { flushBufferAndResetTimer(); })) {
  host->cluster().stats().upstream_cx_total_.inc();
  host->stats().cx_total_.inc();
  host->cluster().stats().upstream_cx_active_.inc();
  host->stats().cx_active_.inc();
  connect_or_op_timer_->enableTimer(host->cluster().connectTimeout());
}

ClientImpl::~ClientImpl() {
  ASSERT(pending_requests_.empty());
  ASSERT(connection_->state() == Network::Connection::State::Closed);
  host_->cluster().stats().upstream_cx_active_.dec();
  host_->stats().cx_active_.dec();
}

void ClientImpl::close() { connection_->close(Network::ConnectionCloseType::NoFlush); }

void ClientImpl::flushBufferAndResetTimer() {
  if (flush_timer_->enabled()) {
    flush_timer_->disableTimer();
  }
  connection_->write(encoder_buffer_, false);
}

PoolRequest* ClientImpl::makeRequest(const RespValue& request, PoolCallbacks& callbacks) {
  ASSERT(connection_->state() == Network::Connection::State::Open);

  const bool empty_buffer = encoder_buffer_.length() == 0;

  pending_requests_.emplace_back(*this, callbacks);
  encoder_->encode(request, encoder_buffer_);

  // If buffer is full, flush. If the buffer was empty before the request, start the timer.
  if (encoder_buffer_.length() >= config_.maxBufferSizeBeforeFlush()) {
    flushBufferAndResetTimer();
  } else if (empty_buffer) {
    flush_timer_->enableTimer(std::chrono::milliseconds(config_.bufferFlushTimeoutInMs()));
  }

  // Only boost the op timeout if:
  // - We are not already connected. Otherwise, we are governed by the connect timeout and the timer
  //   will be reset when/if connection occurs. This allows a relatively long connection spin up
  //   time for example if TLS is being used.
  // - This is the first request on the pipeline. Otherwise the timeout would effectively start on
  //   the last operation.
  if (connected_ && pending_requests_.size() == 1) {
    connect_or_op_timer_->enableTimer(config_.opTimeout());
  }

  return &pending_requests_.back();
}

void ClientImpl::onConnectOrOpTimeout() {
  putOutlierEvent(Upstream::Outlier::Result::LOCAL_ORIGIN_TIMEOUT);
  if (connected_) {
    host_->cluster().stats().upstream_rq_timeout_.inc();
    host_->stats().rq_timeout_.inc();
  } else {
    host_->cluster().stats().upstream_cx_connect_timeout_.inc();
    host_->stats().cx_connect_fail_.inc();
  }

  connection_->close(Network::ConnectionCloseType::NoFlush);
}

void ClientImpl::onData(Buffer::Instance& data) {
  try {
    decoder_->decode(data);
  } catch (ProtocolError&) {
    putOutlierEvent(Upstream::Outlier::Result::EXT_ORIGIN_REQUEST_FAILED);
    host_->cluster().stats().upstream_cx_protocol_error_.inc();
    host_->stats().rq_error_.inc();
    connection_->close(Network::ConnectionCloseType::NoFlush);
  }
}

void ClientImpl::putOutlierEvent(Upstream::Outlier::Result result) {
  if (!config_.disableOutlierEvents()) {
    host_->outlierDetector().putResult(result);
  }
}

void ClientImpl::onEvent(Network::ConnectionEvent event) {
  if (event == Network::ConnectionEvent::RemoteClose ||
      event == Network::ConnectionEvent::LocalClose) {
    if (!pending_requests_.empty()) {
      host_->cluster().stats().upstream_cx_destroy_with_active_rq_.inc();
      if (event == Network::ConnectionEvent::RemoteClose) {
        putOutlierEvent(Upstream::Outlier::Result::LOCAL_ORIGIN_CONNECT_FAILED);
        host_->cluster().stats().upstream_cx_destroy_remote_with_active_rq_.inc();
      }
      if (event == Network::ConnectionEvent::LocalClose) {
        host_->cluster().stats().upstream_cx_destroy_local_with_active_rq_.inc();
      }
    }

    while (!pending_requests_.empty()) {
      PendingRequest& request = pending_requests_.front();
      if (!request.canceled_) {
        request.callbacks_.onFailure();
      } else {
        host_->cluster().stats().upstream_rq_cancelled_.inc();
      }
      pending_requests_.pop_front();
    }

    connect_or_op_timer_->disableTimer();
  } else if (event == Network::ConnectionEvent::Connected) {
    connected_ = true;
    ASSERT(!pending_requests_.empty());
    connect_or_op_timer_->enableTimer(config_.opTimeout());
  }

  if (event == Network::ConnectionEvent::RemoteClose && !connected_) {
    host_->cluster().stats().upstream_cx_connect_fail_.inc();
    host_->stats().cx_connect_fail_.inc();
  }
}

void ClientImpl::onRespValue(RespValuePtr&& value) {
  ASSERT(!pending_requests_.empty());
  PendingRequest& request = pending_requests_.front();

  if (request.canceled_) {
    host_->cluster().stats().upstream_rq_cancelled_.inc();
  } else if (config_.enableRedirection() && (value->type() == Common::Redis::RespType::Error)) {
    std::vector<absl::string_view> err = StringUtil::splitToken(value->asString(), " ", false);
    bool redirected = false;
    if (err.size() == 3) {
      if (err[0] == RedirectionResponse::get().MOVED || err[0] == RedirectionResponse::get().ASK) {
        redirected = request.callbacks_.onRedirection(*value);
        if (redirected) {
          host_->cluster().stats().upstream_internal_redirect_succeeded_total_.inc();
        } else {
          host_->cluster().stats().upstream_internal_redirect_failed_total_.inc();
        }
      }
    }
    if (!redirected) {
      request.callbacks_.onResponse(std::move(value));
    }
  } else {
    request.callbacks_.onResponse(std::move(value));
  }

  pending_requests_.pop_front();

  // If there are no remaining ops in the pipeline we need to disable the timer.
  // Otherwise we boost the timer since we are receiving responses and there are more to flush
  // out.
  if (pending_requests_.empty()) {
    connect_or_op_timer_->disableTimer();
  } else {
    connect_or_op_timer_->enableTimer(config_.opTimeout());
  }

  putOutlierEvent(Upstream::Outlier::Result::EXT_ORIGIN_REQUEST_SUCCESS);
}

ClientImpl::PendingRequest::PendingRequest(ClientImpl& parent, PoolCallbacks& callbacks)
    : parent_(parent), callbacks_(callbacks) {
  parent.host_->cluster().stats().upstream_rq_total_.inc();
  parent.host_->stats().rq_total_.inc();
  parent.host_->cluster().stats().upstream_rq_active_.inc();
  parent.host_->stats().rq_active_.inc();
}

ClientImpl::PendingRequest::~PendingRequest() {
  parent_.host_->cluster().stats().upstream_rq_active_.dec();
  parent_.host_->stats().rq_active_.dec();
}

void ClientImpl::PendingRequest::cancel() {
  // If we get a cancellation, we just mark the pending request as cancelled, and then we drop
  // the response as it comes through. There is no reason to blow away the connection when the
  // remote is already responding as fast as possible.
  canceled_ = true;
}

ClientFactoryImpl ClientFactoryImpl::instance_;

ClientPtr ClientFactoryImpl::create(Upstream::HostConstSharedPtr host,
                                    Event::Dispatcher& dispatcher, const Config& config) {
  return ClientImpl::create(host, dispatcher, EncoderPtr{new EncoderImpl()}, decoder_factory_,
                            config);
}

} // namespace Client
} // namespace Redis
} // namespace Common
} // namespace NetworkFilters
} // namespace Extensions
} // namespace Envoy
<commit_msg>redis: remove redundant move (#7520)<commit_after>#include "extensions/filters/network/common/redis/client_impl.h"

namespace Envoy {
namespace Extensions {
namespace NetworkFilters {
namespace Common {
namespace Redis {
namespace Client {

ConfigImpl::ConfigImpl(
    const envoy::config::filter::network::redis_proxy::v2::RedisProxy::ConnPoolSettings& config)
    : op_timeout_(PROTOBUF_GET_MS_REQUIRED(config, op_timeout)),
      enable_hashtagging_(config.enable_hashtagging()),
      enable_redirection_(config.enable_redirection()),
      max_buffer_size_before_flush_(
          config.max_buffer_size_before_flush()), // This is a scalar, so default is zero.
      buffer_flush_timeout_(PROTOBUF_GET_MS_OR_DEFAULT(
          config, buffer_flush_timeout,
          3)) // Default timeout is 3ms. If max_buffer_size_before_flush is zero, this is not used
              // as the buffer is flushed on each request immediately.
{}

ClientPtr ClientImpl::create(Upstream::HostConstSharedPtr host, Event::Dispatcher& dispatcher,
                             EncoderPtr&& encoder, DecoderFactory& decoder_factory,
                             const Config& config) {

  std::unique_ptr<ClientImpl> client(
      new ClientImpl(host, dispatcher, std::move(encoder), decoder_factory, config));
  client->connection_ = host->createConnection(dispatcher, nullptr, nullptr).connection_;
  client->connection_->addConnectionCallbacks(*client);
  client->connection_->addReadFilter(Network::ReadFilterSharedPtr{new UpstreamReadFilter(*client)});
  client->connection_->connect();
  client->connection_->noDelay(true);
  return client;
}

ClientImpl::ClientImpl(Upstream::HostConstSharedPtr host, Event::Dispatcher& dispatcher,
                       EncoderPtr&& encoder, DecoderFactory& decoder_factory, const Config& config)
    : host_(host), encoder_(std::move(encoder)), decoder_(decoder_factory.create(*this)),
      config_(config),
      connect_or_op_timer_(dispatcher.createTimer([this]() -> void { onConnectOrOpTimeout(); })),
      flush_timer_(dispatcher.createTimer([this]() -> void { flushBufferAndResetTimer(); })) {
  host->cluster().stats().upstream_cx_total_.inc();
  host->stats().cx_total_.inc();
  host->cluster().stats().upstream_cx_active_.inc();
  host->stats().cx_active_.inc();
  connect_or_op_timer_->enableTimer(host->cluster().connectTimeout());
}

ClientImpl::~ClientImpl() {
  ASSERT(pending_requests_.empty());
  ASSERT(connection_->state() == Network::Connection::State::Closed);
  host_->cluster().stats().upstream_cx_active_.dec();
  host_->stats().cx_active_.dec();
}

void ClientImpl::close() { connection_->close(Network::ConnectionCloseType::NoFlush); }

void ClientImpl::flushBufferAndResetTimer() {
  if (flush_timer_->enabled()) {
    flush_timer_->disableTimer();
  }
  connection_->write(encoder_buffer_, false);
}

PoolRequest* ClientImpl::makeRequest(const RespValue& request, PoolCallbacks& callbacks) {
  ASSERT(connection_->state() == Network::Connection::State::Open);

  const bool empty_buffer = encoder_buffer_.length() == 0;

  pending_requests_.emplace_back(*this, callbacks);
  encoder_->encode(request, encoder_buffer_);

  // If buffer is full, flush. If the buffer was empty before the request, start the timer.
  if (encoder_buffer_.length() >= config_.maxBufferSizeBeforeFlush()) {
    flushBufferAndResetTimer();
  } else if (empty_buffer) {
    flush_timer_->enableTimer(std::chrono::milliseconds(config_.bufferFlushTimeoutInMs()));
  }

  // Only boost the op timeout if:
  // - We are not already connected. Otherwise, we are governed by the connect timeout and the timer
  //   will be reset when/if connection occurs. This allows a relatively long connection spin up
  //   time for example if TLS is being used.
  // - This is the first request on the pipeline. Otherwise the timeout would effectively start on
  //   the last operation.
  if (connected_ && pending_requests_.size() == 1) {
    connect_or_op_timer_->enableTimer(config_.opTimeout());
  }

  return &pending_requests_.back();
}

void ClientImpl::onConnectOrOpTimeout() {
  putOutlierEvent(Upstream::Outlier::Result::LOCAL_ORIGIN_TIMEOUT);
  if (connected_) {
    host_->cluster().stats().upstream_rq_timeout_.inc();
    host_->stats().rq_timeout_.inc();
  } else {
    host_->cluster().stats().upstream_cx_connect_timeout_.inc();
    host_->stats().cx_connect_fail_.inc();
  }

  connection_->close(Network::ConnectionCloseType::NoFlush);
}

void ClientImpl::onData(Buffer::Instance& data) {
  try {
    decoder_->decode(data);
  } catch (ProtocolError&) {
    putOutlierEvent(Upstream::Outlier::Result::EXT_ORIGIN_REQUEST_FAILED);
    host_->cluster().stats().upstream_cx_protocol_error_.inc();
    host_->stats().rq_error_.inc();
    connection_->close(Network::ConnectionCloseType::NoFlush);
  }
}

void ClientImpl::putOutlierEvent(Upstream::Outlier::Result result) {
  if (!config_.disableOutlierEvents()) {
    host_->outlierDetector().putResult(result);
  }
}

void ClientImpl::onEvent(Network::ConnectionEvent event) {
  if (event == Network::ConnectionEvent::RemoteClose ||
      event == Network::ConnectionEvent::LocalClose) {
    if (!pending_requests_.empty()) {
      host_->cluster().stats().upstream_cx_destroy_with_active_rq_.inc();
      if (event == Network::ConnectionEvent::RemoteClose) {
        putOutlierEvent(Upstream::Outlier::Result::LOCAL_ORIGIN_CONNECT_FAILED);
        host_->cluster().stats().upstream_cx_destroy_remote_with_active_rq_.inc();
      }
      if (event == Network::ConnectionEvent::LocalClose) {
        host_->cluster().stats().upstream_cx_destroy_local_with_active_rq_.inc();
      }
    }

    while (!pending_requests_.empty()) {
      PendingRequest& request = pending_requests_.front();
      if (!request.canceled_) {
        request.callbacks_.onFailure();
      } else {
        host_->cluster().stats().upstream_rq_cancelled_.inc();
      }
      pending_requests_.pop_front();
    }

    connect_or_op_timer_->disableTimer();
  } else if (event == Network::ConnectionEvent::Connected) {
    connected_ = true;
    ASSERT(!pending_requests_.empty());
    connect_or_op_timer_->enableTimer(config_.opTimeout());
  }

  if (event == Network::ConnectionEvent::RemoteClose && !connected_) {
    host_->cluster().stats().upstream_cx_connect_fail_.inc();
    host_->stats().cx_connect_fail_.inc();
  }
}

void ClientImpl::onRespValue(RespValuePtr&& value) {
  ASSERT(!pending_requests_.empty());
  PendingRequest& request = pending_requests_.front();

  if (request.canceled_) {
    host_->cluster().stats().upstream_rq_cancelled_.inc();
  } else if (config_.enableRedirection() && (value->type() == Common::Redis::RespType::Error)) {
    std::vector<absl::string_view> err = StringUtil::splitToken(value->asString(), " ", false);
    bool redirected = false;
    if (err.size() == 3) {
      if (err[0] == RedirectionResponse::get().MOVED || err[0] == RedirectionResponse::get().ASK) {
        redirected = request.callbacks_.onRedirection(*value);
        if (redirected) {
          host_->cluster().stats().upstream_internal_redirect_succeeded_total_.inc();
        } else {
          host_->cluster().stats().upstream_internal_redirect_failed_total_.inc();
        }
      }
    }
    if (!redirected) {
      request.callbacks_.onResponse(std::move(value));
    }
  } else {
    request.callbacks_.onResponse(std::move(value));
  }

  pending_requests_.pop_front();

  // If there are no remaining ops in the pipeline we need to disable the timer.
  // Otherwise we boost the timer since we are receiving responses and there are more to flush
  // out.
  if (pending_requests_.empty()) {
    connect_or_op_timer_->disableTimer();
  } else {
    connect_or_op_timer_->enableTimer(config_.opTimeout());
  }

  putOutlierEvent(Upstream::Outlier::Result::EXT_ORIGIN_REQUEST_SUCCESS);
}

ClientImpl::PendingRequest::PendingRequest(ClientImpl& parent, PoolCallbacks& callbacks)
    : parent_(parent), callbacks_(callbacks) {
  parent.host_->cluster().stats().upstream_rq_total_.inc();
  parent.host_->stats().rq_total_.inc();
  parent.host_->cluster().stats().upstream_rq_active_.inc();
  parent.host_->stats().rq_active_.inc();
}

ClientImpl::PendingRequest::~PendingRequest() {
  parent_.host_->cluster().stats().upstream_rq_active_.dec();
  parent_.host_->stats().rq_active_.dec();
}

void ClientImpl::PendingRequest::cancel() {
  // If we get a cancellation, we just mark the pending request as cancelled, and then we drop
  // the response as it comes through. There is no reason to blow away the connection when the
  // remote is already responding as fast as possible.
  canceled_ = true;
}

ClientFactoryImpl ClientFactoryImpl::instance_;

ClientPtr ClientFactoryImpl::create(Upstream::HostConstSharedPtr host,
                                    Event::Dispatcher& dispatcher, const Config& config) {
  return ClientImpl::create(host, dispatcher, EncoderPtr{new EncoderImpl()}, decoder_factory_,
                            config);
}

} // namespace Client
} // namespace Redis
} // namespace Common
} // namespace NetworkFilters
} // namespace Extensions
} // namespace Envoy
<|endoftext|>


<commit_before>// $Id$
// $MpId: testReadSector.C,v 1.16 2006/01/11 10:00:50 ivana Exp $
//
// Test macro for reading sector data.

#include <iomanip>

void testReadSector(AliMp::StationType station = AliMp::kStation1,
                    AliMp::PlaneType plane = AliMp::kBendingPlane,
	 	    Bool_t rootInput = false)
{
  AliMpSector *sector = 0;
  if (!rootInput) {
    AliMpSectorReader r(station, plane);
    //reader.SetVerboseLevel(1);
    sector=r.BuildSector();

    // Write sector on Root file
    TString filePath = AliMpFiles::SectorFilePath(station,plane);
    filePath.ReplaceAll("zones.dat", "sector.root");

    TFile f(filePath.Data(), "RECREATE");
    sector->Write();
    f.Close();
  }
  else  {
    TString filePath = AliMpFiles::SectorFilePath(station,plane);
    filePath.ReplaceAll("zones.dat", "sector.root");

    TFile f(filePath.Data(), "READ");
    sector = (AliMpSector*)f.Get("Sector");
  }

  cout << endl;

  // Sector geometry
  sector->PrintGeometry();

  cout << endl;

  // Find row test
  if (plane == AliMp::kBendingPlane)
    cout << "0th row low border " << sector->FindRow(TVector2(0., 0.))->GetID() << endl;
  if (plane == AliMp::kNonBendingPlane)
    cout << "0th row low border " << sector->FindRow(TVector2(0., 0.215))->GetID() << endl;
  cout << "in 0th row         " << sector->FindRow(TVector2(0., 2.5))->GetID() << endl;
  cout << "0th row up border  " << sector->FindRow(TVector2(0., 6.72))->GetID() << endl;
  cout << "in 4th row         " << sector->FindRow(TVector2(0., 30.))->GetID() << endl;
  if (plane == AliMp::kBendingPlane)
    cout << "12th row up border " << sector->FindRow(TVector2(0., 89.46))->GetID() << endl;
  if (plane == AliMp::kNonBendingPlane)
    cout << "12th row up border " << sector->FindRow(TVector2(0., 84.84))->GetID() << endl;
  cout << endl;

  // Find motif position test
  Int_t ids[15] = { 19, 14, 9, 32, 36, 136, 187, 212, 207, 220, 1, 131, 239, 243, 250 };
  for (Int_t i=0; i<15 ; i++) {
    Int_t id = ids[i];
    cout << "Motif pos " << std::setw(3) << id;
    if (!sector->FindRowSegment(id)) {
       cout << " not found." << endl;
    }
    else {
       cout << " found in : "
            << sector->FindRow(id)->GetID() << " row, "
            << " motif id: "
            << sector->FindRowSegment(id)->GetMotif(0)->GetID().Data()
	    << endl;
    }
  }
  cout << endl;

  // Find motif by coordinates test
  for (Int_t i=0; i<2 ; i++) {
    TVector2 pos(0.5, 18.6 - i*2.);  // i=0 in motif 1001,
                                     // i=1 outside (below) motif 1001
    AliMpMotif* motif = sector->FindMotif(pos);
    cout << "In the position " << pos.X() << " " << pos.Y();

    if (motif)
      cout << " found motif " << motif->GetID() << endl;
    else
      cout << " motif not found " << endl;
  }

  // Find special motif test
  if (plane == AliMp::kNonBendingPlane) {

    Int_t ids[6] = { 20, 46, 47, 74, 75, 76 };
    for (Int_t i=0; i<6 ; i++) {

      Int_t id = ids[i];
      cout << "Motif pos " << id;
      if (!sector->FindRowSegment(id)) {
         cout << " not found." << endl;
      }
      else {
         cout << " found in : "
              << sector->FindRow(id)->GetID() << " row, "
	      << " position : "
	      << sector->FindPosition(id).X() << "  " <<  sector->FindPosition(id).Y()
	      << endl;
      }
    }
  }
  cout << endl;

  // Motif map
  sector->GetMotifMap()->Print();

  delete sector;
}

<commit_msg>Applying ManuMask in motif position test<commit_after>// $Id$
// $MpId: testReadSector.C,v 1.16 2006/01/11 10:00:50 ivana Exp $
//
// Test macro for reading sector data.

#include <iomanip>

void testReadSector(AliMp::StationType station = AliMp::kStation1,
                    AliMp::PlaneType plane = AliMp::kBendingPlane,
	 	    Bool_t rootInput = false)
{
  AliMpSector *sector = 0;
  if (!rootInput) {
    AliMpSectorReader r(station, plane);
    //reader.SetVerboseLevel(1);
    sector=r.BuildSector();

    // Write sector on Root file
    TString filePath = AliMpFiles::SectorFilePath(station,plane);
    filePath.ReplaceAll("zones.dat", "sector.root");

    TFile f(filePath.Data(), "RECREATE");
    sector->Write();
    f.Close();
  }
  else  {
    TString filePath = AliMpFiles::SectorFilePath(station,plane);
    filePath.ReplaceAll("zones.dat", "sector.root");

    TFile f(filePath.Data(), "READ");
    sector = (AliMpSector*)f.Get("Sector");
  }

  cout << endl;

  // Sector geometry
  sector->PrintGeometry();

  cout << endl;

  // Find row test
  if (plane == AliMp::kBendingPlane)
    cout << "0th row low border " << sector->FindRow(TVector2(0., 0.))->GetID() << endl;
  if (plane == AliMp::kNonBendingPlane)
    cout << "0th row low border " << sector->FindRow(TVector2(0., 0.215))->GetID() << endl;
  cout << "in 0th row         " << sector->FindRow(TVector2(0., 2.5))->GetID() << endl;
  cout << "0th row up border  " << sector->FindRow(TVector2(0., 6.72))->GetID() << endl;
  cout << "in 4th row         " << sector->FindRow(TVector2(0., 30.))->GetID() << endl;
  if (plane == AliMp::kBendingPlane)
    cout << "12th row up border " << sector->FindRow(TVector2(0., 89.46))->GetID() << endl;
  if (plane == AliMp::kNonBendingPlane)
    cout << "12th row up border " << sector->FindRow(TVector2(0., 84.84))->GetID() << endl;
  cout << endl;

  // Find motif position test
  Int_t ids[15] = { 19, 14, 9, 32, 36, 136, 187, 212, 207, 220, 1, 131, 239, 243, 250 };
  for (Int_t i=0; i<15 ; i++) {
    Int_t id = ids[i];
    id |= AliMpConstants::ManuMask(plane);
    cout << "Motif pos " << std::setw(3) << id;
    if (!sector->FindRowSegment(id)) {
       cout << " not found." << endl;
    }
    else {
       cout << " found in : "
            << sector->FindRow(id)->GetID() << " row, "
            << " motif id: "
            << sector->FindRowSegment(id)->GetMotif(0)->GetID().Data()
	    << endl;
    }
  }
  cout << endl;

  // Find motif by coordinates test
  for (Int_t i=0; i<2 ; i++) {
    TVector2 pos(0.5, 18.6 - i*2.);  // i=0 in motif 1001,
                                     // i=1 outside (below) motif 1001
    AliMpMotif* motif = sector->FindMotif(pos);
    cout << "In the position " << pos.X() << " " << pos.Y();

    if (motif)
      cout << " found motif " << motif->GetID() << endl;
    else
      cout << " motif not found " << endl;
  }

  // Find special motif test
  if (plane == AliMp::kNonBendingPlane) {

    Int_t ids[6] = { 20, 46, 47, 74, 75, 76 };
    for (Int_t i=0; i<6 ; i++) {

      Int_t id = ids[i];
      cout << "Motif pos " << id;
      if (!sector->FindRowSegment(id)) {
         cout << " not found." << endl;
      }
      else {
         cout << " found in : "
              << sector->FindRow(id)->GetID() << " row, "
	      << " position : "
	      << sector->FindPosition(id).X() << "  " <<  sector->FindPosition(id).Y()
	      << endl;
      }
    }
  }
  cout << endl;

  // Motif map
  sector->GetMotifMap()->Print();

  delete sector;
}

<|endoftext|>


<commit_before>#pragma once
#include "api/HttpUrlConnection.hpp"

namespace ledger {
    namespace core {
        namespace test {
            struct UrlConnectionData {
                int32_t statusCode;
                std::string statusText;
                std::unordered_map<std::string, std::string> headers;
                std::string body;
            };

            class FakeUrlConnection : public api::HttpUrlConnection {
            public:
                static std::shared_ptr<FakeUrlConnection> FakeUrlConnection::fromString(const std::string& responseData);
                FakeUrlConnection(const UrlConnectionData& data);
                int32_t getStatusCode() override;
                std::string getStatusText() override;
                std::unordered_map<std::string, std::string> getHeaders() override;
                api::HttpReadBodyResult readBody() override;
            private:
                UrlConnectionData _data;
            };
        }
    }
}<commit_msg>Remove class name from function def.<commit_after>#pragma once
#include "api/HttpUrlConnection.hpp"
#include <memory>

namespace ledger {
    namespace core {
        namespace test {
            struct UrlConnectionData {
                int32_t statusCode;
                std::string statusText;
                std::unordered_map<std::string, std::string> headers;
                std::string body;
            };

            class FakeUrlConnection : public api::HttpUrlConnection {
            public:
                static std::shared_ptr<FakeUrlConnection> fromString(const std::string& responseData);
                FakeUrlConnection(const UrlConnectionData& data);
                int32_t getStatusCode() override;
                std::string getStatusText() override;
                std::unordered_map<std::string, std::string> getHeaders() override;
                api::HttpReadBodyResult readBody() override;
            private:
                UrlConnectionData _data;
            };
        }
    }
}<|endoftext|>


<commit_before>/** \file    extract_vufind_translations_for_translation.cc
 *  \brief   A tool for extracting translations that need to be translated.  The keywords and any possibly
 *           pre-existing translations will be stored in an SQL database.
 *  \author  Dr. Johannes Ruscheinski
 */

/*
    Copyright (C) 2016, Library of the University of Tübingen

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero 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 Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <iostream>
#include <string>
#include <map>
#include <unordered_map>
#include <cstdlib>
#include "Compiler.h"
#include "DbConnection.h"
#include "DbResultSet.h"
#include "DbRow.h"
#include "File.h"
#include "IniFile.h"
#include "StringUtil.h"
#include "TranslationUtil.h"
#include "util.h"

void Usage() {
    std::cerr << "Usage: " << progname << " translation.ini...\n";
    std::exit(EXIT_FAILURE);
}

void InsertTranslations(
    DbConnection * const connection, const std::string &language_code,
    const std::unordered_map<std::string, std::pair<unsigned, std::string>> &keys_to_line_no_and_translation_map)
{
    for (const auto &keys_to_line_no_and_translation : keys_to_line_no_and_translation_map) {
        const std::string key = connection->escapeString(keys_to_line_no_and_translation.first);
        const std::string translation = connection->escapeString(keys_to_line_no_and_translation.second.second);

        // Skip inserting translations if we have a translator, i.e. the web translation tool was used
        // to insert the translations into the database
        const std::string GET_TRANSLATOR("SELECT translator FROM vufind_translations WHERE language_code=\""
           + TranslationUtil::MapGermanLanguageCodesToFake3LetterEnglishLanguagesCodes(language_code)
           + "\" AND token=\"" + key + "\"");
        if (not connection->query(GET_TRANSLATOR))
            Error("Select failed: " + GET_TRANSLATOR + " (" + connection->getLastErrorMessage() + ")");
        DbResultSet result(connection->getLastResultSet());
        if (not result.hasColumn("translator"))
            Error("Translator column not found");
        const std::string translator(result.getNextRow()["translator"]);
        if (not translator.empty())
            continue;

        const std::string INSERT_OTHER(
           "REPLACE INTO vufind_translations SET language_code=\""
	   + TranslationUtil::MapGermanLanguageCodesToFake3LetterEnglishLanguagesCodes(language_code)
	   + "\", token=\"" + key + "\", translation=\"" + translation + "\"");
        if (not connection->query(INSERT_OTHER))
            Error("Insert failed: " + INSERT_OTHER + " (" + connection->getLastErrorMessage() + ")");
    }
}

const std::string CONF_FILE_PATH("/var/lib/tuelib/translations.conf");

int main(int argc, char **argv) {
    progname = argv[0];

    if (argc < 2)
        Usage();

    try {
        const IniFile ini_file(CONF_FILE_PATH);
        const std::string sql_database(ini_file.getString("Database", "sql_database"));
        const std::string sql_username(ini_file.getString("Database", "sql_username"));
        const std::string sql_password(ini_file.getString("Database", "sql_password"));
        DbConnection db_connection(sql_database, sql_username, sql_password);

        for (int arg_no(1); arg_no < argc; ++arg_no) {
            // Get the 2-letter language code from the filename.  We expect filenames of the form "xx.ini" or
            // "some_path/xx.ini":
            const std::string ini_filename(argv[arg_no]);
            if (unlikely(not StringUtil::EndsWith(ini_filename, ".ini")))
                Error("expected filename \"" + ini_filename + "\" to end in \".ini\"!");
            std::string two_letter_code;
            if (ini_filename.length() == 6)
                two_letter_code = ini_filename.substr(0, 2);
            else {
                const std::string::size_type last_slash_pos(ini_filename.rfind('/'));
                if (unlikely(last_slash_pos == std::string::npos or (last_slash_pos + 6 + 1 != ini_filename.length())))
                    Error("INI filename does not match expected pattern: \"" + ini_filename + "\"!");
                two_letter_code = ini_filename.substr(last_slash_pos + 1, 2);
            }

            const std::string german_3letter_code(
                TranslationUtil::MapInternational2LetterCodeToGerman3LetterCode(two_letter_code));

            std::unordered_map<std::string, std::pair<unsigned, std::string>> keys_to_line_no_and_translation_map;
            TranslationUtil::ReadIniFile(ini_filename, &keys_to_line_no_and_translation_map);
            std::cout << "Read " << keys_to_line_no_and_translation_map.size()
                      << " mappings from English to another language from \"" << ini_filename << "\".\n";

            InsertTranslations(&db_connection, german_3letter_code, keys_to_line_no_and_translation_map);
        }
    } catch (const std::exception &x) {
        Error("caught exception: " + std::string(x.what()));
    }
}
<commit_msg>SEGFAULT fix<commit_after>/** \file    extract_vufind_translations_for_translation.cc
 *  \brief   A tool for extracting translations that need to be translated.  The keywords and any possibly
 *           pre-existing translations will be stored in an SQL database.
 *  \author  Dr. Johannes Ruscheinski
 */

/*
    Copyright (C) 2016, Library of the University of Tübingen

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero 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 Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <iostream>
#include <string>
#include <map>
#include <unordered_map>
#include <cstdlib>
#include "Compiler.h"
#include "DbConnection.h"
#include "DbResultSet.h"
#include "DbRow.h"
#include "File.h"
#include "IniFile.h"
#include "StringUtil.h"
#include "TranslationUtil.h"
#include "util.h"

void Usage() {
    std::cerr << "Usage: " << progname << " translation.ini...\n";
    std::exit(EXIT_FAILURE);
}

void InsertTranslations(
    DbConnection * const connection, const std::string &language_code,
    const std::unordered_map<std::string, std::pair<unsigned, std::string>> &keys_to_line_no_and_translation_map)
{
    for (const auto &keys_to_line_no_and_translation : keys_to_line_no_and_translation_map) {
        const std::string key = connection->escapeString(keys_to_line_no_and_translation.first);
        const std::string translation = connection->escapeString(keys_to_line_no_and_translation.second.second);

        // Skip inserting translations if we have a translator, i.e. the web translation tool was used
        // to insert the translations into the database
        const std::string GET_TRANSLATOR("SELECT translator FROM vufind_translations WHERE language_code=\""
           + TranslationUtil::MapGermanLanguageCodesToFake3LetterEnglishLanguagesCodes(language_code)
           + "\" AND token=\"" + key + "\"");
        if (not connection->query(GET_TRANSLATOR))
            Error("Select failed: " + GET_TRANSLATOR + " (" + connection->getLastErrorMessage() + ")");
        DbResultSet result(connection->getLastResultSet());
        if (not result.empty()) {
            const DbRow row(result.getNextRow());
            if (not row.isNull("translator")) {
                const std::string translator(row["translator"]);
                if (not translator.empty())
                continue;
            }
        }

        const std::string INSERT_OTHER(
           "REPLACE INTO vufind_translations SET language_code=\""
	   + TranslationUtil::MapGermanLanguageCodesToFake3LetterEnglishLanguagesCodes(language_code)
	   + "\", token=\"" + key + "\", translation=\"" + translation + "\"");
        if (not connection->query(INSERT_OTHER))
            Error("Insert failed: " + INSERT_OTHER + " (" + connection->getLastErrorMessage() + ")");
    }
}

const std::string CONF_FILE_PATH("/var/lib/tuelib/translations.conf");

int main(int argc, char **argv) {
    progname = argv[0];

    if (argc < 2)
        Usage();

    try {
        const IniFile ini_file(CONF_FILE_PATH);
        const std::string sql_database(ini_file.getString("Database", "sql_database"));
        const std::string sql_username(ini_file.getString("Database", "sql_username"));
        const std::string sql_password(ini_file.getString("Database", "sql_password"));
        DbConnection db_connection(sql_database, sql_username, sql_password);

        for (int arg_no(1); arg_no < argc; ++arg_no) {
            // Get the 2-letter language code from the filename.  We expect filenames of the form "xx.ini" or
            // "some_path/xx.ini":
            const std::string ini_filename(argv[arg_no]);
            if (unlikely(not StringUtil::EndsWith(ini_filename, ".ini")))
                Error("expected filename \"" + ini_filename + "\" to end in \".ini\"!");
            std::string two_letter_code;
            if (ini_filename.length() == 6)
                two_letter_code = ini_filename.substr(0, 2);
            else {
                const std::string::size_type last_slash_pos(ini_filename.rfind('/'));
                if (unlikely(last_slash_pos == std::string::npos or (last_slash_pos + 6 + 1 != ini_filename.length())))
                    Error("INI filename does not match expected pattern: \"" + ini_filename + "\"!");
                two_letter_code = ini_filename.substr(last_slash_pos + 1, 2);
            }

            const std::string german_3letter_code(
                TranslationUtil::MapInternational2LetterCodeToGerman3LetterCode(two_letter_code));

            std::unordered_map<std::string, std::pair<unsigned, std::string>> keys_to_line_no_and_translation_map;
            TranslationUtil::ReadIniFile(ini_filename, &keys_to_line_no_and_translation_map);
            std::cout << "Read " << keys_to_line_no_and_translation_map.size()
                      << " mappings from English to another language from \"" << ini_filename << "\".\n";

            InsertTranslations(&db_connection, german_3letter_code, keys_to_line_no_and_translation_map);
        }
    } catch (const std::exception &x) {
        Error("caught exception: " + std::string(x.what()));
    }
}
<|endoftext|>


<commit_before>/*  This file is part of the KDE project.

Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).

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

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

You should have received a copy of the GNU Lesser General Public License
along with this library.  If not, see <http://www.gnu.org/licenses/>.

*/

#include <QTextStream>
#include <QWidget>
#include <coecntrl.h>
#include "objectdump_symbian.h"

QT_BEGIN_NAMESPACE

namespace ObjectDump
{
namespace Symbian
{

QList<QByteArray> QAnnotatorControl::annotation(const QObject& object)
{
    QList<QByteArray> result;

    const QWidget* widget = qobject_cast<const QWidget*>(&object);
    if(widget) {

        const CCoeControl* control = widget->effectiveWinId();
        if(control) {

            QByteArray array;
            QTextStream stream(&array);

            stream << "control: " << control << ' ';
            stream << "parent " << control->Parent() << ' ';

            if(control->IsVisible())
                stream << "visible ";
            else
                stream << "invisible ";

            stream << control->Position().iX << ',' << control->Position().iY << ' ';
            stream << control->Size().iWidth << 'x' << control->Size().iHeight;

            if(control->OwnsWindow())
                stream << " ownsWindow ";

            stream.flush();
            result.append(array);
        }
    }

    return result;
}

QList<QByteArray> QAnnotatorWindow::annotation(const QObject& object)
{
    QList<QByteArray> result;

    const QWidget* widget = qobject_cast<const QWidget*>(&object);
    if(widget) {

        const CCoeControl* control = widget->effectiveWinId();
        if(control) {

            RDrawableWindow& window = *(control->DrawableWindow());

            QByteArray array;
            QTextStream stream(&array);

            stream << "window: ";

            // Client-side window handle
            // Cast to a void pointer so that log output is in hexadecimal format.
            stream << "cli " << reinterpret_cast<const void*>(window.ClientHandle()) << ' ';

            // Server-side address of CWsWindow object
            // This is useful for correlation with the window tree dumped by the window
            // server (see RWsSession::LogCommand).
            // Cast to a void pointer so that log output is in hexadecimal format.
            stream << "srv " << reinterpret_cast<const void*>(window.WsHandle()) << ' ';

            stream << "group " << window.WindowGroupId() << ' ';

            // Client-side handle to the parent window.
            // Cast to a void pointer so that log output is in hexadecimal format.
            stream << "parent " << reinterpret_cast<const void*>(window.Parent()) << ' ';

            stream << window.Position().iX << ',' << window.Position().iY << ' ';
            stream << '(' << window.AbsPosition().iX << ',' << window.AbsPosition().iY << ") ";
            stream << window.Size().iWidth << 'x' << window.Size().iHeight;

            stream.flush();
            result.append(array);
        }
    }

    return result;
}

} // namespace Symbian

void addDefaultAnnotators_sys(QDumper& dumper)
{
    dumper.addAnnotator(new Symbian::QAnnotatorControl);
    dumper.addAnnotator(new Symbian::QAnnotatorWindow);
}

void addDefaultAnnotators_sys(QVisitor& visitor)
{
    visitor.addAnnotator(new Symbian::QAnnotatorControl);
    visitor.addAnnotator(new Symbian::QAnnotatorWindow);
}

} // namespace ObjectDump

QT_END_NAMESPACE

<commit_msg>Modified object annotator to dump display mode of Symbian windows<commit_after>/*  This file is part of the KDE project.

Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).

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

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

You should have received a copy of the GNU Lesser General Public License
along with this library.  If not, see <http://www.gnu.org/licenses/>.

*/

#include <QTextStream>
#include <QWidget>
#include <coecntrl.h>
#include "objectdump_symbian.h"

QT_BEGIN_NAMESPACE

namespace ObjectDump
{
namespace Symbian
{

QList<QByteArray> QAnnotatorControl::annotation(const QObject& object)
{
    QList<QByteArray> result;

    const QWidget* widget = qobject_cast<const QWidget*>(&object);
    if(widget) {

        const CCoeControl* control = widget->effectiveWinId();
        if(control) {

            QByteArray array;
            QTextStream stream(&array);

            stream << "control: " << control << ' ';
            stream << "parent " << control->Parent() << ' ';

            if(control->IsVisible())
                stream << "visible ";
            else
                stream << "invisible ";

            stream << control->Position().iX << ',' << control->Position().iY << ' ';
            stream << control->Size().iWidth << 'x' << control->Size().iHeight;

            if(control->OwnsWindow())
                stream << " ownsWindow ";

            stream.flush();
            result.append(array);
        }
    }

    return result;
}

QList<QByteArray> QAnnotatorWindow::annotation(const QObject& object)
{
    QList<QByteArray> result;

    const QWidget* widget = qobject_cast<const QWidget*>(&object);
    if(widget) {

        const CCoeControl* control = widget->effectiveWinId();
        if(control) {

            RDrawableWindow& window = *(control->DrawableWindow());

            QByteArray array;
            QTextStream stream(&array);

            stream << "window: ";

            // Client-side window handle
            // Cast to a void pointer so that log output is in hexadecimal format.
            stream << "cli " << reinterpret_cast<const void*>(window.ClientHandle()) << ' ';

            // Server-side address of CWsWindow object
            // This is useful for correlation with the window tree dumped by the window
            // server (see RWsSession::LogCommand).
            // Cast to a void pointer so that log output is in hexadecimal format.
            stream << "srv " << reinterpret_cast<const void*>(window.WsHandle()) << ' ';

            stream << "group " << window.WindowGroupId() << ' ';

            // Client-side handle to the parent window.
            // Cast to a void pointer so that log output is in hexadecimal format.
            stream << "parent " << reinterpret_cast<const void*>(window.Parent()) << ' ';

            stream << window.Position().iX << ',' << window.Position().iY << ' ';
            stream << '(' << window.AbsPosition().iX << ',' << window.AbsPosition().iY << ") ";
            stream << window.Size().iWidth << 'x' << window.Size().iHeight << ' ';

            const TDisplayMode displayMode = window.DisplayMode();
            stream << "mode " << displayMode;

            stream.flush();
            result.append(array);
        }
    }

    return result;
}

} // namespace Symbian

void addDefaultAnnotators_sys(QDumper& dumper)
{
    dumper.addAnnotator(new Symbian::QAnnotatorControl);
    dumper.addAnnotator(new Symbian::QAnnotatorWindow);
}

void addDefaultAnnotators_sys(QVisitor& visitor)
{
    visitor.addAnnotator(new Symbian::QAnnotatorControl);
    visitor.addAnnotator(new Symbian::QAnnotatorWindow);
}

} // namespace ObjectDump

QT_END_NAMESPACE

<|endoftext|>


<commit_before>/** \file    extract_vufind_translations_for_translation.cc
 *  \brief   A tool for extracting translations that need to be translated.  The keywords and any possibly
 *           pre-existing translations will be stored in an SQL database.
 *  \author  Dr. Johannes Ruscheinski
 */

/*
    Copyright (C) 2016, Library of the University of Tübingen

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero 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 Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <iostream>
#include <string>
#include <map>
#include <unordered_map>
#include <cstdlib>
#include "Compiler.h"
#include "DbConnection.h"
#include "File.h"
#include "IniFile.h"
#include "StringUtil.h"
#include "TranslationUtil.h"
#include "util.h"

void Usage() {
    std::cerr << "Usage: " << progname << " translation.ini...\n";
    std::exit(EXIT_FAILURE);
}

void InsertTranslations(
    DbConnection * const connection, const std::string &language_code,
    const std::unordered_map<std::string, std::pair<unsigned, std::string>> &keys_to_line_no_and_translation_map)
{
    for (const auto &keys_to_line_no_and_translation : keys_to_line_no_and_translation_map) {
        const std::string key = connection->escapeString(keys_to_line_no_and_translation.first);
        const std::string translation = connection->escapeString(keys_to_line_no_and_translation.second.second);
        const std::string INSERT_OTHER(
           "REPLACE INTO vufind_translations SET language_code=\""
	   + TranslationUtil::MapGermanLanguageCodesToFake3LetterEnglishLanguagesCodes(language_code)
	   + "\", token=\"" + key + "\", translation=\"" + translation + "\"");
        if (not connection->query(INSERT_OTHER))
            Error("Insert failed: " + INSERT_OTHER + " (" + connection->getLastErrorMessage() + ")");
    }
}

const std::string CONF_FILE_PATH("/var/lib/tuelib/translations.conf");

int main(int argc, char **argv) {
    progname = argv[0];

    if (argc < 2)
        Usage();

    try {
        const IniFile ini_file(CONF_FILE_PATH);
        const std::string sql_database(ini_file.getString("Database", "sql_database"));
        const std::string sql_username(ini_file.getString("Database", "sql_username"));
        const std::string sql_password(ini_file.getString("Database", "sql_password"));
        DbConnection db_connection(sql_database, sql_username, sql_password);

        for (int arg_no(1); arg_no < argc; ++arg_no) {
            // Get the 2-letter language code from the filename.  We expect filenames of the form "xx.ini" or
            // "some_path/xx.ini":
            const std::string ini_filename(argv[arg_no]);
            if (unlikely(not StringUtil::EndsWith(ini_filename, ".ini")))
                Error("expected filename \"" + ini_filename + "\" to end in \".ini\"!");
            std::string two_letter_code;
            if (ini_filename.length() == 6)
                two_letter_code = ini_filename.substr(0, 2);
            else {
                const std::string::size_type last_slash_pos(ini_filename.rfind('/'));
                if (unlikely(last_slash_pos == std::string::npos or (last_slash_pos + 6 + 1 != ini_filename.length())))
                    Error("INI filename does not match expected pattern: \"" + ini_filename + "\"!");
                two_letter_code = ini_filename.substr(last_slash_pos + 1, 2);
            }

            const std::string german_3letter_code(
                TranslationUtil::MapInternational2LetterCodeToGerman3LetterCode(two_letter_code));

            std::unordered_map<std::string, std::pair<unsigned, std::string>> keys_to_line_no_and_translation_map;
            TranslationUtil::ReadIniFile(ini_filename, &keys_to_line_no_and_translation_map);
            std::cout << "Read " << keys_to_line_no_and_translation_map.size()
                      << " mappings from English to another language from \"" << ini_filename << "\".\n";

            InsertTranslations(&db_connection, german_3letter_code, keys_to_line_no_and_translation_map);
        }
    } catch (const std::exception &x) {
        Error("caught exception: " + std::string(x.what()));
    }
}
<commit_msg>Pay attention to existing translators<commit_after>/** \file    extract_vufind_translations_for_translation.cc
 *  \brief   A tool for extracting translations that need to be translated.  The keywords and any possibly
 *           pre-existing translations will be stored in an SQL database.
 *  \author  Dr. Johannes Ruscheinski
 */

/*
    Copyright (C) 2016, Library of the University of Tübingen

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero 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 Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <iostream>
#include <string>
#include <map>
#include <unordered_map>
#include <cstdlib>
#include "Compiler.h"
#include "DbConnection.h"
#include "DbResultSet.h"
#include "DbRow.h"
#include "File.h"
#include "IniFile.h"
#include "StringUtil.h"
#include "TranslationUtil.h"
#include "util.h"

void Usage() {
    std::cerr << "Usage: " << progname << " translation.ini...\n";
    std::exit(EXIT_FAILURE);
}

void InsertTranslations(
    DbConnection * const connection, const std::string &language_code,
    const std::unordered_map<std::string, std::pair<unsigned, std::string>> &keys_to_line_no_and_translation_map)
{
    for (const auto &keys_to_line_no_and_translation : keys_to_line_no_and_translation_map) {
        const std::string key = connection->escapeString(keys_to_line_no_and_translation.first);
        const std::string translation = connection->escapeString(keys_to_line_no_and_translation.second.second);

        // Skip inserting translations if we have a translator, i.e. the web translation tool was used
        // to insert the translations into the database
        const std::string GET_TRANSLATOR("SELECT translator FROM vufind_translations WHERE language_code=\""
           + TranslationUtil::MapGermanLanguageCodesToFake3LetterEnglishLanguagesCodes(language_code)
           + "\" AND token=\"" + key + "\"");
        if (not connection->query(GET_TRANSLATOR))
            Error("Select failed: " + GET_TRANSLATOR + " (" + connection->getLastErrorMessage() + ")");
        DbResultSet result(connection->getLastResultSet());
        if (not result.hasColumn("translator"))
            Error("Translator column not found");
        const std::string translator(result.getNextRow()["translator"]);
        if (not translator.empty())
            continue;

        const std::string INSERT_OTHER(
           "REPLACE INTO vufind_translations SET language_code=\""
	   + TranslationUtil::MapGermanLanguageCodesToFake3LetterEnglishLanguagesCodes(language_code)
	   + "\", token=\"" + key + "\", translation=\"" + translation + "\"");
        if (not connection->query(INSERT_OTHER))
            Error("Insert failed: " + INSERT_OTHER + " (" + connection->getLastErrorMessage() + ")");
    }
}

const std::string CONF_FILE_PATH("/var/lib/tuelib/translations.conf");

int main(int argc, char **argv) {
    progname = argv[0];

    if (argc < 2)
        Usage();

    try {
        const IniFile ini_file(CONF_FILE_PATH);
        const std::string sql_database(ini_file.getString("Database", "sql_database"));
        const std::string sql_username(ini_file.getString("Database", "sql_username"));
        const std::string sql_password(ini_file.getString("Database", "sql_password"));
        DbConnection db_connection(sql_database, sql_username, sql_password);

        for (int arg_no(1); arg_no < argc; ++arg_no) {
            // Get the 2-letter language code from the filename.  We expect filenames of the form "xx.ini" or
            // "some_path/xx.ini":
            const std::string ini_filename(argv[arg_no]);
            if (unlikely(not StringUtil::EndsWith(ini_filename, ".ini")))
                Error("expected filename \"" + ini_filename + "\" to end in \".ini\"!");
            std::string two_letter_code;
            if (ini_filename.length() == 6)
                two_letter_code = ini_filename.substr(0, 2);
            else {
                const std::string::size_type last_slash_pos(ini_filename.rfind('/'));
                if (unlikely(last_slash_pos == std::string::npos or (last_slash_pos + 6 + 1 != ini_filename.length())))
                    Error("INI filename does not match expected pattern: \"" + ini_filename + "\"!");
                two_letter_code = ini_filename.substr(last_slash_pos + 1, 2);
            }

            const std::string german_3letter_code(
                TranslationUtil::MapInternational2LetterCodeToGerman3LetterCode(two_letter_code));

            std::unordered_map<std::string, std::pair<unsigned, std::string>> keys_to_line_no_and_translation_map;
            TranslationUtil::ReadIniFile(ini_filename, &keys_to_line_no_and_translation_map);
            std::cout << "Read " << keys_to_line_no_and_translation_map.size()
                      << " mappings from English to another language from \"" << ini_filename << "\".\n";

            InsertTranslations(&db_connection, german_3letter_code, keys_to_line_no_and_translation_map);
        }
    } catch (const std::exception &x) {
        Error("caught exception: " + std::string(x.what()));
    }
}
<|endoftext|>


<commit_before>/*  This file is part of the KDE project.

Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).

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

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

You should have received a copy of the GNU Lesser General Public License
along with this library.  If not, see <http://www.gnu.org/licenses/>.

*/

#include <QTextStream>
#include <QWidget>
#include <coecntrl.h>
#include "objectdump_symbian.h"

QT_BEGIN_NAMESPACE

namespace ObjectDump
{
namespace Symbian
{

QList<QByteArray> QAnnotatorControl::annotation(const QObject& object)
{
    QList<QByteArray> result;

    const QWidget* widget = qobject_cast<const QWidget*>(&object);
    if(widget) {

        const CCoeControl* control = widget->effectiveWinId();
        if(control) {

            QByteArray array;
            QTextStream stream(&array);

            stream << "control: " << control << ' ';
            stream << "parent " << control->Parent() << ' ';

            if(control->IsVisible())
                stream << "visible ";
            else
                stream << "invisible ";

            stream << control->Position().iX << ',' << control->Position().iY << ' ';
            stream << control->Size().iWidth << 'x' << control->Size().iHeight;

            if(control->OwnsWindow())
                stream << " ownsWindow ";

            stream.flush();
            result.append(array);
        }
    }

    return result;
}

QList<QByteArray> QAnnotatorWindow::annotation(const QObject& object)
{
    QList<QByteArray> result;

    const QWidget* widget = qobject_cast<const QWidget*>(&object);
    if(widget) {

        const CCoeControl* control = widget->effectiveWinId();
        if(control) {

            RDrawableWindow& window = *(control->DrawableWindow());

            QByteArray array;
            QTextStream stream(&array);

            stream << "window: ";

            // Client-side window handle
            // Cast to a void pointer so that log output is in hexadecimal format.
            stream << "cli " << reinterpret_cast<const void*>(window.ClientHandle()) << ' ';

            // Server-side address of CWsWindow object
            // This is useful for correlation with the window tree dumped by the window
            // server (see RWsSession::LogCommand).
            // Cast to a void pointer so that log output is in hexadecimal format.
            stream << "srv " << reinterpret_cast<const void*>(window.WsHandle()) << ' ';

            stream << "group " << window.WindowGroupId() << ' ';

            // Client-side handle to the parent window.
            // Cast to a void pointer so that log output is in hexadecimal format.
            stream << "parent " << reinterpret_cast<const void*>(window.Parent()) << ' ';

            stream << window.Position().iX << ',' << window.Position().iY << ' ';
            stream << '(' << window.AbsPosition().iX << ',' << window.AbsPosition().iY << ") ";
            stream << window.Size().iWidth << 'x' << window.Size().iHeight << ' ';

            const TDisplayMode displayMode = window.DisplayMode();
            stream << "mode " << displayMode;

            stream.flush();
            result.append(array);
        }
    }

    return result;
}

} // namespace Symbian

void addDefaultAnnotators_sys(QDumper& dumper)
{
    dumper.addAnnotator(new Symbian::QAnnotatorControl);
    dumper.addAnnotator(new Symbian::QAnnotatorWindow);
}

void addDefaultAnnotators_sys(QVisitor& visitor)
{
    visitor.addAnnotator(new Symbian::QAnnotatorControl);
    visitor.addAnnotator(new Symbian::QAnnotatorWindow);
}

} // namespace ObjectDump

QT_END_NAMESPACE

<commit_msg>Build fix for SDK 3.1 and 3.2.<commit_after>/*  This file is part of the KDE project.

Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).

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

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

You should have received a copy of the GNU Lesser General Public License
along with this library.  If not, see <http://www.gnu.org/licenses/>.

*/

#include <QTextStream>
#include <QWidget>
#include <coecntrl.h>
#include "objectdump_symbian.h"

QT_BEGIN_NAMESPACE

namespace ObjectDump
{
namespace Symbian
{

QList<QByteArray> QAnnotatorControl::annotation(const QObject& object)
{
    QList<QByteArray> result;

    const QWidget* widget = qobject_cast<const QWidget*>(&object);
    if(widget) {

        const CCoeControl* control = widget->effectiveWinId();
        if(control) {

            QByteArray array;
            QTextStream stream(&array);

            stream << "control: " << control << ' ';
            stream << "parent " << control->Parent() << ' ';

            if(control->IsVisible())
                stream << "visible ";
            else
                stream << "invisible ";

            stream << control->Position().iX << ',' << control->Position().iY << ' ';
            stream << control->Size().iWidth << 'x' << control->Size().iHeight;

            if(control->OwnsWindow())
                stream << " ownsWindow ";

            stream.flush();
            result.append(array);
        }
    }

    return result;
}

QList<QByteArray> QAnnotatorWindow::annotation(const QObject& object)
{
    QList<QByteArray> result;

    const QWidget* widget = qobject_cast<const QWidget*>(&object);
    if(widget) {

        const CCoeControl* control = widget->effectiveWinId();
        if(control) {

            RDrawableWindow& window = *(control->DrawableWindow());

            QByteArray array;
            QTextStream stream(&array);

            stream << "window: ";

            // ClientHandle() is available first in 5.0.
#if !defined(__SERIES60_31__) && !defined(__S60_32__)
            // Client-side window handle
            // Cast to a void pointer so that log output is in hexadecimal format.
            stream << "cli " << reinterpret_cast<const void*>(window.ClientHandle()) << ' ';
#endif

            // Server-side address of CWsWindow object
            // This is useful for correlation with the window tree dumped by the window
            // server (see RWsSession::LogCommand).
            // Cast to a void pointer so that log output is in hexadecimal format.
            stream << "srv " << reinterpret_cast<const void*>(window.WsHandle()) << ' ';

            stream << "group " << window.WindowGroupId() << ' ';

            // Client-side handle to the parent window.
            // Cast to a void pointer so that log output is in hexadecimal format.
            stream << "parent " << reinterpret_cast<const void*>(window.Parent()) << ' ';

            stream << window.Position().iX << ',' << window.Position().iY << ' ';
            stream << '(' << window.AbsPosition().iX << ',' << window.AbsPosition().iY << ") ";
            stream << window.Size().iWidth << 'x' << window.Size().iHeight << ' ';

            const TDisplayMode displayMode = window.DisplayMode();
            stream << "mode " << displayMode;

            stream.flush();
            result.append(array);
        }
    }

    return result;
}

} // namespace Symbian

void addDefaultAnnotators_sys(QDumper& dumper)
{
    dumper.addAnnotator(new Symbian::QAnnotatorControl);
    dumper.addAnnotator(new Symbian::QAnnotatorWindow);
}

void addDefaultAnnotators_sys(QVisitor& visitor)
{
    visitor.addAnnotator(new Symbian::QAnnotatorControl);
    visitor.addAnnotator(new Symbian::QAnnotatorWindow);
}

} // namespace ObjectDump

QT_END_NAMESPACE

<|endoftext|>