<commit_before>// For conditions of distribution and use, see copyright notice in license.txt

#include "StableHeaders.h"
#include "QOgreUIView.h"

#ifdef Q_WS_X11
#include <QX11Info>
#endif

#ifdef Q_WS_WIN
#include <windows.h>
#endif

namespace OgreRenderer
{
    QOgreUIView::QOgreUIView () :
        QGraphicsView(),
        win_(0),
        view_(0)
    {
        Initialize_();
    }

    QOgreUIView::QOgreUIView (QWidget *parent, QGraphicsScene *scene) :
        QGraphicsView(scene, parent),
        win_(0),
        view_(0)
    {
        Initialize_();
    }

    QOgreUIView::~QOgreUIView ()
    {
        if (scene())
        {
            // FIX PYTHON:
            // python module crashes viewer on exit if these are not removed
            // better to have viewer not crash and leave some memory leaks
            // python should delete the QWidgets it put to scene in ~PythonModule() to avoid this
            //QList<QGraphicsItem*> remaining_items = scene()->items();
            //foreach(QGraphicsItem *item, remaining_items)
            //    scene()->removeItem(item);
            delete scene();
        }
    }

    void QOgreUIView::Initialize_()
    {
        // Setup QGrapchicsView
        setUpdatesEnabled (false);
        setAutoFillBackground (false);
        setFocusPolicy (Qt::StrongFocus);
        setViewportUpdateMode (QGraphicsView::FullViewportUpdate);
        setHorizontalScrollBarPolicy (Qt::ScrollBarAlwaysOff);
        setVerticalScrollBarPolicy (Qt::ScrollBarAlwaysOff);

        // Get rid of extra white layers under widgets
        // Qt doesn't respect the above request to not fill background
        QPalette empty_background = palette ();
        empty_background.setColor (QPalette::Window, Qt::transparent);
        empty_background.setColor (QPalette::Base, Qt::transparent);
        setPalette (empty_background);

        setAttribute (Qt::WA_OpaquePaintEvent, false);

        #ifdef Q_WS_WIN
        // Determine if we are running under windows 7 that has certain paint issues with Qt 4.6 in a QGraphicsView
        // If we are under win 7 we do some dirty hacks to go around this as a temp solution
        OSVERSIONINFOEX os_version_info;
        ZeroMemory(&os_version_info, sizeof(OSVERSIONINFOEX));
        os_version_info.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
        if (GetVersionEx((OSVERSIONINFO *)&os_version_info))
            if (os_version_info.dwMajorVersion == 6 && os_version_info.dwMinorVersion == 1)
                setAttribute(Qt::WA_DontShowOnScreen, true);
        #endif
    }

    void QOgreUIView::SetWorldView(QOgreWorldView *view)
    {
        view_ = view;
        QObject::connect(scene(), SIGNAL( changed (const QList<QRectF> &) ), this, SLOT( SceneChange() ));
    }

    void QOgreUIView::InitializeWorldView(int width, int height)
    {
        if (view_) view_->InitializeOverlay(width, height);
    }

    Ogre::RenderWindow *QOgreUIView::CreateRenderWindow (const std::string &name,  int width, int height, int left, int top, bool fullscreen)
    {
        bool stealparent
            ((parentWidget())? true : false);

        QWidget *nativewin
            ((stealparent)? parentWidget() : this);

        Ogre::NameValuePairList params;
        Ogre::String winhandle;

    #ifdef Q_WS_WIN
        // According to Ogre Docs
        // positive integer for W32 (HWND handle)
        winhandle = Ogre::StringConverter::toString
            ((unsigned int)
             (nativewin-> winId ()));

        //Add the external window handle parameters to the existing params set.
        params["externalWindowHandle"] = winhandle;

    #endif

    #ifdef Q_WS_X11
        // GLX - According to Ogre Docs:
        // poslong:posint:poslong:poslong (display*:screen:windowHandle:XVisualInfo*)
        QX11Info info =  x11Info ();

        winhandle  = Ogre::StringConverter::toString
            ((unsigned long)
             (info.display ()));
        winhandle += ":";

        winhandle += Ogre::StringConverter::toString
            ((unsigned int)
             (info.screen ()));
        winhandle += ":";

        winhandle += Ogre::StringConverter::toString
            ((unsigned long)
             nativewin-> winId());

        //Add the external window handle parameters to the existing params set.
        params["parentWindowHandle"] = winhandle;
    #endif

        // Window position to params
        if (left != -1)
            params["left"] = ToString(left);
        if (top != -1)
            params["top"] = ToString(top);

        win_ = Ogre::Root::getSingletonPtr()-> createRenderWindow(name, width, height, fullscreen, &params);

        return win_;
    }

    void QOgreUIView::keyPressEvent (QKeyEvent *e)
    {
        if (e->key() == Qt::Key_F1 && scene()->focusItem())
            emit ConsoleToggleRequest();
        QGraphicsView::keyPressEvent(e);
    }

    void QOgreUIView::resizeEvent (QResizeEvent *e)
    {
        QGraphicsView::resizeEvent(e);

        // Resize render window and UI texture to match this
        if (view_)
        {
            view_->ResizeWindow(width(), height());
            view_->ResizeOverlay(viewport()->width(), viewport()->height());
        }

        if (scene())
            scene()->setSceneRect(viewport()->rect());
    }

    void QOgreUIView::SceneChange()
    {
        setDirty(true);
    }
}
<commit_msg>add mac version of qt-ogre window shuffle code that doesn't work<commit_after>// For conditions of distribution and use, see copyright notice in license.txt

#include "StableHeaders.h"
#include "QOgreUIView.h"

#ifdef Q_WS_X11
#include <QX11Info>
#endif

#ifdef Q_WS_WIN
#include <windows.h>
#endif

namespace OgreRenderer
{
    QOgreUIView::QOgreUIView () :
        QGraphicsView(),
        win_(0),
        view_(0)
    {
        Initialize_();
    }

    QOgreUIView::QOgreUIView (QWidget *parent, QGraphicsScene *scene) :
        QGraphicsView(scene, parent),
        win_(0),
        view_(0)
    {
        Initialize_();
    }

    QOgreUIView::~QOgreUIView ()
    {
        if (scene())
        {
            // FIX PYTHON:
            // python module crashes viewer on exit if these are not removed
            // better to have viewer not crash and leave some memory leaks
            // python should delete the QWidgets it put to scene in ~PythonModule() to avoid this
            //QList<QGraphicsItem*> remaining_items = scene()->items();
            //foreach(QGraphicsItem *item, remaining_items)
            //    scene()->removeItem(item);
            delete scene();
        }
    }

    void QOgreUIView::Initialize_()
    {
        // Setup QGrapchicsView
        setUpdatesEnabled (false);
        setAutoFillBackground (false);
        setFocusPolicy (Qt::StrongFocus);
        setViewportUpdateMode (QGraphicsView::FullViewportUpdate);
        setHorizontalScrollBarPolicy (Qt::ScrollBarAlwaysOff);
        setVerticalScrollBarPolicy (Qt::ScrollBarAlwaysOff);

        // Get rid of extra white layers under widgets
        // Qt doesn't respect the above request to not fill background
        QPalette empty_background = palette ();
        empty_background.setColor (QPalette::Window, Qt::transparent);
        empty_background.setColor (QPalette::Base, Qt::transparent);
        setPalette (empty_background);

        setAttribute (Qt::WA_OpaquePaintEvent, false);

        #ifdef Q_WS_WIN
        // Determine if we are running under windows 7 that has certain paint issues with Qt 4.6 in a QGraphicsView
        // If we are under win 7 we do some dirty hacks to go around this as a temp solution
        OSVERSIONINFOEX os_version_info;
        ZeroMemory(&os_version_info, sizeof(OSVERSIONINFOEX));
        os_version_info.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
        if (GetVersionEx((OSVERSIONINFO *)&os_version_info))
            if (os_version_info.dwMajorVersion == 6 && os_version_info.dwMinorVersion == 1)
                setAttribute(Qt::WA_DontShowOnScreen, true);
        #endif

	#ifdef Q_WS_MAC
        setAttribute(Qt::WA_PaintOnScreen);
	setAttribute(Qt::WA_NoSystemBackground);
        #endif
    }

    void QOgreUIView::SetWorldView(QOgreWorldView *view)
    {
        view_ = view;
        QObject::connect(scene(), SIGNAL( changed (const QList<QRectF> &) ), this, SLOT( SceneChange() ));
    }

    void QOgreUIView::InitializeWorldView(int width, int height)
    {
        if (view_) view_->InitializeOverlay(width, height);
    }

    Ogre::RenderWindow *QOgreUIView::CreateRenderWindow (const std::string &name,  int width, int height, int left, int top, bool fullscreen)
    {
        bool stealparent
            ((parentWidget())? true : false);

        QWidget *nativewin
            ((stealparent)? parentWidget() : this);

        Ogre::NameValuePairList params;
        Ogre::String winhandle;

    #ifdef Q_WS_WIN
        // According to Ogre Docs
        // positive integer for W32 (HWND handle)
        winhandle = Ogre::StringConverter::toString
            ((unsigned int)
             (nativewin-> winId ()));

        //Add the external window handle parameters to the existing params set.
        params["externalWindowHandle"] = winhandle;

    #endif

    #ifdef Q_WS_MAC
	// qt docs say it's a HIViewRef on carbon,
 	// carbon docs say HIViewGetWindow gets a WindowRef out of it

    #if 0
	HIViewRef vref = (HIViewRef) nativewin-> winId ();
	WindowRef wref = HIViewGetWindow(vref);
        winhandle = Ogre::StringConverter::toString(
           (unsigned long) (HIViewGetRoot(wref)));
    #else
        // according to
        // http://www.ogre3d.org/forums/viewtopic.php?f=2&t=27027 does
        winhandle = Ogre::StringConverter::toString(
                     (unsigned long) nativewin->winId());
    #endif
        //Add the external window handle parameters to the existing params set.
        params["externalWindowHandle"] = winhandle;
    #endif

    #ifdef Q_WS_X11
        // GLX - According to Ogre Docs:
        // poslong:posint:poslong:poslong (display*:screen:windowHandle:XVisualInfo*)
        QX11Info info =  x11Info ();

        winhandle  = Ogre::StringConverter::toString
            ((unsigned long)
             (info.display ()));
        winhandle += ":";

        winhandle += Ogre::StringConverter::toString
            ((unsigned int)
             (info.screen ()));
        winhandle += ":";

        winhandle += Ogre::StringConverter::toString
            ((unsigned long)
             nativewin-> winId());

        //Add the external window handle parameters to the existing params set.
        params["parentWindowHandle"] = winhandle;
    #endif

        // Window position to params
        if (left != -1)
            params["left"] = ToString(left);
        if (top != -1)
            params["top"] = ToString(top);

        win_ = Ogre::Root::getSingletonPtr()-> createRenderWindow(name, width, height, fullscreen, &params);

        return win_;
    }

    void QOgreUIView::keyPressEvent (QKeyEvent *e)
    {
        if (e->key() == Qt::Key_F1 && scene()->focusItem())
            emit ConsoleToggleRequest();
        QGraphicsView::keyPressEvent(e);
    }

    void QOgreUIView::resizeEvent (QResizeEvent *e)
    {
        QGraphicsView::resizeEvent(e);

        // Resize render window and UI texture to match this
        if (view_)
        {
            view_->ResizeWindow(width(), height());
            view_->ResizeOverlay(viewport()->width(), viewport()->height());
        }

        if (scene())
            scene()->setSceneRect(viewport()->rect());
    }

    void QOgreUIView::SceneChange()
    {
        setDirty(true);
    }
}
<|endoftext|>


