<commit_before>
#include "ros/ros.h"
#include "geometry_msgs/PoseStamped.h"

#include <pcl_ros/point_cloud.h>
#include <pcl/point_types.h>
#include <boost/foreach.hpp>
#include <stdio.h>
#include <cv_bridge/cv_bridge.h>
#include <image_transport/image_transport.h>
#include <sensor_msgs/image_encodings.h>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>

#include <iostream>
#include <cstdio>
#include <ctime>

typedef pcl::PointCloud<pcl::PointXYZRGB> PointCloud;

sensor_msgs::ImageConstPtr image;

struct my_pose {
    float x;
    float y;
} m, a1, b1, c1, d1, a2, b2, c2, d2;

/*
    a           b
       m
    c           d
    -------------
1, board near conference room
2, board near 400/500 doors
*/
    // M of coordinates(x,y) is inside the rectangle iff,
    // (0 < AM dot AB < AB dot AB) AND (0 < AM dot AC < AC dot AC)

bool inRectangle(my_pose* m, my_pose* a, my_pose* b, my_pose* c)
{

    float am_ab, ab_ab, am_ad, ad_ad;
    am_ab = (m->x - a->x) * (b->x - a->x) + (m->y - a->y) * (b->y - a->y);
    ab_ab = (b->x - a->x) * (b->x - a->x) + (b->y - a->y) * (b->y - a->y);
    am_ac = (m->x - a->x) * (c->x - a->x) + (m->y - a->y) * (c->y - a->y);
    ac_ac = (c->x - a->x) * (c->x - a->x) + (c->y - a->y) * (c->y - a->y);

    if (0 < am_ab && am_ab < ab_ab && 0 < am_ac && am_ac < ac_ac)
        return true;
    else
        return false;
}

void callback(const geometry_msgs::PoseStamped::ConstPtr& msg)
{
    a1.x = 62.67;
    a1.y = 9.89;
    b1.x = 62.27;
    b1.y = 4.27;
    c1.x = 60.85;
    c1.y = 9.36;

    a2.x = 39.73;
    a2.y = 17.12;
    b2.x = 39.80;
    b2.y = 11.17;
    c2.x = 38.24;
    c2.y = 16.94;

    geometry_msgs::PoseStampedConstPtr poseStamped = msg;

    m.x = poseStamped->pose.position.x;
    m.y = poseStamped->pose.position.y;

    if (inRectangle(&m, &a1, &b1, &c1) || inRectangle(&m, &a2, &b2, &c2))
    {
        std::time_t rawtime;
        std::tm* timeinfo;
        char buffer [80];

        std::time(&rawtime);
        timeinfo = std::localtime(&rawtime);
        std::strftime(buffer, 80, "%Y-%m-%d-%H-%M-%S", timeinfo);
        std::puts(buffer);
        std::string str(buffer);

        ROS_INFO("People detected in frout of a white board, picture saved.");

        cv_bridge::CvImageConstPtr cv_ptr;
        try
        {
            cv_ptr = cv_bridge::toCvShare(image, sensor_msgs::image_encodings::BGR8);
            cv::imwrite("/home/bwi/Desktop/whiteboard_" + str + ".jpg",
                        cv_ptr->image);
        }
        catch (cv_bridge::Exception& e)
        {
            ROS_ERROR("cv_bridge exception: %s", e.what());
            return;
        }
    }
}

// keep saving the most recent image
void callback_image_saver(const sensor_msgs::ImageConstPtr& msg)
{
  image = msg;
}

// main function of the node
int main(int argc, char ** argv)
{
    ros::init(argc, argv, "white_board");
    ros::NodeHandle nh;
    ros::Subscriber sub1 = nh.subscribe(
                    "/segbot_pcl_person_detector/human_poses", 100, callback);

    image_transport::ImageTransport it(nh);
    image_transport::Subscriber sub2 = it.subscribe(
                    "/nav_kinect/rgb/image_color", 1, callback_image_saver);

    ros::spin();

    return 0;
}

<commit_msg>minor<commit_after>
#include "ros/ros.h"
#include "geometry_msgs/PoseStamped.h"

#include <pcl_ros/point_cloud.h>
#include <pcl/point_types.h>
#include <boost/foreach.hpp>
#include <stdio.h>
#include <cv_bridge/cv_bridge.h>
#include <image_transport/image_transport.h>
#include <sensor_msgs/image_encodings.h>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>

#include <iostream>
#include <cstdio>
#include <ctime>

typedef pcl::PointCloud<pcl::PointXYZRGB> PointCloud;

sensor_msgs::ImageConstPtr image;

struct my_pose {
    float x;
    float y;
} m, a1, b1, c1, d1, a2, b2, c2, d2;

/*
    a           b
       m
    c           d
    -------------
1, board near conference room
2, board near 400/500 doors
*/
    // M of coordinates(x,y) is inside the rectangle iff,
    // (0 < AM dot AB < AB dot AB) AND (0 < AM dot AC < AC dot AC)

bool inRectangle(my_pose* m, my_pose* a, my_pose* b, my_pose* c)
{

    float am_ab, ab_ab, am_ac, ac_ac;
    am_ab = (m->x - a->x) * (b->x - a->x) + (m->y - a->y) * (b->y - a->y);
    ab_ab = (b->x - a->x) * (b->x - a->x) + (b->y - a->y) * (b->y - a->y);
    am_ac = (m->x - a->x) * (c->x - a->x) + (m->y - a->y) * (c->y - a->y);
    ac_ac = (c->x - a->x) * (c->x - a->x) + (c->y - a->y) * (c->y - a->y);

    if (0 < am_ab && am_ab < ab_ab && 0 < am_ac && am_ac < ac_ac)
        return true;
    else
        return false;
}

void callback(const geometry_msgs::PoseStamped::ConstPtr& msg)
{
    a1.x = 62.67;
    a1.y = 9.89;
    b1.x = 62.27;
    b1.y = 4.27;
    c1.x = 60.85;
    c1.y = 9.36;

    a2.x = 39.73;
    a2.y = 17.12;
    b2.x = 39.80;
    b2.y = 11.17;
    c2.x = 38.24;
    c2.y = 16.94;

    geometry_msgs::PoseStampedConstPtr poseStamped = msg;

    m.x = poseStamped->pose.position.x;
    m.y = poseStamped->pose.position.y;

    if (inRectangle(&m, &a1, &b1, &c1) || inRectangle(&m, &a2, &b2, &c2))
    {
        std::time_t rawtime;
        std::tm* timeinfo;
        char buffer [80];

        std::time(&rawtime);
        timeinfo = std::localtime(&rawtime);
        std::strftime(buffer, 80, "%Y-%m-%d-%H-%M-%S", timeinfo);
        std::puts(buffer);
        std::string str(buffer);

        ROS_INFO("People detected in frout of a white board, picture saved.");

        cv_bridge::CvImageConstPtr cv_ptr;
        try
        {
            cv_ptr = cv_bridge::toCvShare(image, sensor_msgs::image_encodings::BGR8);
            cv::imwrite("/home/bwi/Desktop/whiteboard_" + str + ".jpg",
                        cv_ptr->image);
        }
        catch (cv_bridge::Exception& e)
        {
            ROS_ERROR("cv_bridge exception: %s", e.what());
            return;
        }
    }
}

// keep saving the most recent image
void callback_image_saver(const sensor_msgs::ImageConstPtr& msg)
{
  image = msg;
}

// main function of the node
int main(int argc, char ** argv)
{
    ros::init(argc, argv, "white_board");
    ros::NodeHandle nh;
    ros::Subscriber sub1 = nh.subscribe(
                    "/segbot_pcl_person_detector/human_poses", 100, callback);

    image_transport::ImageTransport it(nh);
    image_transport::Subscriber sub2 = it.subscribe(
                    "/nav_kinect/rgb/image_color", 1, callback_image_saver);

    ros::spin();

    return 0;
}

<|endoftext|>


<commit_before>#if !defined(__CINT__) || defined(__MAKECINT__)
   #include <TMath.h>
   #include <TROOT.h>
   #include <Riostream.h>
   #include <TCanvas.h>

   #include <TString.h>

   #include <TFile.h>
   #include <TList.h>
   #include <TH1F.h>
   #include <TH1D.h>
   #include <TF2.h>
   #include <TFitResult.h>
   #include <TFitResultPtr.h>
   #include <TH2F.h>
   #include <TH3F.h>
#endif

extern TROOT *gROOT;
//extern TFile *gFile;

void PostProcessCTau(Int_t corrType=1) {
  //-----------------------------------------------------------------
  // PostProcess the histograms produced by AliAnalysisTaskCTau*
  // Produce:
  // -- V0 particle spectra (not corrected for the feeddown)
  // -- Estimated (anti)Lambda feed-down spectra (from Xi's only)
  // -- V0 particle c*tau distributions (feeddown corrected)
  //-----------------------------------------------------------------

  TString name("cTau_0090"); //centrality
  //TString name("cTau_0005"); //centrality
  //TString name("cTau_2040"); //centrality
  //TString name("cTau_4060"); //centrality
  //TString name("cTau_6080"); //centrality
  //TString name("cTau_8090"); //centrality

  //+++++ Real data histograms
  TFile::Open("new/real/all/" + name + ".root");
  TList *list=(TList *)gFile->Get(name);

  TH2F *fK0sSi=(TH2F*)list->FindObject("fK0sSi");fK0sSi->Sumw2();
  TH2F *fLambdaSi=(TH2F*)list->FindObject("fLambdaSi");fLambdaSi->Sumw2();
  TH1F *fXiSiP=(TH1F*)list->FindObject("fXiSiP"); fXiSiP->Sumw2();
  TH2F *fLambdaBarSi=
        (TH2F*)list->FindObject("fLambdaBarSi"); fLambdaBarSi->Sumw2();
  TH1F *fXiBarSiP=(TH1F*)list->FindObject("fXiBarSiP"); fXiBarSiP->Sumw2();

  TH1F *fMult=(TH1F*)list->FindObject("fMult");
  //+++++

  const Double_t nEvents=fMult->Integral();

  //+++++ MC histograms
  TFile::Open("new/mc_b_plus/all/" + name + "_mc.root");
  TList *listmc=(TList *)gFile->Get(name+"_mc");

  TH2F *fK0sMC=(TH2F*)listmc->FindObject("fK0sMC"); fK0sMC->Sumw2();
  TH2F *fK0sAs=(TH2F*)listmc->FindObject("fK0sAs"); fK0sAs->Sumw2();

  TH2F *fLambdaMC=(TH2F*)listmc->FindObject("fLambdaMC"); fLambdaMC->Sumw2();
  TH2F *fLambdaAs=(TH2F*)listmc->FindObject("fLambdaAs"); fLambdaAs->Sumw2();

  TH2F *fLambdaBarMC=
        (TH2F*)listmc->FindObject("fLambdaBarMC"); fLambdaBarMC->Sumw2();
  TH2F *fLambdaBarAs=
        (TH2F*)listmc->FindObject("fLambdaBarAs"); fLambdaBarAs->Sumw2();

  TH1F *fXiSiPMC=(TH1F*)listmc->FindObject("fXiSiP");fXiSiPMC->Sumw2();
  TH3F *fLambdaFromXi=(TH3F*)listmc->FindObject("fLambdaFromXi");
  fLambdaFromXi->Sumw2();

  TH1F *fXiBarSiPMC=(TH1F*)listmc->FindObject("fXiBarSiP");fXiBarSiPMC->Sumw2();
  TH3F *fLambdaBarFromXiBar=(TH3F*)listmc->FindObject("fLambdaBarFromXiBar");
  fLambdaBarFromXiBar->Sumw2();
  //+++++

  Double_t myExp2(Double_t *v, Double_t *p);
  void Correct(TH1 *rw, const TH1 *as, const TH1 *mc);
  void Normalise(Double_t, Double_t, Double_t, Double_t, TH1 *h);

  const Int_t    iMax=3;   // Number of V0 particles
  const TString  pnam[]={"K^{0}_{S}", "#Lambda", "#bar{#Lambda}"};
  const Double_t brch[]={0.69, 0.64, 0.64};
  const Double_t mass[]={0.4977, 1.115, 1.115};
  const Double_t ctau[]={2.68, 7.89, 7.89};
  const Double_t yWin=2*0.5; // rapidity window
  const Double_t wbx=fK0sSi->GetBinWidth(3);
  const Int_t nbx=fLambdaFromXi->GetNbinsX();
  const Int_t nby=fLambdaFromXi->GetNbinsY();
  const Int_t nbz=fLambdaFromXi->GetNbinsZ();

  const TH2 *in[]={
    fK0sSi,fK0sAs,fK0sMC,
    fLambdaSi,fLambdaAs,fLambdaMC,
    fLambdaBarSi,fLambdaBarAs,fLambdaBarMC
  };
  TH1 *fd[]={
    0,0,0,
    fLambdaFromXi,fXiSiP,fXiSiPMC,
    fLambdaBarFromXiBar,fXiBarSiP,fXiBarSiPMC
  };

  for (Int_t i=0; i<iMax; i++) {
      const TH2 *ptRw=in[3*i+0], *ptAs=in[3*i+1], *ptMc=in[3*i+2];
      TH1 *ptAsPx=0, *ptMcPx=0, *pt=0;

      TH2 *cr=(TH2*)ptRw->Clone();
      Correct(cr, ptAs, ptMc);

      //++++ pT spectrum
      if (corrType==1) {
         pt    =ptRw->ProjectionX("_px",0,-1,"e");
         ptAsPx=ptAs->ProjectionX("_px",0,-1,"e");
         ptMcPx=ptMc->ProjectionX("_px",0,-1,"e");
         Correct(pt, ptAsPx, ptMcPx);
	 /*
         TString effName = "Efficiency for " + pnam[i] + " (" + name + ")";
         TH1 *eff = (TH1*)ptAsPx->Clone();
         eff->SetTitle(effName.Data());
         eff->Divide(ptAsPx,ptMcPx,1,1,"b");
         eff->SetName("eff");
         eff->Scale(brch[i]);
         new TCanvas; eff->Draw();
	 */
      } else {
         pt=cr->ProjectionX("_px",0,-1,"e");
      }
      TString ptName = pnam[i] + " p_{T} spectrum";
      pt->SetTitle(ptName.Data());
      Normalise(brch[i], yWin, wbx, nEvents, pt);

      new TCanvas;
      pt->Draw();

      if (i>0) {
      //++++ feeddown
	 TH3 *fd3=(TH3*)fd[3*i + 0];
	 TH1 *rl =(TH1*)fd[3*i + 1];
	 TH1 *mc =(TH1*)fd[3*i + 2];

         Double_t nLambdaFromXiMc=fd3->Integral();
         Double_t nXiMc=mc->Integral();
         Double_t nXiRl=rl->Integral();
         Double_t f=(nLambdaFromXiMc*nXiRl/nXiMc)/ptRw->Integral();
         Double_t ef=f*TMath::Sqrt(nXiMc)/nXiMc;
         cout<<endl<<"Global FD correction: "<<f<<"+/-"<<ef<<endl;

         rl->Divide(mc);

         for (Int_t k=1; k<=nbx; k++) {
             for (Int_t l=1; l<=nby; l++) {
                 for (Int_t m=1; m<=nbz; m++) {
                     Float_t c=fd3->GetBinContent(k,l,m);
                     c *= rl->GetBinContent(m);
                     fd3->SetBinContent(k,l,m,c);
		 }
	     }
	 }

         TH2 *fd2=(TH2*)fd3->Project3D("yxe");
         Correct(fd2, ptAs, ptMc);

         TH1 *fd1=0;
         if (corrType==1) {
            fd1=(TH1*)fd3->Project3D("x");
            Correct(fd1, ptAsPx, ptMcPx);
         } else {
            fd1=fd2->ProjectionX("_px",0,-1,"e");
	 }
         Normalise(brch[i], yWin, wbx, nEvents, fd1);

         //new TCanvas();
         fd1->Draw("same");

         cr->Add(fd2,-1);
      }
      //continue;

      //++++ c*tau
      TF2 *f2=new TF2("myexpo2",myExp2,0.,10.,0.,100.,1+1+1+nbx);
      f2->SetParameter(0, ctau[i]);
      f2->FixParameter(1, ctau[i]);
      f2->FixParameter(2, mass[i]);
      for (Int_t p=1+1+1; p<=nbx+1+1; p++)
          f2->SetParameter(p,fK0sSi->GetBinContent(p,1));

      new TCanvas;
      TFitResultPtr r=cr->Fit(f2,"SQ");

      Int_t status   = r;
      Double_t chi2  = r->Chi2()/r->Ndf();
      Double_t slope = r->Parameter(0);
      Double_t error = r->ParError(0);
      cout<<endl<<pnam[i]<<"  \tstatus: "<<status<<"   chi2/ndf: "<<chi2<<
	"\tc*tau: "<<slope<<"+/-"<<error<<endl<<endl;
  }

  return;
}

Double_t myExp2(Double_t *v, Double_t *p) {
   Double_t pt=v[0];
   Double_t lt=v[1];

   Double_t ctau=p[1];
   Double_t mass=p[2];
   Double_t ct=mass*lt/pt;
   if ((lt < 2) || (ct > 2.5*ctau)) {
      TF1::RejectPoint();
      return 0;
   }

   Int_t i=pt/0.1 + 1 + 1;
   return p[i]*TMath::Exp(-ct/p[0]);
}

void Correct(TH1 *rw, const TH1 *as, const TH1 *mc) {
  TH1 *eff = (TH1*)as->Clone();
  eff->Divide(as,mc,1,1,"b");
  rw->Divide(eff);
  delete eff;
}

void Normalise(Double_t br, Double_t yw, Double_t bw, Double_t ne, TH1 *pt) {
   pt->Scale(1/br);    // branching ratio
   pt->Scale(1/yw);    // rapidity window
   pt->Scale(1/bw);    // bin width
   pt->Scale(1/ne);    // number of events
}
<commit_msg>Branching is now included in efficiency<commit_after>#if !defined(__CINT__) || defined(__MAKECINT__)
   #include <TMath.h>
   #include <TROOT.h>
   #include <Riostream.h>
   #include <TCanvas.h>

   #include <TString.h>

   #include <TFile.h>
   #include <TList.h>
   #include <TH1F.h>
   #include <TH1D.h>
   #include <TF2.h>
   #include <TFitResult.h>
   #include <TFitResultPtr.h>
   #include <TH2F.h>
   #include <TH3F.h>
#endif

extern TROOT *gROOT;
//extern TFile *gFile;