<commit_before>/////////////////////////////////////////////////
//
// Macro for plotting MC rates of electrons
// for the EMCAL PPR
//
// J.L. Klay (Cal Poly)
//
/////////////////////////////////////////////////

TH1F* all;
TH1F* bele;
TH1F* cele;
TH1F* candb;
TH1F* conv;
TH1F* dalitz;
TH1F* wz;
TH1F* other;
TH1F* mchad;
TLegend* leg;

void plotMCRates(char* hijfname = "data/histos-merged-LHC0bd6.root",
		 char* jjfname = "data/histosscaledLHC09b2ESDb.root",
		 char* bfname = "data/histosscaledLHC09b4v2.root",
		 char* wfname = "data/histos_wboson_pt29b.root") {

  //For HIJING need to divide by the number of events, which we
  //can get from the file and do when we perform scaling
  double hijscale = 0.05*(1.E6)*0.5*208*208; //0-5% * seconds*lumi*Pb*Pb
  //For bjet and jet-jet events
  double pyscale = (1.E6)*0.5*208*208; //seconds*lumi*Pb*Pb
  double wscale = pyscale*6.29e-05; //JLK: This is temporary X-sec
				     //info from 2-29 GeV bin until we get pyxsec files

  TFile* hijfile = new TFile(hijfname);
  if(!hijfile) { printf("NO HIJING FILE\n"); return; }
  TList* hijlist = (TList*)hijfile->Get("histos");
  TH2F* hijmcele = (TH2F*)hijlist->FindObject("AnaElectron_hPtMCElectron");
  TH1F* hijmchad = (TH1F*)hijlist->FindObject("AnaElectron_hPtMCHadron");
  TH1F* refmult = (TH1F*)hijlist->FindObject("AnaElectron_hRefMult");
  Int_t nEvt = refmult->GetEntries();
  if(nEvt == 0) { printf("NO HIJING EVENTS\n"); return; }
  hijmcele->Scale(hijscale/nEvt);
  hijmchad->Scale(hijscale/nEvt);

  TFile* jjfile = new TFile(jjfname);
  if(!jjfile) { printf("NO JET-JET FILE\n"); return; }
  TList* jjlist = (TList*)jjfile->Get("histos");
  TH2F* jjmcele = (TH2F*)histosscaled->FindObject("AnaElectron_hPtMCElectronScaled");
  TH1F* jjmchad = (TH1F*)histosscaled->FindObject("AnaElectron_hPtMCHadronScaled");
  jjmcele->Scale(pyscale);
  jjmchad->Scale(pyscale);

  TFile* bfile = new TFile(bfname);
  if(!bfile) { printf("NO B-JET FILE\n"); return; }
  TList* blist = (TList*)bfile->Get("histos");
  TH2F* bmcele = (TH2F*)histosscaled->FindObject("AnaElectron_hPtMCElectronScaled");
  TH1F* bmchad = (TH1F*)histosscaled->FindObject("AnaElectron_hPtMCHadronScaled");
  bmcele->Scale(pyscale);
  bmchad->Scale(pyscale);

  TFile* wfile = new TFile(wfname);
  if(!wfile) { printf("NO W-BOSON FILE\n"); return; }
  TList* wlist = (TList*)wfile->Get("histos");
  TH2F* wmcele = (TH2F*)histos->FindObject("AnaElectron_hPtMCElectron");
  TH1F* wmchad = (TH1F*)histos->FindObject("AnaElectron_hPtMCHadron");
  wmcele->Scale(wscale);
  wmchad->Scale(wscale);

  TH2F* combined = (TH2F*)hijmcele->Clone();
  combined->Add(jjmcele);
  combined->Add(bmcele);
  combined->SetTitle("MC electrons in Pb+Pb in EMCAL acceptance");
  combined->SetName("CombinedMCEle");
  combined->SetXTitle("p_T (GeV/c)");

  mchad = (TH1F*)hijmchad->Clone();
  mchad->Add(jjmchad);
  mchad->Add(bmchad);
  mchad->Add(wmchad);
  mchad->SetTitle("MC hadrons in Pb+Pb in EMCAL acceptance");
  mchad->SetName("CombinedMCHad");
  mchad->SetXTitle("p_T (GeV/c)");

  all = (TH1F*)combined->ProjectionX("all",1,1);
  bele = (TH1F*)combined->ProjectionX("b",2,2);
  cele = (TH1F*)combined->ProjectionX("c",3,3);
  candb = (TH1F*)combined->ProjectionX("candb",4,4);
  conv = (TH1F*)combined->ProjectionX("conv",5,5);
  dalitz = (TH1F*)combined->ProjectionX("dalitz",6,6);
  other = (TH1F*)combined->ProjectionX("other",8,8);

  wz = (TH1F*)wmcele->ProjectionX("wz",7,7);

  double myscale = 1.; //we already scaled them
  ScaleAndConfigure(all,myscale,kBlack,kFALSE);
  ScaleAndConfigure(bele,myscale,kRed,kFALSE);
  ScaleAndConfigure(cele,myscale,kBlue,kFALSE);
  ScaleAndConfigure(candb,myscale,kViolet,kFALSE);
  ScaleAndConfigure(conv,myscale,kOrange-3,kFALSE);
  ScaleAndConfigure(dalitz,myscale,kGreen-3,kFALSE);
  ScaleAndConfigure(wz,myscale,kOrange-7,kFALSE);
  ScaleAndConfigure(mchad,myscale,kGreen+2,kFALSE);

  gStyle->SetOptStat(0);
  //drawXSRates();
  drawAnnualYields();
  drawPtCutRates();
  drawHadEleRatios();

}

void ScaleAndConfigure(TH1F* hist,Double_t scale, Int_t color,Bool_t keepErr)
{
  hist->Scale(scale);
  hist->SetLineColor(color);
  hist->SetLineWidth(2);
  if(keepErr == kFALSE) {
    //remove the error bars - useful for MC rates
    for(Int_t i = 1; i < hist->GetNbinsX(); i++) {
      hist->SetBinError(i,0.);
    }
  }
}

void drawAnnualYields() {

  TCanvas* crates = new TCanvas("crates","crates",20,20,600,400);
  crates->cd();
  gPad->SetLogy();
  all->SetXTitle("p_{T} (GeV/c)");
  all->SetYTitle("Annual yield");
  all->GetYaxis()->SetRangeUser(1.E1,3.E9);
  all->GetXaxis()->SetRangeUser(0.,50.);
  all->Draw();
  bele->Draw("same");
  cele->Draw("same");
  candb->Draw("same");
  conv->Draw("same");
  dalitz->Draw("same");
  wz->Draw("same");

  leg = new TLegend(0.6,0.6,0.9,0.9);
  leg->SetTextSize(leg->GetTextSize()*1.2);
  leg->AddEntry(all,"All MC electrons","l");
  leg->AddEntry(bele,"Bottom e","l");
  leg->AddEntry(cele,"Charm e","l");
  leg->AddEntry(candb,"B-->C e","l");
  leg->AddEntry(dalitz,"Dalitz e","l");
  leg->AddEntry(conv,"Conversion e","l");
  leg->AddEntry(wz,"W Boson e","l");
  leg->Draw();

}

void drawPtCutRates() {

  TCanvas* cptcut = new TCanvas();
  cptcut->cd();
  gPad->SetLogy();
  TH1F* alleptcut = GetPtCutHisto(all);
  TH1F* beleptcut = GetPtCutHisto(bele);
  TH1F* celeptcut = GetPtCutHisto(cele);
  TH1F* cbeleptcut = GetPtCutHisto(candb);
  TH1F* dalitzptcut = GetPtCutHisto(dalitz);
  TH1F* convptcut = GetPtCutHisto(conv);
  alleptcut->GetXaxis()->SetRangeUser(0,50);
  alleptcut->GetYaxis()->SetRangeUser(100,alleptcut->GetMaximum()*2);
  alleptcut->SetXTitle("p_{T}^{cut} (GeV/c)");
  alleptcut->SetYTitle("Annual Yield in EMCAL for p_{T}>p_{T}^{cut}");
  alleptcut->SetTitle("Annual electron yield in Pb+Pb for p_{T}>p_{T}^{cut}");
  alleptcut->Draw();
  beleptcut->Draw("same");
  celeptcut->Draw("same");
  cbeleptcut->Draw("same");
  dalitzptcut->Draw("same");
  convptcut->Draw("same");
  leg->Draw();

}

void drawHadEleRatios() {

  TCanvas* ceh = new TCanvas();
  ceh->cd();
  gPad->SetLogy();
  gStyle->SetOptStat(0);
  TH1F* allratio = (TH1F*)all->Clone();
  TH1F* behratio = (TH1F*)bele->Clone();
  allratio->SetTitle("Pb+Pb, 5.5 TeV");
  allratio->SetXTitle("p_{T} (GeV/c)");
  allratio->SetYTitle("Hadrons/Electrons");
  for(Int_t i = 1; i < all->GetNbinsX(); i++) {
    Double_t vale = all->GetBinContent(i);
    Double_t valb = bele->GetBinContent(i);
    Double_t valh = mchad->GetBinContent(i);
    //printf("pT %.2f, Hadron %.1f, Electron %.1f, B-electron %.1f\n",all->GetBinCenter(i),valh,vale,valb);
    if(vale>0) allratio->SetBinContent(i,valh/vale);
    else allratio->SetBinContent(i,0.);

    if(valb>0) behratio->SetBinContent(i,valh/valb);
    else behratio->SetBinContent(i,0.);

    allratio->SetBinError(i,0.);
    behratio->SetBinError(i,0.);
  }
  allratio->Rebin();
  behratio->Rebin();
  allratio->GetYaxis()->SetRangeUser(1,10000);
  allratio->GetXaxis()->SetRangeUser(0,50);
  behratio->GetXaxis()->SetRangeUser(0,50);
  allratio->SetMarkerStyle(20);
  behratio->SetMarkerStyle(24);
  allratio->Draw();
  behratio->Draw("psame");

  TLegend *heleg = new TLegend(0.4,0.75,0.75,0.9);
  heleg->SetTextSize(heleg->GetTextSize()*1.5);
  heleg->AddEntry(allratio,"All electrons","l");
  heleg->AddEntry(behratio,"Bottom electrons","p");
  heleg->Draw();

}

TH1F* GetPtCutHisto(TH1F* input)
{
  //Given a rate histogram vs pt, return the histogram with yield
  //above a given pTcut

  TH1F* result = (TH1F*)input->Clone();
  char name[100];
  sprintf(name,"%s_ptCut",result->GetName());
  result->SetNameTitle(name,name);
  for(Int_t i = 1; i <= result->GetNbinsX(); i++) {
    Double_t val = input->Integral(i,result->GetNbinsX());
    result->SetBinContent(i,val);
    result->SetBinError(i,0.);
  }

  return result;

}

<commit_msg>correct hijing scale factor<commit_after>/////////////////////////////////////////////////
//
// Macro for plotting MC rates of electrons
// for the EMCAL PPR
//
// J.L. Klay (Cal Poly)
//
/////////////////////////////////////////////////

TH1F* all;
TH1F* bele;
TH1F* cele;
TH1F* candb;
TH1F* conv;
TH1F* dalitz;
TH1F* wz;
TH1F* other;
TH1F* mchad;
TLegend* leg;