void PostProcessCTau(Int_t corrType=1) {
  //-----------------------------------------------------------------
  // PostProcess the histograms produced by AliAnalysisTaskCTau*
  // Produce:
  // -- V0 particle spectra (not corrected for the feeddown)
  // -- Estimated (anti)Lambda feed-down spectra (from Xi's only)
  // -- V0 particle c*tau distributions (feeddown corrected)
  //-----------------------------------------------------------------

  TString name("cTau_0090"); //centrality
  //TString name("cTau_0005"); //centrality
  //TString name("cTau_2040"); //centrality
  //TString name("cTau_4060"); //centrality
  //TString name("cTau_6080"); //centrality
  //TString name("cTau_8090"); //centrality

  //+++++ Real data histograms
  TFile::Open("new/real/all/" + name + ".root");
  TList *list=(TList *)gFile->Get(name);

  TH2F *fK0sSi=(TH2F*)list->FindObject("fK0sSi");fK0sSi->Sumw2();
  TH2F *fLambdaSi=(TH2F*)list->FindObject("fLambdaSi");fLambdaSi->Sumw2();
  TH1F *fXiSiP=(TH1F*)list->FindObject("fXiSiP"); fXiSiP->Sumw2();
  TH2F *fLambdaBarSi=
        (TH2F*)list->FindObject("fLambdaBarSi"); fLambdaBarSi->Sumw2();
  TH1F *fXiBarSiP=(TH1F*)list->FindObject("fXiBarSiP"); fXiBarSiP->Sumw2();

  TH1F *fMult=(TH1F*)list->FindObject("fMult");
  //+++++

  const Double_t nEvents=fMult->Integral();

  //+++++ MC histograms
  TFile::Open("new/mc_b_plus/all/" + name + "_mc.root");
  TList *listmc=(TList *)gFile->Get(name+"_mc");

  TH2F *fK0sMC=(TH2F*)listmc->FindObject("fK0sMC"); fK0sMC->Sumw2();
  TH2F *fK0sAs=(TH2F*)listmc->FindObject("fK0sAs"); fK0sAs->Sumw2();

  TH2F *fLambdaMC=(TH2F*)listmc->FindObject("fLambdaMC"); fLambdaMC->Sumw2();
  TH2F *fLambdaAs=(TH2F*)listmc->FindObject("fLambdaAs"); fLambdaAs->Sumw2();

  TH2F *fLambdaBarMC=
        (TH2F*)listmc->FindObject("fLambdaBarMC"); fLambdaBarMC->Sumw2();
  TH2F *fLambdaBarAs=
        (TH2F*)listmc->FindObject("fLambdaBarAs"); fLambdaBarAs->Sumw2();

  TH1F *fXiSiPMC=(TH1F*)listmc->FindObject("fXiSiP");fXiSiPMC->Sumw2();
  TH3F *fLambdaFromXi=(TH3F*)listmc->FindObject("fLambdaFromXi");
  fLambdaFromXi->Sumw2();

  TH1F *fXiBarSiPMC=(TH1F*)listmc->FindObject("fXiBarSiP");fXiBarSiPMC->Sumw2();
  TH3F *fLambdaBarFromXiBar=(TH3F*)listmc->FindObject("fLambdaBarFromXiBar");
  fLambdaBarFromXiBar->Sumw2();
  //+++++

  Double_t myExp2(Double_t *v, Double_t *p);
  void Correct(TH1 *rw, const TH1 *as, const TH1 *mc);
  void Normalise(Double_t, Double_t, Double_t, TH1 *h);

  const Int_t    iMax=3;   // Number of V0 particles
  const TString  pnam[]={"K^{0}_{S}", "#Lambda", "#bar{#Lambda}"};
  const Double_t brch[]={0.69, 0.64, 0.64};
  const Double_t mass[]={0.4977, 1.115, 1.115};
  const Double_t ctau[]={2.68, 7.89, 7.89};
  const Double_t yWin=2*0.5; // rapidity window
  const Double_t wbx=fK0sSi->GetBinWidth(3);
  const Int_t nbx=fLambdaFromXi->GetNbinsX();
  const Int_t nby=fLambdaFromXi->GetNbinsY();
  const Int_t nbz=fLambdaFromXi->GetNbinsZ();

  fK0sMC->Scale(1/brch[0]);
  fLambdaMC->Scale(1/brch[1]);
  fLambdaBarMC->Scale(1/brch[2]);

  const TH2 *in[]={
    fK0sSi,fK0sAs,fK0sMC,
    fLambdaSi,fLambdaAs,fLambdaMC,
    fLambdaBarSi,fLambdaBarAs,fLambdaBarMC
  };
  TH1 *fd[]={
    0,0,0,
    fLambdaFromXi,fXiSiP,fXiSiPMC,
    fLambdaBarFromXiBar,fXiBarSiP,fXiBarSiPMC
  };

  for (Int_t i=0; i<iMax; i++) {
      const TH2 *ptRw=in[3*i+0], *ptAs=in[3*i+1], *ptMc=in[3*i+2];
      TH1 *ptAsPx=0, *ptMcPx=0, *pt=0;

      TH2 *cr=(TH2*)ptRw->Clone();
      Correct(cr, ptAs, ptMc);

      //++++ pT spectrum
      if (corrType==1) {
         pt    =ptRw->ProjectionX("_px",0,-1,"e");
         ptAsPx=ptAs->ProjectionX("_px",0,-1,"e");
         ptMcPx=ptMc->ProjectionX("_px",0,-1,"e");
         Correct(pt, ptAsPx, ptMcPx);

         TString effName = "Efficiency for " + pnam[i] + " (" + name + ")";
         TH1 *eff = (TH1*)ptAsPx->Clone();
         eff->SetTitle(effName.Data());
         eff->Divide(ptAsPx,ptMcPx,1,1,"b");
         eff->SetName("eff");
         new TCanvas; eff->Draw();
      } else {
         pt=cr->ProjectionX("_px",0,-1,"e");
      }
      TString ptName = pnam[i] + " p_{T} spectrum";
      pt->SetTitle(ptName.Data());
      Normalise(yWin, wbx, nEvents, pt);

      new TCanvas;
      pt->Draw();

      if (i>0) {
      //++++ feeddown
	 TH3 *fd3=(TH3*)fd[3*i + 0];
	 TH1 *rl =(TH1*)fd[3*i + 1];
	 TH1 *mc =(TH1*)fd[3*i + 2];

         Double_t nLambdaFromXiMc=fd3->Integral();
         Double_t nXiMc=mc->Integral();
         Double_t nXiRl=rl->Integral();
         Double_t f=(nLambdaFromXiMc*nXiRl/nXiMc)/ptRw->Integral();
         Double_t ef=f*TMath::Sqrt(nXiMc)/nXiMc;
         cout<<endl<<"Global FD correction: "<<f<<"+/-"<<ef<<endl;

         rl->Divide(mc);

         for (Int_t k=1; k<=nbx; k++) {
             for (Int_t l=1; l<=nby; l++) {
                 for (Int_t m=1; m<=nbz; m++) {
                     Float_t c=fd3->GetBinContent(k,l,m);
                     c *= rl->GetBinContent(m);
                     fd3->SetBinContent(k,l,m,c);
		 }
	     }
	 }

         TH2 *fd2=(TH2*)fd3->Project3D("yxe");
         Correct(fd2, ptAs, ptMc);

         TH1 *fd1=0;
         if (corrType==1) {
            fd1=(TH1*)fd3->Project3D("x");
            Correct(fd1, ptAsPx, ptMcPx);
         } else {
            fd1=fd2->ProjectionX("_px",0,-1,"e");
	 }
         Normalise(yWin, wbx, nEvents, fd1);

         //new TCanvas();
         fd1->Draw("same");

         cr->Add(fd2,-1);
      }
      continue;

      //++++ c*tau
      TF2 *f2=new TF2("myexpo2",myExp2,0.,10.,0.,100.,1+1+1+nbx);
      f2->SetParameter(0, ctau[i]);
      f2->FixParameter(1, ctau[i]);
      f2->FixParameter(2, mass[i]);
      for (Int_t p=1+1+1; p<=nbx+1+1; p++)
          f2->SetParameter(p,fK0sSi->GetBinContent(p,1));

      new TCanvas;
      TFitResultPtr r=cr->Fit(f2,"SQ");

      Int_t status   = r;
      Double_t chi2  = r->Chi2()/r->Ndf();
      Double_t slope = r->Parameter(0);
      Double_t error = r->ParError(0);
      cout<<endl<<pnam[i]<<"  \tstatus: "<<status<<"   chi2/ndf: "<<chi2<<
	"\tc*tau: "<<slope<<"+/-"<<error<<endl<<endl;
  }

  return;
}

Double_t myExp2(Double_t *v, Double_t *p) {
   Double_t pt=v[0];
   Double_t lt=v[1];

   Double_t ctau=p[1];
   Double_t mass=p[2];
   Double_t ct=mass*lt/pt;
   if ((lt < 2) || (ct > 2.5*ctau)) {
      TF1::RejectPoint();
      return 0;
   }

   Int_t i=pt/0.1 + 1 + 1;
   return p[i]*TMath::Exp(-ct/p[0]);
}

void Correct(TH1 *rw, const TH1 *as, const TH1 *mc) {
  TH1 *eff = (TH1*)as->Clone();
  eff->Divide(as,mc,1,1,"b");
  rw->Divide(eff);
  delete eff;
}