void plotMCRates(char* hijfname = "data/histos-merged-LHC0bd6.root",
		 char* jjfname = "data/histosscaledLHC09b2ESDb.root",
		 char* bfname = "data/histosscaledLHC09b4v2.root",
		 char* wfname = "data/histos_wboson_pt29b.root") {

  //For HIJING need to divide by the number of events, which we
  //can get from the file and do when we perform scaling
  double hijscale = 0.05*(1.E6)*0.5*7700; //0-5% * seconds*lumi*PbPb x-section
  //For bjet and jet-jet events
  double pyscale = (1.E6)*0.5*208*208; //seconds*lumi*Pb*Pb
  double wscale = pyscale*6.29e-05; //JLK: This is temporary X-sec
				     //info from 2-29 GeV bin until we get pyxsec files

  TFile* hijfile = new TFile(hijfname);
  if(!hijfile) { printf("NO HIJING FILE\n"); return; }
  TList* hijlist = (TList*)hijfile->Get("histos");
  TH2F* hijmcele = (TH2F*)hijlist->FindObject("AnaElectron_hPtMCElectron");
  TH1F* hijmchad = (TH1F*)hijlist->FindObject("AnaElectron_hPtMCHadron");
  TH1F* refmult = (TH1F*)hijlist->FindObject("AnaElectron_hRefMult");
  Int_t nEvt = refmult->GetEntries();
  if(nEvt == 0) { printf("NO HIJING EVENTS\n"); return; }
  hijmcele->Scale(hijscale/nEvt);
  hijmchad->Scale(hijscale/nEvt);

  TFile* jjfile = new TFile(jjfname);
  if(!jjfile) { printf("NO JET-JET FILE\n"); return; }
  TList* jjlist = (TList*)jjfile->Get("histos");
  TH2F* jjmcele = (TH2F*)histosscaled->FindObject("AnaElectron_hPtMCElectronScaled");
  TH1F* jjmchad = (TH1F*)histosscaled->FindObject("AnaElectron_hPtMCHadronScaled");
  jjmcele->Scale(pyscale);
  jjmchad->Scale(pyscale);

  TFile* bfile = new TFile(bfname);
  if(!bfile) { printf("NO B-JET FILE\n"); return; }
  TList* blist = (TList*)bfile->Get("histos");
  TH2F* bmcele = (TH2F*)histosscaled->FindObject("AnaElectron_hPtMCElectronScaled");
  TH1F* bmchad = (TH1F*)histosscaled->FindObject("AnaElectron_hPtMCHadronScaled");
  bmcele->Scale(pyscale);
  bmchad->Scale(pyscale);

  TFile* wfile = new TFile(wfname);
  if(!wfile) { printf("NO W-BOSON FILE\n"); return; }
  TList* wlist = (TList*)wfile->Get("histos");
  TH2F* wmcele = (TH2F*)histos->FindObject("AnaElectron_hPtMCElectron");
  TH1F* wmchad = (TH1F*)histos->FindObject("AnaElectron_hPtMCHadron");
  wmcele->Scale(wscale);
  wmchad->Scale(wscale);

  TH2F* combined = (TH2F*)hijmcele->Clone();
  combined->Add(jjmcele);
  combined->Add(bmcele);
  combined->SetTitle("MC electrons in Pb+Pb in EMCAL acceptance");
  combined->SetName("CombinedMCEle");
  combined->SetXTitle("p_T (GeV/c)");

  mchad = (TH1F*)hijmchad->Clone();
  mchad->Add(jjmchad);
  mchad->Add(bmchad);
  mchad->Add(wmchad);
  mchad->SetTitle("MC hadrons in Pb+Pb in EMCAL acceptance");
  mchad->SetName("CombinedMCHad");
  mchad->SetXTitle("p_T (GeV/c)");

  all = (TH1F*)combined->ProjectionX("all",1,1);
  bele = (TH1F*)combined->ProjectionX("b",2,2);
  cele = (TH1F*)combined->ProjectionX("c",3,3);
  candb = (TH1F*)combined->ProjectionX("candb",4,4);
  conv = (TH1F*)combined->ProjectionX("conv",5,5);
  dalitz = (TH1F*)combined->ProjectionX("dalitz",6,6);
  other = (TH1F*)combined->ProjectionX("other",8,8);

  wz = (TH1F*)wmcele->ProjectionX("wz",7,7);

  double myscale = 1.; //we already scaled them
  ScaleAndConfigure(all,myscale,kBlack,kFALSE);
  ScaleAndConfigure(bele,myscale,kRed,kFALSE);
  ScaleAndConfigure(cele,myscale,kBlue,kFALSE);
  ScaleAndConfigure(candb,myscale,kViolet,kFALSE);
  ScaleAndConfigure(conv,myscale,kOrange-3,kFALSE);
  ScaleAndConfigure(dalitz,myscale,kGreen-3,kFALSE);
  ScaleAndConfigure(wz,myscale,kOrange-7,kFALSE);
  ScaleAndConfigure(mchad,myscale,kGreen+2,kFALSE);

  gStyle->SetOptStat(0);
  //drawXSRates();
  drawAnnualYields();
  drawPtCutRates();
  drawHadEleRatios();

}

void ScaleAndConfigure(TH1F* hist,Double_t scale, Int_t color,Bool_t keepErr)
{
  hist->Scale(scale);
  hist->SetLineColor(color);
  hist->SetLineWidth(2);
  if(keepErr == kFALSE) {
    //remove the error bars - useful for MC rates
    for(Int_t i = 1; i < hist->GetNbinsX(); i++) {
      hist->SetBinError(i,0.);
    }
  }
}

void drawAnnualYields() {

  TCanvas* crates = new TCanvas("crates","crates",20,20,600,400);
  crates->cd();
  gPad->SetLogy();
  all->SetXTitle("p_{T} (GeV/c)");
  all->SetYTitle("Annual yield");
  all->GetYaxis()->SetRangeUser(1.E1,3.E9);
  all->GetXaxis()->SetRangeUser(0.,50.);
  all->Draw();
  bele->Draw("same");
  cele->Draw("same");
  candb->Draw("same");
  conv->Draw("same");
  dalitz->Draw("same");
  wz->Draw("same");

  leg = new TLegend(0.6,0.6,0.9,0.9);
  leg->SetTextSize(leg->GetTextSize()*1.2);
  leg->AddEntry(all,"All MC electrons","l");
  leg->AddEntry(bele,"Bottom e","l");
  leg->AddEntry(cele,"Charm e","l");
  leg->AddEntry(candb,"B-->C e","l");
  leg->AddEntry(dalitz,"Dalitz e","l");
  leg->AddEntry(conv,"Conversion e","l");
  leg->AddEntry(wz,"W Boson e","l");
  leg->Draw();

}

void drawPtCutRates() {

  TCanvas* cptcut = new TCanvas();
  cptcut->cd();
  gPad->SetLogy();
  TH1F* alleptcut = GetPtCutHisto(all);
  TH1F* beleptcut = GetPtCutHisto(bele);
  TH1F* celeptcut = GetPtCutHisto(cele);
  TH1F* cbeleptcut = GetPtCutHisto(candb);
  TH1F* dalitzptcut = GetPtCutHisto(dalitz);
  TH1F* convptcut = GetPtCutHisto(conv);
  alleptcut->GetXaxis()->SetRangeUser(0,50);
  alleptcut->GetYaxis()->SetRangeUser(100,alleptcut->GetMaximum()*2);
  alleptcut->SetXTitle("p_{T}^{cut} (GeV/c)");
  alleptcut->SetYTitle("Annual Yield in EMCAL for p_{T}>p_{T}^{cut}");
  alleptcut->SetTitle("Annual electron yield in Pb+Pb for p_{T}>p_{T}^{cut}");
  alleptcut->Draw();
  beleptcut->Draw("same");
  celeptcut->Draw("same");
  cbeleptcut->Draw("same");
  dalitzptcut->Draw("same");
  convptcut->Draw("same");
  leg->Draw();

}

void drawHadEleRatios() {

  TCanvas* ceh = new TCanvas();
  ceh->cd();
  gPad->SetLogy();
  gStyle->SetOptStat(0);
  TH1F* allratio = (TH1F*)all->Clone();
  TH1F* behratio = (TH1F*)bele->Clone();
  allratio->SetTitle("Pb+Pb, 5.5 TeV");
  allratio->SetXTitle("p_{T} (GeV/c)");
  allratio->SetYTitle("Hadrons/Electrons");
  for(Int_t i = 1; i < all->GetNbinsX(); i++) {
    Double_t vale = all->GetBinContent(i);
    Double_t valb = bele->GetBinContent(i);
    Double_t valh = mchad->GetBinContent(i);
    //printf("pT %.2f, Hadron %.1f, Electron %.1f, B-electron %.1f\n",all->GetBinCenter(i),valh,vale,valb);
    if(vale>0) allratio->SetBinContent(i,valh/vale);
    else allratio->SetBinContent(i,0.);

    if(valb>0) behratio->SetBinContent(i,valh/valb);
    else behratio->SetBinContent(i,0.);

    allratio->SetBinError(i,0.);
    behratio->SetBinError(i,0.);
  }
  allratio->Rebin();
  behratio->Rebin();
  allratio->GetYaxis()->SetRangeUser(1,10000);
  allratio->GetXaxis()->SetRangeUser(0,50);
  behratio->GetXaxis()->SetRangeUser(0,50);
  allratio->SetMarkerStyle(20);
  behratio->SetMarkerStyle(24);
  allratio->Draw();
  behratio->Draw("psame");

  TLegend *heleg = new TLegend(0.4,0.75,0.75,0.9);
  heleg->SetTextSize(heleg->GetTextSize()*1.5);
  heleg->AddEntry(allratio,"All electrons","l");
  heleg->AddEntry(behratio,"Bottom electrons","p");
  heleg->Draw();

}

TH1F* GetPtCutHisto(TH1F* input)
{
  //Given a rate histogram vs pt, return the histogram with yield
  //above a given pTcut

  TH1F* result = (TH1F*)input->Clone();
  char name[100];
  sprintf(name,"%s_ptCut",result->GetName());
  result->SetNameTitle(name,name);
  for(Int_t i = 1; i <= result->GetNbinsX(); i++) {
    Double_t val = input->Integral(i,result->GetNbinsX());
    result->SetBinContent(i,val);
    result->SetBinError(i,0.);
  }

  return result;

}

<|endoftext|>


<commit_before><commit_msg>bugfix<commit_after><|endoftext|>


<commit_before><commit_msg>Prefix: crash fixes<commit_after><|endoftext|>


<commit_before><commit_msg>added basic exit<commit_after><|endoftext|>


<commit_before><commit_msg>Enable reload<commit_after><|endoftext|>


<commit_before><commit_msg>update to descriptions of configuration options<commit_after><|endoftext|>


<commit_before>#include <cassert>
#include <cstdint>
#include <cstdlib>
#include <iostream>
#include <sstream>
#include <string>
#include <unistd.h>
#include <vector>
#include "snarkfront.hpp"

using namespace snarkfront;
using namespace std;

void printUsage(const char* exeName) {
    cout << "usage: cat NIST_SHAVS_byte_test_vector_file | " << exeName
         << " -c BN128|Edwards -b 1|224|256|384|512 [-i Len|COUNT] [-p]" << endl
         << endl
         << "example: SHA1 short messages" << endl
         << "cat SHA1ShortMsg.rsp | " << exeName << " -c BN128 -b 1" << endl
         << endl
         << "example: SHA256 long messages with proof" << endl
         << "cat SHA256LongMsg.rsp | " << exeName << " -c Edwards -b 256 -p" << endl
         << endl
         << "example: SHA512 Monte Carlo mode" << endl
         << "cat SHA512Monte.txt | " << exeName << " -c BN128 -b 512" << endl
         << endl
         << "example: SHA224 short messages, only Len = 464 test case" << endl
         << "cat SHA224ShortMsg.rsp | " << exeName << " -c Edwards -b 224 -i 464" << endl
         << endl
         << "example: SHA384 Monte Carlo mode, only COUNT = 75 test case" << endl
         << "cat SHA384Monte.txt | " << exeName << " -c BN128 -b 384 -i 75" << endl;

    exit(EXIT_FAILURE);
}

// short and long message tests
template <typename ZK_SHA, typename EVAL_SHA>
bool runHash(const string& msg, const string& MD)
{
    // convert hexadecimal message text to binary
    vector<uint8_t> v;
    if ("00" != msg && !asciiHexToVector(msg, v)) // 00 is null msg
        return false;

    // compute message digest
    const auto zk_digest = digest(ZK_SHA(), v);
    const auto eval_digest = digest(EVAL_SHA(), v);

    assert(zk_digest.size() == eval_digest.size());

    // compare message zk and eval digest values
    bool valueOK = true;
    for (size_t i = 0; i < zk_digest.size(); ++i) {
        if (zk_digest[i]->value() != eval_digest[i])
            valueOK = false;
    }

    // message digest proof constraint
    assert_true(zk_digest == eval_digest);

    // compare eval digest and SHAVS test case MD
    if (MD != asciiHex(eval_digest))
        valueOK = false;

    return valueOK;
}

// Monte Carlo tests
template <typename EVAL_SHA>
bool runMC(const string& prevMD, const string& MD)
{
    // prevMD is message digest input
    vector<typename EVAL_SHA::WordType> v0, v1, v2;
    if (!asciiHexToVector(prevMD, v2)) return false;
    v0 = v1 = v2;

    for (size_t i = 3; i < 1003; ++i) {
        // compute message digest
        // message is concatenation of last three digests
        const auto eval_digest = digest(EVAL_SHA(), v0, v1, v2);

        // rotate message digests
        v0 = v1;
        v1 = v2;
        assert(eval_digest.size() == v2.size());
        for (size_t j = 0; j < v2.size(); ++j)
            v2[j] = eval_digest[j];
    }

    // compare final message digest with test case MD
    return MD == asciiHex(v2);
}

bool readAssignment(const string& line, string& lhs, string& rhs)
{
    stringstream ss(line);

    // left hand side
    if (!ss.eof())
        ss >> lhs;

    // should be =
    string op;
    if (!!ss && !ss.eof() && !lhs.empty())
        ss >> op;

    // right hand side
    if (!!ss && !ss.eof() && ("=" == op))
        ss >> rhs;

    // true if lhs and rhs both defined and op is =
    return !!ss && !lhs.empty() && !rhs.empty();
}

template <typename PAIRING>
void readLoop(const size_t shaBits, const size_t testCase, const bool zkProof)
{
    typedef typename PAIRING::Fr FR;

    stringstream ss;
    ss << testCase;
    const auto testCaseStr = ss.str(); // specific test case by Len/COUNT

    string line, count, seed, len, msg, MD;
    while (!cin.eof() && getline(cin, line)) {
        // skip empty lines and comments
        if (line.empty() || '#' == line[0])
            continue;

        string lhs, rhs;
        if (! readAssignment(line, lhs, rhs))
            continue;

        if ("Len" == lhs) {
            // length of message
            len = rhs;

        } else if ("Msg" == lhs) {
            // message
            msg = rhs;

        } else if ("MD" == lhs) {
            // message digest
            MD = rhs;

        } else if ("COUNT" == lhs) {
            // Monte-Carlo mode
            count = rhs;

        } else if ("Seed" == lhs) {
            // Monte-Carlo mode
            seed = rhs;

            // warning message if zero knowledge proof mode selected
            if (zkProof) {
                cout << "warning: proof generation disabled for Monte Carlo tests (too expensive)"
                     << endl;
            }
        }

        if (seed.empty()) {
            // short and long message modes
            if (!len.empty() && !msg.empty() && !MD.empty()) {
                if (-1 == testCase || testCaseStr == len) {
                    reset<PAIRING>();

                    bool result;

                    if (1 == shaBits) {
                        result = runHash<zk::SHA1<FR>, eval::SHA1>(msg, MD);
                    } else if (224 == shaBits) {
                        result = runHash<zk::SHA224<FR>, eval::SHA224>(msg, MD);
                    } else if (256 == shaBits) {
                        result = runHash<zk::SHA256<FR>, eval::SHA256>(msg, MD);
                    } else if (384 == shaBits) {
                        result = runHash<zk::SHA384<FR>, eval::SHA384>(msg, MD);
                    } else if (512 == shaBits) {
                        result = runHash<zk::SHA512<FR>, eval::SHA512>(msg, MD);
                    }

                    if (zkProof) {
                        GenericProgressBar progress1(cerr), progress2(cerr, 50);

                        cerr << "generate key pair";
                        const auto key = keypair<PAIRING>(progress2);
                        cerr << endl;

                        const auto in = input<PAIRING>();

                        cerr << "generate proof";
                        const auto p = proof(key, progress2);
                        cerr << endl;

                        cerr << "verify proof ";
                        const bool proofOK = verify(key, in, p, progress1);
                        cerr << endl;

                        if (! proofOK) result = false;
                    }

                    cout << (result ? "OK" : "FAIL") << " "
                         << len << " " << MD << endl;
                }

                len.clear();
                msg.clear();
                MD.clear();
            }

        } else {
            // Monte-Carlo mode
            if (!MD.empty()) {
                if (-1 == testCase || testCaseStr == count) {
                    bool result;

                    if (1 == shaBits) {
                        result = runMC<eval::SHA1>(seed, MD);
                    } else if (224 == shaBits) {
                        result = runMC<eval::SHA224>(seed, MD);
                    } else if (256 == shaBits) {
                        result = runMC<eval::SHA256>(seed, MD);
                    } else if (384 == shaBits) {
                        result = runMC<eval::SHA384>(seed, MD);
                    } else if (512 == shaBits) {
                        result = runMC<eval::SHA512>(seed, MD);
                    }

                    cout << (result ? "OK" : "FAIL") << " "
                         << count << " " << seed << " " << MD << endl;
                }

                seed = MD;
                MD.clear();
            }
        }
    }
}

int main(int argc, char *argv[])
{
    // command line switches
    string ellipticCurve;
    std::size_t shaBits = 0, testCase = -1;
    bool zkProof = false;
    int opt;
    while (-1 != (opt = getopt(argc, argv, "c:b:i:p"))) {
        switch (opt) {
        case ('c') :
            ellipticCurve = optarg;
            break;
        case ('b') :
            {
                stringstream ss(optarg);
                ss >> shaBits;
                if (!ss) printUsage(argv[0]);
            }
            break;
        case ('i') :
            {
                stringstream ss(optarg);
                ss >> testCase;
                if (!ss) printUsage(argv[0]);
            }
            break;
        case ('p') :
            zkProof = true;
            break;
        }
    }

    // check for valid SHA bits
    if (1 != shaBits &&
        224 != shaBits &&
        256 != shaBits &&
        384 != shaBits &&
        512 != shaBits)
        printUsage(argv[0]);

    if ("BN128" == ellipticCurve) {
        // Barreto-Naehrig 128 bits
        init_BN128();
        readLoop<BN128_PAIRING>(shaBits, testCase, zkProof);

    } else if ("Edwards" == ellipticCurve) {
        // Edwards 80 bits
        init_Edwards();
        readLoop<EDWARDS_PAIRING>(shaBits, testCase, zkProof);

    } else {
        // no elliptic curve specified
        printUsage(argv[0]);
    }

    exit(EXIT_SUCCESS);
}
<commit_msg>command line option -p pairing<commit_after>#include <cassert>
#include <cstdint>
#include <cstdlib>
#include <iostream>
#include <sstream>
#include <string>
#include <unistd.h>
#include <vector>
#include "snarkfront.hpp"

using namespace snarkfront;
using namespace std;

void printUsage(const char* exeName) {
    cout << "usage: cat NIST_SHAVS_byte_test_vector_file | " << exeName
         << " -p BN128|Edwards -b 1|224|256|384|512 [-i Len|COUNT] [-z]" << endl
         << endl
         << "example: SHA1 short messages" << endl
         << "cat SHA1ShortMsg.rsp | " << exeName << " -p BN128 -b 1" << endl
         << endl
         << "example: SHA256 long messages with proof" << endl
         << "cat SHA256LongMsg.rsp | " << exeName << " -p Edwards -b 256 -z" << endl
         << endl
         << "example: SHA512 Monte Carlo mode" << endl
         << "cat SHA512Monte.txt | " << exeName << " -p BN128 -b 512" << endl
         << endl
         << "example: SHA224 short messages, only Len = 464 test case" << endl
         << "cat SHA224ShortMsg.rsp | " << exeName << " -p Edwards -b 224 -i 464" << endl
         << endl
         << "example: SHA384 Monte Carlo mode, only COUNT = 75 test case" << endl
         << "cat SHA384Monte.txt | " << exeName << " -p BN128 -b 384 -i 75" << endl;

    exit(EXIT_FAILURE);
}

// short and long message tests
template <typename ZK_SHA, typename EVAL_SHA>
bool runHash(const string& msg, const string& MD)
{
    // convert hexadecimal message text to binary
    vector<uint8_t> v;
    if ("00" != msg && !asciiHexToVector(msg, v)) // 00 is null msg
        return false;

    // compute message digest
    const auto zk_digest = digest(ZK_SHA(), v);
    const auto eval_digest = digest(EVAL_SHA(), v);

    assert(zk_digest.size() == eval_digest.size());

    // compare message zk and eval digest values
    bool valueOK = true;
    for (size_t i = 0; i < zk_digest.size(); ++i) {
        if (zk_digest[i]->value() != eval_digest[i])
            valueOK = false;
    }

    // message digest proof constraint
    assert_true(zk_digest == eval_digest);

    // compare eval digest and SHAVS test case MD
    if (MD != asciiHex(eval_digest))
        valueOK = false;

    return valueOK;
}

// Monte Carlo tests
template <typename EVAL_SHA>
bool runMC(const string& prevMD, const string& MD)
{
    // prevMD is message digest input
    vector<typename EVAL_SHA::WordType> v0, v1, v2;
    if (!asciiHexToVector(prevMD, v2)) return false;
    v0 = v1 = v2;

    for (size_t i = 3; i < 1003; ++i) {
        // compute message digest
        // message is concatenation of last three digests
        const auto eval_digest = digest(EVAL_SHA(), v0, v1, v2);

        // rotate message digests
        v0 = v1;
        v1 = v2;
        assert(eval_digest.size() == v2.size());
        for (size_t j = 0; j < v2.size(); ++j)
            v2[j] = eval_digest[j];
    }

    // compare final message digest with test case MD
    return MD == asciiHex(v2);
}

bool readAssignment(const string& line, string& lhs, string& rhs)
{
    stringstream ss(line);

    // left hand side
    if (!ss.eof())
        ss >> lhs;

    // should be =
    string op;
    if (!!ss && !ss.eof() && !lhs.empty())
        ss >> op;

    // right hand side
    if (!!ss && !ss.eof() && ("=" == op))
        ss >> rhs;

    // true if lhs and rhs both defined and op is =
    return !!ss && !lhs.empty() && !rhs.empty();
}