void Normalise(Double_t yw, Double_t bw, Double_t ne, TH1 *pt) {
   pt->Scale(1/yw);    // rapidity window
   pt->Scale(1/bw);    // bin width
   pt->Scale(1/ne);    // number of events
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2004-2005 The Regents of The University of Michigan
 * Copyright (c) 2013 Advanced Micro Devices, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Kevin Lim
 */

#include <vector>

#include "cpu/o3/rename_map.hh"
#include "debug/Rename.hh"

using namespace std;

/**** SimpleRenameMap methods ****/

SimpleRenameMap::SimpleRenameMap()
    : freeList(NULL), zeroReg(0)
{
}

void
SimpleRenameMap::init(unsigned size, SimpleFreeList *_freeList,
                      RegIndex _zeroReg)
{
    assert(freeList == NULL);
    assert(map.empty());

    map.resize(size);
    freeList = _freeList;
    zeroReg = _zeroReg;
}

SimpleRenameMap::RenameInfo
SimpleRenameMap::rename(RegIndex arch_reg)
{
    PhysRegIndex renamed_reg;

    // Record the current physical register that is renamed to the
    // requested architected register.
    PhysRegIndex prev_reg = map[arch_reg];

    // If it's not referencing the zero register, then rename the
    // register.
    if (arch_reg != zeroReg) {
        renamed_reg = freeList->getReg();

        map[arch_reg] = renamed_reg;
    } else {
        // Otherwise return the zero register so nothing bad happens.
        assert(prev_reg == zeroReg);
        renamed_reg = zeroReg;
    }

    DPRINTF(Rename, "Renamed reg %d to physical reg %d old mapping was %d\n",
            arch_reg, renamed_reg, prev_reg);

    return RenameInfo(renamed_reg, prev_reg);
}

/**** UnifiedRenameMap methods ****/

void
UnifiedRenameMap::init(PhysRegFile *_regFile,
                       RegIndex _intZeroReg,
                       RegIndex _floatZeroReg,
                       UnifiedFreeList *freeList)
{
    regFile = _regFile;

    intMap.init(TheISA::NumIntRegs, &(freeList->intList), _intZeroReg);

    floatMap.init(TheISA::NumFloatRegs, &(freeList->floatList), _floatZeroReg);

    ccMap.init(TheISA::NumFloatRegs, &(freeList->ccList), (RegIndex)-1);
}

UnifiedRenameMap::RenameInfo
UnifiedRenameMap::rename(RegIndex arch_reg)
{
    RegIndex rel_arch_reg;

    switch (regIdxToClass(arch_reg, &rel_arch_reg)) {
      case IntRegClass:
        return renameInt(rel_arch_reg);

      case FloatRegClass:
        return renameFloat(rel_arch_reg);

      case CCRegClass:
        return renameCC(rel_arch_reg);

      case MiscRegClass:
        return renameMisc(rel_arch_reg);

      default:
        panic("rename rename(): unknown reg class %s\n",
              RegClassStrings[regIdxToClass(arch_reg)]);
    }
}

PhysRegIndex
UnifiedRenameMap::lookup(RegIndex arch_reg) const
{
    RegIndex rel_arch_reg;

    switch (regIdxToClass(arch_reg, &rel_arch_reg)) {
      case IntRegClass:
        return lookupInt(rel_arch_reg);

      case FloatRegClass:
        return lookupFloat(rel_arch_reg);

      case CCRegClass:
        return lookupCC(rel_arch_reg);

      case MiscRegClass:
        return lookupMisc(rel_arch_reg);

      default:
        panic("rename lookup(): unknown reg class %s\n",
              RegClassStrings[regIdxToClass(arch_reg)]);
    }
}

void
UnifiedRenameMap::setEntry(RegIndex arch_reg, PhysRegIndex phys_reg)
{
    RegIndex rel_arch_reg;

    switch (regIdxToClass(arch_reg, &rel_arch_reg)) {
      case IntRegClass:
        return setIntEntry(rel_arch_reg, phys_reg);

      case FloatRegClass:
        return setFloatEntry(rel_arch_reg, phys_reg);

      case CCRegClass:
        return setCCEntry(rel_arch_reg, phys_reg);

      case MiscRegClass:
        // Misc registers do not actually rename, so don't change
        // their mappings.  We end up here when a commit or squash
        // tries to update or undo a hardwired misc reg nmapping,
        // which should always be setting it to what it already is.
        assert(phys_reg == lookupMisc(rel_arch_reg));
        return;

      default:
        panic("rename setEntry(): unknown reg class %s\n",
              RegClassStrings[regIdxToClass(arch_reg)]);
    }
}
<commit_msg>o3: correct the number of cc registers in rename map<commit_after>/*
 * Copyright (c) 2004-2005 The Regents of The University of Michigan
 * Copyright (c) 2013 Advanced Micro Devices, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Kevin Lim
 */

#include <vector>

#include "cpu/o3/rename_map.hh"
#include "debug/Rename.hh"

using namespace std;

/**** SimpleRenameMap methods ****/

SimpleRenameMap::SimpleRenameMap()
    : freeList(NULL), zeroReg(0)
{
}

void
SimpleRenameMap::init(unsigned size, SimpleFreeList *_freeList,
                      RegIndex _zeroReg)
{
    assert(freeList == NULL);
    assert(map.empty());

    map.resize(size);
    freeList = _freeList;
    zeroReg = _zeroReg;
}

SimpleRenameMap::RenameInfo
SimpleRenameMap::rename(RegIndex arch_reg)
{
    PhysRegIndex renamed_reg;

    // Record the current physical register that is renamed to the
    // requested architected register.
    PhysRegIndex prev_reg = map[arch_reg];

    // If it's not referencing the zero register, then rename the
    // register.
    if (arch_reg != zeroReg) {
        renamed_reg = freeList->getReg();

        map[arch_reg] = renamed_reg;
    } else {
        // Otherwise return the zero register so nothing bad happens.
        assert(prev_reg == zeroReg);
        renamed_reg = zeroReg;
    }

    DPRINTF(Rename, "Renamed reg %d to physical reg %d old mapping was %d\n",
            arch_reg, renamed_reg, prev_reg);

    return RenameInfo(renamed_reg, prev_reg);
}

/**** UnifiedRenameMap methods ****/

void
UnifiedRenameMap::init(PhysRegFile *_regFile,
                       RegIndex _intZeroReg,
                       RegIndex _floatZeroReg,
                       UnifiedFreeList *freeList)
{
    regFile = _regFile;

    intMap.init(TheISA::NumIntRegs, &(freeList->intList), _intZeroReg);

    floatMap.init(TheISA::NumFloatRegs, &(freeList->floatList), _floatZeroReg);

    ccMap.init(TheISA::NumCCRegs, &(freeList->ccList), (RegIndex)-1);
}

UnifiedRenameMap::RenameInfo
UnifiedRenameMap::rename(RegIndex arch_reg)
{
    RegIndex rel_arch_reg;

    switch (regIdxToClass(arch_reg, &rel_arch_reg)) {
      case IntRegClass:
        return renameInt(rel_arch_reg);

      case FloatRegClass:
        return renameFloat(rel_arch_reg);

      case CCRegClass:
        return renameCC(rel_arch_reg);

      case MiscRegClass:
        return renameMisc(rel_arch_reg);

      default:
        panic("rename rename(): unknown reg class %s\n",
              RegClassStrings[regIdxToClass(arch_reg)]);
    }
}

PhysRegIndex
UnifiedRenameMap::lookup(RegIndex arch_reg) const
{
    RegIndex rel_arch_reg;

    switch (regIdxToClass(arch_reg, &rel_arch_reg)) {
      case IntRegClass:
        return lookupInt(rel_arch_reg);

      case FloatRegClass:
        return lookupFloat(rel_arch_reg);

      case CCRegClass:
        return lookupCC(rel_arch_reg);

      case MiscRegClass:
        return lookupMisc(rel_arch_reg);

      default:
        panic("rename lookup(): unknown reg class %s\n",
              RegClassStrings[regIdxToClass(arch_reg)]);
    }
}

void
UnifiedRenameMap::setEntry(RegIndex arch_reg, PhysRegIndex phys_reg)
{
    RegIndex rel_arch_reg;

    switch (regIdxToClass(arch_reg, &rel_arch_reg)) {
      case IntRegClass:
        return setIntEntry(rel_arch_reg, phys_reg);

      case FloatRegClass:
        return setFloatEntry(rel_arch_reg, phys_reg);

      case CCRegClass:
        return setCCEntry(rel_arch_reg, phys_reg);

      case MiscRegClass:
        // Misc registers do not actually rename, so don't change
        // their mappings.  We end up here when a commit or squash
        // tries to update or undo a hardwired misc reg nmapping,
        // which should always be setting it to what it already is.
        assert(phys_reg == lookupMisc(rel_arch_reg));
        return;

      default:
        panic("rename setEntry(): unknown reg class %s\n",
              RegClassStrings[regIdxToClass(arch_reg)]);
    }
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2007-2008 Digital Bazaar, Inc.  All rights reserved.
 */
#include "db/modest/ModuleLoader.h"
#include "db/modest/ModuleApi.h"
#include "db/rt/DynamicLibrary.h"

#include <cstring>

using namespace db::modest;
using namespace db::rt;

ModuleLoader::ModuleLoader()
{
}

ModuleLoader::~ModuleLoader()
{
}

ModuleInfo* ModuleLoader::loadModule(const char* filename)
{
   ModuleInfo* rval = NULL;

   // open library
   void* handle = dlopen(filename, RTLD_NOW | RTLD_GLOBAL);
   if(handle != NULL)
   {
      CreateModestModuleFn create;
      FreeModestModuleFn free;

      // clear error
      char* error = dlerror();

      // try to get create module function
      create = (CreateModestModuleFn)dlsym(handle, "createModestModule");
      if((error = dlerror()) == NULL)
      {
         // clear error
         error = dlerror();

         // try to get free module function
         free = (FreeModestModuleFn)dlsym(handle, "freeModestModule");
         error = dlerror();
      }

      if(error == NULL)
      {
         // create ModuleInfo
         rval = new ModuleInfo();
         rval->handle = handle;
         rval->module = create();
         rval->freeModule = free;
      }
      else
      {
         // could not load create or free functions
         char temp[100 + strlen(filename) + strlen(error)];
         sprintf(temp, "Could not load module '%s', error=%s", filename, error);
         ExceptionRef e = new Exception(temp, "db.modest.BadModule");
         Exception::setLast(e, false);
      }
   }
   else
   {
      // failed to open module
      char* error = dlerror();
      char temp[100 + strlen(filename) + strlen(error)];
      sprintf(temp,
         "Could not load module '%s', could not open module file, error=%s",
         filename, error);
      ExceptionRef e = new Exception(temp, "db.modest.BadModuleFile");
      Exception::setLast(e, false);
   }

   return rval;
}

void ModuleLoader::unloadModule(ModuleInfo* mi)
{
   // free module
   mi->freeModule(mi->module);

   // close handle
   dlclose(mi->handle);

   // delete module info
   delete mi;
}
<commit_msg>Cleaned up exception code.<commit_after>/*
 * Copyright (c) 2007-2008 Digital Bazaar, Inc.  All rights reserved.
 */
#include "db/modest/ModuleLoader.h"

#include "db/modest/ModuleApi.h"
#include "db/rt/DynamicLibrary.h"
#include "db/rt/DynamicObject.h"

#include <cstring>

using namespace db::modest;
using namespace db::rt;

ModuleLoader::ModuleLoader()
{
}

ModuleLoader::~ModuleLoader()
{
}

ModuleInfo* ModuleLoader::loadModule(const char* filename)
{
   ModuleInfo* rval = NULL;

   // open library
   void* handle = dlopen(filename, RTLD_NOW | RTLD_GLOBAL);
   if(handle != NULL)
   {
      CreateModestModuleFn create;
      FreeModestModuleFn free;

      // clear error
      char* error = dlerror();

      // try to get create module function
      create = (CreateModestModuleFn)dlsym(handle, "createModestModule");
      if((error = dlerror()) == NULL)
      {
         // clear error
         error = dlerror();

         // try to get free module function
         free = (FreeModestModuleFn)dlsym(handle, "freeModestModule");
         error = dlerror();
      }

      if(error == NULL)
      {
         // create ModuleInfo
         rval = new ModuleInfo();
         rval->handle = handle;
         rval->module = create();
         rval->freeModule = free;
      }
      else
      {
         // could not load create or free functions
         ExceptionRef e = new Exception(
            "Could not load module.", "db.modest.BadModule");
         e->getDetails()["filename"] = filename;
         e->getDetails()["error"] = error;
         Exception::setLast(e, false);
      }
   }
   else
   {
      // failed to open module
      char* error = dlerror();
      ExceptionRef e = new Exception(
         "Could not open module file.", "db.modest.BadModuleFile");
      e->getDetails()["filename"] = filename;
      e->getDetails()["error"] = error;
      Exception::setLast(e, false);
   }

   return rval;
}

void ModuleLoader::unloadModule(ModuleInfo* mi)
{
   // free module
   mi->freeModule(mi->module);

   // close handle
   dlclose(mi->handle);

   // delete module info
   delete mi;
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2009 Digital Bazaar, Inc. All rights reserved.
 */
#include "db/test/Test.h"
#include "db/test/Tester.h"
#include "db/test/TestRunner.h"
#include "db/io/ByteArrayInputStream.h"
#include "db/data/xml/DomTypes.h"
#include "db/upnp/ControlPoint.h"
#include "db/upnp/DeviceDiscoverer.h"
#include "db/upnp/SoapEnvelope.h"

using namespace std;
using namespace db::test;
using namespace db::data::xml;
using namespace db::io;
using namespace db::rt;
using namespace db::upnp;

void runSoapEnvelopeTest(TestRunner& tr)
{
   tr.group("SoapEnvelope");

   tr.test("create");
   {
      const char* expect =
         "<soap:Envelope "
         "soap:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding\" "
         "xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope\">"
         "<soap:Body xmlns:m=\"http://www.example.org/stock\">"
         "<m:GetStockPrice>"
         "<m:StockName>IBM</m:StockName>"
         "</m:GetStockPrice>"
         "</soap:Body>"
         "</soap:Envelope>";

      SoapEnvelope env;
      SoapMessage msg;
      msg["name"] = "GetStockPrice";
      msg["namespace"] = "http://www.example.org/stock";
      msg["params"]["StockName"] = "IBM";
      string envelope = env.create(msg);

      assertStrCmp(expect, envelope.c_str());
   }
   tr.passIfNoException();

   tr.test("parse message");
   {
      const char* expect =
         "<soap:Envelope "
         "soap:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding\" "
         "xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope\">"
         "<soap:Body xmlns:m=\"http://www.example.org/stock\">"
         "<m:GetStockPrice>"
         "<m:StockName>IBM</m:StockName>"
         "</m:GetStockPrice>"
         "</soap:Body>"
         "</soap:Envelope>";

      ByteArrayInputStream bais(expect, strlen(expect));

      SoapEnvelope env;
      SoapResult result;
      env.parse(&bais, result);
      assertNoException();

      // result is not a fault
      assert(!result["fault"]->getBoolean());

      // compare message
      SoapMessage expectMessage;
      expectMessage["name"] = "GetStockPrice";
      expectMessage["namespace"] = "http://www.example.org/stock";
      expectMessage["params"]["StockName"] = "IBM";
      assert(expectMessage == result["message"]);
   }
   tr.passIfNoException();

   tr.test("parse fault");
   {
      const char* expect =
         "<soap:Envelope "
         "soap:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding\" "
         "xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope\">"
         "<soap:Body xmlns:m=\"http://www.example.org/stock\">"
         "<soap:Fault>"
         "<faultcode>soap:Client.AppError</faultcode>"
         "<faultstring>Application Error</faultstring>"
         "<detail>"
         "<message>You did something wrong.</message>"
         "<errorcode>1000</errorcode>"
         "</detail>"
         "</soap:Fault>"
         "</soap:Body>"
         "</soap:Envelope>";

      ByteArrayInputStream bais(expect, strlen(expect));

      SoapEnvelope env;
      SoapResult result;
      env.parse(&bais, result);
      assertNoException();

      // result is a fault
      assert(result["fault"]->getBoolean());

      // compare message
      SoapMessage expectMessage;
      expectMessage["name"] = "Fault";
      expectMessage["namespace"] = "http://schemas.xmlsoap.org/soap/envelope";
      expectMessage["params"]["faultcode"] = "soap:Client.AppError";
      expectMessage["params"]["faultstring"] = "Application Error";
      expectMessage["params"]["detail"]["message"] = "You did something wrong.";
      expectMessage["params"]["detail"]["errorcode"] = 1000;
      assert(expectMessage == result["message"]);
   }
   tr.passIfNoException();

   tr.ungroup();
}

void runPortMappingTest(TestRunner& tr)
{
   tr.group("PortMapping");

   PortMapping mapping;
   mapping["NewRemoteHost"] = "";
   mapping["NewExternalPort"] = 19100;
   mapping["NewProtocol"] = "TCP";
   mapping["NewInternalPort"] = 19100;
   mapping["NewInternalClient"] = "10.10.0.10";
   mapping["NewEnabled"] = "1";
   mapping["NewPortMappingDescription"] = "A test port mapping.";
   mapping["NewLeaseDuration"] = "0";

   Device igd(NULL);
   Service wipcs(NULL);

   tr.test("discover internet gateway device");
   {
      // search for 1 internet gateway device... 30 seconds to find one
      DeviceDiscoverer dd;
      DeviceList devices;
      if(dd.discover(devices, UPNP_DEVICE_TYPE_IGD, 30 * 1000, 1) == 1)
      {
         // found!
         igd = devices.first();
      }
      assert(!igd.isNull());
   }
   tr.passIfNoException();

   tr.test("get device description");
   {
      ControlPoint cp;
      cp.getDeviceDescription(igd);
      assertNoException();
   }
   tr.passIfNoException();

   tr.test("get wan ip connection service");
   {
      ControlPoint cp;
      wipcs = cp.getWanIpConnectionService(igd);
      assert(!wipcs.isNull());
   }
   tr.passIfNoException();

   tr.test("get service description");
   {
      ControlPoint cp;
      cp.getServiceDescription(wipcs);
      assertNoException();
   }
   tr.passIfNoException();
#if 0
   tr.test("remove if exists");
   {
      ControlPoint cp;
      PortMapping pm = mapping.clone();
      bool dne;
      if(!cp.removePortMapping(pm, wipcs, &dne))
      {
         // if dne then the mapping already does not exist, which is fine
         if(dne)
         {
            Exception::clear();
         }
      }
   }
   tr.passIfNoException();
#endif
   tr.test("add mapping");
   {
      ControlPoint cp;
      PortMapping pm = mapping.clone();
      cp.addPortMapping(pm, wipcs);
   }
   tr.passIfNoException();

   tr.test("get all mappings");
   {
      ControlPoint cp;
      PortMapping pm;
      pm->setType(Map);
      printf("\nSTART PORT MAPPINGS:\n");
      for(int i = 0; !pm.isNull(); i++)
      {
         pm->clear();
         if(cp.getPortMapping(pm, i, wipcs))
         {
            if(pm.isNull())
            {
               // last port mapping found
               Exception::clear();
            }
            else
            {
               dumpDynamicObject(pm);
            }
         }
         else
         {
            pm.setNull();
         }
      }
      printf("END PORT MAPPINGS.\n");
   }
   tr.passIfNoException();

   tr.test("get specific mapping");
   {
      ControlPoint cp;
      PortMapping pm;
      pm["NewRemoteHost"] = mapping["NewRemoteHost"].clone();
      pm["NewExternalPort"] = mapping["NewExternalPort"].clone();
      pm["NewProtocol"] = mapping["NewProtocol"].clone();
      cp.getPortMapping(pm, wipcs);
      //dumpDynamicObject(pm);
      assert(pm == mapping);
   }
   tr.passIfNoException();
#if 0
   tr.test("remove mapping");
   {
      ControlPoint cp;
      PortMapping pm = mapping.clone();
      cp.removePortMapping(pm, wipcs, NULL);
   }
   tr.passIfNoException();
#endif
   tr.ungroup();
}

class DbUpnpTester : public db::test::Tester
{
public:
   DbUpnpTester()
   {
      setName("upnp");
   }

   /**
    * Run automatic unit tests.
    */
   virtual int runAutomaticTests(TestRunner& tr)
   {
      runSoapEnvelopeTest(tr);

      return 0;
   }

   /**
    * Runs interactive unit tests.
    */
   virtual int runInteractiveTests(TestRunner& tr)
   {
      runPortMappingTest(tr);

      return 0;
   }
};

db::test::Tester* getDbUpnpTester() { return new DbUpnpTester(); }

DB_TEST_MAIN(DbUpnpTester)
<commit_msg>Added test to get all mappings after deleting the test mapping.<commit_after>/*
 * Copyright (c) 2009 Digital Bazaar, Inc. All rights reserved.
 */
#include "db/test/Test.h"
#include "db/test/Tester.h"
#include "db/test/TestRunner.h"
#include "db/io/ByteArrayInputStream.h"
#include "db/data/xml/DomTypes.h"
#include "db/upnp/ControlPoint.h"
#include "db/upnp/DeviceDiscoverer.h"
#include "db/upnp/SoapEnvelope.h"

using namespace std;
using namespace db::test;
using namespace db::data::xml;
using namespace db::io;
using namespace db::rt;
using namespace db::upnp;

void runSoapEnvelopeTest(TestRunner& tr)
{
   tr.group("SoapEnvelope");

   tr.test("create");
   {
      const char* expect =
         "<soap:Envelope "
         "soap:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding\" "
         "xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope\">"
         "<soap:Body xmlns:m=\"http://www.example.org/stock\">"
         "<m:GetStockPrice>"
         "<m:StockName>IBM</m:StockName>"
         "</m:GetStockPrice>"
         "</soap:Body>"
         "</soap:Envelope>";

      SoapEnvelope env;
      SoapMessage msg;
      msg["name"] = "GetStockPrice";
      msg["namespace"] = "http://www.example.org/stock";
      msg["params"]["StockName"] = "IBM";
      string envelope = env.create(msg);

      assertStrCmp(expect, envelope.c_str());
   }
   tr.passIfNoException();

   tr.test("parse message");
   {
      const char* expect =
         "<soap:Envelope "
         "soap:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding\" "
         "xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope\">"
         "<soap:Body xmlns:m=\"http://www.example.org/stock\">"
         "<m:GetStockPrice>"
         "<m:StockName>IBM</m:StockName>"
         "</m:GetStockPrice>"
         "</soap:Body>"
         "</soap:Envelope>";

      ByteArrayInputStream bais(expect, strlen(expect));

      SoapEnvelope env;
      SoapResult result;
      env.parse(&bais, result);
      assertNoException();

      // result is not a fault
      assert(!result["fault"]->getBoolean());

      // compare message
      SoapMessage expectMessage;
      expectMessage["name"] = "GetStockPrice";
      expectMessage["namespace"] = "http://www.example.org/stock";
      expectMessage["params"]["StockName"] = "IBM";
      assert(expectMessage == result["message"]);
   }
   tr.passIfNoException();

   tr.test("parse fault");
   {
      const char* expect =
         "<soap:Envelope "
         "soap:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding\" "
         "xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope\">"
         "<soap:Body xmlns:m=\"http://www.example.org/stock\">"
         "<soap:Fault>"
         "<faultcode>soap:Client.AppError</faultcode>"
         "<faultstring>Application Error</faultstring>"
         "<detail>"
         "<message>You did something wrong.</message>"
         "<errorcode>1000</errorcode>"
         "</detail>"
         "</soap:Fault>"
         "</soap:Body>"
         "</soap:Envelope>";

      ByteArrayInputStream bais(expect, strlen(expect));

      SoapEnvelope env;
      SoapResult result;
      env.parse(&bais, result);
      assertNoException();

      // result is a fault
      assert(result["fault"]->getBoolean());

      // compare message
      SoapMessage expectMessage;
      expectMessage["name"] = "Fault";
      expectMessage["namespace"] = "http://schemas.xmlsoap.org/soap/envelope";
      expectMessage["params"]["faultcode"] = "soap:Client.AppError";
      expectMessage["params"]["faultstring"] = "Application Error";
      expectMessage["params"]["detail"]["message"] = "You did something wrong.";
      expectMessage["params"]["detail"]["errorcode"] = 1000;
      assert(expectMessage == result["message"]);
   }
   tr.passIfNoException();

   tr.ungroup();
}

void runPortMappingTest(TestRunner& tr)
{
   tr.group("PortMapping");

   PortMapping mapping;
   mapping["NewRemoteHost"] = "";
   mapping["NewExternalPort"] = 19100;
   mapping["NewProtocol"] = "TCP";
   mapping["NewInternalPort"] = 19100;
   mapping["NewInternalClient"] = "10.10.0.10";
   mapping["NewEnabled"] = "1";
   mapping["NewPortMappingDescription"] = "A test port mapping.";
   mapping["NewLeaseDuration"] = "0";

   Device igd(NULL);
   Service wipcs(NULL);

   tr.test("discover internet gateway device");
   {
      // search for 1 internet gateway device... 30 seconds to find one
      DeviceDiscoverer dd;
      DeviceList devices;
      if(dd.discover(devices, UPNP_DEVICE_TYPE_IGD, 30 * 1000, 1) == 1)
      {
         // found!
         igd = devices.first();
      }
      assert(!igd.isNull());
   }
   tr.passIfNoException();

   tr.test("get device description");
   {
      ControlPoint cp;
      cp.getDeviceDescription(igd);
      assertNoException();
   }
   tr.passIfNoException();

   tr.test("get wan ip connection service");
   {
      ControlPoint cp;
      wipcs = cp.getWanIpConnectionService(igd);
      assert(!wipcs.isNull());
   }
   tr.passIfNoException();

   tr.test("get service description");
   {
      ControlPoint cp;
      cp.getServiceDescription(wipcs);
      assertNoException();
   }
   tr.passIfNoException();

   tr.test("remove if exists");
   {
      ControlPoint cp;
      PortMapping pm = mapping.clone();
      bool dne;
      if(!cp.removePortMapping(pm, wipcs, &dne))
      {
         // if dne then the mapping already does not exist, which is fine
         if(dne)
         {
            Exception::clear();
         }
      }
   }
   tr.passIfNoException();

   tr.test("add mapping");
   {
      ControlPoint cp;
      PortMapping pm = mapping.clone();
      cp.addPortMapping(pm, wipcs);
   }
   tr.passIfNoException();

   tr.test("get all mappings");
   {
      ControlPoint cp;
      PortMapping pm;
      pm->setType(Map);
      printf("\nSTART PORT MAPPINGS:\n");
      for(int i = 0; !pm.isNull(); i++)
      {
         pm->clear();
         if(cp.getPortMapping(pm, i, wipcs))
         {
            if(pm.isNull())
            {
               // last port mapping found
               Exception::clear();
            }
            else
            {
               dumpDynamicObject(pm);
            }
         }
         else
         {
            pm.setNull();
         }
      }
      printf("END PORT MAPPINGS.\n");
   }
   tr.passIfNoException();

   tr.test("get specific mapping");
   {
      ControlPoint cp;
      PortMapping pm;
      pm["NewRemoteHost"] = mapping["NewRemoteHost"].clone();
      pm["NewExternalPort"] = mapping["NewExternalPort"].clone();
      pm["NewProtocol"] = mapping["NewProtocol"].clone();
      cp.getPortMapping(pm, wipcs);
      //dumpDynamicObject(pm);
      assert(pm == mapping);
   }
   tr.passIfNoException();

   tr.test("remove mapping");
   {
      ControlPoint cp;
      PortMapping pm = mapping.clone();
      cp.removePortMapping(pm, wipcs, NULL);
   }
   tr.passIfNoException();

   tr.test("get all mappings after remove");
   {
      ControlPoint cp;
      PortMapping pm;
      pm->setType(Map);
      printf("\nSTART PORT MAPPINGS:\n");
      for(int i = 0; !pm.isNull(); i++)
      {
         pm->clear();
         if(cp.getPortMapping(pm, i, wipcs))
         {
            if(pm.isNull())
            {
               // last port mapping found
               Exception::clear();
            }
            else
            {
               dumpDynamicObject(pm);
            }
         }
         else
         {
            pm.setNull();
         }
      }
      printf("END PORT MAPPINGS.\n");
   }
   tr.passIfNoException();

   tr.ungroup();
}

class DbUpnpTester : public db::test::Tester
{
public:
   DbUpnpTester()
   {
      setName("upnp");
   }

   /**
    * Run automatic unit tests.
    */
   virtual int runAutomaticTests(TestRunner& tr)
   {
      runSoapEnvelopeTest(tr);

      return 0;
   }

   /**
    * Runs interactive unit tests.
    */
   virtual int runInteractiveTests(TestRunner& tr)
   {
      runPortMappingTest(tr);

      return 0;
   }
};

db::test::Tester* getDbUpnpTester() { return new DbUpnpTester(); }

DB_TEST_MAIN(DbUpnpTester)
<|endoftext|>


<commit_before>//******************************************************************
//
// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//
// 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.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

#ifndef OC_LOG_STREAM_HPP_
#define OC_LOG_STREAM_HPP_

#include <iosfwd>
#include <memory>
#include <cassert>
#include <iostream>

#include <boost/config.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/categories.hpp>
#include <boost/iostreams/detail/ios.hpp>

#include "oc_logger.h"

namespace OC {

class oc_log_stream : boost::iostreams::sink
{
 std::shared_ptr<oc_log_ctx_t> m_log;

 public:
 typedef char                            char_type;
 typedef boost::iostreams::sink_tag      category;

 public:
 template <class ContextCtor>
 oc_log_stream(ContextCtor& c)
  : m_log { c(), oc_log_destroy }
 {}

 template <class ContextCtor>
 oc_log_stream(ContextCtor& c, void *world)
  : m_log { c(world), oc_log_destroy }
 {}

 public:
 inline void flush()                                    BOOST_NOEXCEPT { return oc_log_flush(m_log.get()); }
 inline void set_level(const oc_log_level new_level)    BOOST_NOEXCEPT { return oc_log_set_level(m_log.get(), new_level); }
 inline int  set_module(const std::string& module_name) BOOST_NOEXCEPT { return oc_log_set_module(m_log.get(), module_name.c_str()); }

 public:
 std::streamsize write(const char_type *s, std::streamsize n)
 {
    /* It may seem strange to do this here, but it's a consequence of the
    underlying library not supporting ptr+len style buffers at this time: */
    std::string s2(s, n + s);

    oc_log_write(m_log.get(), s2.c_str());

    return n;
 }

 private:
 oc_log_stream operator=(const oc_log_stream&)  = delete;
};

} // namespace OC

#endif
<commit_msg>oc_logger: Removing /W4 warnings<commit_after>//******************************************************************
//
// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//
// 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.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

#ifndef OC_LOG_STREAM_HPP_
#define OC_LOG_STREAM_HPP_

#include <iosfwd>
#include <memory>
#include <cassert>
#include <iostream>

#include <boost/config.hpp>

// Warning disabled due to a known "unreachable code" issue in boost iostreams.
// For more information see: https://svn.boost.org/trac/boost/ticket/5904
#if defined(_MSC_VER)
#pragma warning(push)
#pragma warning(disable : 4702)
#endif

#include <boost/iostreams/stream.hpp>

#if defined(_MSC_VER)
#pragma warning(pop)
#endif

#include <boost/iostreams/categories.hpp>
#include <boost/iostreams/detail/ios.hpp>

#include "oc_logger.h"

namespace OC {

class oc_log_stream : boost::iostreams::sink
{
 std::shared_ptr<oc_log_ctx_t> m_log;

 public:
 typedef char                            char_type;
 typedef boost::iostreams::sink_tag      category;

 public:
 template <class ContextCtor>
 oc_log_stream(ContextCtor& c)
  : m_log { c(), oc_log_destroy }
 {}

 template <class ContextCtor>
 oc_log_stream(ContextCtor& c, void *world)
  : m_log { c(world), oc_log_destroy }
 {}

 public:
 inline void flush()                                    BOOST_NOEXCEPT { return oc_log_flush(m_log.get()); }
 inline void set_level(const oc_log_level new_level)    BOOST_NOEXCEPT { return oc_log_set_level(m_log.get(), new_level); }
 inline int  set_module(const std::string& module_name) BOOST_NOEXCEPT { return oc_log_set_module(m_log.get(), module_name.c_str()); }

 public:
 std::streamsize write(const char_type *s, std::streamsize n)
 {
    /* It may seem strange to do this here, but it's a consequence of the
    underlying library not supporting ptr+len style buffers at this time: */
    std::string s2(s, n + s);

    oc_log_write(m_log.get(), s2.c_str());

    return n;
 }

 private:
 oc_log_stream operator=(const oc_log_stream&)  = delete;
};

} // namespace OC

#endif
<|endoftext|>


<commit_before>/* -*- Mode: C -*-

  $Id$

  Copyright (C) 2001 by Klarlvdalens Datakonsult AB

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

  GPGMEPLUG is distributed in the hope that it will be useful,
  it under the terms of GNU General Public License as published by
  the Free Software Foundation; version 2 of the License
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

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

#include <qlistview.h>
#include <qtextedit.h>
#include <qheader.h>
#include <qpushbutton.h>
#include <qcursor.h>
#include <qapplication.h>

#include <klocale.h>
#include <kdialogbase.h>
#include <kmessagebox.h>

#include "certificateinfowidgetimpl.h"
#include "certmanager.h"

CertificateInfoWidgetImpl::CertificateInfoWidgetImpl( CertManager* manager, bool external,
						      QWidget* parent, const char* name )
  : CertificateInfoWidget( parent, name ), _manager(manager), _external( external )
{
  if( !external ) importButton->setEnabled(false);
  listView->setColumnWidthMode( 1, QListView::Manual );
  listView->setResizeMode( QListView::LastColumn );
  QFontMetrics fm = fontMetrics();
  listView->setColumnWidth( 1, fm.width( i18n("Information") ) * 5 );

  listView->header()->setClickEnabled( false );
  listView->setSorting( -1 );

  connect( listView, SIGNAL( selectionChanged( QListViewItem* ) ),
	   this, SLOT( slotShowInfo( QListViewItem* ) ) );
  pathView->setColumnWidthMode( 0, QListView::Manual );
  pathView->setResizeMode( QListView::LastColumn );
  pathView->header()->hide();

  connect( pathView, SIGNAL( doubleClicked( QListViewItem* ) ),
	   this, SLOT( slotShowCertPathDetails( QListViewItem* ) ) );
  connect( pathView, SIGNAL( returnPressed( QListViewItem* ) ),
	   this, SLOT( slotShowCertPathDetails( QListViewItem* ) ) );
  connect( importButton, SIGNAL( clicked() ),
	   this, SLOT( slotImportCertificate() ) );
}

void CertificateInfoWidgetImpl::setCert( const CryptPlugWrapper::CertificateInfo& info )
{
  listView->clear();
  pathView->clear();
  _info = info;

  /* Check if we already have the cert in question */
  if( _manager ) {
    importButton->setEnabled( !_manager->haveCertificate( info.fingerprint ) );
  } else {
    importButton->setEnabled( false );
  }
  // These will show in the opposite order
  new QListViewItem( listView, i18n("Fingerprint"), info.fingerprint );
  new QListViewItem( listView, i18n("Can be used for certification"),
		     info.certify?i18n("Yes"):i18n("No") );
  new QListViewItem( listView, i18n("Can be used for encryption"),
		     info.encrypt?i18n("Yes"):i18n("No") );
  new QListViewItem( listView, i18n("Can be used for signing"),
		     info.sign?i18n("Yes"):i18n("No") );

  new QListViewItem( listView, i18n("Valid"), QString("From %1 to %2")
		     .arg( info.created.toString() ).arg(info.expire.toString()) );

  //new QListViewItem( listView, i18n("Email"), info.dn["1.2.840.113549.1.9.1"] );
  new QListViewItem( listView, i18n("Country"), info.dn["C"] );
  new QListViewItem( listView, i18n("Organizational Unit"), info.dn["OU"] );
  new QListViewItem( listView, i18n("Organization"), info.dn["O"] );
  new QListViewItem( listView, i18n("Location"), info.dn["L"] );
  new QListViewItem( listView, i18n("Name"), info.dn["CN"] );
  new QListViewItem( listView, i18n("Issuer"), info.issuer.stripWhiteSpace() );

  QStringList::ConstIterator it = info.userid.begin();
  QListViewItem* item = new QListViewItem( listView, i18n("Subject"),
			    (*it).stripWhiteSpace() );
  ++it;
  while( it != info.userid.end() ) {
    if( (*it)[0] == '<' ) {
      item = new QListViewItem( listView, item, i18n("Email"), (*it).mid(1,(*it).length()-2));
    } else {
      item = new QListViewItem( listView, item, i18n("Aka"), (*it).stripWhiteSpace() );
    }
    ++it;
  }

  // Set up cert. path
  if( !_manager ) return;
  const CryptPlugWrapper::CertificateInfoList& lst = _manager->certList();
  QString issuer = info.issuer;
  QStringList items;
  items << info.userid[0];
  while( true ) {
    bool found = false;
    CryptPlugWrapper::CertificateInfo info;
    for( CryptPlugWrapper::CertificateInfoList::ConstIterator it = lst.begin();
	 it != lst.end(); ++it ) {
      if( (*it).userid[0] == issuer && !items.contains( info.userid[0] ) ) {
	info = (*it);
	found = true;
	break;
      }
    }
    if( found ) {
      items.prepend( info.userid[0] );
      issuer = info.issuer;
      // FIXME(steffen): Use real DN comparison
      if( info.userid[0] == info.issuer ) {
	// Root item
	break;
      }
    } else break;
  }
  item = 0;
  for( QStringList::Iterator it = items.begin(); it != items.end(); ++it ) {
    if( item ) item = new QListViewItem( item, (*it) );
    else item = new QListViewItem( pathView, (*it) );
    item->setOpen( true );
  }
}

void CertificateInfoWidgetImpl::slotShowInfo( QListViewItem* item )
{
  textView->setText( item->text(1) );
}

void CertificateInfoWidgetImpl::slotShowCertPathDetails( QListViewItem* item )
{
  if( !_manager ) return;
  const CryptPlugWrapper::CertificateInfoList& lst = _manager->certList();
  for( CryptPlugWrapper::CertificateInfoList::ConstIterator it = lst.begin();
       it != lst.end(); ++it ) {
    if( (*it).userid[0] == item->text(0) ) {
      KDialogBase* dialog = new KDialogBase( this, "dialog", true, i18n("Additional Information for Key"), KDialogBase::Close, KDialogBase::Close );

      CertificateInfoWidgetImpl* top = new CertificateInfoWidgetImpl( _manager, _manager->isRemote(), dialog );
      dialog->setMainWidget( top );
      top->setCert( *it );
      dialog->exec();
      delete dialog;
    }
  }
}

void CertificateInfoWidgetImpl::slotImportCertificate()
{
  if( !_manager ) return;
  QApplication::setOverrideCursor( QCursor::WaitCursor );
  QString info;
  int retval = _manager->importCertificateWithFingerprint( _info.fingerprint, &info );
  QApplication::restoreOverrideCursor();

  if( retval == -42 ) {
    KMessageBox::error( this, i18n("Cryptplug returned success, but no certiftcate was imported.\nYou may need to import the issuer certificate %1 first.").arg( _info.issuer ), i18n("Import error") );
  } else if( retval ) {
    KMessageBox::error( this, i18n("Error importing certificate.\nCryptPlug returned %1. Additional info: %2").arg(retval).arg( info ), i18n("Import error") );
  } else {
    KMessageBox::information( this, i18n("Certificate %1 with fingerprint %2 is imported to the local database. Additional info: %3").arg(_info.userid[0]).arg(_info.fingerprint).arg( info ), i18n("Certificate Imported") );
    importButton->setEnabled( false );
  }
}
#include "certificateinfowidgetimpl.moc"
<commit_msg>indicate when the root certificate is unknown<commit_after>/* -*- Mode: C -*-

  $Id$

  Copyright (C) 2001 by Klarlvdalens Datakonsult AB

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

  GPGMEPLUG is distributed in the hope that it will be useful,
  it under the terms of GNU General Public License as published by
  the Free Software Foundation; version 2 of the License
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

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

#include <qlistview.h>
#include <qtextedit.h>
#include <qheader.h>
#include <qpushbutton.h>
#include <qcursor.h>
#include <qapplication.h>

#include <klocale.h>
#include <kdialogbase.h>
#include <kmessagebox.h>

#include "certificateinfowidgetimpl.h"
#include "certmanager.h"

CertificateInfoWidgetImpl::CertificateInfoWidgetImpl( CertManager* manager, bool external,
						      QWidget* parent, const char* name )
  : CertificateInfoWidget( parent, name ), _manager(manager), _external( external )
{
  if( !external ) importButton->setEnabled(false);
  listView->setColumnWidthMode( 1, QListView::Manual );
  listView->setResizeMode( QListView::LastColumn );
  QFontMetrics fm = fontMetrics();
  listView->setColumnWidth( 1, fm.width( i18n("Information") ) * 5 );

  listView->header()->setClickEnabled( false );
  listView->setSorting( -1 );

  connect( listView, SIGNAL( selectionChanged( QListViewItem* ) ),
	   this, SLOT( slotShowInfo( QListViewItem* ) ) );
  pathView->setColumnWidthMode( 0, QListView::Manual );
  pathView->setResizeMode( QListView::LastColumn );
  pathView->header()->hide();

  connect( pathView, SIGNAL( doubleClicked( QListViewItem* ) ),
	   this, SLOT( slotShowCertPathDetails( QListViewItem* ) ) );
  connect( pathView, SIGNAL( returnPressed( QListViewItem* ) ),
	   this, SLOT( slotShowCertPathDetails( QListViewItem* ) ) );
  connect( importButton, SIGNAL( clicked() ),
	   this, SLOT( slotImportCertificate() ) );
}

void CertificateInfoWidgetImpl::setCert( const CryptPlugWrapper::CertificateInfo& info )
{
  listView->clear();
  pathView->clear();
  _info = info;

  /* Check if we already have the cert in question */
  if( _manager ) {
    importButton->setEnabled( !_manager->haveCertificate( info.fingerprint ) );
  } else {
    importButton->setEnabled( false );
  }
  // These will show in the opposite order
  new QListViewItem( listView, i18n("Fingerprint"), info.fingerprint );
  new QListViewItem( listView, i18n("Can be used for certification"),
		     info.certify?i18n("Yes"):i18n("No") );
  new QListViewItem( listView, i18n("Can be used for encryption"),
		     info.encrypt?i18n("Yes"):i18n("No") );
  new QListViewItem( listView, i18n("Can be used for signing"),
		     info.sign?i18n("Yes"):i18n("No") );

  new QListViewItem( listView, i18n("Valid"), QString("From %1 to %2")
		     .arg( info.created.toString() ).arg(info.expire.toString()) );

  //new QListViewItem( listView, i18n("Email"), info.dn["1.2.840.113549.1.9.1"] );
  new QListViewItem( listView, i18n("Country"), info.dn["C"] );
  new QListViewItem( listView, i18n("Organizational Unit"), info.dn["OU"] );
  new QListViewItem( listView, i18n("Organization"), info.dn["O"] );
  new QListViewItem( listView, i18n("Location"), info.dn["L"] );
  new QListViewItem( listView, i18n("Name"), info.dn["CN"] );
  new QListViewItem( listView, i18n("Issuer"), info.issuer.stripWhiteSpace() );

  QStringList::ConstIterator it = info.userid.begin();
  QListViewItem* item = new QListViewItem( listView, i18n("Subject"),
			    (*it).stripWhiteSpace() );
  ++it;
  while( it != info.userid.end() ) {
    if( (*it)[0] == '<' ) {
      item = new QListViewItem( listView, item, i18n("Email"), (*it).mid(1,(*it).length()-2));
    } else {
      item = new QListViewItem( listView, item, i18n("Aka"), (*it).stripWhiteSpace() );
    }
    ++it;
  }

  // Set up cert. path
  if( !_manager ) return;
  const CryptPlugWrapper::CertificateInfoList& lst = _manager->certList();
  QString issuer = info.issuer;
  QStringList items;
  items << info.userid[0];
  bool root_found = false;
  while( true ) {
    bool found = false;
    CryptPlugWrapper::CertificateInfo info;
    for( CryptPlugWrapper::CertificateInfoList::ConstIterator it = lst.begin();
	 it != lst.end(); ++it ) {
      if( (*it).userid[0] == issuer && !items.contains( info.userid[0] ) ) {
	info = (*it);
	found = true;
	break;
      }
    }
    if( found ) {
      items.prepend( info.userid[0] );
      issuer = info.issuer;
      // FIXME(steffen): Use real DN comparison
      if( info.userid[0] == info.issuer ) {
	// Root item
	root_found = true;
	break;
      }
    } else break;
  }
  item = 0;
  if( !root_found ) {
    if( items.count() > 0 ) items.prepend( QString::fromUtf8("Root certificate not found (%1)").arg( issuer ) );
    else items.prepend( "Root certificate not found" );
  }
  for( QStringList::Iterator it = items.begin(); it != items.end(); ++it ) {
    if( item ) item = new QListViewItem( item, (*it) );
    else item = new QListViewItem( pathView, (*it) );
    item->setOpen( true );
  }
}

void CertificateInfoWidgetImpl::slotShowInfo( QListViewItem* item )
{
  textView->setText( item->text(1) );
}

void CertificateInfoWidgetImpl::slotShowCertPathDetails( QListViewItem* item )
{
  if( !_manager ) return;
  const CryptPlugWrapper::CertificateInfoList& lst = _manager->certList();
  for( CryptPlugWrapper::CertificateInfoList::ConstIterator it = lst.begin();
       it != lst.end(); ++it ) {
    if( (*it).userid[0] == item->text(0) ) {
      KDialogBase* dialog = new KDialogBase( this, "dialog", true, i18n("Additional Information for Key"), KDialogBase::Close, KDialogBase::Close );

      CertificateInfoWidgetImpl* top = new CertificateInfoWidgetImpl( _manager, _manager->isRemote(), dialog );
      dialog->setMainWidget( top );
      top->setCert( *it );
      dialog->exec();
      delete dialog;
    }
  }
}

void CertificateInfoWidgetImpl::slotImportCertificate()
{
  if( !_manager ) return;
  QApplication::setOverrideCursor( QCursor::WaitCursor );
  QString info;
  int retval = _manager->importCertificateWithFingerprint( _info.fingerprint, &info );
  QApplication::restoreOverrideCursor();

  if( retval == -42 ) {
    KMessageBox::error( this, i18n("Cryptplug returned success, but no certiftcate was imported.\nYou may need to import the issuer certificate %1 first.").arg( _info.issuer ), i18n("Import error") );
  } else if( retval ) {
    KMessageBox::error( this, i18n("Error importing certificate.\nCryptPlug returned %1. Additional info: %2").arg(retval).arg( info ), i18n("Import error") );
  } else {
    KMessageBox::information( this, i18n("Certificate %1 with fingerprint %2 is imported to the local database. Additional info: %3").arg(_info.userid[0]).arg(_info.fingerprint).arg( info ), i18n("Certificate Imported") );
    importButton->setEnabled( false );
  }
}
#include "certificateinfowidgetimpl.moc"
<|endoftext|>


<commit_before>#include <SpecificLogFile.hpp>

#include <Utility/Utilities/Include/Logging/LogTag.hpp>
#include <Utility/Utilities/Include/Logging/LogLevel.hpp>
#include <Utility/Utilities/Include/Logging/LogTagConverter.hpp>
#include <Utility/Utilities/Include/Logging/LogTextData.hpp>
#include <Utility/Utilities/Include/String/StringHelper.hpp>
#include <Utility/Utilities/Include/Chrono/Timer.hpp>
#include <Utility/Utilities/Include/PointerArithmetic/PointerArithmetic.hpp>

#include <iostream>
#include <exception>
#include <Windows.h>

using namespace Doremi::Utilities;

SpecificLogFile::SpecificLogFile() : m_fileStream(nullptr), m_timer(nullptr), m_flushTimerLimit(0), m_elapsedTime(0) {}

SpecificLogFile::~SpecificLogFile()
{
    if(m_fileStream != nullptr)
    {
        m_fileStream->close();
        delete m_fileStream;
    }

    if(m_timer != nullptr)
    {
        delete m_timer;
    }
}

void SpecificLogFile::Initialize(const Logging::LogTag& p_logTag)
{
    m_flushTimerLimit = 1.0;
    m_timer = new Chrono::Timer();
    Logging::LogTagInfo fileNameInfo = Logging::LogTagConverter::convert(p_logTag);
    fileNameInfo.name.append(".txt");
    BuildLogFile(fileNameInfo.name);
    OpenFileStream(fileNameInfo.name);
}

void SpecificLogFile::BuildLogFile(const std::string& p_fileName)
{
    void* fileHandle = CreateFile(String::StringToWideString(p_fileName).c_str(), GENERIC_WRITE, FILE_SHARE_READ, 0, OPEN_ALWAYS, 0, 0);
    if(fileHandle == nullptr)
    {
        const std::string message = std::string("Failed to build logfile with given name: ") + p_fileName;
        throw std::runtime_error(message);
    }
    CloseHandle(fileHandle);
}

void SpecificLogFile::OpenFileStream(const std::string& p_fileName)
{
    m_fileStream = new std::ofstream(p_fileName, std::ofstream::out | std::ofstream::app);
    if(m_fileStream->is_open() == false)
    {
        const std::string message = std::string("Failed to open filestream to given filename: ") + p_fileName;
        throw std::runtime_error(message);
    }
}

void SpecificLogFile::Write(void*& p_data)
{
    // Rebuilddata
    const Logging::TextMetaData* textMetaData = static_cast<Logging::TextMetaData*>(p_data);

    // Fetch pointer to function text
    void* function = PointerArithmetic::Addition(p_data, sizeof(Logging::TextMetaData));

    // Fetch pointer to messagetext
    void* message = PointerArithmetic::Addition(p_data, sizeof(Logging::TextMetaData) + textMetaData->functionLength);

    // Actually cout the data to a file
    *m_fileStream << static_cast<char*>(message) << "\n";
    if(textMetaData->logLevel == Logging::LogLevel::INFO)
    {
        std::cout << static_cast<char*>(message) << "\n";
    }

    // If called often, flush
    m_elapsedTime += m_timer->Tick().GetElapsedTimeInSeconds();
    if(m_elapsedTime > m_flushTimerLimit)
    {
        Flush();
    }
}

void SpecificLogFile::Flush()
{
    m_elapsedTime = 0;
    m_fileStream->flush();
}
<commit_msg>Color in logger, also logs more of the message<commit_after>#include <SpecificLogFile.hpp>

#include <Utility/Utilities/Include/Logging/LogTag.hpp>
#include <Utility/Utilities/Include/Logging/LogLevel.hpp>
#include <Utility/Utilities/Include/Logging/LogTagConverter.hpp>
#include <Utility/Utilities/Include/Logging/LogTextData.hpp>
#include <Utility/Utilities/Include/String/StringHelper.hpp>
#include <Utility/Utilities/Include/Chrono/Timer.hpp>
#include <Utility/Utilities/Include/PointerArithmetic/PointerArithmetic.hpp>
#include <Utility/Utilities/Include/Logging/LogLevelConverter.hpp>
#include <Utility/Utilities/Include/Logging/LogTagConverter.hpp>

#include <iostream>
#include <exception>
#include <Windows.h>

using namespace Doremi::Utilities;

SpecificLogFile::SpecificLogFile() : m_fileStream(nullptr), m_timer(nullptr), m_flushTimerLimit(0), m_elapsedTime(0) {}

SpecificLogFile::~SpecificLogFile()
{
    if(m_fileStream != nullptr)
    {
        m_fileStream->close();
        delete m_fileStream;
    }

    if(m_timer != nullptr)
    {
        delete m_timer;
    }
}

void SpecificLogFile::Initialize(const Logging::LogTag& p_logTag)
{
    m_flushTimerLimit = 1.0;
    m_timer = new Chrono::Timer();
    Logging::LogTagInfo fileNameInfo = Logging::LogTagConverter::convert(p_logTag);
    fileNameInfo.name.append(".txt");
    BuildLogFile(fileNameInfo.name);
    OpenFileStream(fileNameInfo.name);
}

void SpecificLogFile::BuildLogFile(const std::string& p_fileName)
{
    void* fileHandle = CreateFile(String::StringToWideString(p_fileName).c_str(), GENERIC_WRITE, FILE_SHARE_READ, 0, OPEN_ALWAYS, 0, 0);
    if(fileHandle == nullptr)
    {
        const std::string message = std::string("Failed to build logfile with given name: ") + p_fileName;
        throw std::runtime_error(message);
    }
    CloseHandle(fileHandle);
}

void SpecificLogFile::OpenFileStream(const std::string& p_fileName)
{
    m_fileStream = new std::ofstream(p_fileName, std::ofstream::out | std::ofstream::app);
    if(m_fileStream->is_open() == false)
    {
        const std::string message = std::string("Failed to open filestream to given filename: ") + p_fileName;
        throw std::runtime_error(message);
    }
}

void SpecificLogFile::Write(void*& p_data)
{
    using namespace Logging;
    // Rebuilddata
    const Logging::TextMetaData* textMetaData = static_cast<Logging::TextMetaData*>(p_data);

    // Fetch pointer to function text
    void* function = PointerArithmetic::Addition(p_data, sizeof(Logging::TextMetaData));

    // Fetch pointer to messagetext
    void* message = PointerArithmetic::Addition(p_data, sizeof(Logging::TextMetaData) + textMetaData->functionLength);

    auto& logtag = LogTagConverter::convert(textMetaData->logTag).name;
    auto& logLevel = LogLevelConverter::convert(textMetaData->logLevel).name;

    // Actually cout the data to a file
    *m_fileStream << "[" << logtag << ":" << logLevel << "] " << static_cast<char*>(message) << "\n";
    if(textMetaData->logLevel == Logging::LogLevel::INFO)
    {
        if(textMetaData->logLevel == LogLevel::WARNING)
        {
            SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 14);
        }
        else if(textMetaData->logLevel == LogLevel::FATAL_ERROR)
        {
            SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 12);
        }
        else
        {
            SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 7);
        }
        std::cout << "[" << logtag << ":" << logLevel << "] " << static_cast<char*>(message) << "\n";
    }

    // If called often, flush
    m_elapsedTime += m_timer->Tick().GetElapsedTimeInSeconds();
    if(m_elapsedTime > m_flushTimerLimit)
    {
        Flush();
    }
}