template <typename PAIRING>
void readLoop(const size_t shaBits, const size_t testCase, const bool zkProof)
{
    typedef typename PAIRING::Fr FR;

    stringstream ss;
    ss << testCase;
    const auto testCaseStr = ss.str(); // specific test case by Len/COUNT

    string line, count, seed, len, msg, MD;
    while (!cin.eof() && getline(cin, line)) {
        // skip empty lines and comments
        if (line.empty() || '#' == line[0])
            continue;

        string lhs, rhs;
        if (! readAssignment(line, lhs, rhs))
            continue;

        if ("Len" == lhs) {
            // length of message
            len = rhs;

        } else if ("Msg" == lhs) {
            // message
            msg = rhs;

        } else if ("MD" == lhs) {
            // message digest
            MD = rhs;

        } else if ("COUNT" == lhs) {
            // Monte-Carlo mode
            count = rhs;

        } else if ("Seed" == lhs) {
            // Monte-Carlo mode
            seed = rhs;

            // warning message if zero knowledge proof mode selected
            if (zkProof) {
                cout << "warning: proof generation disabled for Monte Carlo tests (too expensive)"
                     << endl;
            }
        }

        if (seed.empty()) {
            // short and long message modes
            if (!len.empty() && !msg.empty() && !MD.empty()) {
                if (-1 == testCase || testCaseStr == len) {
                    reset<PAIRING>();

                    bool result;

                    if (1 == shaBits) {
                        result = runHash<zk::SHA1<FR>, eval::SHA1>(msg, MD);
                    } else if (224 == shaBits) {
                        result = runHash<zk::SHA224<FR>, eval::SHA224>(msg, MD);
                    } else if (256 == shaBits) {
                        result = runHash<zk::SHA256<FR>, eval::SHA256>(msg, MD);
                    } else if (384 == shaBits) {
                        result = runHash<zk::SHA384<FR>, eval::SHA384>(msg, MD);
                    } else if (512 == shaBits) {
                        result = runHash<zk::SHA512<FR>, eval::SHA512>(msg, MD);
                    }

                    if (zkProof) {
                        GenericProgressBar progress1(cerr), progress2(cerr, 50);

                        cerr << "generate key pair";
                        const auto key = keypair<PAIRING>(progress2);
                        cerr << endl;

                        const auto in = input<PAIRING>();

                        cerr << "generate proof";
                        const auto p = proof(key, progress2);
                        cerr << endl;

                        cerr << "verify proof ";
                        const bool proofOK = verify(key, in, p, progress1);
                        cerr << endl;

                        if (! proofOK) result = false;
                    }

                    cout << (result ? "OK" : "FAIL") << " "
                         << len << " " << MD << endl;
                }

                len.clear();
                msg.clear();
                MD.clear();
            }

        } else {
            // Monte-Carlo mode
            if (!MD.empty()) {
                if (-1 == testCase || testCaseStr == count) {
                    bool result;

                    if (1 == shaBits) {
                        result = runMC<eval::SHA1>(seed, MD);
                    } else if (224 == shaBits) {
                        result = runMC<eval::SHA224>(seed, MD);
                    } else if (256 == shaBits) {
                        result = runMC<eval::SHA256>(seed, MD);
                    } else if (384 == shaBits) {
                        result = runMC<eval::SHA384>(seed, MD);
                    } else if (512 == shaBits) {
                        result = runMC<eval::SHA512>(seed, MD);
                    }

                    cout << (result ? "OK" : "FAIL") << " "
                         << count << " " << seed << " " << MD << endl;
                }

                seed = MD;
                MD.clear();
            }
        }
    }
}

int main(int argc, char *argv[])
{
    // command line switches
    string pairing;
    std::size_t shaBits = 0, testCase = -1;
    bool zkProof = false;
    int opt;
    while (-1 != (opt = getopt(argc, argv, "p:b:i:z"))) {
        switch (opt) {
        case ('p') :
            pairing = optarg;
            break;
        case ('b') : {
                stringstream ss(optarg);
                ss >> shaBits;
                if (!ss) printUsage(argv[0]);
            }
            break;
        case ('i') : {
                stringstream ss(optarg);
                ss >> testCase;
                if (!ss) printUsage(argv[0]);
            }
            break;
        case ('z') :
            zkProof = true;
            break;
        }
    }

    // check for valid SHA bits
    if (1 != shaBits &&
        224 != shaBits &&
        256 != shaBits &&
        384 != shaBits &&
        512 != shaBits)
        printUsage(argv[0]);

    if (pairingBN128(pairing)) {
        // Barreto-Naehrig 128 bits
        init_BN128();
        readLoop<BN128_PAIRING>(shaBits, testCase, zkProof);

    } else if (pairingEdwards(pairing)) {
        // Edwards 80 bits
        init_Edwards();
        readLoop<EDWARDS_PAIRING>(shaBits, testCase, zkProof);

    } else {
        // no elliptic curve specified
        printUsage(argv[0]);
    }

    exit(EXIT_SUCCESS);
}
<|endoftext|>


<commit_before>// -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*-
// vi: set ts=2 noet:
//
// Copyright (c) 2016 Sergey Lyskov <sergey.lyskov@jhu.edu>
//
// All rights reserved. Use of this source code is governed by a
// MIT license that can be found in the LICENSE file.

/// @file   binder/test/T10.override.hpp
/// @brief  Binder self-test file. Bindings tests for overriding classes in Python.
/// @author Sergey Lyskov

#ifndef _INCLUDED_T10_override_hpp_
#define _INCLUDED_T10_override_hpp_

#include <memory>
#include <string>

class Base
{
public:
	std::string s_;

	virtual void foo_void() {}
	virtual void foo_void_pure() = 0;

	virtual int         foo_int() { return 0; }
	virtual std::string foo_sring() { return ""; }

	virtual std::string &foo_sring_r() { return s_; }
};

#endif // _INCLUDED_T10_override_hpp_
<commit_msg>Added _GLIBCXX_USE_CXX11<commit_after>// -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*-
// vi: set ts=2 noet:
//
// Copyright (c) 2016 Sergey Lyskov <sergey.lyskov@jhu.edu>
//
// All rights reserved. Use of this source code is governed by a
// MIT license that can be found in the LICENSE file.

/// @file   binder/test/T10.override.hpp
/// @brief  Binder self-test file. Bindings tests for overriding classes in Python.
/// @author Sergey Lyskov

#ifndef _INCLUDED_T10_override_hpp_
#define _INCLUDED_T10_override_hpp_

#define _GLIBCXX_USE_CXX11_ABI 0
#include <string>

class Base
{
public:
	std::string s_;

	virtual void foo_void() {}
	virtual void foo_void_pure() = 0;

	virtual int         foo_int() { return 0; }
	virtual std::string foo_sring() { return ""; }

	virtual std::string &foo_sring_r() { return s_; }
};

#endif // _INCLUDED_T10_override_hpp_
<|endoftext|>


<commit_before>// Copyright (c) 2017 offa
//
// 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 "danek/internal/ToString.h"
#include "danek/internal/ConfigItem.h"
#include "danek/internal/ConfigScope.h"
#include <gmock/gmock.h>

using namespace danek;
using namespace testing;

class ToStringTest : public testing::Test
{
};

TEST_F(ToStringTest, toStringEscapesSpecialCharacters)
{
    const ConfigItem item{"name", "value\t_\n_%_\"_"};
    const auto str = toString(item, "xyz", false);
    EXPECT_THAT(str, StrEq("xyz = \"value%t_%n_%%_%\"_\";\n"));
}

TEST_F(ToStringTest, toStringWithIndention)
{
    const ConfigItem item{"name", "value"};
    const auto str = toString(item, "xyz", false, 2);
    EXPECT_THAT(str, StrEq("        xyz = \"value\";\n"));
}

TEST_F(ToStringTest, toStringStringItem)
{
    const ConfigItem item{"name", "value"};
    const auto str = toString(item, "xyz", false);
    EXPECT_THAT(str, StrEq("xyz = \"value\";\n"));
}

TEST_F(ToStringTest, toStringListItem)
{
    const std::vector<std::string> v{"a", "b\n"};
    const ConfigItem item{"name", v};

    const auto str = toString(item, "xyz", false);
    EXPECT_THAT(str, StrEq("xyz = [\"a\", \"b%n\"];\n"));
}

TEST_F(ToStringTest, toStringListItemSingleElement)
{
    const std::vector<std::string> v{};
    const ConfigItem item{"name", v};

    const auto str = toString(item, "xyz", false);
    EXPECT_THAT(str, StrEq("xyz = [];\n"));
}

TEST_F(ToStringTest, toStringListItemIfEmpty)
{
    const std::vector<std::string> v{};
    const ConfigItem item{"name", v};

    const auto str = toString(item, "xyz", false);
    EXPECT_THAT(str, StrEq("xyz = [];\n"));
}

TEST_F(ToStringTest, toStringScopeItem)
{
    const char c = '\0';
    const ConfigItem item{"name", std::make_unique<ConfigScope>(nullptr, &c)};
    const auto str = toString(item, "xyz", false);
    EXPECT_THAT(str, StrEq("xyz {\n}\n"));
}

TEST_F(ToStringTest, dumpRoot)
{
    ConfigScope root{nullptr, "\0"};
    StringBuffer buffer;
    const auto str = toString(root, true);
    EXPECT_THAT(str, StrEq(""));
}

TEST_F(ToStringTest, dumpStringNode)
{
    ConfigScope root{nullptr, "\0"};
    ConfigScope node{&root, "abc"};
    node.addOrReplaceString("x", "y");
    node.addOrReplaceString("1", "2");

    const auto str = toString(node, true);
    EXPECT_THAT(str, StrEq("1 = \"2\";\nx = \"y\";\n"));
}

TEST_F(ToStringTest, dumpStringNodeWithIndention)
{
    ConfigScope root{nullptr, "\0"};
    ConfigScope node{&root, "abc"};
    node.addOrReplaceString("x", "y");
    node.addOrReplaceString("1", "2");

    const auto str = toString(node, true, 1);
    EXPECT_THAT(str, StrEq("    1 = \"2\";\n    x = \"y\";\n"));
}

TEST_F(ToStringTest, dumpScopeNode)
{
    ConfigScope root{nullptr, "\0"};
    ConfigScope scope{&root, "xy"};
    ConfigScope* ptr = &scope;
    root.ensureScopeExists("scope-name", ptr);

    const auto str = toString(root, true);
    EXPECT_THAT(str, StrEq("scope-name {\n}\n"));
}

TEST_F(ToStringTest, dumpMixedType)
{
    ConfigScope root{nullptr, "\0"};
    ConfigScope scope0{&root, "s0"};
    ConfigScope* ptr0 = &scope0;
    ConfigScope scope1{ptr0, "s1"};
    ConfigScope* ptr1 = &scope1;

    root.ensureScopeExists("sn0", ptr0);
    ptr0->addOrReplaceString("a", "b");
    ptr0->ensureScopeExists("sn1", ptr1);
    ptr1->addOrReplaceString("x", "y");

    const auto str = toString(root, true);
    EXPECT_THAT(str, StrEq("sn0 {\n    a = \"b\";\n    sn1 {\n            x = \"y\";\n}\n}\n"));
}

<commit_msg>Testcase updated: Indention used for formatting fixed.<commit_after>// Copyright (c) 2017 offa
//
// 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 "danek/internal/ToString.h"
#include "danek/internal/ConfigItem.h"
#include "danek/internal/ConfigScope.h"
#include <gmock/gmock.h>

using namespace danek;
using namespace testing;

class ToStringTest : public testing::Test
{
};

TEST_F(ToStringTest, toStringEscapesSpecialCharacters)
{
    const ConfigItem item{"name", "value\t_\n_%_\"_"};
    const auto str = toString(item, "xyz", false);
    EXPECT_THAT(str, StrEq("xyz = \"value%t_%n_%%_%\"_\";\n"));
}

TEST_F(ToStringTest, toStringWithIndention)
{
    const ConfigItem item{"name", "value"};
    const auto str = toString(item, "xyz", false, 2);
    EXPECT_THAT(str, StrEq("        xyz = \"value\";\n"));
}

TEST_F(ToStringTest, toStringStringItem)
{
    const ConfigItem item{"name", "value"};
    const auto str = toString(item, "xyz", false);
    EXPECT_THAT(str, StrEq("xyz = \"value\";\n"));
}

TEST_F(ToStringTest, toStringListItem)
{
    const std::vector<std::string> v{"a", "b\n"};
    const ConfigItem item{"name", v};

    const auto str = toString(item, "xyz", false);
    EXPECT_THAT(str, StrEq("xyz = [\"a\", \"b%n\"];\n"));
}

TEST_F(ToStringTest, toStringListItemSingleElement)
{
    const std::vector<std::string> v{};
    const ConfigItem item{"name", v};

    const auto str = toString(item, "xyz", false);
    EXPECT_THAT(str, StrEq("xyz = [];\n"));
}

TEST_F(ToStringTest, toStringListItemIfEmpty)
{
    const std::vector<std::string> v{};
    const ConfigItem item{"name", v};

    const auto str = toString(item, "xyz", false);
    EXPECT_THAT(str, StrEq("xyz = [];\n"));
}

TEST_F(ToStringTest, toStringScopeItem)
{
    const char c = '\0';
    const ConfigItem item{"name", std::make_unique<ConfigScope>(nullptr, &c)};
    const auto str = toString(item, "xyz", false);
    EXPECT_THAT(str, StrEq("xyz {\n}\n"));
}

TEST_F(ToStringTest, dumpRoot)
{
    ConfigScope root{nullptr, "\0"};
    StringBuffer buffer;
    const auto str = toString(root, true);
    EXPECT_THAT(str, StrEq(""));
}

TEST_F(ToStringTest, dumpStringNode)
{
    ConfigScope root{nullptr, "\0"};
    ConfigScope node{&root, "abc"};
    node.addOrReplaceString("x", "y");
    node.addOrReplaceString("1", "2");

    const auto str = toString(node, true);
    EXPECT_THAT(str, StrEq("1 = \"2\";\nx = \"y\";\n"));
}

TEST_F(ToStringTest, dumpStringNodeWithIndention)
{
    ConfigScope root{nullptr, "\0"};
    ConfigScope node{&root, "abc"};
    node.addOrReplaceString("x", "y");
    node.addOrReplaceString("1", "2");

    const auto str = toString(node, true, 1);
    EXPECT_THAT(str, StrEq("    1 = \"2\";\n    x = \"y\";\n"));
}

TEST_F(ToStringTest, dumpScopeNode)
{
    ConfigScope root{nullptr, "\0"};
    ConfigScope scope{&root, "xy"};
    ConfigScope* ptr = &scope;
    root.ensureScopeExists("scope-name", ptr);

    const auto str = toString(root, true);
    EXPECT_THAT(str, StrEq("scope-name {\n}\n"));
}

TEST_F(ToStringTest, dumpMixedType)
{
    ConfigScope root{nullptr, "\0"};
    ConfigScope scope0{&root, "s0"};
    ConfigScope* ptr0 = &scope0;
    ConfigScope scope1{ptr0, "s1"};
    ConfigScope* ptr1 = &scope1;

    root.ensureScopeExists("sn0", ptr0);
    ptr0->addOrReplaceString("a", "b");
    ptr0->ensureScopeExists("sn1", ptr1);
    ptr1->addOrReplaceString("x", "y");

    const auto str = toString(root, true);
    EXPECT_THAT(str, StrEq("sn0 {\n    a = \"b\";\n    sn1 {\n        x = \"y\";\n    }\n}\n"));
}

<|endoftext|>


<commit_before>#include "3rd-party/catch.hpp"

#include <FilterParser.h>

TEST_CASE("FilterParser doesn't crash parsing expression with invalid character "
          "in operator", "[FilterParser]") {
	FilterParser fp;

	REQUIRE_FALSE(fp.parse_string("title =¯ \"foo\""));
}

TEST_CASE("FilterParser raises errors on invalid queries", "[FilterParser]") {
	FilterParser fp;

	SECTION("incorrect string quoting") {
		REQUIRE_FALSE(fp.parse_string("a = \"b"));
	}

	SECTION("non-value to the right of equality check operator") {
		REQUIRE_FALSE(fp.parse_string("a = b"));
	}

	SECTION("unbalanced parentheses") {
		REQUIRE_FALSE(fp.parse_string("((a=\"b\")))"));
	}

	SECTION("non-existent operator") {
		REQUIRE_FALSE(fp.parse_string("a !! \"b\""));
	}
}

TEST_CASE("FilterParser doesn't raise errors on valid queries",
          "[FilterParser]")
{
	FilterParser fp;

	SECTION("test parser") {
		REQUIRE(fp.parse_string("a = \"b\""));
		REQUIRE(fp.parse_string("(a=\"b\")"));
		REQUIRE(fp.parse_string("((a=\"b\"))"));
	}

	SECTION("test operators") {
		REQUIRE(fp.parse_string("a != \"b\""));
		REQUIRE(fp.parse_string("a =~ \"b\""));
		REQUIRE(fp.parse_string("a !~ \"b\""));
	}

	SECTION("Parse string of complex query") {
		REQUIRE(fp.parse_string("( a = \"b\") and ( b = \"c\" ) or ( ( c != \"d\" ) and ( c !~ \"asdf\" )) or c != \"xx\""));
	}
}
<commit_msg>Test == and = in FilterParser<commit_after>#include "3rd-party/catch.hpp"

#include <FilterParser.h>

TEST_CASE("FilterParser doesn't crash parsing expression with invalid character "
          "in operator", "[FilterParser]") {
	FilterParser fp;

	REQUIRE_FALSE(fp.parse_string("title =¯ \"foo\""));
}

TEST_CASE("FilterParser raises errors on invalid queries", "[FilterParser]") {
	FilterParser fp;

	SECTION("incorrect string quoting") {
		REQUIRE_FALSE(fp.parse_string("a = \"b"));
	}

	SECTION("non-value to the right of equality check operator") {
		REQUIRE_FALSE(fp.parse_string("a = b"));
	}

	SECTION("unbalanced parentheses") {
		REQUIRE_FALSE(fp.parse_string("((a=\"b\")))"));
	}

	SECTION("non-existent operator") {
		REQUIRE_FALSE(fp.parse_string("a !! \"b\""));
	}
}

TEST_CASE("FilterParser doesn't raise errors on valid queries",
          "[FilterParser]")
{
	FilterParser fp;

	SECTION("test parser") {
		REQUIRE(fp.parse_string("a = \"b\""));
		REQUIRE(fp.parse_string("(a=\"b\")"));
		REQUIRE(fp.parse_string("((a=\"b\"))"));
	}

	SECTION("test operators") {
		REQUIRE(fp.parse_string("a != \"b\""));
		REQUIRE(fp.parse_string("a =~ \"b\""));
		REQUIRE(fp.parse_string("a !~ \"b\""));
	}

	SECTION("Parse string of complex query") {
		REQUIRE(fp.parse_string("( a = \"b\") and ( b = \"c\" ) or ( ( c != \"d\" ) and ( c !~ \"asdf\" )) or c != \"xx\""));
	}
}

TEST_CASE("Both = and == are accepted", "[FilterParser]")
{
	FilterParser fp;

	REQUIRE(fp.parse_string("a = \"abc\""));
	REQUIRE(fp.parse_string("a == \"abc\""));
}
<|endoftext|>


<commit_before>// Test search algorithms speed without thrift

#include "lvvlib/mmap.h"
#include "search.h"

#include <vector>
	using std::vector;

#include <string>
	using std::string;

#include <iostream>
	using std::cout;
	using std::clog;
	using std::endl;

#ifdef LVV
#include <ro/ro.h>
#include <scc/simple.h>
#endif

#include <chrono>
	using namespace std::chrono;
//	namespace chrono = std::chrono;

using namespace std;

int main() {

	cout << ID << endl;
	auto start = high_resolution_clock::now();

	/////////////////////////////////////////////////  READ NAMES MMAP

	size_t 	names_size;	// number of names (size of names_begin-1)
	size_t 	names_mem;      // size of names_data;
	char 	*names_data  = lvv::mmap_read<char>  ("names_data.mmap",  names_mem);
	size_t	*names_begin = lvv::mmap_read<size_t>("names_begin.mmap", names_size);
	names_size--;

	/////////////////////////////////////////////////  CONSTRUCT NAMES_T

	names_t		names;

	for (size_t i=0;  i<names_size;  ++i) {
						cerr << "addeing name: " <<  i << " " <<  names_begin[i] <<   names_begin[i+1]
						<< " (" << string(names_data+names_begin[i], names_data+names_begin[i+1]) << endl;
		names.insert(names_data+names_begin[i], names_data+names_begin[i+1]);
	}

	names.post_ctor();

	///////////////////////////////////////////////  TIMER
	{
	auto diff = high_resolution_clock::now() - start;
	double sec = duration_cast<nanoseconds>(diff).count()/1e9;
	cerr << "Names: "  	                 << names_size << "\n";
	cerr << "Names construction time: "      << sec        << " sec\n";
	}

	////////////////////////////////////////////////  CONTENT
	size_t  corpus_mem;
	const char  *corpus = lvv::mmap_read<char>("data/corpus.mmap", corpus_mem);

	start = high_resolution_clock::now();

	pos_t		match_b, match_e;
	size_t 		match_count=0;
						// find all instanses of needle
	names.set_content(corpus, corpus+corpus_mem);

	while (names.find_next(match_b, match_e)) {

	       	#ifdef DISPLAY_MATCH
	        cout << "with content: " <<  match_b - corpus << "\t("  << string(match_b, match_e) << ")\n\n";
	        #endif

	        if (match_e - match_b > 2000) {
		       cerr << "warning: big match: " << match_e - match_b << "  at: " << match_b - corpus << endl;
	        }
	        match_count++;
	}

	///////////////////////////////////////////////  TIMER
	{
	auto diff = high_resolution_clock::now() - start;
	double sec                 = duration_cast<nanoseconds>(diff).count()/1e9;
	cerr << "matches: "      << match_count  << "\n"
	     << "search time: "  << sec << " sec\n"
	     << "MB/sec: "       << corpus_mem/sec/1000000 << "\n";
	}
}
<commit_msg>added max_names and N macro to bench.cc<commit_after>// Test search algorithms speed without thrift

#include "lvvlib/mmap.h"
#include "search.h"

#include <vector>
	using std::vector;

#include <string>
	using std::string;

#include <iostream>
	using std::cout;
	using std::clog;
	using std::endl;

#ifdef LVV
#include <ro/ro.h>
#include <scc/simple.h>
#endif

#include <chrono>
	using namespace std::chrono;
//	namespace chrono = std::chrono;

using namespace std;