void SpecificLogFile::Flush()
{
    m_elapsedTime = 0;
    m_fileStream->flush();
}
<|endoftext|>


<commit_before>/***********************************************************************************************************************
**
** Copyright (c) 2011, ETH Zurich
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
** following conditions are met:
**
**    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following
**      disclaimer.
**    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
**      following disclaimer in the documentation and/or other materials provided with the distribution.
**    * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products
**      derived from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
***********************************************************************************************************************/

/***********************************************************************************************************************
 * SceneHandlerItem.cpp
 *
 *  Created on: Jan 17, 2011
 *      Author: Dimitar Asenov
 **********************************************************************************************************************/

#include "items/SceneHandlerItem.h"
#include "Scene.h"
#include "items/ItemStyle.h"

namespace Visualization {

ITEM_COMMON_DEFINITIONS(SceneHandlerItem, "item")

SceneHandlerItem::SceneHandlerItem(Scene* scene) :
	Item(nullptr, itemStyles().get())
{
	// It should be possible to click inside the item. This happens when the user clicks on an "empty" space in the scene
	// as this item is automatically moved to that empty spot before the click is processed.
	setSize(3,3);
	scene->addItem(this);

	// Make sure this item is behind all others.
	setZValue(Item::LAYER_DEFAULT_Z - 1);
}

void SceneHandlerItem::determineChildren()
{
}

void SceneHandlerItem::updateGeometry(int, int)
{
}

}
<commit_msg>Make the scenehandler item be a menu item<commit_after>/***********************************************************************************************************************
**
** Copyright (c) 2011, ETH Zurich
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
** following conditions are met:
**
**    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following
**      disclaimer.
**    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
**      following disclaimer in the documentation and/or other materials provided with the distribution.
**    * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products
**      derived from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
***********************************************************************************************************************/

/***********************************************************************************************************************
 * SceneHandlerItem.cpp
 *
 *  Created on: Jan 17, 2011
 *      Author: Dimitar Asenov
 **********************************************************************************************************************/

#include "items/SceneHandlerItem.h"
#include "Scene.h"
#include "items/ItemStyle.h"

namespace Visualization {

ITEM_COMMON_DEFINITIONS(SceneHandlerItem, "item")

SceneHandlerItem::SceneHandlerItem(Scene* scene) :
	Item(nullptr, itemStyles().get())
{
	// It should be possible to click inside the item. This happens when the user clicks on an "empty" space in the scene
	// as this item is automatically moved to that empty spot before the click is processed.
	setSize(3,3);
	setItemCategory(Scene::MenuItemCategory);
	scene->addItem(this);

	// Make sure this item is behind all others.
	setZValue(Item::LAYER_DEFAULT_Z - 1);
}

void SceneHandlerItem::determineChildren()
{
}

void SceneHandlerItem::updateGeometry(int, int)
{
}

}
<|endoftext|>