int main() {

	cout << ID << endl;
	auto start = high_resolution_clock::now();

	long		max_names	=
		#ifdef N
			N
		#else
			numeric_limits<long>::max();
		#endif
	;

	/////////////////////////////////////////////////  READ NAMES MMAP

	size_t 	names_size;	// number of names (size of names_begin-1)
	size_t 	names_mem;      // size of names_data;
	char 	*names_data  = lvv::mmap_read<char>  ("names_data.mmap",  names_mem);
	size_t	*names_begin = lvv::mmap_read<size_t>("names_begin.mmap", names_size);
	names_size--;

	/////////////////////////////////////////////////  CONSTRUCT NAMES_T

	names_t		names;

	for (size_t i=0;  i<names_size;  ++i) {
						//cerr << "addeing name: " <<  i << " " <<  names_begin[i] <<   names_begin[i+1]
						//<< " (" << string(names_data+names_begin[i], names_data+names_begin[i+1]) << endl;
		names.insert(names_data+names_begin[i], names_data+names_begin[i+1]);
		if (i>max_names) break;
	}

	names.post_ctor();

	///////////////////////////////////////////////  TIMER
	{
	auto diff = high_resolution_clock::now() - start;
	double sec = duration_cast<nanoseconds>(diff).count()/1e9;
	cerr << "Names: "  	                 << names_size << "\n";
	cerr << "Names used: "  	         << max_size << "\n";
	cerr << "Names construction time: "      << sec        << " sec\n";
	}

	////////////////////////////////////////////////  CONTENT
	size_t  corpus_mem;
	const char  *corpus = lvv::mmap_read<char>("data/corpus.mmap", corpus_mem);

	start = high_resolution_clock::now();

	pos_t		match_b, match_e;
	size_t 		match_count=0;
						// find all instanses of needle
	names.set_content(corpus, corpus+corpus_mem);

	while (names.find_next(match_b, match_e)) {

	       	#ifdef DISPLAY_MATCH
	        cout << "with content: " <<  match_b - corpus << "\t("  << string(match_b, match_e) << ")\n\n";
	        #endif

	        if (match_e - match_b > 2000) {
		       cerr << "warning: big match: " << match_e - match_b << "  at: " << match_b - corpus << endl;
	        }
	        match_count++;
	}

	///////////////////////////////////////////////  TIMER
	{
	auto diff = high_resolution_clock::now() - start;
	double sec                 = duration_cast<nanoseconds>(diff).count()/1e9;
	cerr << "matches: "      << match_count  << "\n"
	     << "search time: "  << sec << " sec\n"
	     << "MB/sec: "       << corpus_mem/sec/1000000 << "\n";
	}
}
<|endoftext|>


<commit_before>#define PUT(x) std::cout << #x "=" << (x) << std::endl
#include <cybozu/test.hpp>
#include <cybozu/benchmark.hpp>
#include <time.h>

#include <mcl/fp.hpp>
struct ZnTag;
typedef mcl::FpT<ZnTag> Zn;
typedef mcl::FpT<> Fp;

struct Montgomery {
	typedef mcl::fp::Unit Unit;
	mpz_class p_;
	mpz_class R_; // (1 << (pn_ * 64)) % p
	mpz_class RR_; // (R * R) % p
	Unit rp_; // rp * p = -1 mod M = 1 << 64
	size_t pn_;
	Montgomery() {}
	explicit Montgomery(const mpz_class& p)
	{
		p_ = p;
		rp_ = mcl::fp::getMontgomeryCoeff(mcl::gmp::getUnit(p, 0));
		pn_ = mcl::gmp::getUnitSize(p);
		R_ = 1;
		R_ = (R_ << (pn_ * 64)) % p_;
		RR_ = (R_ * R_) % p_;
	}

	void toMont(mpz_class& x) const { mul(x, x, RR_); }
	void fromMont(mpz_class& x) const { mul(x, x, 1); }

	void mul(mpz_class& z, const mpz_class& x, const mpz_class& y) const
	{
#if 0
		const size_t ySize = mcl::gmp::getUnitSize(y);
		mpz_class c = x * mcl::gmp::getUnit(y, 0);
		Unit q = mcl::gmp::getUnit(c, 0) * rp_;
		c += p_ * q;
		c >>= sizeof(Unit) * 8;
		for (size_t i = 1; i < pn_; i++) {
			if (i < ySize) {
				c += x * mcl::gmp::getUnit(y, i);
			}
			Unit q = mcl::gmp::getUnit(c, 0) * rp_;
			c += p_ * q;
			c >>= sizeof(Unit) * 8;
		}
		if (c >= p_) {
			c -= p_;
		}
		z = c;
#else
		z = x * y;
		for (size_t i = 0; i < pn_; i++) {
			Unit q = mcl::gmp::getUnit(z, 0) * rp_;
#ifdef MCL_USE_VINT
			z += p_ * q;
#else
			mpz_class t;
			mcl::gmp::set(t, q);
			z += p_ * t;
#endif
			z >>= sizeof(Unit) * 8;
		}
		if (z >= p_) {
			z -= p_;
		}
#endif
	}
};

template<class T>
mpz_class getMpz(const T& x)
{
	std::string str = x.getStr();
	mpz_class t;
	mcl::gmp::setStr(t, str);
	return t;
}

template<class T>
std::string getStr(const T& x)
{
	std::ostringstream os;
	os << x;
	return os.str();
}

template<class T, class U>
T castTo(const U& x)
{
	T t;
	t.setStr(getStr(x));
	return t;
}

template<class T>
void putRaw(const T& x)
{
	const uint64_t *p = x.getInnerValue();
	for (size_t i = 0, n = T::BlockSize; i < n; i++) {
		printf("%016llx", p[n - 1 - i]);
	}
	printf("\n");
}

template<size_t N>
void put(const uint64_t (&x)[N])
{
	for (size_t i = 0; i < N; i++) {
		printf("%016llx", x[N - 1 - i]);
	}
	printf("\n");
}

struct Test {
	typedef mcl::FpT<> Fp;
	void run(const char *p)
	{
		Fp::init(p);
		Fp x("-123456789");
		Fp y("-0x7ffffffff");
		CYBOZU_BENCH("add", operator+, x, x);
		CYBOZU_BENCH("sub", operator-, x, y);
		CYBOZU_BENCH("mul", operator*, x, x);
		CYBOZU_BENCH("sqr", Fp::sqr, x, x);
		CYBOZU_BENCH("div", y += x; operator/, x, y);
	}
};

void customTest(const char *pStr, const char *xStr, const char *yStr)
{
#if 0
	{
		pStr = "0xfffffffffffffffffffffffffffffffffffffffeffffee37",
		Fp::init(pStr);
		static uint64_t x[3] = { 1, 0, 0 };
		uint64_t z[3];
std::cout<<std::hex;
		Fp::inv(*(Fp*)z, *(const Fp*)x);
put(z);
		exit(1);
	}
#endif
#if 0
	std::cout << std::hex;
	uint64_t x[9] = { 0xff7fffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0x1ff };
	uint64_t y[9] = { 0xff7fffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0x1ff };
	uint64_t z1[9], z2[9];
	Fp::init(pStr);
	Fp::fg_.mul_(z2, x, y);
	put(z2);
	{
		puts("C");
		mpz_class p(pStr);
		Montgomery mont(p);
		mpz_class xx, yy;
		mcl::gmp::setArray(xx, x, CYBOZU_NUM_OF_ARRAY(x));
		mcl::gmp::setArray(yy, y, CYBOZU_NUM_OF_ARRAY(y));
		mpz_class z;
		mont.mul(z, xx, yy);
		std::cout << std::hex << z << std::endl;
	}
	exit(1);
#else
	std::string rOrg, rC, rAsm;
	Zn::init(pStr);
	Zn s(xStr), t(yStr);
	s *= t;
	rOrg = getStr(s);
	{
		puts("C");
		mpz_class p(pStr);
		Montgomery mont(p);
		mpz_class x(xStr), y(yStr);
		mont.toMont(x);
		mont.toMont(y);
		mpz_class z;
		mont.mul(z, x, y);
		mont.fromMont(z);
		rC = getStr(z);
	}

	puts("asm");
	Fp::init(pStr);
	Fp x(xStr), y(yStr);
	x *= y;
	rAsm = getStr(x);
	CYBOZU_TEST_EQUAL(rOrg, rC);
	CYBOZU_TEST_EQUAL(rOrg, rAsm);
#endif
}

#if MCL_MAX_BIT_SIZE >= 521
CYBOZU_TEST_AUTO(customTest)
{
	const struct {
		const char *p;
		const char *x;
		const char *y;
	} tbl[] = {
		{
			"0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
//			"0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff",
//			"0xfffffffffffffffffffffffffffffffffffffffeffffee37",
			"0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe",
			"0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe"
		},
	};
	for (size_t i = 0; i < CYBOZU_NUM_OF_ARRAY(tbl); i++) {
		customTest(tbl[i].p, tbl[i].x, tbl[i].y);
	}
}
#endif

CYBOZU_TEST_AUTO(test)
{
	Test test;
	const char *tbl[] = {
		// N = 2
		"0x0000000000000001000000000000000d",
		"0x7fffffffffffffffffffffffffffffff",
		"0x8000000000000000000000000000001d",
		"0xffffffffffffffffffffffffffffff61",

		// N = 3
		"0x000000000000000100000000000000000000000000000033", // min prime
		"0x00000000fffffffffffffffffffffffffffffffeffffac73",
		"0x0000000100000000000000000001b8fa16dfab9aca16b6b3",
		"0x000000010000000000000000000000000000000000000007",
		"0x30000000000000000000000000000000000000000000002b",
		"0x70000000000000000000000000000000000000000000001f",
		"0x800000000000000000000000000000000000000000000005",
		"0xfffffffffffffffffffffffffffffffffffffffeffffee37",
		"0xfffffffffffffffffffffffe26f2fc170f69466a74defd8d",
		"0xffffffffffffffffffffffffffffffffffffffffffffff13", // max prime

		// N = 4
		"0x0000000000000001000000000000000000000000000000000000000000000085", // min prime
		"0x2523648240000001ba344d80000000086121000000000013a700000000000013",
		"0x7523648240000001ba344d80000000086121000000000013a700000000000017",
		"0x800000000000000000000000000000000000000000000000000000000000005f",
		"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff43", // max prime

#if MCL_MAX_BIT_SIZE >= 384
		// N = 6
		"0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff",
#endif

#if MCL_MAX_BIT_SIZE >= 521
		// N = 9
		"0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
#endif
	};
	for (size_t i = 0; i < CYBOZU_NUM_OF_ARRAY(tbl); i++) {
		printf("prime=%s\n", tbl[i]);
		test.run(tbl[i]);
	}
}
<commit_msg>add test for bls12-381 prime<commit_after>#define PUT(x) std::cout << #x "=" << (x) << std::endl
#include <cybozu/test.hpp>
#include <cybozu/benchmark.hpp>
#include <cybozu/xorshift.hpp>
#include <time.h>

#if 0
#include <mcl/bls12_381.hpp>
using namespace mcl::bls12;
typedef Fr Zn;
#else
#include <mcl/fp.hpp>
struct ZnTag;
typedef mcl::FpT<ZnTag> Zn;
typedef mcl::FpT<> Fp;
#endif

struct Montgomery {
	typedef mcl::fp::Unit Unit;
	mpz_class p_;
	mpz_class R_; // (1 << (pn_ * 64)) % p
	mpz_class RR_; // (R * R) % p
	Unit rp_; // rp * p = -1 mod M = 1 << 64
	size_t pn_;
	Montgomery() {}
	explicit Montgomery(const mpz_class& p)
	{
		p_ = p;
		rp_ = mcl::fp::getMontgomeryCoeff(mcl::gmp::getUnit(p, 0));
		pn_ = mcl::gmp::getUnitSize(p);
		R_ = 1;
		R_ = (R_ << (pn_ * 64)) % p_;
		RR_ = (R_ * R_) % p_;
	}

	void toMont(mpz_class& x) const { mul(x, x, RR_); }
	void fromMont(mpz_class& x) const { mul(x, x, 1); }

	void mul(mpz_class& z, const mpz_class& x, const mpz_class& y) const
	{
#if 0
		const size_t ySize = mcl::gmp::getUnitSize(y);
		mpz_class c = x * mcl::gmp::getUnit(y, 0);
		Unit q = mcl::gmp::getUnit(c, 0) * rp_;
		c += p_ * q;
		c >>= sizeof(Unit) * 8;
		for (size_t i = 1; i < pn_; i++) {
			if (i < ySize) {
				c += x * mcl::gmp::getUnit(y, i);
			}
			Unit q = mcl::gmp::getUnit(c, 0) * rp_;
			c += p_ * q;
			c >>= sizeof(Unit) * 8;
		}
		if (c >= p_) {
			c -= p_;
		}
		z = c;
#else
		z = x * y;
		for (size_t i = 0; i < pn_; i++) {
			Unit q = mcl::gmp::getUnit(z, 0) * rp_;
#ifdef MCL_USE_VINT
			z += p_ * q;
#else
			mpz_class t;
			mcl::gmp::set(t, q);
			z += p_ * t;
#endif
			z >>= sizeof(Unit) * 8;
		}
		if (z >= p_) {
			z -= p_;
		}
#endif
	}
	void mod(mpz_class& z, const mpz_class& xy) const
	{
		z = xy;
		for (size_t i = 0; i < pn_; i++) {
//printf("i=%zd\n", i);
//std::cout << "z=" << std::hex << z << std::endl;
			Unit q = mcl::gmp::getUnit(z, 0) * rp_;
//std::cout << "q=" << q << std::endl;
			mpz_class t;
			mcl::gmp::set(t, q);
			z += p_ * t;
			z >>= sizeof(Unit) * 8;
//std::cout << "z=" << std::hex << z << std::endl;
		}
		if (z >= p_) {
			z -= p_;
		}
//std::cout << "z=" << std::hex << z << std::endl;
	}
};

template<class T>
mpz_class getMpz(const T& x)
{
	std::string str = x.getStr();
	mpz_class t;
	mcl::gmp::setStr(t, str);
	return t;
}

template<class T>
std::string getStr(const T& x)
{
	std::ostringstream os;
	os << x;
	return os.str();
}

template<class T, class U>
T castTo(const U& x)
{
	T t;
	t.setStr(getStr(x));
	return t;
}

template<class T>
void putRaw(const T& x)
{
	const uint64_t *p = x.getInnerValue();
	for (size_t i = 0, n = T::BlockSize; i < n; i++) {
		printf("%016llx", p[n - 1 - i]);
	}
	printf("\n");
}

template<size_t N>
void put(const uint64_t (&x)[N])
{
	for (size_t i = 0; i < N; i++) {
		printf("%016llx", x[N - 1 - i]);
	}
	printf("\n");
}

struct Test {
	typedef mcl::FpT<> Fp;
	void run(const char *p)
	{
		Fp::init(p);
		Fp x("-123456789");
		Fp y("-0x7ffffffff");
		CYBOZU_BENCH("add", operator+, x, x);
		CYBOZU_BENCH("sub", operator-, x, y);
		CYBOZU_BENCH("mul", operator*, x, x);
		CYBOZU_BENCH("sqr", Fp::sqr, x, x);
		CYBOZU_BENCH("div", y += x; operator/, x, y);
	}
};

void customTest(const char *pStr, const char *xStr, const char *yStr)
{
#if 0
	{
		pStr = "0xfffffffffffffffffffffffffffffffffffffffeffffee37",
		Fp::init(pStr);
		static uint64_t x[3] = { 1, 0, 0 };
		uint64_t z[3];
std::cout<<std::hex;
		Fp::inv(*(Fp*)z, *(const Fp*)x);
put(z);
		exit(1);
	}
#endif
#if 0
	std::cout << std::hex;
	uint64_t x[9] = { 0xff7fffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0x1ff };
	uint64_t y[9] = { 0xff7fffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0x1ff };
	uint64_t z1[9], z2[9];
	Fp::init(pStr);
	Fp::fg_.mul_(z2, x, y);
	put(z2);
	{
		puts("C");
		mpz_class p(pStr);
		Montgomery mont(p);
		mpz_class xx, yy;
		mcl::gmp::setArray(xx, x, CYBOZU_NUM_OF_ARRAY(x));
		mcl::gmp::setArray(yy, y, CYBOZU_NUM_OF_ARRAY(y));
		mpz_class z;
		mont.mul(z, xx, yy);
		std::cout << std::hex << z << std::endl;
	}
	exit(1);
#else
	std::string rOrg, rC, rAsm;
	Zn::init(pStr);
	Zn s(xStr), t(yStr);
	s *= t;
	rOrg = getStr(s);
	{
		puts("C");
		mpz_class p(pStr);
		Montgomery mont(p);
		mpz_class x(xStr), y(yStr);
		mont.toMont(x);
		mont.toMont(y);
		mpz_class z;
		mont.mul(z, x, y);
		mont.fromMont(z);
		rC = getStr(z);
	}

	puts("asm");
	Fp::init(pStr);
	Fp x(xStr), y(yStr);
	x *= y;
	rAsm = getStr(x);
	CYBOZU_TEST_EQUAL(rOrg, rC);
	CYBOZU_TEST_EQUAL(rOrg, rAsm);
#endif
}

#if MCL_MAX_BIT_SIZE >= 521
CYBOZU_TEST_AUTO(customTest)
{
	const struct {
		const char *p;
		const char *x;
		const char *y;
	} tbl[] = {
		{
			"0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
//			"0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff",
//			"0xfffffffffffffffffffffffffffffffffffffffeffffee37",
			"0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe",
			"0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe"
		},
	};
	for (size_t i = 0; i < CYBOZU_NUM_OF_ARRAY(tbl); i++) {
		customTest(tbl[i].p, tbl[i].x, tbl[i].y);
	}
}
#endif

CYBOZU_TEST_AUTO(test)
{
	Test test;
	const char *tbl[] = {
#if 1
		// N = 2
		"0x0000000000000001000000000000000d",
		"0x7fffffffffffffffffffffffffffffff",
		"0x8000000000000000000000000000001d",
		"0xffffffffffffffffffffffffffffff61",

		// N = 3
		"0x000000000000000100000000000000000000000000000033", // min prime
		"0x00000000fffffffffffffffffffffffffffffffeffffac73",
		"0x0000000100000000000000000001b8fa16dfab9aca16b6b3",
		"0x000000010000000000000000000000000000000000000007",
		"0x30000000000000000000000000000000000000000000002b",
		"0x70000000000000000000000000000000000000000000001f",
		"0x800000000000000000000000000000000000000000000005",
		"0xfffffffffffffffffffffffffffffffffffffffeffffee37",
		"0xfffffffffffffffffffffffe26f2fc170f69466a74defd8d",
		"0xffffffffffffffffffffffffffffffffffffffffffffff13", // max prime

		// N = 4
		"0x0000000000000001000000000000000000000000000000000000000000000085", // min prime
		"0x2523648240000001ba344d80000000086121000000000013a700000000000013",
		"0x7523648240000001ba344d80000000086121000000000013a700000000000017",
		"0x800000000000000000000000000000000000000000000000000000000000005f",
		"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff43", // max prime
#endif

#if MCL_MAX_BIT_SIZE >= 384
		// N = 6
		"0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab",
		"0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff",
#endif

#if MCL_MAX_BIT_SIZE >= 521
		// N = 9
		"0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
#endif
	};
	for (size_t i = 0; i < CYBOZU_NUM_OF_ARRAY(tbl); i++) {
		printf("prime=%s\n", tbl[i]);
#if 0
		mpz_class p(tbl[i]);
		initPairing(mcl::BLS12_381);
printf("FpDbl::mod=%p\n", FpDbl::mod);
#if 1
		cybozu::XorShift rg;
		for (int i = 0; i < 1000; i++) {
			Fp x, y, z;
			FpDbl xy;
			x.setByCSPRNG(rg);
			y.setByCSPRNG(rg);
			FpDbl::mulPre(xy, x, y);
			FpDbl::mod(z, xy);
			if (z != x * y) {
				puts("ERR");
				std::cout << std::hex;
				PUT(x);
				PUT(y);
				PUT(z);
				PUT(x * y);
				exit(1);
			}
		}
#else
		Montgomery mont(p);
		mpz_class xy1("00783239517141aafb2ffc854bebe27a47655610fa048c1bb6482ba78a79f232c9043ac4a898274ced5b2f65cf281204f4266605b5602ca09cacd1ea9e650c7936a436836ecfd3861d601ef424dbd6e8dbc8c71e9bc7da343f640cf5dffb903f", 16);
//		mpz_class xy1 = (mpz_class(1) << (64 * 12 - 4)) - 1;
		mpz_class z1;
		mont.mod(z1, xy1);
std::cout << "1=" << z1 << std::endl;
		FpDbl xy2, z2;
		Fp z3;
		z3.clear();
		xy2.setMpz(xy1);
xy2.dump();
		FpDbl::mod(z3, xy2);
		z3.dump();
#endif
		exit(1);
#endif
		test.run(tbl[i]);
	}
}
<|endoftext|>


<commit_before>#include <stack.hpp>
#include <catch.hpp>
#include <iostream>
using namespace std;

SCENARIO("count", "[count]"){
  stack<int> s;
  s.push(1);
  REQUIRE(s.count()==1);
}

SCENARIO("push", "[push]"){
  stack<int> s;
  s.push(1);
  REQUIRE(s.count()==1);
}

SCENARIO("pop", "[pop]"){
  stack<int> s;
  s.push(1);
  REQUIRE(*(s.pop())==1);
  REQUIRE(s.count()==0);
}

SCENARIO("prisv", "[prisv]"){
  stack<int> s;
  s.push(1);
  stack<int> s2;
  s2=s;
  REQUIRE(s.count()==1);
}

SCENARIO("empty", "[empty]"){
  stack<int> s1, s2;
  s1.push(1);
  REQUIRE(!s1.empty());
  REQUIRE(s2.empty());
}
SCENARIO("Stack: top and pop threads", "threads") {
	stack<size_t> st;
	st.push(0);
	std::thread t1(&stack<size_t>::push, &st, 1);
	t1.join();
	REQUIRE(st.count() == 2);
	REQUIRE(*st.pop() == 1);
	REQUIRE(st.empty() == false);
	std::thread t2(&stack<size_t>::pop, &st);
	t2.join();
	REQUIRE(st.count() == 0);
	REQUIRE(st.empty());
}
<commit_msg>Update init.cpp<commit_after>#include <stack.hpp>
#include <catch.hpp>
#include <thread>
#include <iostream>
using namespace std;

SCENARIO("count", "[count]"){
  stack<int> s;
  s.push(1);
  REQUIRE(s.count()==1);
}

SCENARIO("push", "[push]"){
  stack<int> s;
  s.push(1);
  REQUIRE(s.count()==1);
}

SCENARIO("pop", "[pop]"){
  stack<int> s;
  s.push(1);
  REQUIRE(*(s.pop())==1);
  REQUIRE(s.count()==0);
}

SCENARIO("prisv", "[prisv]"){
  stack<int> s;
  s.push(1);
  stack<int> s2;
  s2=s;
  REQUIRE(s.count()==1);
}

SCENARIO("empty", "[empty]"){
  stack<int> s1, s2;
  s1.push(1);
  REQUIRE(!s1.empty());
  REQUIRE(s2.empty());
}
SCENARIO("Stack: top and pop threads", "threads") {
	stack<size_t> st;
	st.push(0);
	std::thread t1(&stack<size_t>::push, &st, 1);
	t1.join();
	REQUIRE(st.count() == 2);
	REQUIRE(*st.pop() == 1);
	REQUIRE(st.empty() == false);
	std::thread t2(&stack<size_t>::pop, &st);
	t2.join();
	REQUIRE(st.count() == 0);
	REQUIRE(st.empty());
}
<|endoftext|>