repo_name
stringlengths 4
116
| path
stringlengths 3
942
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
mainecivichackday/wheresyourtrash | wheresyourtrash/apps/email2sms/templates/email2sms/provider_detail.html | 565 | {% extends "base.html" %}
{% load static %}
{% block content %}
<p><a class="btn btn-default" href="{% url 'email2sms_provider_list' %}">Provider Listing</a></p>
<table class="table">
<tr><td>name</td><td>{{ object.name }}</td></tr>
<tr><td>slug</td><td>{{ object.slug }}</td></tr>
<tr><td>created</td><td>{{ object.created }}</td></tr>
<tr><td>last_updated</td><td>{{ object.last_updated }}</td></tr>
<tr><td>email_root</td><td>{{ object.email_root }}</td></tr>
</table>
<a class="btn btn-primary" href="{{object.get_update_url}}">Edit Provider</a>
{% endblock %} | bsd-3-clause |
thuctoa/ungdungtoan | views/site/signup.php | 1196 | <?php
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
/* @var $this yii\web\View */
/* @var $form yii\bootstrap\ActiveForm */
/* @var $model \app\models\SignupForm */
$this->title = Yii::t('app','Signup');
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="site-signup">
<h1><?= Html::encode($this->title) ?></h1>
<p><?= Yii::t("app", "Please fill out the following fields to sign up"); ?></p>
<div class="row">
<div class="col-lg-5">
<?php $form = ActiveForm::begin(['id' => 'form-signup']); ?>
<fieldset><legend><?= Yii::t('app', 'User')?></legend>
<?= $form->field($model, 'username') ?>
<?= $form->field($model, 'email') ?>
<?= $form->field($model, 'password')->passwordInput() ?>
<?= $form->field($model, 'password_repeat')->passwordInput() ?>
</fieldset>
<div class="form-group">
<?= Html::submitButton(Yii::t('app','Signup'), ['class' => 'btn btn-primary', 'name' => 'signup-button']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
</div>
</div>
| bsd-3-clause |
JianpingZeng/xcc | xcc/test/juliet/testcases/CWE606_Unchecked_Loop_Condition/CWE606_Unchecked_Loop_Condition__char_console_09.c | 9499 | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE606_Unchecked_Loop_Condition__char_console_09.c
Label Definition File: CWE606_Unchecked_Loop_Condition.label.xml
Template File: sources-sinks-09.tmpl.c
*/
/*
* @description
* CWE: 606 Unchecked Input For Loop Condition
* BadSource: console Read input from the console
* GoodSource: Input a number less than MAX_LOOP
* Sinks:
* GoodSink: Use data as the for loop variant after checking to see if it is less than MAX_LOOP
* BadSink : Use data as the for loop variant without checking its size
* Flow Variant: 09 Control flow: if(GLOBAL_CONST_TRUE) and if(GLOBAL_CONST_FALSE)
*
* */
#include "std_testcase.h"
#define MAX_LOOP 10000
#ifndef _WIN32
#include <wchar.h>
#endif
#ifndef OMITBAD
void CWE606_Unchecked_Loop_Condition__char_console_09_bad()
{
char * data;
char dataBuffer[100] = "";
data = dataBuffer;
if(GLOBAL_CONST_TRUE)
{
{
/* Read input from the console */
size_t dataLen = strlen(data);
/* if there is room in data, read into it from the console */
if (100-dataLen > 1)
{
/* POTENTIAL FLAW: Read data from the console */
if (fgets(data+dataLen, (int)(100-dataLen), stdin) != NULL)
{
/* The next few lines remove the carriage return from the string that is
* inserted by fgets() */
dataLen = strlen(data);
if (dataLen > 0 && data[dataLen-1] == '\n')
{
data[dataLen-1] = '\0';
}
}
else
{
printLine("fgets() failed");
/* Restore NUL terminator if fgets fails */
data[dataLen] = '\0';
}
}
}
}
if(GLOBAL_CONST_TRUE)
{
{
int i, n, intVariable;
if (sscanf(data, "%d", &n) == 1)
{
/* POTENTIAL FLAW: user-supplied value 'n' could lead to very large loop iteration */
intVariable = 0;
for (i = 0; i < n; i++)
{
/* INCIDENTAL: CWE 561: Dead Code - non-avoidable if n <= 0 */
intVariable++; /* avoid a dead/empty code block issue */
}
printIntLine(intVariable);
}
}
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodB2G1() - use badsource and goodsink by changing the second GLOBAL_CONST_TRUE to GLOBAL_CONST_FALSE */
static void goodB2G1()
{
char * data;
char dataBuffer[100] = "";
data = dataBuffer;
if(GLOBAL_CONST_TRUE)
{
{
/* Read input from the console */
size_t dataLen = strlen(data);
/* if there is room in data, read into it from the console */
if (100-dataLen > 1)
{
/* POTENTIAL FLAW: Read data from the console */
if (fgets(data+dataLen, (int)(100-dataLen), stdin) != NULL)
{
/* The next few lines remove the carriage return from the string that is
* inserted by fgets() */
dataLen = strlen(data);
if (dataLen > 0 && data[dataLen-1] == '\n')
{
data[dataLen-1] = '\0';
}
}
else
{
printLine("fgets() failed");
/* Restore NUL terminator if fgets fails */
data[dataLen] = '\0';
}
}
}
}
if(GLOBAL_CONST_FALSE)
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
printLine("Benign, fixed string");
}
else
{
{
int i, n, intVariable;
if (sscanf(data, "%d", &n) == 1)
{
/* FIX: limit loop iteration counts */
if (n < MAX_LOOP)
{
intVariable = 0;
for (i = 0; i < n; i++)
{
/* INCIDENTAL: CWE 561: Dead Code - non-avoidable if n <= 0 */
intVariable++; /* avoid a dead/empty code block issue */
}
printIntLine(intVariable);
}
}
}
}
}
/* goodB2G2() - use badsource and goodsink by reversing the blocks in the second if */
static void goodB2G2()
{
char * data;
char dataBuffer[100] = "";
data = dataBuffer;
if(GLOBAL_CONST_TRUE)
{
{
/* Read input from the console */
size_t dataLen = strlen(data);
/* if there is room in data, read into it from the console */
if (100-dataLen > 1)
{
/* POTENTIAL FLAW: Read data from the console */
if (fgets(data+dataLen, (int)(100-dataLen), stdin) != NULL)
{
/* The next few lines remove the carriage return from the string that is
* inserted by fgets() */
dataLen = strlen(data);
if (dataLen > 0 && data[dataLen-1] == '\n')
{
data[dataLen-1] = '\0';
}
}
else
{
printLine("fgets() failed");
/* Restore NUL terminator if fgets fails */
data[dataLen] = '\0';
}
}
}
}
if(GLOBAL_CONST_TRUE)
{
{
int i, n, intVariable;
if (sscanf(data, "%d", &n) == 1)
{
/* FIX: limit loop iteration counts */
if (n < MAX_LOOP)
{
intVariable = 0;
for (i = 0; i < n; i++)
{
/* INCIDENTAL: CWE 561: Dead Code - non-avoidable if n <= 0 */
intVariable++; /* avoid a dead/empty code block issue */
}
printIntLine(intVariable);
}
}
}
}
}
/* goodG2B1() - use goodsource and badsink by changing the first GLOBAL_CONST_TRUE to GLOBAL_CONST_FALSE */
static void goodG2B1()
{
char * data;
char dataBuffer[100] = "";
data = dataBuffer;
if(GLOBAL_CONST_FALSE)
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
printLine("Benign, fixed string");
}
else
{
/* FIX: Set data to a number less than MAX_LOOP */
strcpy(data, "15");
}
if(GLOBAL_CONST_TRUE)
{
{
int i, n, intVariable;
if (sscanf(data, "%d", &n) == 1)
{
/* POTENTIAL FLAW: user-supplied value 'n' could lead to very large loop iteration */
intVariable = 0;
for (i = 0; i < n; i++)
{
/* INCIDENTAL: CWE 561: Dead Code - non-avoidable if n <= 0 */
intVariable++; /* avoid a dead/empty code block issue */
}
printIntLine(intVariable);
}
}
}
}
/* goodG2B2() - use goodsource and badsink by reversing the blocks in the first if */
static void goodG2B2()
{
char * data;
char dataBuffer[100] = "";
data = dataBuffer;
if(GLOBAL_CONST_TRUE)
{
/* FIX: Set data to a number less than MAX_LOOP */
strcpy(data, "15");
}
if(GLOBAL_CONST_TRUE)
{
{
int i, n, intVariable;
if (sscanf(data, "%d", &n) == 1)
{
/* POTENTIAL FLAW: user-supplied value 'n' could lead to very large loop iteration */
intVariable = 0;
for (i = 0; i < n; i++)
{
/* INCIDENTAL: CWE 561: Dead Code - non-avoidable if n <= 0 */
intVariable++; /* avoid a dead/empty code block issue */
}
printIntLine(intVariable);
}
}
}
}
void CWE606_Unchecked_Loop_Condition__char_console_09_good()
{
goodB2G1();
goodB2G2();
goodG2B1();
goodG2B2();
}
#endif /* OMITGOOD */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
CWE606_Unchecked_Loop_Condition__char_console_09_good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
CWE606_Unchecked_Loop_Condition__char_console_09_bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| bsd-3-clause |
dstocco/AliPhysics | PWGGA/CaloTrackCorrelations/macros/plotting/invmass/InvMassFit.C | 85625 | ///
/// \file InvMassFit.C
/// \ingroup CaloTrackCorrMacrosPlotting
/// \brief Fit invariant mass distributions
///
/// Macro using as input the 2D histograms mass vs pT of AliAnaPi0
/// For a given set of pT bins invariant mass plots are fitted and mass vs pT
/// and width vs pT and neutral meson spectra plots are obtained.
/// Also pure MC histograms checking the origin of the clusters and generated spectra
/// is used to plot efficiencies and acceptance
///
/// Based on old macros
///
/// \author Gustavo Conesa Balbastre <[email protected]>, (LPSC-CNRS)
///
#if !defined(__CINT__) || defined(__MAKECINT__)
#include <TString.h>
#include <TH2F.h>
#include <TH1F.h>
#include <TH3F.h>
#include <TH1D.h>
#include <TF1.h>
#include <TMath.h>
#include <TCanvas.h>
#include <TStyle.h>
#include <TPad.h>
#include <TFile.h>
#include <TLegend.h>
#include <TObject.h>
#include <TDirectoryFile.h>
#include <TGraphErrors.h>
#include <TList.h>
#include <TArrayD.h>
#include <TGaxis.h>
#include <TROOT.h>
#include "PlotUtils.C"
#endif
// Settings
Bool_t kMix = kFALSE; /// use mixed event to constrain combinatorial background
Int_t kPolN = 1; /// polinomyal type for residual background under the peak
Bool_t kSumw2 = kTRUE; /// Apply Root method Sumw2(), off for pT hard prod where already done before
Float_t kNPairCut = 20; /// Minimum number of cluster pairs in pi0 or eta window
Float_t kFirstTRDSM = -1; /// First Calo SM covered by a TRD SM, 6 in 2011 and 4 in 2012-13
TString kHistoStartName = "AnaPi0"; /// Common starting name in histograms
TString kProdName = "LHC18c3_NystromOn"; /// Input production directory name where input file is located
TString kFileName = "AnalysisResults"; /// Name of file with input histograms
TString kPlotFormat = "eps"; /// Automatic plots format
TString kCalorimeter= "EMCAL"; /// Calorimeter, EMCAL, DCAL (PHOS)
TString kParticle = "Pi0"; /// Particle searched: "Pi0", "Eta"
Bool_t kTrunMixFunc= kTRUE; /// Use a truncated function to get the mixed event scale
Float_t kChi2NDFMax = 1000; /// Maximum value of chi2/ndf to define a fit as good (set lower than 1e6)
Int_t kRebin = 1; /// Rebin invariant mass histograms default binning with this value
// Initializations
Double_t nEvt = 0;
TFile * fil = 0;
TFile * fout = 0;
TList * lis = 0;
TF1 * fitfun= 0;
TDirectoryFile * direc =0;
// Mixing
TF1 *tPolPi0 = 0;
TF1 *tPolEta = 0;
Int_t modColorIndex[]={1 , 1, 2, 2, 3, 3, 4, 4, 7, 7, 6, 6, 2, 3, 4, 7, 6, 2, 2, 3, 3, 4, 4, 6, 6};
Int_t modStyleIndex[]={24,25,25,24,25,24,25,24,25,24,25,21,21,21,21,21,22,26,22,26,22,26,22,26};
///
/// Open the file and the list and the number of analyzed events
///
//-----------------------------------------------------------------------------
Bool_t GetFileAndEvents( TString dirName , TString listName )
{
fil = new TFile(Form("%s/%s.root",kProdName.Data(),kFileName.Data()),"read");
printf("Open Input File: %s/%s.root\n",kProdName.Data(),kFileName.Data());
if ( !fil ) return kFALSE;
direc = (TDirectoryFile*) fil->Get(dirName);
if ( !direc && dirName != "" ) return kFALSE;
//printf("dir %p, list %s\n",dir,listName.Data());
if(direc)
lis = (TList*) direc ->Get(listName);
else
lis = (TList*) fil->Get(listName);
if ( !lis && listName != "") return kFALSE;
if(!lis)
nEvt = ((TH1F*) fil->Get("hNEvents"))->GetBinContent(1);
else
nEvt = ((TH1F*) lis->FindObject("hNEvents"))->GetBinContent(1);
printf("nEvt = %2.3e\n",nEvt);
//nEvt = 1;
return kTRUE;
}
///
/// Initialize the fitting function
/// The function definitions are in PlotUtils.C
///
//-----------------------------------------------------------------------------
void SetFitFun()
{
//Fitting function
//if(mix) kPolN = 0;
if(kParticle == "Pi0")
{
if ( kPolN == 0)
fitfun = new TF1("fitfun",FunctionGaussPol0,0.100,0.250,4);
else if (kPolN == 1)
fitfun = new TF1("fitfun",FunctionGaussPol1,0.100,0.250,5);
else if (kPolN == 2)
fitfun = new TF1("fitfun",FunctionGaussPol2,0.100,0.250,6);
else if (kPolN == 3)
fitfun = new TF1("fitfun",FunctionGaussPol3,0.100,0.250,7);
else
{
printf("*** <<< Set Crystal Ball!!! >>> ***\n");
fitfun = new TF1("fitfun",FunctionCrystalBall,0.100,0.250,6);
}
if(kPolN < 4)
{
fitfun->SetParLimits(0, kNPairCut/5,kNPairCut*1.e4);
fitfun->SetParLimits(1, 0.105,0.185);
fitfun->SetParLimits(2, 0.001,0.040);
}
else
{
fitfun->SetParLimits(0, kNPairCut/5,kNPairCut*1.e6);
fitfun->SetParLimits(2, 0.105,0.185);
fitfun->SetParLimits(1, 0.001,0.040);
fitfun->SetParLimits(3, 0.001,0.040);
fitfun->SetParLimits(4, 0,10);
fitfun->SetParLimits(5, 1,1.e+6);
}
} // Pi0
else // Eta
{
if ( kPolN == 0)
fitfun = new TF1("fitfun",FunctionGaussPol0,0.400,0.650,4);
else if (kPolN == 1)
fitfun = new TF1("fitfun",FunctionGaussPol1,0.400,0.650,5);
else if (kPolN == 2)
fitfun = new TF1("fitfun",FunctionGaussPol2,0.400,0.650,6);
else if (kPolN == 3)
fitfun = new TF1("fitfun",FunctionGaussPol3,0.400,0.650,7);
if(kPolN < 4)
{
fitfun->SetParLimits(0, kNPairCut/10,1.e+6);
fitfun->SetParLimits(1, 0.20,0.80);
fitfun->SetParLimits(2, 0.001,0.06);
}
}
fitfun->SetLineColor(kRed);
fitfun->SetLineWidth(2);
fitfun->SetParName(0,"A");
fitfun->SetParName(1,"m_{0}");
fitfun->SetParName(2,"#sigma");
// fitfun->SetParName(3,"a_{0}");
// fitfun->SetParName(4,"a_{1}");
if (kPolN > 1)
{
fitfun->SetParName(5,"a_{2}");
if (kPolN > 2) fitfun->SetParName(6,"a_{3}");
}
//Mix fit func
tPolPi0 = new TF1("truncatedPolPi0" , FunctionTruncatedPolPi0 , 0.02, 0.25, 2);
tPolEta = new TF1("truncatedPolEta" , FunctionTruncatedPolEta , 0.2, 1, 2);
}
//-----------------------
/// Efficiency calculation called in ProjectAndFit()
//-----------------------
void Efficiency
(Int_t nPt,
TArrayD xPt , TArrayD exPt ,
TArrayD mesonPt , TArrayD emesonPt ,
TArrayD mesonPtBC, TArrayD emesonPtBC,
TString hname)
{
gStyle->SetOptTitle(1);
gStyle->SetTitleOffset(2,"Y");
gStyle->SetOptStat(0);
gStyle->SetOptFit(000000);
TGraphErrors * gPrim = (TGraphErrors*) fout->Get("Primary");
TGraphErrors * gPrimAcc = (TGraphErrors*) fout->Get("PrimaryInAcceptance");
if ( !gPrim || !gPrimAcc ) return ;
TArrayD effPt ; effPt .Set(nPt);
TArrayD effBCPt ; effBCPt .Set(nPt);
TArrayD effPtAcc ; effPtAcc .Set(nPt);
TArrayD effBCPtAcc ; effBCPtAcc .Set(nPt);
TArrayD effPtErr ; effPtErr .Set(nPt);
TArrayD effBCPtErr ; effBCPtErr .Set(nPt);
TArrayD effPtAccErr ; effPtAccErr .Set(nPt);
TArrayD effBCPtAccErr; effBCPtAccErr.Set(nPt);
for(Int_t ibin = 0; ibin < nPt; ibin++ )
{
//printf("Bin %d \n",ibin);
//printf("- Fit Reco %2.3e, Prim %2.3e, PrimAcc %2.3e\n",
// mesonPt[ibin],gPrim->GetY()[ibin],gPrimAcc->GetY()[ibin]);
if ( gPrim->GetY()[ibin] > 0 && mesonPt[ibin] > 0 )
{
effPt [ibin] = 100 * mesonPt[ibin] / gPrim->GetY()[ibin];
effPtErr[ibin] = 100 * GetFractionError( mesonPt[ibin], gPrim->GetY ()[ibin],
emesonPt[ibin], gPrim->GetEY()[ibin]); // PlotUtils.C
//printf("\t EffxAcc %f, err %f\n",effPt[ibin],effPtErr[ibin]);
}
else { effPt[ibin] = 0; effPtErr[ibin] = 0; }
if ( gPrimAcc->GetY()[ibin] > 0 && mesonPt[ibin] > 0 )
{
effPtAcc [ibin] = 100 * mesonPt[ibin] / gPrimAcc->GetY()[ibin];
effPtAccErr[ibin] = 100 * GetFractionError( mesonPt[ibin], gPrimAcc->GetY ()[ibin],
emesonPt[ibin], gPrimAcc->GetEY()[ibin]); // PlotUtils.C
//printf("\t Eff %f, err %f\n",effPtAcc[ibin],effPtAccErr[ibin]);
}
else { effPtAcc[ibin] = 0; effPtAccErr[ibin] = 0; }
if ( kMix || hname.Contains("MCpT") )
{
//printf("- BC Reco %2.3e, Prim %2.3e, PrimAcc %2.3e\n",
// mesonPtBC[ibin],gPrim->GetY()[ibin],gPrimAcc->GetY()[ibin]);
if ( gPrim->GetY()[ibin] > 0 && mesonPtBC[ibin] > 0 )
{
effBCPt [ibin] = 100 * mesonPtBC[ibin] / gPrim->GetY()[ibin];
effBCPtErr[ibin] = 100 * GetFractionError( mesonPtBC[ibin], gPrim->GetY ()[ibin],
emesonPtBC[ibin], gPrim->GetEY()[ibin]); // PlotUtils.C
//printf("\t EffxAcc %f, err %f\n",effBCPt[ibin],effBCPtErr[ibin]);
}
else { effBCPt[ibin] = 0; effBCPtErr[ibin] = 0; }
if ( gPrimAcc->GetY()[ibin] > 0 && mesonPtBC[ibin] > 0 )
{
effBCPtAcc [ibin] = 100 * mesonPtBC[ibin] / gPrimAcc->GetY()[ibin];
effBCPtAccErr[ibin] = 100 * GetFractionError( mesonPtBC[ibin], gPrimAcc->GetY ()[ibin],
emesonPtBC[ibin], gPrimAcc->GetEY()[ibin]); // PlotUtils.C
//printf("\t EffxAcc %f, err %f\n",effBCPtAcc[ibin],effBCPtAccErr[ibin]);
}
else { effBCPtAcc[ibin] = 0; effBCPtAccErr[ibin] = 0; }
} // Bin counting
} // pt bin loop
TGraphErrors *gEff = new TGraphErrors(nPt,xPt.GetArray(),effPt.GetArray(),exPt.GetArray(),effPtErr.GetArray());
gEff->SetName(Form("EfficiencyxAcceptance_%s",hname.Data()));
gEff->GetHistogram()->SetYTitle("#epsilon_{Reco #times PID #times Acc} (%)");
gEff->GetHistogram()->SetTitleOffset(1.4,"Y");
gEff->GetHistogram()->SetXTitle("#it{p}_{T} (GeV/#it{c})");
gEff->GetHistogram()->SetTitleOffset(1.2,"X");
gEff->GetHistogram()->SetTitle("Reconstruction efficiency #times acceptance");
gEff->SetMarkerColor(1);
gEff->SetLineColor(1);
gEff->SetMarkerStyle(20);
gEff->Write();
TGraphErrors *gEffAcc = new TGraphErrors(nPt,xPt.GetArray(),effPtAcc.GetArray(),exPt.GetArray(),effPtAccErr.GetArray());
gEffAcc->SetName(Form("Efficiency_%s",hname.Data()));
gEffAcc->GetHistogram()->SetYTitle("#epsilon_{Reco #times PID} (%)");
gEffAcc->GetHistogram()->SetTitleOffset(1.5,"Y");
gEffAcc->GetHistogram()->SetXTitle("#it{p}_{T} (GeV/#it{c})");
gEffAcc->GetHistogram()->SetTitleOffset(1.2,"X");
gEffAcc->SetMarkerColor(1);
gEffAcc->SetLineColor(1);
gEffAcc->SetMarkerStyle(20);
gEffAcc->GetHistogram()->SetTitle("Reconstruction efficiency");
gEffAcc->Write();
TGraphErrors *gBCEff = 0;
TGraphErrors *gBCEffAcc = 0;
if(kMix)
{
gBCEff = new TGraphErrors(nPt,xPt.GetArray(),effBCPt.GetArray(),exPt.GetArray(),effBCPtErr.GetArray());
gBCEff->SetName(Form("EfficiencyxAcceptance_BC_%s",hname.Data()));
gBCEff->GetHistogram()->SetYTitle("#epsilon_{Reco #times PID #times Acc}");
gBCEff->GetHistogram()->SetTitleOffset(1.5,"Y");
gBCEff->GetHistogram()->SetXTitle("#it{p}_{T} (GeV/#it{c})");
gBCEff->GetHistogram()->SetTitleOffset(1.2,"X");
gBCEff->SetMarkerColor(4);
gBCEff->SetLineColor(4);
gBCEff->SetMarkerStyle(24);
gBCEff->Write();
gBCEffAcc = new TGraphErrors(nPt,xPt.GetArray(),effBCPtAcc.GetArray(),exPt.GetArray(),effBCPtAccErr.GetArray());
gBCEffAcc->SetName(Form("Efficiency_BC_%s",hname.Data()));
gBCEffAcc->GetHistogram()->SetYTitle("#epsilon_{Reco #times PID}");
gBCEffAcc->GetHistogram()->SetTitleOffset(1.4,"Y");
gBCEffAcc->GetHistogram()->SetXTitle("#it{p}_{T} (GeV/#it{c})");
gBCEffAcc->GetHistogram()->SetTitleOffset(1.2,"X");
gBCEffAcc->SetMarkerColor(4);
gBCEffAcc->SetLineColor(4);
gBCEffAcc->SetMarkerStyle(24);
gBCEffAcc->Write();
}
// Plot efficiencies
//
TCanvas *cEff = new TCanvas(Form("cEff_%s",hname.Data()),
Form("Efficiency Graphs for %s",hname.Data()),2*600,600);
cEff->Divide(2, 1);
cEff->cd(1);
gPad->SetGridx();
gPad->SetGridy();
//gPad->SetLogy();
//gEff->SetMaximum(1);
//gEff->SetMinimum(1e-8);
gEff->Draw("AP");
if(kMix)
{
gBCEff ->Draw("P");
TLegend * legend = new TLegend(0.5,0.7,0.9,0.9);
legend->AddEntry(gEff ,"From fit","P");
legend->AddEntry(gBCEff,"From bin counting","P");
legend->Draw();
}
cEff->cd(2);
gPad->SetGridx();
gPad->SetGridy();
//gPad->SetLogy();
//gEffAcc->SetMaximum(1);
//gEffAcc->SetMinimum(1e-8);
gEffAcc->Draw("AP");
if(kMix)
{
gBCEffAcc->Draw("P");
TLegend * legend = new TLegend(0.5,0.7,0.9,0.9);
legend->AddEntry(gEffAcc ,"From fit","P");
legend->AddEntry(gBCEffAcc,"From bin counting","P");
legend->Draw();
}
cEff->Print(Form("IMfigures/%s_%s_Efficiency_%s_%s.%s",
kProdName.Data(),kCalorimeter.Data(),kParticle.Data(),hname.Data(),
/*kFileName.Data(),*/ kPlotFormat.Data()));
}
//-------------------------------------
/// Do energy projections, fits and plotting
/// of invariant mass distributions.
//-------------------------------------
void ProjectAndFit
(
const Int_t nPt, TString comment, TString leg, TString hname,
TArrayD xPtLimits, TArrayD xPt, TArrayD exPt,
TH2F * hRe, TH2F * hMi
)
{
if ( !hRe )
{
printf("ProjectAndFit() - Null inv mass 2D histo for %s, skip!\n",hname.Data());
return;
}
gStyle->SetOptTitle(1);
gStyle->SetTitleOffset(2,"Y");
gStyle->SetOptStat(0);
gStyle->SetOptFit(000000);
Double_t mmin = 0;
Double_t mmax = 1;
TString particleN = "";
if(kParticle=="Pi0")
{
mmin = 0.04;
mmax = 0.44;
particleN = " #pi^{0}";
}
else // eta
{
mmin = 0.25;
mmax = 0.95;
particleN = " #eta";
}
TLegend * pLegendIM[nPt];
TH1D* hIM [nPt];
TH1D* hMix [nPt];
TH1D* hMixCorrected [nPt];
TH1D* hRatio [nPt];
TH1D* hSignal [nPt];
for(Int_t ipt = 0; ipt< nPt; ipt++)
{
hIM [ipt] = 0 ;
hMix [ipt] = 0 ;
hMixCorrected[ipt] = 0 ;
hRatio [ipt] = 0 ;
hSignal [ipt] = 0 ;
}
TArrayD mesonPt ; mesonPt .Set(nPt);
TArrayD mesonPtBC ; mesonPtBC .Set(nPt);
TArrayD mesonMass ; mesonMass .Set(nPt);
TArrayD mesonWidth; mesonWidth.Set(nPt);
TArrayD emesonPt ; emesonPt .Set(nPt);
TArrayD emesonPtBC ; emesonPtBC .Set(nPt);
TArrayD emesonMass ; emesonMass .Set(nPt);
TArrayD emesonWidth; emesonWidth.Set(nPt);
Int_t rebin2 = 2*kRebin;
Int_t col = TMath::Ceil(TMath::Sqrt(nPt));
//hRe->Scale(1./nEvt);
// Mix correction factor
TF1 *line3[nPt];// = new TF1("line3", "[0]+[1]*x+[2]*x*x+[3]*x*x*x", 0.0, 1);
TF1 * fitFunction = 0;
Bool_t ok = kFALSE;
TCanvas * cIMModi = new TCanvas(Form("c%s", hname.Data()), Form("%s", leg.Data()), 1200, 1200) ;
cIMModi->Divide(col, col);
for(Int_t i = 0; i < nPt; i++)
{
cIMModi->cd(i+1) ;
//gPad->SetLogy();
Double_t ptMin = xPtLimits[i];
Double_t ptMax = xPtLimits[i+1];
//printf("Bin %d (%2.1f, %2.1f)\n",i, ptMin,ptMax);
hIM[i] = hRe->ProjectionY(Form("IM_%s_PtBin%d",hname.Data(),i),
hRe->GetXaxis()->FindBin(ptMin),
hRe->GetXaxis()->FindBin(ptMax));
hIM[i]->SetTitle(Form("%2.1f < #it{p}_{T, #gamma#gamma} < %2.1f GeV/#it{c}",ptMin,ptMax));
if(i < nPt-3)
hIM[i]->Rebin(kRebin);
else
hIM[i]->Rebin(rebin2);
if ( kSumw2 )
hIM[i]->Sumw2();
hIM[i]->SetXTitle("M_{#gamma,#gamma} (GeV/#it{c}^{2})");
//printf("mmin %f, mmax %f\n",mmin,mmax);
hIM[i]->SetAxisRange(mmin,mmax,"X");
hIM[i]->SetLineWidth(2);
hIM[i]->SetLineColor(4);
Double_t mStep = hIM[i]->GetBinWidth(1);
hSignal[i] = (TH1D*) hIM[i]->Clone();
//--------------------------------------------------
// Mix: Project, scale and subract to real pairs
//--------------------------------------------------
if ( kMix && hMi )
{
hMix[i] = (TH1D*) hMi->ProjectionY(Form("MiMass_PtBin%d_%s",i,hname.Data()),
hMi->GetXaxis()->FindBin(ptMin),
hMi->GetXaxis()->FindBin(ptMax));
hMix[i]->SetLineColor(1);
hMix[i]->SetTitle(Form("%2.2f < #it{p}_{T, #gamma#gamma} < %2.2f GeV/#it{c}",ptMin,ptMax));
if(i < nPt-3)
hMix[i]->Rebin(kRebin);
else
hMix[i]->Rebin(rebin2);
// Double_t sptmin = 0.2;
// Double_t sptmax = 0.45;
// Double_t scalereal = hIM->Integral(hIM->FindBin(sptmin),
// hIM->FindBin(sptmax));
// Double_t scalemix = hMix->Integral(hMix->FindBin(sptmin),
// hMix->FindBin(sptmax));
// if(scalemix > 0)
// hMix->Scale(scalereal/scalemix);
// else{
// //printf("could not scale: re %f mi %f\n",scalereal,scalemix);
// continue;
// }
// hMix[i]->SetLineWidth(1);
if ( kSumw2 )
hMix[i]->Sumw2();
// --- Ratio ---
hRatio[i] = (TH1D*)hIM[i]->Clone(Form("RatioRealMix_PtBin%d_%s",i,hname.Data()));
hRatio[i]->SetAxisRange(mmin,mmax,"X");
hRatio[i]->Divide(hMix[i]);
Double_t p0 =0;
Double_t p1 =0;
Double_t p2 =0;
Double_t p3 =0;
// --- Subtract from signal ---
hSignal[i] ->SetName(Form("Signal_PtBin%d_%s",i,hname.Data()));
if ( hMix[i]->GetEntries() > kNPairCut*3 )
{
hSignal[i] ->SetLineColor(kViolet);
if ( kTrunMixFunc )
{
if ( kParticle == "Pi0" )
{
hRatio[i]->Fit("truncatedPolPi0", "NQRL","",0.11,0.4);
p0= tPolPi0->GetParameter(0);
p1= tPolPi0->GetParameter(1);
//p2= tPolPi0->GetParameter(2);
//p3= tPolPi0->GetParameter(3);
} // pi0
else // eta
{
hRatio[i]->SetAxisRange(mmin,mmax);
hRatio[i]->Fit("truncatedPolEta", "NQRL","",0.35,0.95);
p0 = tPolEta->GetParameter(0);
p1 = tPolEta->GetParameter(1);
//p2 = tPolEta->GetParameter(2);
//p3 = tPolEta->GetParameter(3);
}
//line3[i] = new TF1("line3", "[0]+[1]*x+[2]*x*x+[3]*x*x*x", mmin, mmax);
line3[i] = new TF1("line3", "[0]+[1]*x", mmin, mmax);
line3[i]->SetParameters(p0,p1,p2,p3);
//printf("Correct\n");
hMixCorrected[i] = (TH1D*) hMix[i]->Clone(Form("MixCorrected_PtBin%d_%s",i,hname.Data()));
for(Int_t j = 0; j< hMix[i]->GetNbinsX(); j++)
{
Double_t x = hMix[i]->GetBinCenter(j);
Double_t correction = line3[i]->Eval(x);
Double_t corrected = hMix[i]->GetBinContent(j)*correction;
Double_t ecorrected = hMix[i]->GetBinError(j) *correction;
//printf("bin %d, center %f, mix %f, corrected %f\n",i,x,hMix[i]->GetBinContent(j),corrected);
hMixCorrected[i]->SetBinContent(j, corrected);
hMixCorrected[i]->SetBinError (j,ecorrected);
}
// Subtract
hSignal[i] ->Add(hMixCorrected[i],-1);
}
else
{
Float_t scale = hRatio[i]->GetBinContent(hRatio[i]->FindBin(0.7));
hMix[i]->Scale(scale);
// Subtract
hSignal[i] ->Add(hMix[i],-1);
}
} // enough mixed entries
} // mixed event histogtam exists
//----------------------------
// ---- Fit subtracted signal
//----------------------------
Double_t nMax = 0;
if(kParticle=="Pi0")
{
nMax= hSignal[i]->Integral(hIM[i]->FindBin(0.1),
hIM[i]->FindBin(0.2));
}
else
{
nMax = hSignal[i]->Integral(hIM[i]->FindBin(0.5),
hIM[i]->FindBin(0.7));
}
if(nMax > kNPairCut)
{
fitfun->SetParLimits(0,nMax/100,nMax*100);
if(kParticle=="Pi0")
{
if(kPolN < 4 )fitfun->SetParameters(nMax/5,0.135,20,0);
else fitfun->SetParameters(nMax/5,20,0.135,20,20,nMax/5);
if(i < nPt-4)
hSignal[i]->Fit("fitfun","QR","",0.11,0.3);
else
hSignal[i]->Fit("fitfun","QR","",0.11,0.3);
}// pi0
else // eta
{
if ( kPolN < 4 ) fitfun->SetParameters(nMax/5,0.54,40,0);
else fitfun->SetParameters(nMax/5,40,0.54,40,40,nMax/5);
//if(i<4)
hSignal[i]->Fit("fitfun","QR","",0.4,0.7);
//else if(i < 15)
// hSignal[i]->Fit("fitfun","QRL","",0.3,0.8);
//else
//hSignal[i]->Fit("fitfun","QRL","",0.3,0.8);
}
}
else
printf("Skip bin %d: n max %2.3e < cut %2.3e\n",i, nMax, kNPairCut);
//----------------------------
// ---- Put fit results in arrays
//----------------------------
// Init results arrays
mesonPt .SetAt(-1,i);
emesonPt .SetAt(-1,i);
mesonPtBC .SetAt(-1,i);
emesonPtBC .SetAt(-1,i);
mesonMass .SetAt(-1,i);
emesonMass .SetAt(-1,i);
mesonWidth.SetAt(-1,i);
emesonWidth.SetAt(-1,i);
fitFunction = (TF1*) hSignal[i]->GetFunction("fitfun");
Float_t chi2ndf = 1e6;
if ( fitFunction )
{
// printf("ipt %d: Chi/NDF %f, Chi %f, NDF %d\n",i,
// fitFunction->GetChisquare()/fitFunction->GetNDF(),
// fitFunction->GetChisquare(),
// fitFunction->GetNDF());
Float_t chi2 = fitFunction->GetChisquare();
Int_t ndf = fitFunction->GetNDF();
if( ndf > 0 ) chi2ndf = chi2 / ndf;
if ( chi2ndf < kChi2NDFMax )
{
Double_t A = fitFunction->GetParameter(0);
Double_t mean = fitFunction->GetParameter(1);
Double_t sigm = fitFunction->GetParameter(2);
// Double_t a0 = fitFunction->GetParameter(3);
// Double_t a1 = fitFunction->GetParameter(4);
// Double_t a2 = 0;
// if (kPolN == 2)
// a2 = fitFunction->GetParameter(5);
Double_t eA = fitFunction->GetParError(0);
Double_t emean = fitFunction->GetParError(1);
Double_t esigm = fitFunction->GetParError(2);
// Double_t ea0 = fitFunction->GetParError(3);
// Double_t ea1 = fitFunction->GetParError(4);
// Double_t ea2 = 0;
// if (kPolN == 2)
// ea2 = fitFunction->GetParError(5);
pLegendIM[i] = new TLegend(0.48,0.65,0.95,0.93);
pLegendIM[i]->SetTextSize(0.035);
pLegendIM[i]->SetFillColor(10);
pLegendIM[i]->SetBorderSize(1);
pLegendIM[i]->SetHeader(Form(" %s - %s",particleN.Data(), leg.Data()));
pLegendIM[i]->AddEntry("",Form("A = %2.1e#pm%2.1e ",A,eA),"");
pLegendIM[i]->AddEntry("",Form("#mu = %3.1f #pm %3.1f GeV/#it{c}^{2}",mean*1000,emean*1000),"");
pLegendIM[i]->AddEntry("",Form("#sigma = %3.1f #pm %3.1f GeV/#it{c}^{2}",sigm*1000,esigm*1000),"");
//pLegendIM[i]->AddEntry("",Form("p_{0} = %2.1f #pm %2.1f ",a0,ea0),"");
//pLegendIM[i]->AddEntry("",Form("p_{1} = %2.1f #pm %2.1f ",a1,ea1),"");
//if(kPolN==2)pLegendIM[i]->AddEntry("",Form("p_{2} = %2.1f#pm %2.1f ",a2,ea2),"");
Double_t counts = A*sigm / mStep * TMath::Sqrt(TMath::TwoPi());
Double_t eCounts =
TMath::Power(eA/A,2) +
TMath::Power(esigm/sigm,2);
eCounts = TMath::Sqrt(eCounts) * counts;
//eCounts = TMath::Min(eCounts, TMath::Sqrt(counts));
counts/=(nEvt*(exPt.At(i)*2));
eCounts/=(nEvt*(exPt.At(i)*2));
mesonPt.SetAt( counts,i);
emesonPt.SetAt(eCounts,i);
//printf("A %e Aerr %e; mu %f muErr %f; sig %f sigErr %f",
// A,eA,mean,emean,sigm,esigm);
//cout << "N(pi0) fit = " << counts << "+-"<< eCounts << " mstep " << mStep<<endl;
mesonMass .SetAt( mean*1000.,i);
emesonMass .SetAt(emean*1000.,i);
mesonWidth.SetAt( sigm*1000.,i);
emesonWidth.SetAt(esigm*1000.,i);
} //Good fit
else
{
printf("Bin %d, Bad fit, Chi2 %f ndf %d, ratio %f!\n",
i,chi2,ndf,chi2ndf);
}
}
else printf("Bin %d, NO fit available!\n",i);
// Set the integration window, depending on mass mean and width
// 2 sigma
Double_t mass = mesonMass [i]/1000.;
Double_t width = mesonWidth[i]/1000.;
Double_t mMinBin = mass - 2 * width;
Double_t mMaxBin = mass + 2 * width;
if(mass <= 0 || width <= 0)
{
if(kParticle=="Pi0")
{
mMinBin = 0.115; mMaxBin = 0.3 ;
}
else // eta
{
mMinBin = 0.4; mMaxBin = 0.9 ;
}
}
//
// Bin counting instead of fit
//
//printf("Signal %p, Mix %p, hname %s\n",hSignal[i], hMix[i], hname.Data());
if ( hSignal[i] && ( hMix[i] || hname.Contains("MCpT") ) )
{
Double_t countsBin = 0.;//hSignal[i]->Integral(hSignal[i]->FindBin(mMinBin), hSignal[i]->FindBin(mMaxBin)) ;
Double_t eCountsBin = 0.;//TMath::Sqrt(countsBin);
// PlotUtils.C
GetRangeIntegralAndError(hSignal[i], hSignal[i]->FindBin(mMinBin), hSignal[i]->FindBin(mMaxBin), countsBin, eCountsBin );
countsBin/=(nEvt*(exPt.At(i)*2));
eCountsBin/=(nEvt*(exPt.At(i)*2));
mesonPtBC.SetAt( countsBin,i);
emesonPtBC.SetAt(eCountsBin,i);
//printf("pt bin %d: [%2.1f,%2.1f] - Mass window [%2.2f, %2.2f] - N(pi0) BC = %2.3e +- %2.4e\n",
// i, xPtLimits[i], xPtLimits[i+1], mMinBin, mMaxBin, countsBin, eCountsBin);
}
if ( nMax > kNPairCut && chi2ndf < kChi2NDFMax )
{
if( kMix && hMix[i] )
{
// if ( !kMix ) hIM[i]->SetMinimum( 0.1);
// else hIM[i]->SetMinimum(-0.1);
hIM[i]->SetMaximum(hIM[i]->GetMaximum()*1.2);
hIM[i]->SetMinimum(hSignal[i]->GetMinimum()*0.2);
hIM[i]->Draw("HE");
pLegendIM[i]->AddEntry(hIM[i],"Raw pairs" ,"L");
if ( hMix[i]->GetEntries() > kNPairCut*3 )
{
if ( kTrunMixFunc )
{
hMixCorrected[i]->Draw("same");
pLegendIM[i]->AddEntry(hMixCorrected[i],"Mixed pairs" ,"L");
}
else
{
hMix[i]->Draw("same");
pLegendIM[i]->AddEntry(hMix[i],"Mixed pairs" ,"L");
}
}
ok = kTRUE;
hSignal[i] -> Draw("same");
pLegendIM[i]->AddEntry(hSignal[i],"Signal pairs","L");
}
else
{
ok = kTRUE;
hSignal[i]->SetMaximum(hSignal[i]->GetMaximum()*1.2);
hSignal[i]->SetMinimum(hSignal[i]->GetMinimum()*0.8);
pLegendIM[i]->AddEntry(hSignal[i],"Raw pairs","L");
hSignal[i] -> Draw("HE");
}
// Plot mass from pairs originated from pi0/eta
if ( hname.Contains("All") )
{
TH1F* hMesonPairOrigin = (TH1F*) fout->Get(Form("IM_MCpTReco_PtBin%d",i));
if ( hMesonPairOrigin )
{
hMesonPairOrigin->SetLineColor(8);
hMesonPairOrigin->Draw("same");
pLegendIM[i]->AddEntry(hMesonPairOrigin,Form("%s origin",particleN.Data()),"L");
}
} // MC origin
// if ( fitFunction )
// pLegendIM[i]->AddEntry(fitFunction,"Fit","L");
pLegendIM[i]->Draw();
}
else
{
// Plot just raw pairs
hIM[i]->Draw("HE");
}
} //pT bins
if ( ok )
cIMModi->Print(Form("IMfigures/%s_%s_Mgg_%s_%s.%s",
kProdName.Data(),kCalorimeter.Data(),kParticle.Data(),/*kFileName.Data(),*/
hname.Data(),kPlotFormat.Data()));
//xxxx Real / Mixxxxx
if(kMix)
{
//printf("Do real/mix\n");
Bool_t okR = kFALSE;
TCanvas * cRat = new TCanvas(Form("Ratio_%s\n",hname.Data()), Form("Ratio %s\n", leg.Data()), 1200, 1200) ;
cRat->Divide(col, col);
for(Int_t i = 0; i < nPt; i++)
{
cRat->cd(i+1) ;
//gPad->SetGridy();
//gPad->SetLog();
if(!hRatio[i])
{
//printf("No ratio in pt bin %d continue\n",i);
continue;
}
Double_t nMax =0;
if(kParticle=="Pi0")
nMax = hRatio[i]->Integral(hRatio[i]->FindBin(0.005),
hRatio[i]->FindBin(0.20));
else
nMax = hRatio[i]->Integral(hRatio[i]->FindBin(0.4),
hRatio[i]->FindBin(0.6));
if ( nMax <= 0 ) continue;
//printf("Ratio nMax = %e \n",nMax);
hRatio[i]->SetMaximum(nMax/4);
hRatio[i]->SetMinimum(1e-6);
hRatio[i]->SetAxisRange(mmin,mmax,"X");
okR = kTRUE;
hRatio[i]->SetYTitle("Real pairs / Mixed pairs");
hRatio[i]->SetTitleOffset(1.5,"Y");
hRatio[i]->Draw();
//if(line3[i]) line3[i]->Draw("same");
}
if ( okR )
cRat->Print(Form("IMfigures/%s_%s_MggRatio_%s_%s.%s",
kProdName.Data(),kCalorimeter.Data(),kParticle.Data(),/*kFileName.Data(),*/
hname.Data(),kPlotFormat.Data()));
} // Mix
if( !ok ) return ;
//------------------------------
// Fit parameters
//------------------------------
// Put fit results in TGraphErrors
TGraphErrors* gPt = new TGraphErrors(nPt,xPt.GetArray(),mesonPt.GetArray(),exPt.GetArray(),emesonPt.GetArray());
gPt->SetName(Form("gPt_%s",hname.Data()));
gPt->GetHistogram()->SetTitle(Form("#it{p}_{T} of reconstructed %s, %s ",particleN.Data(), comment.Data()));
gPt->GetHistogram()->SetXTitle("#it{p}_{T} (GeV/#it{c}) ");
gPt->GetHistogram()->SetYTitle(Form("dN_{%s}/d#it{p}_{T} (GeV/#it{c})^{-1} / N_{events} ",particleN.Data()));
//gPt->GetHistogram()->SetAxisRange(0.,30);
gPt->GetHistogram()->SetTitleOffset(1.5,"Y");
gPt->SetMarkerStyle(20);
//gPt->SetMarkerSize(1);
gPt->SetMarkerColor(1);
// gPt->GetHistogram()->SetMaximum(1e8);
// gPt->GetHistogram()->SetMinimum(1e-8);
TGraphErrors* gPtBC = new TGraphErrors(nPt,xPt.GetArray(),mesonPtBC.GetArray(),exPt.GetArray(),emesonPtBC.GetArray());
gPtBC->SetName(Form("gPtBC_%s",hname.Data()));
gPtBC->GetHistogram()->SetTitle(Form("#it{p}_{T} of reconstructed %s, %s ",particleN.Data(), comment.Data()));
gPtBC->GetHistogram()->SetXTitle("#it{p}_{T} (GeV/#it{c}) ");
gPtBC->GetHistogram()->SetYTitle(Form("d#it{N}_{%s}/d#it{p}_{T} (GeV/#it{c})^{-1} / #it{N}_{events} ",particleN.Data()));
//gPtBC->GetHistogram()->SetAxisRange(0.,30);
gPtBC->GetHistogram()->SetTitleOffset(1.5,"Y");
gPtBC->SetMarkerStyle(24);
//gPtBC->SetMarkerSize(1);
gPtBC->SetMarkerColor(4);
// gPtBC->GetHistogram()->SetMaximum(1e8);
// gPtBC->GetHistogram()->SetMinimum(1e-8);
TGraphErrors* gMass = new TGraphErrors(nPt,xPt.GetArray(),mesonMass.GetArray(),exPt.GetArray(),emesonMass.GetArray());
gMass->SetName(Form("gMass_%s",hname.Data()));
gMass->GetHistogram()->SetTitle(Form("mass vs #it{p}_{T} of reconstructed %s, %s ",particleN.Data(), comment.Data()));
gMass->GetHistogram()->SetXTitle("#it{p}_{T} (GeV/#it{c}) ");
gMass->GetHistogram()->SetYTitle(Form("mass_{%s} (MeV/#it{c}^{2}) ",particleN.Data()));
//gMass->GetHistogram()->SetAxisRange(0.,30);
gMass->GetHistogram()->SetTitleOffset(1.5,"Y");
gMass->SetMarkerStyle(20);
//gMass->SetMarkerSize(1);
gMass->SetMarkerColor(1);
TGraphErrors* gWidth= new TGraphErrors(nPt,xPt.GetArray(),mesonWidth.GetArray(),exPt.GetArray(),emesonWidth.GetArray());
gWidth->SetName(Form("gWidth_%s",hname.Data()));
gWidth->GetHistogram()->SetTitle(Form("Width vs #it{p}_{T} of reconstructed %s, %s ",particleN.Data(), comment.Data()));
gWidth->GetHistogram()->SetXTitle("#it{p}_{T} (GeV/#it{c}) ");
gWidth->GetHistogram()->SetYTitle(Form("#sigma_{%s} (MeV/#it{c}^{2}) ",particleN.Data()));
//gWidth->GetHistogram()->SetAxisRange(0.,30);
gWidth->GetHistogram()->SetTitleOffset(1.5,"Y");
gWidth->SetMarkerStyle(20);
//gWidth->SetMarkerSize(1);
gWidth->SetMarkerColor(1);
// Plot the fitted results
TCanvas *cFitGraph = new TCanvas(Form("cFitGraph_%s",hname.Data()),
Form("Fit Graphs for %s",hname.Data()),600,600);
cFitGraph->Divide(2, 2);
// Mass
cFitGraph->cd(1);
gPad->SetGridx();
gPad->SetGridy();
if ( kParticle=="Pi0" )
{
gMass->SetMaximum(160);
gMass->SetMinimum(100);
}
else
{
gMass->SetMaximum(660);
gMass->SetMinimum(420);
}
gMass->Draw("AP");
cFitGraph->cd(2);
gPad->SetGridx();
gPad->SetGridy();
if(kParticle=="Pi0")
{
gWidth->SetMaximum(16);
gWidth->SetMinimum(6);
}
else
{
gWidth->SetMaximum(60);
gWidth->SetMinimum(0);
}
gWidth->Draw("AP");
cFitGraph->cd(3);
gPad->SetGridx();
gPad->SetGridy();
gPad->SetLogy();
gPt->Draw("AP");
Double_t maximum = gPt->GetHistogram()->GetMaximum();
Double_t minimum = gPt->GetHistogram()->GetMinimum();
//printf("A-maximum %e, minimum %e\n",maximum,minimum);
// Double_t maximum = gPrim->GetHistogram()->GetMaximum();
// Double_t minimum = gPrim->GetHistogram()->GetMinimum();
//
// if ( gPrimAcc->GetMaximum() > maximum ) maximum = gPrimAcc->GetMaximum() ;
// if ( gPrimAcc->GetMinimum() > minimum ) minimum = gPrimAcc->GetMinimum() ;
//
// gPrim->SetMaximum(maximum*10);
// gPrim->SetMinimum(minimum/10);
if(kMix)
{
gPtBC ->Draw("P");
if(maximum < gPtBC->GetHistogram()->GetMaximum()) maximum = gPtBC->GetHistogram()->GetMaximum();
if(minimum > gPtBC->GetHistogram()->GetMinimum()) minimum = gPtBC->GetHistogram()->GetMaximum();
//printf("B-maximum %e, minimum %e\n",maximum,minimum);
if(minimum < 0 ) minimum = 2.e-9 ;
gPtBC->SetMaximum(maximum*2.);
gPtBC->SetMinimum(minimum/2.);
TLegend * legend = new TLegend(0.5,0.7,0.9,0.9);
legend->AddEntry(gPt ,"From fit","P");
legend->AddEntry(gPtBC,"From bin counting","P");
legend->Draw();
}
gPt->SetMaximum(maximum*2.);
gPt->SetMinimum(minimum/2.);
cFitGraph->Print(Form("IMfigures/%s_%s_MassWidthPtSpectra_%s_%s.%s",
kProdName.Data(),kCalorimeter.Data(),kParticle.Data(),hname.Data(),
/*kFileName.Data(),*/ kPlotFormat.Data()));
//-----------------------
// Write results to file
//-----------------------
hRe->Write();
if ( hMi ) hMi->Write();
for(Int_t ipt = 0; ipt < nPt; ipt++)
{
if ( hIM[ipt] ) hIM[ipt]->Write();
if ( kMix )
{
if (hMix [ipt] ) hMix [ipt]->Write();
if (hMixCorrected[ipt] ) hMixCorrected[ipt]->Write();
if (hRatio [ipt] ) hRatio [ipt]->Write();
if (hSignal [ipt] ) hSignal [ipt]->Write();
}
}
gPt ->Write();
gMass ->Write();
gWidth->Write();
if ( kMix ) gPtBC->Write();
// Do some final efficiency calculations if MC
Efficiency(nPt, xPt, exPt, mesonPt, emesonPt, mesonPtBC, emesonPtBC, hname);
}
///
/// Plot combinations of graphs with fit results
/// SM/Sector/Side/SM group by SM/Sector/Side/SM group comparisons
///
//-----------------------------------------------------------------------------
void PlotGraphs(TString opt, Int_t first, Int_t last)
{
gStyle->SetOptTitle(1);
gStyle->SetTitleOffset(2,"Y");
gStyle->SetOptStat(0);
gStyle->SetOptFit(000000);
const Int_t nCombi = last-first+1;
Int_t nCombiActive = 0;
Float_t xmin = 0.7;
Float_t ymin = 0.3;
Float_t xmax = 0.9;
Float_t ymax = 0.9;
if(opt.Contains("Group"))
{
xmin = 0.3;
ymin = 0.7;
}
if(opt.Contains("Sector"))
{
xmin = 0.65;
ymin = 0.5;
}
TLegend * legend = new TLegend(xmin,ymin,xmax,ymax);
legend->SetTextSize(0.05);
TString particleN = " #pi^{0}";
if(kParticle=="Eta") particleN = " #eta";
// recover the graphs from output file
//printf("%s\n",opt.Data());
// Recover SUM
TString opt2 = opt;
if(opt.Contains("SMGroup")) opt2 = "SM";
TGraphErrors* gSumPt = (TGraphErrors*) fout->Get(Form("gPt_Same%s" ,opt2.Data()));
TGraphErrors* gSumPtBC = (TGraphErrors*) fout->Get(Form("gPtBC_Same%s" ,opt2.Data()));
TGraphErrors* gSumMass = (TGraphErrors*) fout->Get(Form("gMass_Same%s" ,opt2.Data()));
TGraphErrors* gSumWidth = (TGraphErrors*) fout->Get(Form("gWidth_Same%s",opt2.Data()));
//printf("\t Sum %p %p %p %p\n",gSumPt,gSumPtBC,gSumMass,gSumWidth);
if ( !gSumMass ) return ;
gSumPt ->SetMarkerStyle(20);
gSumPt ->SetMarkerColor(1);
gSumPt ->SetLineColor (1);
gSumMass->SetMarkerStyle(20);
gSumMass->SetMarkerColor(1);
gSumMass->SetLineColor (1);
gSumWidth->SetMarkerStyle(20);
gSumWidth->SetMarkerColor(1);
gSumWidth->SetLineColor (1);
if ( kMix )
{
gSumPtBC ->SetMarkerStyle(20);
gSumPtBC ->SetMarkerColor(1);
gSumPtBC ->SetLineColor (1);
}
legend->AddEntry(gSumPt,"Sum","P");
// Normalize to total number of SMs/Sectors/Sides
if ( opt != "SMGroup" )
{
for (Int_t ibin = 0; ibin < gSumPt->GetN(); ibin++)
{
gSumPt->GetY ()[ibin] /= nCombi;
gSumPt->GetEY()[ibin] /= nCombi;
if ( kMix )
{
gSumPtBC->GetY ()[ibin] /= nCombi;
gSumPtBC->GetEY()[ibin] /= nCombi;
}
}
}
TGraphErrors* gSumTRDnotPt = 0;
TGraphErrors* gSumTRDnotPtBC = 0;
TGraphErrors* gSumTRDnotMass = 0;
TGraphErrors* gSumTRDnotWidth = 0;
TGraphErrors* gSumTRDyesPt = 0;
TGraphErrors* gSumTRDyesPtBC = 0;
TGraphErrors* gSumTRDyesMass = 0;
TGraphErrors* gSumTRDyesWidth = 0;
//
//// TRD covered
//
if ( kFirstTRDSM > 0 && opt == "SM" ) // it could be extended to sector/side
{
gSumTRDnotPt = (TGraphErrors*) fout->Get(Form("gPt_Same%sTRDNot" ,opt2.Data()));
gSumTRDnotPtBC = (TGraphErrors*) fout->Get(Form("gPtBC_Same%sTRDNot" ,opt2.Data()));
gSumTRDnotMass = (TGraphErrors*) fout->Get(Form("gMass_Same%sTRDNot" ,opt2.Data()));
gSumTRDnotWidth = (TGraphErrors*) fout->Get(Form("gWidth_Same%sTRDNot",opt2.Data()));
printf("\t Sum Not TRD %p %p %p %p\n",gSumTRDnotPt,gSumTRDnotPtBC,gSumTRDnotMass,gSumTRDnotWidth);
gSumTRDnotPt ->SetMarkerStyle(20);
gSumTRDnotPt ->SetMarkerColor(kGray);
gSumTRDnotPt ->SetLineColor (kGray);
gSumTRDnotMass->SetMarkerStyle(20);
gSumTRDnotMass->SetMarkerColor(kGray);
gSumTRDnotMass->SetLineColor (kGray);
gSumTRDnotWidth->SetMarkerStyle(20);
gSumTRDnotWidth->SetMarkerColor(kGray);
gSumTRDnotWidth->SetLineColor (kGray);
if ( kMix )
{
gSumTRDnotPtBC ->SetMarkerStyle(20);
gSumTRDnotPtBC ->SetMarkerColor(kGray);
gSumTRDnotPtBC ->SetLineColor (kGray);
}
legend->AddEntry(gSumTRDnotPt,"w/o TRD","P");
for (Int_t ibin = 0; ibin < gSumPt->GetN(); ibin++)
{
gSumTRDnotPt->GetY ()[ibin] /= kFirstTRDSM;
gSumTRDnotPt->GetEY()[ibin] /= kFirstTRDSM;
if ( kMix )
{
gSumTRDnotPtBC->GetY ()[ibin] /= kFirstTRDSM;
gSumTRDnotPtBC->GetEY()[ibin] /= kFirstTRDSM;
}
}
gSumTRDyesPt = (TGraphErrors*) fout->Get(Form("gPt_Same%sTRDYes" ,opt2.Data()));
gSumTRDyesPtBC = (TGraphErrors*) fout->Get(Form("gPtBC_Same%sTRDYes" ,opt2.Data()));
gSumTRDyesMass = (TGraphErrors*) fout->Get(Form("gMass_Same%sTRDYes" ,opt2.Data()));
gSumTRDyesWidth = (TGraphErrors*) fout->Get(Form("gWidth_Same%sTRDYes",opt2.Data()));
printf("\t Sum Yes TRD %p %p %p %p\n",gSumTRDyesPt,gSumTRDyesPtBC,gSumTRDyesMass,gSumTRDyesWidth);
gSumTRDyesPt ->SetMarkerStyle(20);
gSumTRDyesPt ->SetMarkerColor(kCyan);
gSumTRDyesPt ->SetLineColor (kCyan);
gSumTRDyesMass->SetMarkerStyle(20);
gSumTRDyesMass->SetMarkerColor(kCyan);
gSumTRDyesMass->SetLineColor (kCyan);
gSumTRDyesWidth->SetMarkerStyle(20);
gSumTRDyesWidth->SetMarkerColor(kCyan);
gSumTRDyesWidth->SetLineColor (kCyan);
if ( kMix )
{
gSumTRDyesPtBC ->SetMarkerStyle(20);
gSumTRDyesPtBC ->SetMarkerColor(kCyan);
gSumTRDyesPtBC ->SetLineColor (kCyan);
}
legend->AddEntry(gSumTRDyesPt,"w/ TRD","P");
Int_t nCovered = 10-kFirstTRDSM;
for (Int_t ibin = 0; ibin < gSumPt->GetN(); ibin++)
{
gSumTRDyesPt->GetY ()[ibin] /= nCovered;
gSumTRDyesPt->GetEY()[ibin] /= nCovered;
if ( kMix )
{
gSumTRDyesPtBC->GetY ()[ibin] /= nCovered;
gSumTRDyesPtBC->GetEY()[ibin] /= nCovered;
}
}
} // TRD
//
// Get different combinations
//
TGraphErrors* gPt [nCombi];
TGraphErrors* gPtBC [nCombi];
TGraphErrors* gMass [nCombi];
TGraphErrors* gWidth[nCombi];
for(Int_t icomb = 0; icomb < nCombi; icomb ++)
{
gPt [icomb] = (TGraphErrors*) fout->Get(Form("gPt_%s%d" ,opt.Data(),icomb+first));
gPtBC [icomb] = (TGraphErrors*) fout->Get(Form("gPtBC_%s%d" ,opt.Data(),icomb+first));
gMass [icomb] = (TGraphErrors*) fout->Get(Form("gMass_%s%d" ,opt.Data(),icomb+first));
gWidth[icomb] = (TGraphErrors*) fout->Get(Form("gWidth_%s%d",opt.Data(),icomb+first));
//printf("\t %d %p %p %p %p\n",icomb,gPt[icomb],gPtBC[icomb],gMass[icomb],gWidth[icomb]);
if ( !gPt[icomb] ) continue ;
nCombiActive++;
gPt [icomb]->SetMarkerStyle(modStyleIndex[icomb]);
gPt [icomb]->SetMarkerColor(modColorIndex[icomb]);
gPt [icomb]->SetLineColor (modColorIndex[icomb]);
gMass[icomb]->SetMarkerStyle(modStyleIndex[icomb]);
gMass[icomb]->SetMarkerColor(modColorIndex[icomb]);
gMass[icomb]->SetLineColor (modColorIndex[icomb]);
gWidth[icomb]->SetMarkerStyle(modStyleIndex[icomb]);
gWidth[icomb]->SetMarkerColor(modColorIndex[icomb]);
gWidth[icomb]->SetLineColor (modColorIndex[icomb]);
gPt [icomb]->GetHistogram()->SetTitle(Form("#it{p}_{T} of %s from fit, %s " ,particleN.Data(), opt.Data()));
gWidth[icomb]->GetHistogram()->SetTitle(Form("%s mass #sigma vs #it{p}_{T}, %s ",particleN.Data(), opt.Data()));
gMass [icomb]->GetHistogram()->SetTitle(Form("%s mass #mu vs #it{p}_{T}, %s " ,particleN.Data(), opt.Data()));
if ( kMix )
{
gPtBC [icomb]->SetMarkerStyle(modStyleIndex[icomb]);
gPtBC [icomb]->SetMarkerColor(modColorIndex[icomb]);
gPtBC [icomb]->SetLineColor (modColorIndex[icomb]);
gPtBC [icomb]->GetHistogram()->SetTitle(Form("#it{p}_{T} of %s bin counted, %s ",particleN.Data(), opt.Data()));
}
if ( !opt.Contains("Group") )
legend->AddEntry(gPt[icomb],Form("%s %d",opt.Data(),icomb),"P");
else
{
if(icomb == 0) legend->AddEntry(gPt[icomb],"SM0+4+5+6+7+8+9","P");
if(icomb == 1) legend->AddEntry(gPt[icomb],"SM1+2","P");
if(icomb == 2) legend->AddEntry(gPt[icomb],"SM3+7","P");
}
}
if ( !gMass[0] ) return ;
//
// PLOT
//
TCanvas *cFitGraph = new TCanvas(Form("cFitGraph_%sCombinations",opt.Data()),
Form("Fit Graphs for %s combinations",opt.Data()),1000,1000);
cFitGraph->Divide(2, 2);
// Mass
cFitGraph->cd(1);
gPad->SetGridx();
gPad->SetGridy();
if ( kParticle == "Pi0" )
{
gMass[0]->SetMaximum(141);
gMass[0]->SetMinimum(116);
}
else
{
gMass[0]->SetMaximum(600);
gMass[0]->SetMinimum(450);
}
gMass[0]->Draw("AP");
for(Int_t icomb = 1; icomb < nCombi; icomb ++)
{
if ( gMass[icomb] ) gMass[icomb]->Draw("P");
}
gSumMass->Draw("P");
if ( kFirstTRDSM > 0 && opt == "SM" )
{
gSumTRDnotMass->Draw("P");
gSumTRDyesMass->Draw("P");
}
legend->Draw();
cFitGraph->cd(2);
gPad->SetGridx();
gPad->SetGridy();
if ( kParticle == "Pi0" )
{
gWidth[0]->SetMaximum(17);
gWidth[0]->SetMinimum(7);
if(opt=="Side") gWidth[0]->SetMinimum(2);
}
else
{
gWidth[0]->SetMaximum(50);
gWidth[0]->SetMinimum(10);
}
gWidth[0]->Draw("AP");
for(Int_t icomb = 1; icomb < nCombi; icomb ++)
{
if ( gWidth[icomb] ) gWidth[icomb]->Draw("P");
}
gSumWidth->Draw("P");
if ( kFirstTRDSM > 0 && opt == "SM" )
{
gSumTRDnotWidth->Draw("P");
gSumTRDyesWidth->Draw("P");
}
legend->Draw();
cFitGraph->cd(3);
gPad->SetGridx();
gPad->SetGridy();
gPad->SetLogy();
gPt[0]->SetMaximum(1);
gPt[0]->SetMinimum(1e-8);
gPt[0]->Draw("AP");
for(Int_t icomb = 1; icomb < nCombi; icomb ++)
{
if ( gPt[icomb] ) gPt[icomb]->Draw("P");
}
gSumPt->Draw("P");
if ( kFirstTRDSM > 0 && opt == "SM" )
{
gSumTRDnotPt->Draw("P");
gSumTRDyesPt->Draw("P");
}
legend->Draw();
if ( kMix )
{
cFitGraph->cd(4);
gPad->SetGridx();
gPad->SetGridy();
gPad->SetLogy();
gPtBC[0]->SetMaximum(1);
gPtBC[0]->SetMinimum(1e-8);
gPtBC[0]->Draw("AP");
for(Int_t icomb = 1; icomb < nCombi; icomb ++)
{
if ( gPtBC[icomb] ) gPtBC[icomb]->Draw("P");
}
gSumPtBC->Draw("P");
if ( kFirstTRDSM > 0 && opt == "SM" )
{
gSumTRDnotPtBC->Draw("P");
gSumTRDyesPtBC->Draw("P");
}
legend->Draw();
}
cFitGraph->Print(Form("IMfigures/%s_%s_MassWidthPtSpectra_%s_%sCombinations.%s",
kProdName.Data(),kCalorimeter.Data(),kParticle.Data(),opt.Data(),
/*kFileName.Data(),*/kPlotFormat.Data()));
//
// Calculate the ratio to the sum
//
TGraphErrors* gRatPt [nCombi];
TGraphErrors* gRatPtBC [nCombi];
TGraphErrors* gRatMass [nCombi];
TGraphErrors* gRatWidth[nCombi];
TLegend * legendR = new TLegend(xmin,ymin,xmax,ymax);
legendR->SetTextSize(0.05);
for(Int_t icomb = 0; icomb < nCombi; icomb ++)
{
//printf("icomb %d\n",icomb);
//printf("\t pt %p %p\n",gPt[icomb],gSumPt);
gRatPt [icomb] = DivideGraphs(gPt [icomb],gSumPt ); // PlotUtils.C
//printf("\t ptBC %p %p\n",gPtBC[icomb],gSumPtBC);
gRatPtBC [icomb] = DivideGraphs(gPtBC [icomb],gSumPtBC ); // PlotUtils.C
//printf("\t pt %p %p\n",gMass[icomb],gSumMass);
gRatMass [icomb] = DivideGraphs(gMass [icomb],gSumMass ); // PlotUtils.C
//printf("\t pt %p %p\n",gWidth[icomb],gSumWidth);
gRatWidth[icomb] = DivideGraphs(gWidth[icomb],gSumWidth); // PlotUtils.C
if(!gRatMass[icomb]) continue;
gRatPt [icomb]->SetMarkerStyle(modStyleIndex[icomb]);
gRatPt [icomb]->SetMarkerColor(modColorIndex[icomb]);
gRatPt [icomb]->SetLineColor (modColorIndex[icomb]);
gRatMass[icomb]->SetMarkerStyle(modStyleIndex[icomb]);
gRatMass[icomb]->SetMarkerColor(modColorIndex[icomb]);
gRatMass[icomb]->SetLineColor (modColorIndex[icomb]);
gRatWidth[icomb]->SetMarkerStyle(modStyleIndex[icomb]);
gRatWidth[icomb]->SetMarkerColor(modColorIndex[icomb]);
gRatWidth[icomb]->SetLineColor (modColorIndex[icomb]);
gRatPt [icomb]->GetHistogram()->SetTitle(Form("#it{p}_{T} of %s from fit, %s " ,particleN.Data(), opt.Data()));
gRatWidth[icomb]->GetHistogram()->SetTitle(Form("%s mass #sigma vs #it{p}_{T}, %s ",particleN.Data(), opt.Data()));
gRatMass [icomb]->GetHistogram()->SetTitle(Form("%s mass #mu vs #it{p}_{T}, %s " ,particleN.Data(), opt.Data()));
gRatPt [icomb]->GetHistogram()->SetYTitle("Ratio to sum");
gRatWidth[icomb]->GetHistogram()->SetYTitle("Ratio to sum");
gRatMass [icomb]->GetHistogram()->SetYTitle("Ratio to sum");
gRatPt [icomb]->GetHistogram()->SetXTitle("#it{p}_{T} (GeV/#it{c})");
gRatWidth[icomb]->GetHistogram()->SetXTitle("#it{p}_{T} (GeV/#it{c})");
gRatMass [icomb]->GetHistogram()->SetXTitle("#it{p}_{T} (GeV/#it{c})");
gRatPt [icomb]->GetHistogram()->SetTitleOffset(1.4,"Y");
gRatWidth[icomb]->GetHistogram()->SetTitleOffset(1.4,"Y");
gRatMass [icomb]->GetHistogram()->SetTitleOffset(1.4,"Y");
if ( kMix )
{
gRatPtBC [icomb]->SetMarkerStyle(modStyleIndex[icomb]);
gRatPtBC [icomb]->SetMarkerColor(modColorIndex[icomb]);
gRatPtBC [icomb]->SetLineColor (modColorIndex[icomb]);
gRatPtBC [icomb]->GetHistogram()->SetTitle(Form("#it{p}_{T} of %s bin counted, %s ",particleN.Data(), opt.Data()));
gRatPtBC [icomb]->GetHistogram()->SetYTitle("Ratio to sum");
gRatPtBC [icomb]->GetHistogram()->SetXTitle("#it{p}_{T} (GeV/#it{c})");
gRatPtBC [icomb]->GetHistogram()->SetTitleOffset(1.5,"Y");
}
if ( !opt.Contains("Group") )
legendR->AddEntry(gPt[icomb],Form("%s %d",opt.Data(),icomb),"P");
else
{
if(icomb == 0) legendR->AddEntry(gPt[icomb],"SM0+4+5+6+7+8+9","P");
if(icomb == 1) legendR->AddEntry(gPt[icomb],"SM1+2","P");
if(icomb == 2) legendR->AddEntry(gPt[icomb],"SM3+7","P");
}
} // combi loop
//
// PLOT
//
TCanvas *cFitGraphRatio = new TCanvas(Form("cFitGraphSumRatio_%sCombinations",opt.Data()),
Form("Fit Graphs ratio to sum for %s combinations",opt.Data()),1000,1000);
cFitGraphRatio->Divide(2, 2);
// Mass
cFitGraphRatio->cd(1);
gPad->SetGridx();
gPad->SetGridy();
gRatMass[0]->SetMaximum(1.03);
gRatMass[0]->SetMinimum(0.97);
gRatMass[0]->Draw("AP");
for(Int_t icomb = 1; icomb < nCombi; icomb ++)
{
if ( gRatMass[icomb] ) gRatMass[icomb]->Draw("P");
}
legendR->Draw();
cFitGraphRatio->cd(2);
gPad->SetGridx();
gPad->SetGridy();
gRatWidth[0]->SetMaximum(1.5);
gRatWidth[0]->SetMinimum(0.7);
gRatWidth[0]->Draw("AP");
for(Int_t icomb = 1; icomb < nCombi; icomb ++)
{
if ( gRatWidth[icomb] ) gRatWidth[icomb]->Draw("P");
}
legendR->Draw();
cFitGraphRatio->cd(3);
gPad->SetGridx();
gPad->SetGridy();
// gPad->SetLogy();
gRatPt[0]->SetMaximum(2);
gRatPt[0]->SetMinimum(0);
gRatPt[0]->Draw("AP");
for(Int_t icomb = 1; icomb < nCombi; icomb ++)
{
if ( gRatPt[icomb] ) gRatPt[icomb]->Draw("P");
}
legendR->Draw();
if ( kMix )
{
cFitGraphRatio->cd(4);
gPad->SetGridx();
gPad->SetGridy();
// gPad->SetLogy();
gRatPtBC[0]->SetMaximum(2);
gRatPtBC[0]->SetMinimum(0);
gRatPtBC[0]->Draw("AP");
for(Int_t icomb = 1; icomb < nCombi; icomb ++)
{
if ( gRatPtBC[icomb] ) gRatPtBC[icomb]->Draw("P");
}
legendR->Draw();
}
cFitGraphRatio->Print(Form("IMfigures/%s_%s_MassWidthPtSpectra_%s_%sCombinations_RatioToSum.%s",
kProdName.Data(),kCalorimeter.Data(),kParticle.Data(),opt.Data(),
/*kFileName.Data(),*/kPlotFormat.Data()));
// Ratio to corresponding TRD case
if ( kFirstTRDSM > 0 && opt == "SM" ) // it could be extended for Sector/Side
{
//
// Calculate the ratio to the sum
//
TGraphErrors* gRatTRDPt [nCombi];
TGraphErrors* gRatTRDPtBC [nCombi];
TGraphErrors* gRatTRDMass [nCombi];
TGraphErrors* gRatTRDWidth[nCombi];
TLegend * legendR = new TLegend(xmin,ymin,xmax,ymax);
legendR->SetTextSize(0.05);
for(Int_t icomb = 0; icomb < nCombi; icomb ++)
{
//printf("icomb %d\n",icomb);
//printf("\t pt %p %p\n",gPt[icomb],gSumPt);
if(icomb < kFirstTRDSM)
{
gRatTRDPt [icomb] = DivideGraphs(gPt [icomb],gSumTRDnotPt ); // PlotUtils.C
gRatTRDPtBC [icomb] = DivideGraphs(gPtBC [icomb],gSumTRDnotPtBC ); // PlotUtils.C
gRatTRDMass [icomb] = DivideGraphs(gMass [icomb],gSumTRDnotMass ); // PlotUtils.C
gRatTRDWidth[icomb] = DivideGraphs(gWidth[icomb],gSumTRDnotWidth); // PlotUtils.C
}
else
{
gRatTRDPt [icomb] = DivideGraphs(gPt [icomb],gSumTRDyesPt ); // PlotUtils.C
gRatTRDPtBC [icomb] = DivideGraphs(gPtBC [icomb],gSumTRDyesPtBC ); // PlotUtils.C
gRatTRDMass [icomb] = DivideGraphs(gMass [icomb],gSumTRDyesMass ); // PlotUtils.C
gRatTRDWidth[icomb] = DivideGraphs(gWidth[icomb],gSumTRDyesWidth); // PlotUtils.C
}
if(!gRatTRDMass[icomb]) continue;
gRatTRDPt [icomb]->SetMarkerStyle(modStyleIndex[icomb]);
gRatTRDPt [icomb]->SetMarkerColor(modColorIndex[icomb]);
gRatTRDPt [icomb]->SetLineColor (modColorIndex[icomb]);
gRatTRDMass[icomb]->SetMarkerStyle(modStyleIndex[icomb]);
gRatTRDMass[icomb]->SetMarkerColor(modColorIndex[icomb]);
gRatTRDMass[icomb]->SetLineColor (modColorIndex[icomb]);
gRatTRDWidth[icomb]->SetMarkerStyle(modStyleIndex[icomb]);
gRatTRDWidth[icomb]->SetMarkerColor(modColorIndex[icomb]);
gRatTRDWidth[icomb]->SetLineColor (modColorIndex[icomb]);
gRatTRDPt [icomb]->GetHistogram()->SetTitle(Form("#it{p}_{T} of %s from fit, %s " ,particleN.Data(), opt.Data()));
gRatTRDWidth[icomb]->GetHistogram()->SetTitle(Form("%s mass #sigma vs #it{p}_{T}, %s ",particleN.Data(), opt.Data()));
gRatTRDMass [icomb]->GetHistogram()->SetTitle(Form("%s mass #mu vs #it{p}_{T}, %s " ,particleN.Data(), opt.Data()));
gRatTRDPt [icomb]->GetHistogram()->SetYTitle("Ratio to sum");
gRatTRDWidth[icomb]->GetHistogram()->SetYTitle("Ratio to sum");
gRatTRDMass [icomb]->GetHistogram()->SetYTitle("Ratio to sum");
gRatTRDPt [icomb]->GetHistogram()->SetXTitle("#it{p}_{T} (GeV/#it{c})");
gRatTRDWidth[icomb]->GetHistogram()->SetXTitle("#it{p}_{T} (GeV/#it{c})");
gRatTRDMass [icomb]->GetHistogram()->SetXTitle("#it{p}_{T} (GeV/#it{c})");
gRatTRDPt [icomb]->GetHistogram()->SetTitleOffset(1.4,"Y");
gRatTRDWidth[icomb]->GetHistogram()->SetTitleOffset(1.4,"Y");
gRatTRDMass [icomb]->GetHistogram()->SetTitleOffset(1.4,"Y");
if ( kMix )
{
gRatTRDPtBC [icomb]->SetMarkerStyle(modStyleIndex[icomb]);
gRatTRDPtBC [icomb]->SetMarkerColor(modColorIndex[icomb]);
gRatTRDPtBC [icomb]->SetLineColor (modColorIndex[icomb]);
gRatTRDPtBC [icomb]->GetHistogram()->SetTitle(Form("#it{p}_{T} of %s bin counted, %s ",particleN.Data(), opt.Data()));
gRatTRDPtBC [icomb]->GetHistogram()->SetYTitle("Ratio to sum");
gRatTRDPtBC [icomb]->GetHistogram()->SetXTitle("#it{p}_{T} (GeV/#it{c})");
gRatTRDPtBC [icomb]->GetHistogram()->SetTitleOffset(1.5,"Y");
}
if ( !opt.Contains("Group") )
legendR->AddEntry(gPt[icomb],Form("%s %d",opt.Data(),icomb),"P");
else
{
if(icomb == 0) legendR->AddEntry(gPt[icomb],"SM0+4+5+6+7+8+9","P");
if(icomb == 1) legendR->AddEntry(gPt[icomb],"SM1+2","P");
if(icomb == 2) legendR->AddEntry(gPt[icomb],"SM3+7","P");
}
} // combi loop
//
// PLOT
//
TCanvas *cFitGraphRatioTRD = new TCanvas(Form("cFitGraphSumRatioTRD_%sCombinations",opt.Data()),
Form("Fit Graphs ratio to sum for %s combinations for TRD cases",opt.Data()),1000,1000);
cFitGraphRatioTRD->Divide(2, 2);
// Mass
cFitGraphRatioTRD->cd(1);
gPad->SetGridx();
gPad->SetGridy();
gRatTRDMass[0]->SetMaximum(1.03);
gRatTRDMass[0]->SetMinimum(0.97);
gRatTRDMass[0]->Draw("AP");
for(Int_t icomb = 1; icomb < nCombi; icomb ++)
{
if ( gRatTRDMass[icomb] ) gRatTRDMass[icomb]->Draw("P");
}
legendR->Draw();
cFitGraphRatioTRD->cd(2);
gPad->SetGridx();
gPad->SetGridy();
gRatTRDWidth[0]->SetMaximum(1.5);
gRatTRDWidth[0]->SetMinimum(0.7);
gRatTRDWidth[0]->Draw("AP");
for(Int_t icomb = 1; icomb < nCombi; icomb ++)
{
if ( gRatTRDWidth[icomb] ) gRatTRDWidth[icomb]->Draw("P");
}
legendR->Draw();
cFitGraphRatioTRD->cd(3);
gPad->SetGridx();
gPad->SetGridy();
// gPad->SetLogy();
gRatTRDPt[0]->SetMaximum(2);
gRatTRDPt[0]->SetMinimum(0);
gRatTRDPt[0]->Draw("AP");
for(Int_t icomb = 1; icomb < nCombi; icomb ++)
{
if ( gRatTRDPt[icomb] ) gRatTRDPt[icomb]->Draw("P");
}
legendR->Draw();
if ( kMix )
{
cFitGraphRatioTRD->cd(4);
gPad->SetGridx();
gPad->SetGridy();
// gPad->SetLogy();
gRatTRDPtBC[0]->SetMaximum(2);
gRatTRDPtBC[0]->SetMinimum(0);
gRatTRDPtBC[0]->Draw("AP");
for(Int_t icomb = 1; icomb < nCombi; icomb ++)
{
if ( gRatTRDPtBC[icomb] ) gRatTRDPtBC[icomb]->Draw("P");
}
legendR->Draw();
}
cFitGraphRatioTRD->Print(Form("IMfigures/%s_%s_MassWidthPtSpectra_%s_%sCombinations_RatioToSumTRD.%s",
kProdName.Data(),kCalorimeter.Data(),kParticle.Data(),opt.Data(),
/*kFileName.Data(),*/kPlotFormat.Data()));
TLegend * legendSums = new TLegend(xmin,ymin,xmax,ymax);
//
// PLOT
//
TCanvas *cFitGraphSums = new TCanvas(Form("cFitGraph_%sSums",opt.Data()),
Form("Fit Graphs for %s Sums",opt.Data()),1000,1000);
cFitGraphSums->Divide(2, 2);
// Mass
cFitGraphSums->cd(1);
gPad->SetGridx();
gPad->SetGridy();
if ( kParticle == "Pi0" )
{
gSumMass->SetMaximum(135);
gSumMass->SetMinimum(125);
}
else
{
gSumMass->SetMaximum(560);
gSumMass->SetMinimum(520);
}
gSumMass->Draw("AP");
gSumTRDnotMass->Draw("P");
gSumTRDyesMass->Draw("P");
legendSums->AddEntry(gSumMass,"Sum","P");
legendSums->AddEntry(gSumTRDnotMass,"w/o TRD","P");
legendSums->AddEntry(gSumTRDyesMass,"w/ TRD","P");
legendSums->Draw();
cFitGraphSums->cd(2);
gPad->SetGridx();
gPad->SetGridy();
if ( kParticle == "Pi0" )
{
gSumWidth->SetMaximum(17);
gSumWidth->SetMinimum(7);
if(opt=="Side") gSumWidth->SetMinimum(2);
}
else
{
gSumWidth->SetMaximum(50);
gSumWidth->SetMinimum(10);
}
gSumWidth->Draw("AP");
gSumTRDnotWidth->Draw("P");
gSumTRDyesWidth->Draw("P");
legendSums->Draw();
cFitGraphSums->cd(3);
gPad->SetGridx();
gPad->SetGridy();
gPad->SetLogy();
gSumPt->SetMaximum(1);
gSumPt->SetMinimum(1e-8);
gSumPt->Draw("AP");
gSumTRDnotPt->Draw("P");
gSumTRDyesPt->Draw("P");
legendSums->Draw();
if ( kMix )
{
cFitGraphSums->cd(4);
gPad->SetGridx();
gPad->SetGridy();
gPad->SetLogy();
gSumPtBC->SetMaximum(1);
gSumPtBC->SetMinimum(1e-8);
gSumPtBC->Draw("AP");
gSumTRDnotPtBC->Draw("P");
gSumTRDyesPtBC->Draw("P");
legend->Draw();
}
cFitGraphSums->Print(Form("IMfigures/%s_%s_MassWidthPtSpectra_%s_%sSums.%s",
kProdName.Data(),kCalorimeter.Data(),kParticle.Data(),opt.Data(),
/*kFileName.Data(),*/kPlotFormat.Data()));
}
}
///
/// Get primary generated spectra and detector acceptance
/// Plot them
///
//-----------------------------------------------------------------------------
void PrimarySpectra(Int_t nPt, TArrayD xPtLimits, TArrayD xPt, TArrayD exPt)
{
gStyle->SetOptTitle(1);
gStyle->SetTitleOffset(2,"Y");
gStyle->SetOptStat(0);
gStyle->SetOptFit(000000);
TArrayD primMesonPt ; primMesonPt .Set(nPt);
TArrayD eprimMesonPt ; eprimMesonPt .Set(nPt);
TArrayD primMesonPtAcc; primMesonPtAcc.Set(nPt);
TArrayD eprimMesonPtAcc; eprimMesonPtAcc.Set(nPt);
TArrayD primMesonAcc ; primMesonAcc.Set(nPt);
TArrayD eprimMesonAcc ; eprimMesonAcc.Set(nPt);
TH2D* h2PrimMesonPtY = (TH2D*) fil->Get( Form("%s_hPrim%sRapidity" ,kHistoStartName.Data(), kParticle.Data() ) );
TH2D* h2PrimMesonPtYAcc = (TH2D*) fil->Get( Form("%s_hPrim%sAccRapidity",kHistoStartName.Data(), kParticle.Data() ) );
if ( !h2PrimMesonPtY ) return ;
if(kSumw2)
{
h2PrimMesonPtY ->Sumw2();
h2PrimMesonPtYAcc->Sumw2();
}
// if ( nEvt < 1 )
// {
// h2PrimMesonPtY ->Scale(1e10);
// h2PrimMesonPtYAcc->Scale(1e10);
// }
// else
{
h2PrimMesonPtY ->Scale(1./nEvt);
h2PrimMesonPtYAcc->Scale(1./nEvt);
}
h2PrimMesonPtY ->Write();
h2PrimMesonPtYAcc->Write();
TH1D* hY = h2PrimMesonPtY->ProjectionY("Rapidity",-1,-1);
Int_t binYmin = hY->FindBin(-0.65);
Int_t binYmax = hY->FindBin(+0.65);
//printf("Y bin min %d, max %d\n",binYmin,binYmax);
TH1D* hPrimMesonPt = (TH1D*) h2PrimMesonPtY->ProjectionX("PrimaryPt" ,binYmin ,binYmax );
hPrimMesonPt->Write();
TH1D* hYAcc = h2PrimMesonPtYAcc->ProjectionY("RapidityAcc",-1,-1);
binYmin = hYAcc->FindBin(-0.65);
binYmax = hYAcc->FindBin(+0.65);
//printf("Y bin min %d, max %d\n",binYmin,binYmax);
TH1D* hPrimMesonPtAcc = (TH1D*) h2PrimMesonPtYAcc->ProjectionX("PrimaryPtAccepted" ,binYmin ,binYmax );
hPrimMesonPtAcc->Write();
// PlotUtils.C
ScaleBinBySize(hPrimMesonPt);
ScaleBinBySize(hPrimMesonPtAcc);
Double_t integralA = 0;
Double_t integralAErr = 0;
Double_t integralB = 0;
Double_t integralBErr = 0;
Double_t ptMin = -1;
Double_t ptMax = -1;
Int_t binMin= -1;
Int_t binMax= -1;
for(Int_t ibin = 0; ibin < nPt; ibin++ )
{
ptMin = xPtLimits[ibin];
ptMax = xPtLimits[ibin+1];
binMin = hPrimMesonPt->FindBin(ptMin);
binMax = hPrimMesonPt->FindBin(ptMax)-1;
// PlotUtils.C
GetRangeIntegralAndError(hPrimMesonPt , binMin, binMax, integralA, integralAErr );
GetRangeIntegralAndError(hPrimMesonPtAcc, binMin, binMax, integralB, integralBErr );
primMesonPt [ibin] = integralA;
eprimMesonPt [ibin] = integralAErr;
primMesonPtAcc[ibin] = integralB;
eprimMesonPtAcc[ibin] = integralBErr;
if ( integralA > 0 && integralB > 0 )
{
primMesonAcc[ibin] = integralB / integralA ;
eprimMesonAcc[ibin] = GetFractionError(integralB,integralA,integralBErr,integralAErr); // PlotUtils.C
}
else
{
primMesonAcc[ibin] = 0;
eprimMesonAcc[ibin] = 0;
}
// printf("Bin %d, [%1.1f,%1.1f] bin size %1.1f, content num %2.2e, content den %2.2e: frac %2.3f+%2.3f\n",
// ibin,xPtLimits[ibin],xPtLimits[ibin+1],2*exPt[ibin],primMesonPtAcc[ibin],primMesonPt[ibin],primMesonAcc[ibin],eprimMesonAcc[ibin] );
primMesonPt [ibin]/=((exPt[ibin]*4)); // It should be 2 not 4???
primMesonPtAcc[ibin]/=((exPt[ibin]*4));
// // Scale biased production
// if(kFileName.Contains("pp_7TeV_Pi0"))
// {
// primMeson[ibin]*=1.e6;
// primMeson[ibin]*=360./100.;
//
// //eprimMeson[ibin]*=1.e6*1.e6;
// eprimMeson[ibin]*=360./100.;
//
// mesonPtBC [0][ibin] /= (0.62 +xPt[ibin]*0.0017 );
// emesonPtBC[0][ibin] /= (0.62 +xPt[ibin]*0.0017 );
//
// primMeson [ibin] /= (0.56 +xPt[ibin]*0.0096 );
// eprimMeson[ibin] /= (0.56 +xPt[ibin]*0.0096 );
// }
} // pT bin loop
TGraphErrors * gPrim = new TGraphErrors(nPt,xPt.GetArray(),primMesonPt.GetArray(),exPt.GetArray(),eprimMesonPt.GetArray());
gPrim->SetName("Primary");
gPrim->GetHistogram()->SetYTitle("d #it{N}/d #it{p}_{T}");
gPrim->GetHistogram()->SetTitleOffset(1.4,"Y");
gPrim->GetHistogram()->SetXTitle("#it{p}_{T,gen} (GeV/#it{c})");
gPrim->GetHistogram()->SetTitleOffset(1.2,"X");
gPrim->GetHistogram()->SetTitle("#it{p}_{T} spectra for |#it{Y}| < 0.65");
gPrim->Write();
TGraphErrors * gPrimAcc = new TGraphErrors(nPt,xPt.GetArray(),primMesonPtAcc.GetArray(),exPt.GetArray(),eprimMesonPtAcc.GetArray());
gPrimAcc->SetName("PrimaryInAcceptance");
gPrimAcc->GetHistogram()->SetYTitle("d#it{N}/d #it{p}_{T}");
gPrimAcc->GetHistogram()->SetTitle(Form("|#it{Y}| < 0.65 in %s",kCalorimeter.Data()));
gPrimAcc->Write();
// Acceptance
TH1D* hAcc = (TH1D*) hPrimMesonPtAcc->Clone("hAcceptance");
hAcc->Divide(hPrimMesonPt);
TGraphErrors * gAcc = new TGraphErrors(nPt,xPt.GetArray(),primMesonAcc.GetArray(),exPt.GetArray(),eprimMesonAcc.GetArray());
gAcc->SetName("Acceptance");
gAcc->GetHistogram()->SetYTitle("Acceptance");
gAcc->GetHistogram()->SetTitleOffset(1.4,"Y");
gAcc->GetHistogram()->SetXTitle("#it{p}_{T,gen} (GeV/#it{c})");
gAcc->GetHistogram()->SetTitleOffset(1.2,"X");
gAcc->GetHistogram()->SetTitle(Form("Acceptance for |#it{Y}| < 0.65 in %s",kCalorimeter.Data()));
gAcc->Write();
// Plot spectra and acceptance
//
TCanvas *cAcc = new TCanvas(Form("cAcceptance"),
Form("Primary generated p_{T} spectra and acceptance"),2*600,600);
cAcc->Divide(2, 1);
cAcc->cd(1);
//gPad->SetGridx();
//gPad->SetGridy();
gPad->SetLogy();
Double_t maximum = gPrim->GetHistogram()->GetMaximum();
Double_t minimum = gPrim->GetHistogram()->GetMinimum();
if ( gPrimAcc->GetMaximum() > maximum ) maximum = gPrimAcc->GetMaximum() ;
if ( gPrimAcc->GetMinimum() > minimum ) minimum = gPrimAcc->GetMinimum() ;
gPrim->SetMaximum(maximum*10);
gPrim->SetMinimum(minimum/10);
gPrim ->Draw("AP");
gPrimAcc->Draw("P");
gPrim ->SetMarkerColor(1);
gPrimAcc->SetMarkerColor(4);
gPrim ->SetLineColor(1);
gPrimAcc->SetLineColor(4);
gPrim ->SetMarkerStyle(24);
gPrimAcc->SetMarkerStyle(24);
hPrimMesonPt ->Draw("same");
hPrimMesonPtAcc->Draw("same");
hPrimMesonPt ->Draw("Hsame");
hPrimMesonPtAcc->Draw("Hsame");
hPrimMesonPt ->SetLineColor(1);
hPrimMesonPtAcc->SetLineColor(4);
TLegend * legendS = new TLegend(0.4,0.7,0.9,0.9);
legendS->AddEntry(gPrim,"|Y| < 0.65","P");
legendS->AddEntry(gPrimAcc,Form("Both in %s",kCalorimeter.Data()),"P");
legendS->AddEntry(hPrimMesonPt,"Histo |Y| < 0.65","L");
legendS->AddEntry(hPrimMesonPtAcc,Form("Histo Both in %s",kCalorimeter.Data()),"L");
legendS->Draw();
cAcc->cd(2);
gPad->SetGridx();
gPad->SetGridy();
//gPad->SetLogy();
//gAcc->SetMaximum(1);
gAcc->SetMaximum(gAcc->GetHistogram()->GetMaximum()*1.3);
gAcc->SetMinimum(0);
gAcc->Draw("AP");
gAcc->SetMarkerColor(1);
gAcc->SetMarkerStyle(24);
hAcc->Draw("Hsame");
hAcc->SetLineColor(4);
TLegend * legendA = new TLegend(0.7,0.75,0.9,0.9);
legendA->AddEntry(gAcc,"Graph","P");
legendA->AddEntry(hAcc,"Histo","L");
legendA->Draw();
cAcc->Print(Form("IMfigures/%s_%s_PrimarySpectraAcceptance_%s.%s",
kProdName.Data(),kCalorimeter.Data(),kParticle.Data(),
/*kFileName.Data(),*/ kPlotFormat.Data()));
}
///
/// Main method
///
/// \param prodname : name of directory with histogram file
/// \param filename : histogram file name
/// \param histoDir : TDirectoryFile folder name
/// \param histoList : TList folder name
/// \param histoStart : begining of histograms name
/// \param calorimeter: "EMCAL","DCAL"
/// \param particle : "Pi0","Eta", define fitting and plotting ranges for particle
/// \param nPairMin : minimum number of entries un the pi0 or eta peak integral to do the fits and plotting. Careful in MC scaled productions.
/// \param sumw2 : bool, apply the histograms Sumw2 method to get proper errors when not done before
/// \param rebin : int, rebin default Inv Mass histograms binning with this value
/// \param firstTRD : int, First EMCal SM covered by a TRD SM, in 2011 and 4 in 2012-13
/// \param mixed : bool, use mixed event to constrain combinatorial background
/// \param truncmix : bool, 1: use truncated function to constrain backgroun; 0: use factor from fixed bin
/// \param pol : int, polinomyal type for residual background under the peak
/// \param drawAll : bool, activate plot per pair in any SM
/// \param drawMCAll : bool, activate plot per pair in any SM and MC
/// \param drawPerSM : bool, activate plot per pair in same SM
/// \param drawPerSMGr: bool, activate plot per pair in same SM adding SM: 3 groups [3,7], [1,2], [0,4,5,6,8,9], needs drawPerSM=kTRUE
/// \param drawPerSector: bool, activate plot per pair in different continuous SM sectors
/// \param drawPerSide: bool, activate plot per pair in different continuous SM sides
/// \param plotFormat : define the type of figures: eps, pdf, etc.
///
//-----------------------------------------------------------------------------
void InvMassFit
(TString prodname = "LHC18c3_NystromOn",//"LHC17l3b_fast",
TString filename = "AnalysisResults",
TString histoDir = "Pi0IM_GammaTrackCorr_EMCAL",
TString histoList = "default",
TString histoStart = "",
TString calorimeter = "EMCAL",
TString particle = "Pi0",
Float_t nPairMin = 20,
Bool_t sumw2 = kTRUE,
Int_t rebin = 1,
Int_t firstTRD = 6,
Bool_t mixed = kTRUE,
Bool_t truncmix = kFALSE,
Int_t pol = 1,
Bool_t drawAll = kFALSE,
Bool_t drawMCAll = kFALSE,
Bool_t drawPerSM = kTRUE,
Bool_t drawPerSMGr = kFALSE,
Bool_t drawPerSector= kFALSE,
Bool_t drawPerSide = kFALSE,
TString plotFormat = "eps")
{
// Load plotting utilities
//gROOT->Macro("$ALICE_PHYSICS/PWGGA/CaloTrackCorrelations/macros/PlotUtils.C"); // Already in include
//gROOT->Macro("$MACROS/style.C");//Set different root style parameters
kSumw2 = sumw2;
kPolN = pol;
kMix = mixed;
kTrunMixFunc= truncmix;
kParticle = particle;
kProdName = prodname;
kFileName = filename;
kPlotFormat = plotFormat;
kCalorimeter= calorimeter;
kNPairCut = nPairMin;
kRebin = rebin;
kFirstTRDSM = firstTRD;
if(histoStart !="")
kHistoStartName = histoStart;
else
{
kHistoStartName = "AnaPi0_Calo0";
if(kCalorimeter=="DCAL")
kHistoStartName = "AnaPi0_Calo1";
}
if(drawPerSMGr) drawPerSM = kTRUE;
//---------------------------------------
// Get input file
//---------------------------------------
Int_t ok = GetFileAndEvents(histoDir, histoList);
// kProdName.ReplaceAll("module/","");
// kProdName.ReplaceAll("TCardChannel","");
kProdName.ReplaceAll("/","_");
// kProdName.ReplaceAll("2_","_");
// kProdName.ReplaceAll("__","_");
if( kFileName !="AnalysisResults" && !kFileName.Contains("Scale") )
kProdName+=kFileName;
printf("Settings: prodname <%s>, filename <%s>, histoDir <%s>, histoList <%s>,\n"
" \t histo start name <%s>, particle <%s>, calorimeter <%s>, \n"
" \t mix %d, kPolN %d, sumw2 %d, n pairs cut %2.2e\n",
kProdName.Data(), kFileName.Data(),histoDir.Data(),histoList.Data(), kHistoStartName.Data(),
kParticle.Data(), kCalorimeter.Data(), kMix, kPolN, kSumw2, kNPairCut);
if ( !ok )
{
printf("Could not recover file <%p> or dir <%p> or list <%p>\n",fil,direc,lis);
return ;
}
// kNPairCut/=nEvt;
//---------------------------------------
// Set-up output file with processed histograms
//---------------------------------------
// Open output file
fout = new TFile(Form("IMfigures/%s_%s_MassWidthPtHistograms_%s.root",
kProdName.Data(),kCalorimeter.Data(),kParticle.Data() /*,kFileName.Data()*/), "recreate");
printf("Open Output File: IMfigures/%s_%s_MassWidthPtHistograms_%s.root\n",
kProdName.Data(),kCalorimeter.Data(),kParticle.Data());//,kFileName.Data());
//---------------------------------------
// Set the pt bins and total range
//---------------------------------------
const Int_t nPtEta = 13;
Double_t xPtLimitsEta[] = {2.,3.,4.,5.,6.,8.,10.,14.,18.,24.,28.,34.,40.,50.};
// const Int_t nPtPi0 = 7;
// Double_t xPtLimitsPi0[] = {1.5,2,2.5,3.,3.5,4.,5.,6.};
const Int_t nPtPi0 = 23;
Double_t xPtLimitsPi0[] = {1.6,1.8,2.,2.2,2.4,2.6,2.8,3.,3.4,3.8,4.2,4.6,5.,5.5,6.,6.5,7.,7.5,8.,9.,10.,12.,15.,17.,20.};
Int_t nPt = nPtPi0;
if(kParticle == "Eta") nPt = nPtEta;
TArrayD xPtLimits; xPtLimits.Set(nPt+1);
TArrayD xPt ; xPt .Set(nPt);
TArrayD exPt ; exPt .Set(nPt);
for(Int_t i = 0; i < nPt; i++)
{
if(kParticle == "Pi0")
{
xPtLimits.SetAt(xPtLimitsPi0[i],i);
exPt .SetAt((xPtLimitsPi0[i+1]-xPtLimitsPi0[i])/2,i);
xPt .SetAt(xPtLimitsPi0[i]+exPt[i],i);
}
else
{
xPtLimits.SetAt(xPtLimitsEta[i],i);
exPt .SetAt((xPtLimitsEta[i+1]-xPtLimitsEta[i])/2,i);
xPt .SetAt(xPtLimitsEta[i]+exPt[i],i);
}
//printf("%s pT bin %d, pT %2.2f, dpT %2.2f, limit %2.2f\n",kParticle.Data(),i,xPt[i],exPt[i],xPtLimits[i]);
}
// Extra entry
if ( kParticle == "Pi0" ) xPtLimits.SetAt(xPtLimitsPi0[nPt],nPt);
else xPtLimits.SetAt(xPtLimitsEta[nPt],nPt);
TString comment = "";
TString leg = "";
TString hname = "";
//---------------------------------------
// Fitting function and histograms initialization
//---------------------------------------
SetFitFun();
TH2F * hRe ;
TH2F * hMi ;
//=======================================
// Get histograms, project per pT bin and fit
// Do it for different kind of histograms:
// Total pairs, MC pairs, pairs per SM combinations
//=======================================
//---------------------------------------
// MC input
//---------------------------------------
if ( drawMCAll )
{
// Get the generated primary pi0 spectra, for efficiency calculation
PrimarySpectra(nPt,xPtLimits, xPt, exPt);
// Reconstructed pT of real meson pairs
//hRe = (TH2F *) fil->Get( Form("%s_hMCOrgMass_2", kHistoStartName.Data()) ); // Pi0
//hRe = (TH2F *) fil->Get( Form("%s_hMCOrgMass_3", kHistoStartName.Data()) ); // Eta
hRe = (TH2F *) fil->Get( Form("%s_hMC%sMassPtRec", kHistoStartName.Data(), kParticle.Data()) );
comment = "MC pT reconstructed";
leg = "MC pT reconstructed";
hname = "MCpTReco" ;
ProjectAndFit(nPt,comment,leg,hname,xPtLimits, xPt, exPt, hRe, 0x0 );
// Reconstructed pT of real eta pairs
hRe = (TH2F *) fil->Get( Form("%s_hMC%sMassPtTrue", kHistoStartName.Data(), kParticle.Data()) );
comment = "MC pT generated";
leg = "MC pT generated";
hname = "MCpTGener" ;
ProjectAndFit(nPt,comment,leg,hname,xPtLimits, xPt, exPt, hRe, 0x0 );
} // MC treatment
//---------------------------------------
// All SM
//---------------------------------------
if ( drawAll )
{
if ( !lis )
{
hRe = (TH2F *) fil->Get(Form("%s_hRe_cen0_pidbit0_asy0_dist1", kHistoStartName.Data()));
hMi = (TH2F *) fil->Get(Form("%s_hMi_cen0_pidbit0_asy0_dist1", kHistoStartName.Data()));
}
else
{
hRe = (TH2F *) lis->FindObject(Form("%s_hRe_cen0_pidbit0_asy0_dist1", kHistoStartName.Data()));
hMi = (TH2F *) lis->FindObject(Form("%s_hMi_cen0_pidbit0_asy0_dist1", kHistoStartName.Data()));
}
printf("histo Re %p - Mix %p All SM\n",hRe,hMi);
if( !hMi ) kMix = kFALSE;
comment = "All SM";
leg = "All SM";
hname = "AllSM";
ProjectAndFit(nPt,comment,leg,hname,xPtLimits, xPt, exPt, hRe, hMi );
}
//-------------------------------------------
// Histograms for cluster pairs in different
// combinations of SM
//-------------------------------------------
//
// Pairs in same SM
//
if ( drawPerSM )
{
Int_t imod;
Int_t firstMod = 0;
Int_t lastMod = 11;
if ( kCalorimeter=="DCAL" )
{
firstMod = 12;
lastMod = 19;
}
// Initialize SM grouping histograms
// 0 : SM 0+4+5+6+8+9
// 1 : SM 1+2
// 2 : SM 3+7
TH2F * hReSMGroups[3] ;
TH2F * hMiSMGroups[3] ;
TH2F * hReSM = 0;
TH2F * hMiSM = 0;
TH2F * hReSMTRDYes = 0;
TH2F * hMiSMTRDYes = 0;
TH2F * hReSMTRDNot = 0;
TH2F * hMiSMTRDNot = 0;
for(Int_t imodgroup = 0; imodgroup<=2; imodgroup++)
{
hReSMGroups[imodgroup] = hMiSMGroups[imodgroup] = 0x0;
}
for(imod = firstMod; imod<=lastMod; imod++)
{
if(!lis)
{
hRe = (TH2F *) fil->Get(Form("%s_hReMod_%d", kHistoStartName.Data(), imod));
hMi = (TH2F *) fil->Get(Form("%s_hMiMod_%d", kHistoStartName.Data(), imod));
}
else
{
hRe = (TH2F *) lis->FindObject(Form("%s_hReMod_%d", kHistoStartName.Data(), imod));
hMi = (TH2F *) lis->FindObject(Form("%s_hMiMod_%d", kHistoStartName.Data(), imod));
}
//printf("histo mod %d Re %p - Mix %p\n",imod, hRe,hMi);
comment = Form("both clusters in SM %d",imod);
leg = Form("SM %d",imod);
hname = Form("SM%d" ,imod);
ProjectAndFit(nPt,comment,leg,hname,xPtLimits, xPt, exPt, hRe, hMi );
// Add all SM
if( imod == firstMod )
{
hReSM = (TH2F*) hRe->Clone("h2D_Re_IM_SM");
if(kMix) hMiSM = (TH2F*) hMi->Clone("h2D_Mi_IM_SM");
}
else
{
hReSM->Add( hRe );
if(kMix) hMiSM ->Add( hMi );
}
// Add TRD covered or not SM
if( kFirstTRDSM > 0 )
{
if ( imod >= kFirstTRDSM && imod < 10 )
{
if( imod == kFirstTRDSM )
{
hReSMTRDYes = (TH2F*) hRe->Clone("h2D_Re_IM_SM_TRD_Yes");
if(kMix) hMiSMTRDYes = (TH2F*) hMi->Clone("h2D_Mi_IM_SM_TRD_Yes");
}
else
{
hReSMTRDYes->Add( hRe );
if(kMix) hMiSMTRDYes ->Add( hMi );
}
}
}
// Group SMs in with particular behaviors
if ( drawPerSMGr )
{
if ( imod == 0 )
{
hReSMGroups[0] = (TH2F*) hRe->Clone("h2D_Re_IM_SM045689");
if(kMix)
hMiSMGroups[0] = (TH2F*) hMi->Clone("h2D_Mi_IM_SM045689");
}
else if ( imod == 1 )
{
hReSMGroups[1] = (TH2F*) hRe->Clone("h2D_Re_IM_SM12");
if(kMix) hMiSMGroups[1] = (TH2F*) hMi->Clone("h2D_Mi_IM_SM12");
}
else if ( imod == 3 )
{
hReSMGroups[2] = (TH2F*) hRe->Clone("h2D_Re_IM_SM37");
if(kMix) hMiSMGroups[2] = (TH2F*) hMi->Clone("h2D_Mi_IM_SM37");
}
else if ( imod == 2 )
{
hReSMGroups[1]->Add(hRe);
if(kMix) hMiSMGroups[1]->Add(hMi);
}
else if ( imod == 7 )
{
hReSMGroups[2]->Add(hRe);
if(kMix) hMiSMGroups[2]->Add(hMi);
}
else if ( imod < 10 )
{
hReSMGroups[0]->Add(hRe);
if(kMix) hMiSMGroups[0]->Add(hMi);
}
} // do SM groups addition
} // SM loop
// Sum of pairs in same SM
comment = "both clusters in same SM";
leg = "Same SM";
hname = "SameSM";
ProjectAndFit(nPt,comment,leg,hname,xPtLimits, xPt, exPt, hReSM, hMiSM );
if ( kFirstTRDSM > 0 )
{
// Sum of pairs in same SM with TRD
comment = "both clusters in same SM, TRD covered";
leg = "Same SM, TRD Yes";
hname = "SameSMTRDYes";
ProjectAndFit(nPt,comment,leg,hname,xPtLimits, xPt, exPt, hReSMTRDYes, hMiSMTRDYes );
// Sum of pairs in same SM without TRD
hReSMTRDNot = (TH2F*) hReSM->Clone("h2D_Re_IM_SM_TRD_Not");
hReSMTRDNot->Add(hReSMTRDYes,-1);
if(kMix)
{
hMiSMTRDNot = (TH2F*) hMiSM->Clone("h2D_Mi_IM_SM_TRD_Not");
hMiSMTRDNot->Add(hMiSMTRDYes,-1);
}
comment = "both clusters in same SM, NOT TRD covered";
leg = "Same SM, TRD No";
hname = "SameSMTRDNot";
ProjectAndFit(nPt,comment,leg,hname,xPtLimits, xPt, exPt, hReSMTRDNot, hMiSMTRDNot );
}
// Fit parameters final plotting
PlotGraphs("SM" ,firstMod ,lastMod );
// Group SMs in with particular behaviors
if( drawPerSMGr )
{
for(Int_t imodgroup = 0; imodgroup<=2; imodgroup++)
{
//printf("histo modgroup %d Re %p - Mix %p\n",
// imod, hReSMGroups[imodgroup], hMiSMGroups[imodgroup]);
comment = Form("both clusters in same SM, group %d",imodgroup);
leg = Form("SMGroup %d",imodgroup);
hname = Form("SMGroup%d" ,imodgroup);
if ( imodgroup != 0 )
{
hReSMGroups[imodgroup]->Scale(1./2.);
if ( kMix ) hMiSMGroups[imodgroup]->Scale(1./2.);
}
else
{
hReSMGroups[imodgroup]->Scale(1./6.);
if ( kMix ) hMiSMGroups[imodgroup]->Scale(1./6.);
}
ProjectAndFit(nPt, comment, leg, hname, xPtLimits, xPt, exPt,
hReSMGroups[imodgroup], hMiSMGroups[imodgroup] );
}
// Fit parameters final plotting
PlotGraphs("SMGroup",0 ,2 );
} // Per SM groups
} // Per SM
//
// Pairs in same sector
//
if(drawPerSector)
{
Int_t firstSector = 0;
Int_t lastSector = 5;
if ( kCalorimeter=="DCAL" )
{
firstSector = 6;
lastSector = 9;
}
TH2F * hReSector = 0;
TH2F * hMiSector = 0;
Int_t isector;
for(isector = firstSector; isector<=lastSector; isector++)
{
if(!lis)
{
hRe = (TH2F *) fil->Get(Form("%s_hReSameSectorEMCALMod_%d", kHistoStartName.Data(), isector));
hMi = (TH2F *) fil->Get(Form("%s_hMiSameSectorEMCALMod_%d", kHistoStartName.Data(), isector));
}
else
{
hRe = (TH2F *) lis->FindObject(Form("%s_hReSameSectorEMCALMod_%d", kHistoStartName.Data(), isector));
hMi = (TH2F *) lis->FindObject(Form("%s_hMiSameSectorEMCALMod_%d", kHistoStartName.Data(), isector));
}
// Add all Sectors
if( isector == firstSector )
{
hReSector = (TH2F*) hRe->Clone("h2D_Re_IM_Sector");
if(kMix) hMiSector = (TH2F*) hMi->Clone("h2D_Mi_IM_Sector");
}
else
{
hReSector->Add( hRe );
if(kMix) hMiSector ->Add( hMi );
}
//printf("histo sector %d Re %p - Mix %p\n",isector, hRe,hMi);
comment = Form("both clusters in Sector %d",isector);
leg = Form("Sector %d",isector);
hname = Form("Sector%d" ,isector);
ProjectAndFit(nPt,comment,leg,hname,xPtLimits, xPt, exPt, hRe, hMi );
}
// Sum of pairs in same Sector
comment = "both clusters in same Sector";
leg = "Same Sector";
hname = "SameSector";
ProjectAndFit(nPt,comment,leg,hname,xPtLimits, xPt, exPt, hReSector, hMiSector );
// Fit parameters final plotting
PlotGraphs("Sector" ,firstSector,lastSector);
} // Per sector
// Pairs in same side
//
if(drawPerSide)
{
Int_t firstSide = 0;
Int_t lastSide = 9;
if ( kCalorimeter=="DCAL" )
{
firstSide = 10;
lastSide = 15;
}
TH2F * hReSide = 0;
TH2F * hMiSide = 0;
Int_t iside;
for(iside = firstSide; iside <= lastSide; iside++)
{
if(!lis)
{
hRe = (TH2F *) fil->Get(Form("%s_hReSameSideEMCALMod_%d", kHistoStartName.Data(), iside));
hMi = (TH2F *) fil->Get(Form("%s_hMiSameSideEMCALMod_%d", kHistoStartName.Data(), iside));
}
else
{
hRe = (TH2F *) lis->FindObject(Form("%s_hReSameSideEMCALMod_%d", kHistoStartName.Data(), iside));
hMi = (TH2F *) lis->FindObject(Form("%s_hMiSameSideEMCALMod_%d", kHistoStartName.Data(), iside));
}
// Add all Sides
if( iside == firstSide )
{
hReSide = (TH2F*) hRe->Clone("h2D_Re_IM_Side");
if(kMix) hMiSide = (TH2F*) hMi->Clone("h2D_Mi_IM_Side");
}
else
{
hReSide->Add( hRe );
if(kMix) hMiSide ->Add( hMi );
}
//printf("histo side %d Re %p - Mix %p\n",iside, hRe,hMi);
comment = Form("both clusters in Side %d",iside);
leg = Form("Side %d",iside);
hname = Form("Side%d" ,iside);
ProjectAndFit(nPt,comment,leg,hname,xPtLimits, xPt, exPt, hRe, hMi );
}
// Sum of pairs in same Side
comment = "both clusters in same Side";
leg = "Same Side";
hname = "SameSide";
ProjectAndFit(nPt,comment,leg,hname,xPtLimits, xPt, exPt, hReSide, hMiSide );
// Fit parameters final plotting
PlotGraphs("Side" ,firstSide ,lastSide );
} // per Side
fout->Close();
}
| bsd-3-clause |
d-bo/unitaly-dev | modules/directory/views/backend/store/update.php | 1520 | <?php
use vova07\themes\admin\widgets\Box;
use modules\directory\Module;
$this->title = Module::t('shop', 'BACKEND_STORE_UPDATE_TITLE');
$this->params['subtitle'] = Module::t('shop', 'BACKEND_STORE_UPDATE_SUBTITLE');
$this->params['breadcrumbs'] = [
[
'label' => $this->title,
'url' => ['index'],
],
$this->params['subtitle']
];
$boxButtons[] = '{create}';
$boxButtons[] = '{delete}';
$boxButtons[] = '{cancel}';
$buttons['cancel'] = [
'url' => ['shop/index'],
'icon' => 'fa-reply',
'options' => [
'class' => 'btn-default',
'title' => Yii::t('vova07/themes/admin/widgets/box', 'Cancel')
]
];
$boxButtons = !empty($boxButtons) ? implode(' ', $boxButtons) : null; ?>
<div class="row">
<div class="col-sm-12">
<?php $box = Box::begin(
[
'title' => $this->params['subtitle'],
'renderBody' => false,
'options' => [
'class' => 'box-success'
],
'bodyOptions' => [
'class' => 'table-responsive'
],
'buttonsTemplate' => $boxButtons,
'buttons' => $buttons,
]
);
echo $this->render(
'_form',
[
'model' => $model,
'formModel' => $formModel,
'box' => $box
]
);
Box::end(); ?>
</div>
</div> | bsd-3-clause |
igorstefurak/pushcourse | lib/layouts.js | 7374 | var archiver = require('archiver'),
async = require('async'),
escape = require('handlebars').Utils.escapeExpression,
fs = require('fs'),
glob = require('glob'),
path = require('path'),
yui = require('yui');
var config = require('../config'),
hbs = require('./hbs');
exports.archive = archiveLayout;
exports.clone = cloneLayouts;
exports.find = findLayout;
exports.load = loadLayouts;
// -----------------------------------------------------------------------------
var DIR_PATH = path.join(config.dirs.views, 'layouts', 'examples'),
LICENSE = fs.readFileSync(path.join(process.cwd(), 'LICENSE.md')),
README = fs.readFileSync(path.join(DIR_PATH, 'README.md')),
cache = null,
pending = null;
function archiveLayout(layout) {
if (!layout) { return null; }
var archive = archiver('zip');
archive.append(LICENSE, {name: 'LICENSE.md'});
archive.append(README, {name: 'README.md'});
archive.append(layout.html, {name: 'index.html'});
// Layout resources.
['css', 'js', 'imgs'].forEach(function (type) {
layout[type].forEach(function (file) {
archive.append(file.data, {name: file.filename});
});
});
return archive.finalize();
}
function cloneLayouts(layouts, options) {
layouts = clone(layouts);
options || (options = {});
layouts.forEach(function (layout) {
// Convert imgs back into Buffers.
layout.imgs.forEach(function (img) {
img.data = new Buffer(img.data);
});
if (options.escape) {
layout.description = escape(layout.description);
layout.html = escape(layout.html);
['css', 'js'].forEach(function (type) {
layout[type].forEach(function (file) {
file.data = escape(file.data);
});
});
}
});
return layouts;
}
function findLayout(layouts, name) {
var layout = null;
layouts.some(function (l) {
if (l.name === name) {
layout = l;
return true;
}
});
return layout;
}
/*
This provides metadata about the layout examples. If the `cache` option is set,
then the hard work is only performed once. A copy of the layouts metadata is
returned to the caller via the `callback`, therefore they are free to mute the
data and it won't affect any other caller.
*/
function loadLayouts(options, callback) {
// Options are optional.
if (typeof options === 'function') {
callback = options;
options = null;
}
options || (options = {});
// Check cache.
if (options.cache && cache) {
// Return clone of the cache.
callback(null, cloneLayouts(cache, options));
return;
}
// Put caller on the queue if the hard work of compiling the layouts
// metadata is currently in progress for another caller.
if (pending) {
pending.push(callback);
return;
}
pending = [callback];
// Run the show!
// 1) Glob the layout examples dir to get a list of filenames.
//
// 2) Create the metadata for the layout examples:
// a) Render each layout and capture its output *and* metadata set from
// within the template itself.
//
// b) Create a metadata object to represent the layout based on the
// data siphoned from the context object in which it was rendered.
//
// 3) Read the CSS, JS, and images associated with the layout example from
// the filesystem and capture it as part of the metadata.
//
// 4) Cache the result and call all queued calls with their own copy of the
// layout examples metadata.
async.waterfall([
glob.bind(null, '*' + hbs.extname, {cwd: DIR_PATH}),
createLayouts,
loadResources
], function (err, layouts) {
if (!err) { cache = layouts; }
while (pending.length) {
pending.shift().call(null, err, cloneLayouts(layouts, options));
}
pending = null;
});
}
// -- Utilities ----------------------------------------------------------------
function clone(obj) {
// Poor-man's clone.
return JSON.parse(JSON.stringify(obj));
}
function createLayouts(filenames, callback) {
// Default context values that mascarade as being the "app" and make the
// layout examples render in a particular way.
var contextProto = {
forDownload: true,
site : 'Pure',
section: 'Layout Examples',
pure: {
version: config.pure.version
},
yui_version: yui.YUI.version,
min: '-min',
layout : 'blank',
relativePath: '/',
helpers: {
pathTo: function () { return ''; }
}
};
function createLayout(filename, context, html, callback) {
var css = [];
// Include all `localCSS` files, including old IE versions.
(context.localCSS || []).forEach(function (entry) {
css.push(entry.path);
if (entry.oldIE) {
css.push(entry.oldIE);
}
});
callback(null, {
name : path.basename(filename, path.extname(filename)),
label : context.title,
description: context.subTitle,
tags : context.tags,
html: html,
css : css,
js : context.localJS || [],
imgs: context.localImgs || []
});
}
function renderTemplate(filename, callback) {
// Create a new context object that inherits from the defaults so when
// the template is rendered the own properties will be enumerable
// allowing us to sniff out the data added by the Handlebars helpers.
var context = Object.create(contextProto);
async.waterfall([
hbs.renderView.bind(hbs, path.join(DIR_PATH, filename), context),
createLayout.bind(null, filename, context)
], callback);
}
async.map(filenames, renderTemplate, callback);
}
function loadResources(layouts, callback) {
function processFile(type, filename, callback) {
fs.readFile(path.join(config.dirs.pub, filename), {
// Set the encoding for non-binary files.
encoding: type === 'imgs' ? null : 'utf8'
}, function (err, data) {
callback(err, {
name : path.basename(filename),
filename: filename,
data : data
});
});
}
function loadFiles(layout, type, callback) {
async.map(layout[type], processFile.bind(null, type), function (err, files) {
// Replace the list of filenames used by this layout with a
// collection of metadata for each file which includes its:
// name, filename, and contents.
layout[type] = files;
callback(err, files);
});
}
async.each(layouts, function (layout, callback) {
async.parallel([
loadFiles.bind(null, layout, 'css'),
loadFiles.bind(null, layout, 'js'),
loadFiles.bind(null, layout, 'imgs')
], callback);
}, function (err) {
callback(err, layouts);
});
}
| bsd-3-clause |
crosswalk-project/blink-crosswalk | Source/platform/graphics/ImageLayerChromiumTest.cpp | 4769 | /*
* Copyright (C) 2011 Google 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:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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.
*/
#include "config.h"
#include "platform/graphics/Image.h"
#include "platform/graphics/GraphicsLayer.h"
#include "wtf/PassOwnPtr.h"
#include <gtest/gtest.h>
namespace blink {
namespace {
class MockGraphicsLayerClient : public GraphicsLayerClient {
public:
void paintContents(const GraphicsLayer*, GraphicsContext&, GraphicsLayerPaintingPhase, const IntRect&) override { }
String debugName(const GraphicsLayer*) override { return String(); }
};
class TestImage : public Image {
public:
static PassRefPtr<TestImage> create(const IntSize& size, bool isOpaque)
{
return adoptRef(new TestImage(size, isOpaque));
}
TestImage(const IntSize& size, bool isOpaque)
: Image(0)
, m_size(size)
{
m_bitmap.allocN32Pixels(size.width(), size.height(), isOpaque);
m_bitmap.eraseColor(SK_ColorTRANSPARENT);
}
bool isBitmapImage() const override
{
return true;
}
bool currentFrameKnownToBeOpaque() override
{
return m_bitmap.isOpaque();
}
IntSize size() const override
{
return m_size;
}
bool bitmapForCurrentFrame(SkBitmap* bitmap) override
{
if (m_size.isZero())
return false;
*bitmap = m_bitmap;
return true;
}
// Stub implementations of pure virtual Image functions.
void destroyDecodedData(bool) override
{
}
void draw(SkCanvas*, const SkPaint&, const FloatRect&, const FloatRect&, RespectImageOrientationEnum, ImageClampingMode) override
{
}
private:
IntSize m_size;
SkBitmap m_bitmap;
};
class GraphicsLayerForTesting : public GraphicsLayer {
public:
explicit GraphicsLayerForTesting(GraphicsLayerClient* client)
: GraphicsLayer(client) { }
WebLayer* contentsLayer() const { return GraphicsLayer::contentsLayer(); }
};
} // anonymous namespace
TEST(ImageLayerChromiumTest, imageLayerContentReset)
{
MockGraphicsLayerClient client;
OwnPtr<GraphicsLayerForTesting> graphicsLayer = adoptPtr(new GraphicsLayerForTesting(&client));
ASSERT_TRUE(graphicsLayer.get());
ASSERT_FALSE(graphicsLayer->hasContentsLayer());
ASSERT_FALSE(graphicsLayer->contentsLayer());
RefPtr<Image> image = TestImage::create(IntSize(100, 100), false);
ASSERT_TRUE(image.get());
graphicsLayer->setContentsToImage(image.get());
ASSERT_TRUE(graphicsLayer->hasContentsLayer());
ASSERT_TRUE(graphicsLayer->contentsLayer());
graphicsLayer->setContentsToImage(0);
ASSERT_FALSE(graphicsLayer->hasContentsLayer());
ASSERT_FALSE(graphicsLayer->contentsLayer());
}
TEST(ImageLayerChromiumTest, opaqueImages)
{
MockGraphicsLayerClient client;
OwnPtr<GraphicsLayerForTesting> graphicsLayer = adoptPtr(new GraphicsLayerForTesting(&client));
ASSERT_TRUE(graphicsLayer.get());
RefPtr<Image> opaqueImage = TestImage::create(IntSize(100, 100), true /* opaque */);
ASSERT_TRUE(opaqueImage.get());
RefPtr<Image> nonOpaqueImage = TestImage::create(IntSize(100, 100), false /* opaque */);
ASSERT_TRUE(nonOpaqueImage.get());
ASSERT_FALSE(graphicsLayer->contentsLayer());
graphicsLayer->setContentsToImage(opaqueImage.get());
ASSERT_TRUE(graphicsLayer->contentsLayer()->opaque());
graphicsLayer->setContentsToImage(nonOpaqueImage.get());
ASSERT_FALSE(graphicsLayer->contentsLayer()->opaque());
}
} // namespace blink
| bsd-3-clause |
aYukiSekiguchi/ACCESS-Chromium | ui/gfx/native_theme_chromeos.h | 3463 | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_GFX_NATIVE_THEME_CHROMEOS_H_
#define UI_GFX_NATIVE_THEME_CHROMEOS_H_
#include <map>
#include "base/compiler_specific.h"
#include "ui/gfx/native_theme_base.h"
class SkBitmap;
namespace gfx {
class NativeThemeChromeos : public NativeThemeBase {
public:
static const NativeThemeChromeos* instance();
private:
NativeThemeChromeos();
virtual ~NativeThemeChromeos();
// NativeTheme overrides
virtual gfx::Size GetPartSize(Part part,
State state,
const ExtraParams& extra) const OVERRIDE;
virtual SkColor GetSystemColor(ColorId color_id) const OVERRIDE;
// NativeThemeBase overrides
virtual void PaintScrollbarTrack(SkCanvas* canvas,
Part part, State state,
const ScrollbarTrackExtraParams& extra_params,
const gfx::Rect& rect) const OVERRIDE;
virtual void PaintArrowButton(SkCanvas* canvas,
const gfx::Rect& rect, Part direction, State state) const OVERRIDE;
virtual void PaintScrollbarThumb(SkCanvas* canvas,
Part part, State state, const gfx::Rect& rect) const OVERRIDE;
// Draw the checkbox.
virtual void PaintCheckbox(SkCanvas* canvas,
State state, const gfx::Rect& rect,
const ButtonExtraParams& button) const OVERRIDE;
// Draw the radio.
virtual void PaintRadio(SkCanvas* canvas,
State state,
const gfx::Rect& rect,
const ButtonExtraParams& button) const OVERRIDE;
// Draw the push button.
virtual void PaintButton(SkCanvas* canvas,
State state,
const gfx::Rect& rect,
const ButtonExtraParams& button) const OVERRIDE;
// Draw the text field.
virtual void PaintTextField(SkCanvas* canvas,
State state,
const gfx::Rect& rect,
const TextFieldExtraParams& text) const OVERRIDE;
// Draw the slider track.
virtual void PaintSliderTrack(SkCanvas* canvas,
State state,
const gfx::Rect& rect,
const SliderExtraParams& slider) const OVERRIDE;
// Draw the slider thumb.
virtual void PaintSliderThumb(SkCanvas* canvas,
State state,
const gfx::Rect& rect,
const SliderExtraParams& slider) const OVERRIDE;
// Draw the inner spin button.
virtual void PaintInnerSpinButton(SkCanvas* canvas,
State state,
const gfx::Rect& rect,
const InnerSpinButtonExtraParams& spin_button) const OVERRIDE;
virtual void PaintMenuPopupBackground(
SkCanvas* canvas,
State state,
const gfx::Rect& rect,
const MenuListExtraParams& menu_list) const OVERRIDE;
// Draw the progress bar.
virtual void PaintProgressBar(SkCanvas* canvas,
State state,
const gfx::Rect& rect,
const ProgressBarExtraParams& progress_bar) const OVERRIDE;
SkBitmap* GetHorizontalBitmapNamed(int resource_id) const;
// Paint a button like rounded rect with gradient background and stroke.
void PaintButtonLike(SkCanvas* canvas,
State state, const gfx::Rect& rect, bool stroke_border) const;
// Cached images. Resource loader caches all retrieved bitmaps and keeps
// ownership of the pointers.
typedef std::map<int, SkBitmap*> SkImageMap;
mutable SkImageMap horizontal_bitmaps_;
DISALLOW_COPY_AND_ASSIGN(NativeThemeChromeos);
};
} // namespace gfx
#endif // UI_GFX_NATIVE_THEME_CHROMEOS_H_
| bsd-3-clause |
zcbenz/cefode-chromium | chrome/browser/ui/singleton_tabs.cc | 4284 | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/singleton_tabs.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_navigator.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/common/url_constants.h"
#include "content/public/browser/browser_url_handler.h"
#include "content/public/browser/web_contents.h"
namespace chrome {
namespace {
// Returns true if two URLs are equal after taking |replacements| into account.
bool CompareURLsWithReplacements(
const GURL& url,
const GURL& other,
const url_canon::Replacements<char>& replacements) {
if (url == other)
return true;
GURL url_replaced = url.ReplaceComponents(replacements);
GURL other_replaced = other.ReplaceComponents(replacements);
return url_replaced == other_replaced;
}
} // namespace
void ShowSingletonTab(Browser* browser, const GURL& url) {
NavigateParams params(GetSingletonTabNavigateParams(browser, url));
Navigate(¶ms);
}
void ShowSingletonTabRespectRef(Browser* browser, const GURL& url) {
NavigateParams params(GetSingletonTabNavigateParams(browser, url));
params.ref_behavior = NavigateParams::RESPECT_REF;
Navigate(¶ms);
}
void ShowSingletonTabOverwritingNTP(Browser* browser,
const NavigateParams& params) {
NavigateParams local_params(params);
content::WebContents* contents =
browser->tab_strip_model()->GetActiveWebContents();
if (contents) {
const GURL& contents_url = contents->GetURL();
if ((contents_url == GURL(kChromeUINewTabURL) ||
contents_url == GURL(kAboutBlankURL)) &&
GetIndexOfSingletonTab(&local_params) < 0) {
local_params.disposition = CURRENT_TAB;
}
}
Navigate(&local_params);
}
NavigateParams GetSingletonTabNavigateParams(Browser* browser,
const GURL& url) {
NavigateParams params(browser, url, content::PAGE_TRANSITION_AUTO_BOOKMARK);
params.disposition = SINGLETON_TAB;
params.window_action = NavigateParams::SHOW_WINDOW;
params.user_gesture = true;
return params;
}
// Returns the index of an existing singleton tab in |params->browser| matching
// the URL specified in |params|.
int GetIndexOfSingletonTab(NavigateParams* params) {
if (params->disposition != SINGLETON_TAB)
return -1;
// In case the URL was rewritten by the BrowserURLHandler we need to ensure
// that we do not open another URL that will get redirected to the rewritten
// URL.
GURL rewritten_url(params->url);
bool reverse_on_redirect = false;
content::BrowserURLHandler::GetInstance()->RewriteURLIfNecessary(
&rewritten_url,
params->browser->profile(),
&reverse_on_redirect);
// If there are several matches: prefer the active tab by starting there.
int start_index =
std::max(0, params->browser->tab_strip_model()->active_index());
int tab_count = params->browser->tab_strip_model()->count();
for (int i = 0; i < tab_count; ++i) {
int tab_index = (start_index + i) % tab_count;
content::WebContents* tab =
params->browser->tab_strip_model()->GetWebContentsAt(tab_index);
url_canon::Replacements<char> replacements;
if (params->ref_behavior == NavigateParams::IGNORE_REF)
replacements.ClearRef();
if (params->path_behavior == NavigateParams::IGNORE_AND_NAVIGATE ||
params->path_behavior == NavigateParams::IGNORE_AND_STAY_PUT) {
replacements.ClearPath();
replacements.ClearQuery();
}
GURL tab_url = tab->GetURL();
GURL rewritten_tab_url = tab_url;
content::BrowserURLHandler::GetInstance()->RewriteURLIfNecessary(
&rewritten_tab_url,
params->browser->profile(),
&reverse_on_redirect);
if (CompareURLsWithReplacements(tab_url, params->url, replacements) ||
CompareURLsWithReplacements(rewritten_tab_url,
rewritten_url,
replacements)) {
params->target_contents = tab;
return tab_index;
}
}
return -1;
}
} // namespace chrome
| bsd-3-clause |
tomfisher/tripleplay | ios/src/main/java/tripleplay/platform/IOSUIOverlay.java | 2336 | //
// Triple Play - utilities for use in PlayN-based games
// Copyright (c) 2011-2014, Three Rings Design, Inc. - All rights reserved.
// http://github.com/threerings/tripleplay/blob/master/LICENSE
package tripleplay.platform;
import cli.MonoTouch.CoreAnimation.CAShapeLayer;
import cli.MonoTouch.CoreGraphics.CGPath;
import cli.MonoTouch.UIKit.UIEvent;
import cli.MonoTouch.UIKit.UIView;
import cli.System.Drawing.PointF;
import cli.System.Drawing.RectangleF;
import pythagoras.f.IRectangle;
public class IOSUIOverlay extends UIView
{
public IOSUIOverlay (RectangleF bounds) {
super(bounds);
set_MultipleTouchEnabled(true);
}
@Override public boolean PointInside (PointF pointF, UIEvent uiEvent) {
// if it's masked, we don't want it
if (_hidden != null && _hidden.Contains(pointF)) return false;
// only accept the touch if it is hitting one of our native widgets
UIView[] subs = get_Subviews();
if (subs == null) return false;
for (UIView view : subs)
if (view.PointInside(ConvertPointToView(pointF, view), uiEvent))
return true;
return false;
}
public void setHiddenArea (IRectangle area) {
_hidden = area == null ? null : new RectangleF(area.x(), area.y(),
area.width(), area.height());
if (_hidden == null) {
get_Layer().set_Mask(null);
return;
}
RectangleF bounds = get_Bounds();
CAShapeLayer maskLayer = new CAShapeLayer();
// draw four rectangles surrounding the area we want to hide, and create a mask out of it.
CGPath path = new CGPath();
// top
path.AddRect(new RectangleF(0, 0, bounds.get_Width(), _hidden.get_Top()));
// bottom
path.AddRect(new RectangleF(0, _hidden.get_Bottom(), bounds.get_Width(),
bounds.get_Bottom() - _hidden.get_Bottom()));
// left
path.AddRect(new RectangleF(0, _hidden.get_Top(), _hidden.get_Left(), _hidden.get_Height()));
// right
path.AddRect(new RectangleF(_hidden.get_Right(), _hidden.get_Top(), bounds.get_Right()
- _hidden.get_Right(), _hidden.get_Height()));
maskLayer.set_Path(path);
get_Layer().set_Mask(maskLayer);
}
protected RectangleF _hidden;
}
| bsd-3-clause |
dropbox/godropbox | io2/reader_to_writer_adapter_test.go | 6281 | package io2
import (
"bytes"
"compress/zlib"
"errors"
"io"
"strings"
. "gopkg.in/check.v1"
)
type ReaderToWriterAdapterSuite struct {
testData string
}
func (rwself *ReaderToWriterAdapterSuite) SetUpTest(c *C) {
localWords := []string{}
for skip := 1; skip < len(words); skip += 6 {
lskip := skip
for i := 0; i < len(words); i += (lskip % 16) {
localWords = append(localWords,
words[i]+string([]byte{byte(i*len(words)+skip)%32 + byte('a')}))
if lskip > 1 {
lskip -= 1
}
}
}
rwself.testData = strings.Join(localWords, " _ ")
}
func (rwself *ReaderToWriterAdapterSuite) TestZlibPipeline(c *C) {
input := bytes.NewBuffer([]byte(rwself.testData))
var compressedOutput bytes.Buffer
compressor, rwaerr := NewReaderToWriterAdapter(
func(a io.Writer) (io.Writer, error) { ret := zlib.NewWriter(a); return ret, nil },
input)
c.Assert(rwaerr, IsNil)
skip := 1
ci := input.Bytes()
var ioerr error
for ioerr == nil {
if skip > len(ci) {
skip = len(ci)
}
buffer := make([]byte, skip)
var count int
count, ioerr = compressor.Read(buffer)
_, _ = compressedOutput.Write(buffer[:count])
if ioerr != io.EOF {
c.Assert(ioerr, IsNil)
}
skip %= 128
skip += 1
}
compressedForm := compressedOutput.Bytes()
r, err := zlib.NewReader(bytes.NewBuffer(compressedForm))
c.Assert(err, IsNil)
var finalOutput bytes.Buffer
_, err = io.Copy(&finalOutput, r)
c.Assert(err, IsNil)
ioerr = compressor.Close()
c.Assert(ioerr, IsNil)
c.Assert(string(finalOutput.Bytes()), Equals, rwself.testData)
}
type DoubleZlibWriter struct {
firstZlib io.WriteCloser
secondZlib io.WriteCloser
}
func NewDoubleZlibWriter(output io.Writer) DoubleZlibWriter {
dzw := DoubleZlibWriter{firstZlib: zlib.NewWriter(output)}
dzw.secondZlib = zlib.NewWriter(dzw.firstZlib)
return dzw
}
func (dzself *DoubleZlibWriter) Write(data []byte) (int, error) {
return dzself.secondZlib.Write(data)
}
func (dzself *DoubleZlibWriter) Close() error {
err := dzself.secondZlib.Close()
err2 := dzself.firstZlib.Close()
if err != nil {
return err
}
return err2
}
func (rwself *ReaderToWriterAdapterSuite) TestDoubleZlibPipeline(c *C) {
input := bytes.NewBuffer([]byte(rwself.testData))
var compressedOutput bytes.Buffer
compressor, rwaerr := NewReaderToWriterAdapter(
func(a io.Writer) (io.Writer, error) {
ret := NewDoubleZlibWriter(a)
return &ret, nil
},
input)
c.Assert(rwaerr, IsNil)
skip := 1
ci := input.Bytes()
var ioerr error
for ioerr == nil {
if skip > len(ci) {
skip = len(ci)
}
buffer := make([]byte, skip)
var count int
count, ioerr = compressor.Read(buffer)
_, _ = compressedOutput.Write(buffer[:count])
if ioerr != io.EOF {
c.Assert(ioerr, IsNil)
}
skip %= 511
skip += 1
}
compressedForm := compressedOutput.Bytes()
r, err := zlib.NewReader(bytes.NewBuffer(compressedForm))
c.Assert(err, IsNil)
r, err = zlib.NewReader(r)
c.Assert(err, IsNil)
var finalOutput bytes.Buffer
_, err = io.Copy(&finalOutput, r)
c.Assert(err, IsNil)
ioerr = compressor.Close()
c.Assert(ioerr, IsNil)
c.Assert(string(finalOutput.Bytes()), Equals, rwself.testData)
}
var _ = Suite(&ReaderToWriterAdapterSuite{})
func (rwself *ReaderToWriterAdapterSuite) TestEarlyError(c *C) {
err := errors.New("Just kidding")
_, rwaerr := NewReaderToWriterAdapter(
func(a io.Writer) (io.Writer, error) { return nil, err },
bytes.NewBuffer([]byte(rwself.testData)))
c.Assert(rwaerr, Equals, err)
}
type ErrorWriter struct {
}
var doa error = errors.New("DOA")
func (ewself ErrorWriter) Write(data []byte) (int, error) {
return 0, doa
}
func (ewself ErrorWriter) Close(data []byte) error {
return nil
}
func (rwself *ReaderToWriterAdapterSuite) TestFirstError(c *C) {
input := bytes.NewBuffer([]byte(rwself.testData))
compressor, rwaerr := NewReaderToWriterAdapter(
func(a io.Writer) (io.Writer, error) { ret := ErrorWriter{}; return ret, nil },
input)
c.Assert(rwaerr, IsNil)
skip := 1
var ioerr error
buffer := make([]byte, skip)
_, ioerr = compressor.Read(buffer)
c.Assert(ioerr, Equals, doa)
}
type CountErrorWriter struct {
count int
downstream io.Writer
}
func (ewself *CountErrorWriter) Write(data []byte) (int, error) {
if ewself.count == 0 {
return 0, doa
} else {
ewself.count -= 1
ewself.downstream.Write(data)
return len(data), nil
}
}
func (ewself *CountErrorWriter) Close() error {
if ewself.count <= -1 {
return doa
}
return nil
}
func (rwself *ReaderToWriterAdapterSuite) TestMidError(c *C) {
input := bytes.NewBuffer([]byte(rwself.testData))
var compressedOutput bytes.Buffer
compressor, rwaerr := NewReaderToWriterAdapter(
func(a io.Writer) (io.Writer, error) {
ret := CountErrorWriter{count: 1, downstream: a}
return &ret, nil
},
input)
c.Assert(rwaerr, IsNil)
skip := 1
ci := input.Bytes()
var ioerr error
okFound := false
badFound := false
for ioerr == nil {
if skip > len(ci) {
skip = len(ci)
}
buffer := make([]byte, skip)
var count int
count, ioerr = compressor.Read(buffer)
_, _ = compressedOutput.Write(buffer[:count])
if ioerr != io.EOF {
if ioerr == nil {
okFound = true
}
if ioerr == doa {
badFound = true
}
}
skip %= 128
skip += 1
}
c.Assert(okFound, Equals, true)
c.Assert(badFound, Equals, true)
ioerr = compressor.Close()
c.Assert(ioerr, IsNil)
}
func (rwself *ReaderToWriterAdapterSuite) TestFinalError(c *C) {
input := bytes.NewBuffer([]byte(rwself.testData))
var compressedOutput bytes.Buffer
compressor, rwaerr := NewReaderToWriterAdapter(
func(a io.Writer) (io.Writer, error) {
ret := CountErrorWriter{count: -1, downstream: a}
return &ret, nil
},
input)
c.Assert(rwaerr, IsNil)
skip := 1
ci := input.Bytes()
var ioerr error
okFound := false
badFound := false
for ioerr == nil {
if skip > len(ci) {
skip = len(ci)
}
buffer := make([]byte, skip)
var count int
count, ioerr = compressor.Read(buffer)
_, _ = compressedOutput.Write(buffer[:count])
if ioerr != io.EOF {
if ioerr == nil {
okFound = true
}
if ioerr == doa {
badFound = true
}
}
skip %= 128
skip += 1
}
c.Assert(okFound, Equals, true)
c.Assert(badFound, Equals, true)
ioerr = compressor.Close()
c.Assert(ioerr, IsNil)
}
| bsd-3-clause |
ljwolf/cytoolz | cytoolz/tests/test_embedded_sigs.py | 2950 | import inspect
import cytoolz
import toolz
from types import BuiltinFunctionType
from cytoolz import curry, identity, keyfilter, valfilter, merge_with
@curry
def isfrommod(modname, func):
mod = getattr(func, '__module__', '') or ''
return modname in mod
def test_class_sigs():
""" Test that all ``cdef class`` extension types in ``cytoolz`` have
correctly embedded the function signature as done in ``toolz``.
"""
# only consider items created in both `toolz` and `cytoolz`
toolz_dict = valfilter(isfrommod('toolz'), toolz.__dict__)
cytoolz_dict = valfilter(isfrommod('cytoolz'), cytoolz.__dict__)
# only test `cdef class` extensions from `cytoolz`
cytoolz_dict = valfilter(lambda x: not isinstance(x, BuiltinFunctionType),
cytoolz_dict)
# full API coverage should be tested elsewhere
toolz_dict = keyfilter(lambda x: x in cytoolz_dict, toolz_dict)
cytoolz_dict = keyfilter(lambda x: x in toolz_dict, cytoolz_dict)
d = merge_with(identity, toolz_dict, cytoolz_dict)
for key, (toolz_func, cytoolz_func) in d.items():
try:
# function
toolz_spec = inspect.getargspec(toolz_func)
except TypeError:
try:
# curried or partial object
toolz_spec = inspect.getargspec(toolz_func.func)
except (TypeError, AttributeError):
# class
toolz_spec = inspect.getargspec(toolz_func.__init__)
toolz_sig = toolz_func.__name__ + inspect.formatargspec(*toolz_spec)
if toolz_sig not in cytoolz_func.__doc__:
message = ('cytoolz.%s does not have correct function signature.'
'\n\nExpected: %s'
'\n\nDocstring in cytoolz is:\n%s'
% (key, toolz_sig, cytoolz_func.__doc__))
assert False, message
skip_sigs = ['identity']
aliases = {'comp': 'compose'}
def test_sig_at_beginning():
""" Test that the function signature is at the beginning of the docstring
and is followed by exactly one blank line.
"""
cytoolz_dict = valfilter(isfrommod('cytoolz'), cytoolz.__dict__)
cytoolz_dict = keyfilter(lambda x: x not in skip_sigs, cytoolz_dict)
for key, val in cytoolz_dict.items():
doclines = val.__doc__.splitlines()
assert len(doclines) > 2, (
'cytoolz.%s docstring too short:\n\n%s' % (key, val.__doc__))
sig = '%s(' % aliases.get(key, key)
assert sig in doclines[0], (
'cytoolz.%s docstring missing signature at beginning:\n\n%s'
% (key, val.__doc__))
assert not doclines[1], (
'cytoolz.%s docstring missing blank line after signature:\n\n%s'
% (key, val.__doc__))
assert doclines[2], (
'cytoolz.%s docstring too many blank lines after signature:\n\n%s'
% (key, val.__doc__))
| bsd-3-clause |
jithinazryah/emperror | backend/modules/admin/controllers/DefaultController.php | 390 | <?php
namespace backend\modules\admin\controllers;
use yii\web\Controller;
/**
* Default controller for the `admin` module
*/
class DefaultController extends Controller {
/**
* Renders the index view for the module
* @return string
*/
public function actionIndex() {
return $this->redirect('admin-posts/index');
}
}
| bsd-3-clause |
NCIP/webgenome | tags/WEBGENOME_R3.2_6MAR2009_BUILD1/java/core/src/org/rti/webgenome/client/ExperimentDTOGenerator.java | 1419 | /*L
* Copyright RTI International
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/webgenome/LICENSE.txt for details.
*/
package org.rti.webgenome.client;
/**
* Generates <code>ExperimentDTO</code> objects for testing.
* @author dhall
*
*/
public class ExperimentDTOGenerator {
/** Bioassay data transfer object generator. */
private final BioAssayDTOGenerator bioAssayDTOGenerator;
/** Number of bioassays per experiment. */
private final int numBioAssays;
/**
* Constructor.
* @param gap Gap between generated reporters.
* @param numBioAssays Number of bioassays generated per experiment.
*/
public ExperimentDTOGenerator(final long gap, final int numBioAssays) {
this.bioAssayDTOGenerator = new BioAssayDTOGenerator(gap);
this.numBioAssays = numBioAssays;
}
/**
* Generate new experiment data transfer object.
* @param experimentId Experiment ID.
* @param constraints Constraints.
* @return Experiment data transfer object
*/
public final ExperimentDTO newExperimentDTO(
final String experimentId,
final BioAssayDataConstraints[] constraints) {
BioAssayDTO[] bioAssayDtos = new BioAssayDTO[this.numBioAssays];
for (int i = 0; i < this.numBioAssays; i++) {
bioAssayDtos[i] =
this.bioAssayDTOGenerator.newBioAssayDTO(constraints);
}
return new DefExperimentDTOImpl(experimentId, bioAssayDtos);
}
}
| bsd-3-clause |
dushmis/Oracle-Cloud | PaaS_SaaS_Accelerator_RESTFulFacade/XJC_Beans/src/com/oracle/xmlns/apps/cdm/foundation/parties/locationservice/applicationmodule/types/UpdateLocation.java | 2082 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2013.10.24 at 02:08:27 PM BST
//
package com.oracle.xmlns.apps.cdm.foundation.parties.locationservice.applicationmodule.types;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import com.oracle.xmlns.apps.cdm.foundation.parties.locationservice.Location;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="location" type="{http://xmlns.oracle.com/apps/cdm/foundation/parties/locationService/}Location"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"location"
})
@XmlRootElement(name = "updateLocation")
public class UpdateLocation {
@XmlElement(required = true)
protected Location location;
/**
* Gets the value of the location property.
*
* @return
* possible object is
* {@link Location }
*
*/
public Location getLocation() {
return location;
}
/**
* Sets the value of the location property.
*
* @param value
* allowed object is
* {@link Location }
*
*/
public void setLocation(Location value) {
this.location = value;
}
}
| bsd-3-clause |
sgenoud/scikit-learn | examples/plot_kernel_approximation.py | 6494 | """
==================================================
Explicit feature map approximation for RBF kernels
==================================================
.. currentmodule:: sklearn.kernel_approximation
An example shows how to use :class:`RBFSampler` to appoximate the feature map
of an RBF kernel for classification with an SVM on the digits dataset. Results
using a linear SVM in the original space, a linear SVM using the approximate
mapping and using a kernelized SVM are compared. Timings and accuracy for
varying amounts of Monte Carlo samplings for the approximate mapping are shown.
Sampling more dimensions clearly leads to better classification results, but
comes at a greater cost. This means there is a tradeoff between runtime and
accuracy, given by the parameter n_components. Note that solving the Linear
SVM and also the approximate kernel SVM could be greatly accelerated by using
stochastic gradient descent via :class:`sklearn.linear_model.SGDClassifier`.
This is not easily possible for the case of the kernelized SVM.
The second plot visualized the decision surfaces of the RBF kernel SVM and
the linear SVM with approximate kernel map.
The plot shows decision surfaces of the classifiers projected onto
the first two principal components of the data. This visualization should
be taken with a grain of salt since it is just an interesting slice through
the decision surface in 64 dimensions. In particular note that
a datapoint (represented as a dot) does not necessarily be classified
into the region it is lying in, since it will not lie on the plane
that the first two principal components span.
The usage of :class:`RBFSampler` is described in detail in
:ref:`kernel_approximation`.
"""
print __doc__
# Author: Gael Varoquaux <gael dot varoquaux at normalesup dot org>
# modified Andreas Mueller
# License: Simplified BSD
# Standard scientific Python imports
import pylab as pl
import numpy as np
from time import time
# Import datasets, classifiers and performance metrics
from sklearn import datasets, svm, pipeline
from sklearn.kernel_approximation import RBFSampler
from sklearn.decomposition import PCA
# The digits dataset
digits = datasets.load_digits(n_class=9)
# To apply an classifier on this data, we need to flatten the image, to
# turn the data in a (samples, feature) matrix:
n_samples = len(digits.data)
data = digits.data / 16.
data -= data.mean(axis=0)
# We learn the digits on the first half of the digits
data_train, targets_train = data[:n_samples / 2], digits.target[:n_samples / 2]
# Now predict the value of the digit on the second half:
data_test, targets_test = data[n_samples / 2:], digits.target[n_samples / 2:]
#data_test = scaler.transform(data_test)
# Create a classifier: a support vector classifier
kernel_svm = svm.SVC(gamma=.2)
linear_svm = svm.LinearSVC()
# create pipeline from kernel approximation
# and linear svm
feature_map = RBFSampler(gamma=.2, random_state=1)
approx_kernel_svm = pipeline.Pipeline([("feature_map", feature_map),
("svm", svm.LinearSVC())])
# fit and predict using linear and kernel svm:
kernel_svm_time = time()
kernel_svm.fit(data_train, targets_train)
kernel_svm_score = kernel_svm.score(data_test, targets_test)
kernel_svm_time = time() - kernel_svm_time
linear_svm_time = time()
linear_svm.fit(data_train, targets_train)
linear_svm_score = linear_svm.score(data_test, targets_test)
linear_svm_time = time() - linear_svm_time
sample_sizes = 50 * np.arange(1, 10)
approx_kernel_scores = []
approx_kernel_times = []
for D in sample_sizes:
approx_kernel_svm.set_params(feature_map__n_components=D)
approx_kernel_timing = time()
approx_kernel_svm.fit(data_train, targets_train)
approx_kernel_times.append(time() - approx_kernel_timing)
score = approx_kernel_svm.score(data_test, targets_test)
approx_kernel_scores.append(score)
# plot the results:
accuracy = pl.subplot(211)
# second y axis for timeings
timescale = pl.subplot(212)
accuracy.plot(sample_sizes, approx_kernel_scores, label="approx. kernel")
timescale.plot(sample_sizes, approx_kernel_times, '--',
label='approx. kernel')
# horizontal lines for exact rbf and linear kernels:
accuracy.plot([sample_sizes[0], sample_sizes[-1]], [linear_svm_score,
linear_svm_score], label="linear svm")
timescale.plot([sample_sizes[0], sample_sizes[-1]], [linear_svm_time,
linear_svm_time], '--', label='linear svm')
accuracy.plot([sample_sizes[0], sample_sizes[-1]], [kernel_svm_score,
kernel_svm_score], label="rbf svm")
timescale.plot([sample_sizes[0], sample_sizes[-1]], [kernel_svm_time,
kernel_svm_time], '--', label='rbf svm')
# vertical line for dataset dimensionality = 64
accuracy.plot([64, 64], [0.7, 1], label="n_features")
# legends and labels
accuracy.set_title("Classification accuracy")
timescale.set_title("Training times")
accuracy.set_xlim(sample_sizes[0], sample_sizes[-1])
accuracy.set_xticks(())
accuracy.set_ylim(np.min(approx_kernel_scores), 1)
timescale.set_xlabel("Sampling steps = transformed feature dimension")
accuracy.set_ylabel("Classification accuracy")
timescale.set_ylabel("Training time in seconds")
accuracy.legend(loc='best')
timescale.legend(loc='best')
# visualize the decision surface, projected down to the first
# two principal components of the dataset
pca = PCA(n_components=8).fit(data_train)
X = pca.transform(data_train)
# Gemerate grid along first two principal components
multiples = np.arange(-2, 2, 0.1)
# steps along first component
first = multiples[:, np.newaxis] * pca.components_[0, :]
# steps along second component
second = multiples[:, np.newaxis] * pca.components_[1, :]
# combine
grid = first[np.newaxis, :, :] + second[:, np.newaxis, :]
flat_grid = grid.reshape(-1, data.shape[1])
# title for the plots
titles = ['SVC with rbf kernel',
'SVC (linear kernel) with rbf feature map\n n_components=100']
pl.figure(figsize=(12, 5))
# predict and plot
for i, clf in enumerate((kernel_svm, approx_kernel_svm)):
# Plot the decision boundary. For that, we will asign a color to each
# point in the mesh [x_min, m_max]x[y_min, y_max].
pl.subplot(1, 2, i + 1)
Z = clf.predict(flat_grid)
# Put the result into a color plot
Z = Z.reshape(grid.shape[:-1])
pl.contourf(multiples, multiples, Z, cmap=pl.cm.Paired)
pl.axis('off')
# Plot also the training points
pl.scatter(X[:, 0], X[:, 1], c=targets_train, cmap=pl.cm.Paired)
pl.title(titles[i])
pl.show()
| bsd-3-clause |
vovanbo/djangocms-redirects | cms_redirects/__init__.py | 69 | """django-cms-redirects"""
VERSION = (1, 0, 6)
__version__ = "1.0.6"
| bsd-3-clause |
7kbird/chrome | chrome/browser/task_manager/guest_information.cc | 4136 | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/task_manager/guest_information.h"
#include "base/strings/string16.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/favicon/favicon_tab_helper.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/task_manager/renderer_resource.h"
#include "chrome/browser/task_manager/resource_provider.h"
#include "chrome/browser/task_manager/task_manager.h"
#include "chrome/browser/task_manager/task_manager_util.h"
#include "chrome/grit/generated_resources.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/render_widget_host_iterator.h"
#include "content/public/browser/site_instance.h"
#include "content/public/browser/web_contents.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/gfx/image/image.h"
#include "ui/gfx/image/image_skia.h"
using content::RenderProcessHost;
using content::RenderViewHost;
using content::RenderWidgetHost;
using content::WebContents;
using extensions::Extension;
namespace task_manager {
class GuestResource : public RendererResource {
public:
explicit GuestResource(content::RenderViewHost* render_view_host);
virtual ~GuestResource();
// Resource methods:
virtual Type GetType() const OVERRIDE;
virtual base::string16 GetTitle() const OVERRIDE;
virtual gfx::ImageSkia GetIcon() const OVERRIDE;
virtual content::WebContents* GetWebContents() const OVERRIDE;
private:
DISALLOW_COPY_AND_ASSIGN(GuestResource);
};
GuestResource::GuestResource(RenderViewHost* render_view_host)
: RendererResource(
render_view_host->GetSiteInstance()->GetProcess()->GetHandle(),
render_view_host) {
}
GuestResource::~GuestResource() {
}
Resource::Type GuestResource::GetType() const {
return GUEST;
}
base::string16 GuestResource::GetTitle() const {
WebContents* web_contents = GetWebContents();
const int message_id = IDS_TASK_MANAGER_WEBVIEW_TAG_PREFIX;
if (web_contents) {
base::string16 title = util::GetTitleFromWebContents(web_contents);
return l10n_util::GetStringFUTF16(message_id, title);
}
return l10n_util::GetStringFUTF16(message_id, base::string16());
}
gfx::ImageSkia GuestResource::GetIcon() const {
WebContents* web_contents = GetWebContents();
if (web_contents && FaviconTabHelper::FromWebContents(web_contents)) {
return FaviconTabHelper::FromWebContents(web_contents)->
GetFavicon().AsImageSkia();
}
return gfx::ImageSkia();
}
WebContents* GuestResource::GetWebContents() const {
return WebContents::FromRenderViewHost(render_view_host());
}
////////////////////////////////////////////////////////////////////////////////
// GuestInformation class
////////////////////////////////////////////////////////////////////////////////
GuestInformation::GuestInformation() {}
GuestInformation::~GuestInformation() {}
bool GuestInformation::CheckOwnership(WebContents* web_contents) {
// Guest WebContentses are created and owned internally by the content layer.
return web_contents->IsSubframe();
}
void GuestInformation::GetAll(const NewWebContentsCallback& callback) {
scoped_ptr<content::RenderWidgetHostIterator> widgets(
content::RenderWidgetHost::GetRenderWidgetHosts());
while (content::RenderWidgetHost* widget = widgets->GetNextHost()) {
if (widget->IsRenderView()) {
content::RenderViewHost* rvh = content::RenderViewHost::From(widget);
WebContents* web_contents = WebContents::FromRenderViewHost(rvh);
if (web_contents && web_contents->IsSubframe())
callback.Run(web_contents);
}
}
}
scoped_ptr<RendererResource> GuestInformation::MakeResource(
WebContents* web_contents) {
return scoped_ptr<RendererResource>(
new GuestResource(web_contents->GetRenderViewHost()));
}
} // namespace task_manager
| bsd-3-clause |
carloscanova/python-odml | odml/gui/__main__.py | 845 | #!/usr/bin/env python
import gtk
import Editor
def main(filenames=[]):
"""
start the editor, with a new empty document
or load all *filenames* as tabs
returns the tab object
"""
Editor.register_stock_icons()
editor = Editor.EditorWindow()
tabs = map(editor.load_document, filenames)
if len(filenames) == 0:
editor.welcome()
return tabs
def run():
"""
handle all initialisation and start main() and gtk.main()
"""
try: # this works only on linux
from ctypes import cdll
libc = cdll.LoadLibrary("libc.so.6")
libc.prctl(15, 'odMLEditor', 0, 0, 0)
except:
pass
from optparse import OptionParser
parser = OptionParser()
(options, args) = parser.parse_args()
main(filenames=args)
gtk.main()
if __name__=="__main__":
run()
| bsd-3-clause |
vebin/rhino-dht | Rhino.DistributedHashTable/Protocol/regen.cmd | 134 | ..\..\..\SharedLibs\Google\protoc ProtocolDef.proto -oProtocolDef.proto.bin
..\..\..\SharedLibs\Google\protogen ProtocolDef.proto.bin | bsd-3-clause |
danakj/chromium | components/upload_list/upload_list.h | 4200 | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMPONENTS_UPLOAD_LIST_UPLOAD_LIST_H_
#define COMPONENTS_UPLOAD_LIST_UPLOAD_LIST_H_
#include <stddef.h>
#include <string>
#include <vector>
#include "base/files/file_path.h"
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "base/threading/thread_checker.h"
#include "base/time/time.h"
namespace base {
class SequencedTaskRunner;
class SequencedWorkerPool;
}
// Loads and parses an upload list text file of the format
// upload_time,upload_id[,local_id[,capture_time[,state]]]
// upload_time,upload_id[,local_id[,capture_time[,state]]]
// etc.
// where each line represents an upload. |upload_time| and |capture_time| are in
// Unix time. |state| is an int in the range of UploadInfo::State. Must be used
// from the UI thread. The loading and parsing is done on a blocking pool task
// runner. A line may or may not contain |local_id|, |capture_time|, and
// |state|.
class UploadList : public base::RefCountedThreadSafe<UploadList> {
public:
struct UploadInfo {
enum class State {
NotUploaded = 0,
Pending = 1,
Uploaded = 2,
};
UploadInfo(const std::string& upload_id,
const base::Time& upload_time,
const std::string& local_id,
const base::Time& capture_time,
State state);
UploadInfo(const std::string& upload_id, const base::Time& upload_time);
~UploadInfo();
// These fields are only valid when |state| == UploadInfo::State::Uploaded.
std::string upload_id;
base::Time upload_time;
// ID for locally stored data that may or may not be uploaded.
std::string local_id;
// The time the data was captured. This is useful if the data is stored
// locally when captured and uploaded at a later time.
base::Time capture_time;
State state;
};
class Delegate {
public:
// Invoked when the upload list has been loaded. Will be called on the
// UI thread.
virtual void OnUploadListAvailable() = 0;
protected:
virtual ~Delegate() {}
};
// Creates a new upload list with the given callback delegate.
UploadList(Delegate* delegate,
const base::FilePath& upload_log_path,
const scoped_refptr<base::SequencedWorkerPool>& worker_pool);
// Starts loading the upload list. OnUploadListAvailable will be called when
// loading is complete.
void LoadUploadListAsynchronously();
// Clears the delegate, so that any outstanding asynchronous load will not
// call the delegate on completion.
void ClearDelegate();
// Populates |uploads| with the |max_count| most recent uploads,
// in reverse chronological order.
// Must be called only after OnUploadListAvailable has been called.
void GetUploads(size_t max_count, std::vector<UploadInfo>* uploads);
protected:
virtual ~UploadList();
// Reads the upload log and stores the entries in |uploads|.
virtual void LoadUploadList(std::vector<UploadInfo>* uploads);
private:
friend class base::RefCountedThreadSafe<UploadList>;
// Manages the background thread work for LoadUploadListAsynchronously().
void PerformLoadAndNotifyDelegate(
const scoped_refptr<base::SequencedTaskRunner>& task_runner);
// Calls the delegate's callback method, if there is a delegate. Stores
// the newly loaded |uploads| into |uploads_| on the delegate's task runner.
void SetUploadsAndNotifyDelegate(std::vector<UploadInfo> uploads);
// Parses upload log lines, converting them to UploadInfo entries.
void ParseLogEntries(const std::vector<std::string>& log_entries,
std::vector<UploadInfo>* uploads);
// |thread_checker_| ensures that |uploads_| is only set from the task runner
// that created the UploadList.
base::ThreadChecker thread_checker_;
std::vector<UploadInfo> uploads_;
Delegate* delegate_;
const base::FilePath upload_log_path_;
scoped_refptr<base::SequencedWorkerPool> worker_pool_;
DISALLOW_COPY_AND_ASSIGN(UploadList);
};
#endif // COMPONENTS_UPLOAD_LIST_UPLOAD_LIST_H_
| bsd-3-clause |
bast/xcint | src/density/density.cpp | 42641 | #include "density.h"
#include <algorithm>
#include <cassert>
#include <cmath>
#include <cstddef>
#include <cstdio>
#include <iostream>
#include "blas_interface.h"
#include "compress.h"
void distribute_matrix(const int mat_dim,
const int block_length,
const bool use_gradient,
const bool use_tau,
const double prefactors[],
const double u[],
double fmat[],
const int k_aoc_num,
const int k_aoc_index[],
const double k_aoc[],
const int l_aoc_num,
const int l_aoc_index[],
const double l_aoc[])
{
// here we compute F(k, l) += AO_k(k, b) u(b) AO_l(l, b)
// in two steps
// step 1: W(k, b) = AO_k(k, b) u(b)
// step 2: F(k, l) += W(k, b) AO_l(l, b)^T
if (k_aoc_num == 0)
return;
if (l_aoc_num == 0)
return;
double *W = new double[k_aoc_num * block_length];
std::fill(&W[0], &W[block_length * k_aoc_num], 0.0);
int kc, lc, iboff;
int num_slices;
(use_gradient) ? (num_slices = 4) : (num_slices = 1);
for (int islice = 0; islice < num_slices; islice++)
{
if (std::abs(prefactors[islice]) > 0.0)
{
for (int k = 0; k < k_aoc_num; k++)
{
iboff = k * block_length;
for (int ib = 0; ib < block_length; ib++)
{
W[iboff + ib] +=
prefactors[islice] * u[islice * block_length + ib] *
k_aoc[islice * block_length * mat_dim + iboff + ib];
}
}
}
}
double *F = new double[k_aoc_num * l_aoc_num];
// we compute F(k, l) += W(k, b) AO_l(l, b)^T
// we transpose W instead of AO_l because we call fortran blas
char ta = 't';
char tb = 'n';
int im = l_aoc_num;
int in = k_aoc_num;
int ik = block_length;
int lda = ik;
int ldb = ik;
int ldc = im;
double alpha = 1.0;
double beta = 0.0;
wrap_dgemm(ta,
tb,
im,
in,
ik,
alpha,
l_aoc,
lda,
W,
ldb,
beta,
F,
ldc);
if (use_tau)
{
if (std::abs(prefactors[4]) > 0.0)
{
for (int ixyz = 0; ixyz < 3; ixyz++)
{
for (int k = 0; k < k_aoc_num; k++)
{
iboff = k * block_length;
for (int ib = 0; ib < block_length; ib++)
{
W[iboff + ib] =
u[4 * block_length + ib] *
k_aoc[(ixyz + 1) * block_length * mat_dim + iboff +
ib];
}
}
alpha = prefactors[4];
beta = 1.0;
wrap_dgemm(ta,
tb,
im,
in,
ik,
alpha,
W,
lda,
&l_aoc[(ixyz + 1) * block_length * mat_dim],
ldb,
beta,
F,
ldc);
}
}
}
delete[] W;
W = NULL;
// FIXME easier route possible if k and l match
for (int k = 0; k < k_aoc_num; k++)
{
kc = k_aoc_index[k];
for (int l = 0; l < l_aoc_num; l++)
{
lc = l_aoc_index[l];
fmat[kc * mat_dim + lc] += F[k * l_aoc_num + l];
}
}
delete[] F;
F = NULL;
}
void get_density(const int mat_dim,
const int block_length,
const bool use_gradient,
const bool use_tau,
const double prefactors[],
double density[],
const double dmat[],
const bool dmat_is_symmetric,
const bool kl_match,
const int k_aoc_num,
const int k_aoc_index[],
const double k_aoc[],
const int l_aoc_num,
const int l_aoc_index[],
const double l_aoc[])
{
// here we compute n(b) = AO_k(k, b) D(k, l) AO_l(l, b)
// in two steps
// step 1: X(k, b) = D(k, l) AO_l(l, b)
// step 2: n(b) = AO_k(k, b) X(k, b)
if (k_aoc_num == 0)
return;
if (l_aoc_num == 0)
return;
int kc, lc, iboff;
double *D = new double[k_aoc_num * l_aoc_num];
double *X = new double[k_aoc_num * block_length];
// compress dmat
if (kl_match)
{
if (dmat_is_symmetric)
{
for (int k = 0; k < k_aoc_num; k++)
{
kc = k_aoc_index[k];
for (int l = 0; l <= k; l++)
{
lc = l_aoc_index[l];
D[k * l_aoc_num + l] = 2.0 * dmat[kc * mat_dim + lc];
}
}
}
else
{
for (int k = 0; k < k_aoc_num; k++)
{
kc = k_aoc_index[k];
for (int l = 0; l < l_aoc_num; l++)
{
lc = l_aoc_index[l];
D[k * l_aoc_num + l] = 2.0 * dmat[kc * mat_dim + lc];
}
}
}
}
else
{
if (dmat_is_symmetric)
{
for (int k = 0; k < k_aoc_num; k++)
{
kc = k_aoc_index[k];
for (int l = 0; l < l_aoc_num; l++)
{
lc = l_aoc_index[l];
D[k * l_aoc_num + l] = 2.0 * dmat[kc * mat_dim + lc];
}
}
}
else
{
for (int k = 0; k < k_aoc_num; k++)
{
kc = k_aoc_index[k];
for (int l = 0; l < l_aoc_num; l++)
{
lc = l_aoc_index[l];
D[k * l_aoc_num + l] =
dmat[kc * mat_dim + lc] + dmat[lc * mat_dim + kc];
}
}
}
}
// form xmat
if (dmat_is_symmetric)
{
char si = 'r';
char up = 'u';
int im = block_length;
int in = k_aoc_num;
int lda = in;
int ldb = im;
int ldc = im;
double alpha = 1.0;
double beta = 0.0;
wrap_dsymm(
si, up, im, in, alpha, D, lda, l_aoc, ldb, beta, X, ldc);
}
else
{
char ta = 'n';
char tb = 'n';
int im = block_length;
int in = k_aoc_num;
int ik = l_aoc_num;
int lda = im;
int ldb = ik;
int ldc = im;
double alpha = 1.0;
double beta = 0.0;
wrap_dgemm(ta,
tb,
im,
in,
ik,
alpha,
l_aoc,
lda,
D,
ldb,
beta,
X,
ldc);
}
int num_slices;
(use_gradient) ? (num_slices = 4) : (num_slices = 1);
// it is not ok to zero out here since geometric
// derivatives are accumulated from several contributions
// std::fill(&density[0], &density[num_slices * block_length], 0.0);
// assemble density and possibly gradient
for (int islice = 0; islice < num_slices; islice++)
{
if (std::abs(prefactors[islice]) > 0.0)
{
for (int k = 0; k < k_aoc_num; k++)
{
iboff = k * block_length;
for (int ib = 0; ib < block_length; ib++)
{
density[islice * block_length + ib] +=
prefactors[islice] * X[iboff + ib] *
k_aoc[islice * block_length * mat_dim + iboff + ib];
}
}
}
}
if (use_tau)
{
if (std::abs(prefactors[4]) > 0.0)
{
for (int ixyz = 0; ixyz < 3; ixyz++)
{
if (dmat_is_symmetric)
{
char si = 'r';
char up = 'u';
int im = block_length;
int in = k_aoc_num;
int lda = in;
int ldb = im;
int ldc = im;
double alpha = 1.0;
double beta = 0.0;
wrap_dsymm(si,
up,
im,
in,
alpha,
D,
lda,
&l_aoc[(ixyz + 1) * block_length * mat_dim],
ldb,
beta,
X,
ldc);
}
else
{
char ta = 'n';
char tb = 'n';
int im = block_length;
int in = k_aoc_num;
int ik = l_aoc_num;
int lda = im;
int ldb = ik;
int ldc = im;
double alpha = 1.0;
double beta = 0.0;
wrap_dgemm(ta,
tb,
im,
in,
ik,
alpha,
&l_aoc[(ixyz + 1) * block_length * mat_dim],
lda,
D,
ldb,
beta,
X,
ldc);
}
for (int k = 0; k < k_aoc_num; k++)
{
iboff = k * block_length;
for (int ib = 0; ib < block_length; ib++)
{
density[4 * block_length + ib] +=
prefactors[4] * X[iboff + ib] *
k_aoc[(ixyz + 1) * block_length * mat_dim + iboff +
ib];
}
}
}
}
}
delete[] D;
D = NULL;
delete[] X;
X = NULL;
}
void get_dens_geo_derv(const int mat_dim,
const int num_aos,
const int block_length,
const int buffer_len,
const double ao[],
const int ao_centers[],
const bool use_gradient,
const bool use_tau,
const std::vector<int> &coor,
std::function<int(int, int, int)> get_geo_offset,
double density[],
const double mat[])
{
/*
1st a,0
2nd ab,0 a,b
/ \ / \
/ \ / \
3rd abc,0 ab,c ac,b a,bc
/ \ / \ / \ / \
4th abcd,0 abc,d abd,c ab,cd acd,b ac,bd ad,bc a,bcd
*/
for (unsigned int i = 0; i < coor.size(); i++)
{
if (coor[i] == 0)
return;
}
// there is a factor 2 because center-a
// differentiation can be left or right
double f = 2.0 * pow(-1.0, (int)coor.size());
std::vector<int> k_coor;
std::vector<int> l_coor;
switch (coor.size())
{
// FIXME implement shortcuts
case 1:
k_coor.push_back(coor[0]);
diff_u_wrt_center_tuple(mat_dim,
num_aos,
block_length,
buffer_len,
ao,
ao_centers,
use_gradient,
use_tau,
f,
get_geo_offset,
k_coor,
l_coor,
density,
mat);
k_coor.clear();
l_coor.clear();
break;
case 2:
k_coor.push_back(coor[0]);
k_coor.push_back(coor[1]);
diff_u_wrt_center_tuple(mat_dim,
num_aos,
block_length,
buffer_len,
ao,
ao_centers,
use_gradient,
use_tau,
f,
get_geo_offset,
k_coor,
l_coor,
density,
mat);
k_coor.clear();
l_coor.clear();
k_coor.push_back(coor[0]);
l_coor.push_back(coor[1]);
diff_u_wrt_center_tuple(mat_dim,
num_aos,
block_length,
buffer_len,
ao,
ao_centers,
use_gradient,
use_tau,
f,
get_geo_offset,
k_coor,
l_coor,
density,
mat);
k_coor.clear();
l_coor.clear();
break;
case 3:
k_coor.push_back(coor[0]);
k_coor.push_back(coor[1]);
k_coor.push_back(coor[2]);
diff_u_wrt_center_tuple(mat_dim,
num_aos,
block_length,
buffer_len,
ao,
ao_centers,
use_gradient,
use_tau,
f,
get_geo_offset,
k_coor,
l_coor,
density,
mat);
k_coor.clear();
l_coor.clear();
k_coor.push_back(coor[0]);
k_coor.push_back(coor[1]);
l_coor.push_back(coor[2]);
diff_u_wrt_center_tuple(mat_dim,
num_aos,
block_length,
buffer_len,
ao,
ao_centers,
use_gradient,
use_tau,
f,
get_geo_offset,
k_coor,
l_coor,
density,
mat);
k_coor.clear();
l_coor.clear();
k_coor.push_back(coor[0]);
l_coor.push_back(coor[1]);
l_coor.push_back(coor[2]);
diff_u_wrt_center_tuple(mat_dim,
num_aos,
block_length,
buffer_len,
ao,
ao_centers,
use_gradient,
use_tau,
f,
get_geo_offset,
k_coor,
l_coor,
density,
mat);
k_coor.clear();
l_coor.clear();
k_coor.push_back(coor[0]);
k_coor.push_back(coor[2]);
l_coor.push_back(coor[1]);
diff_u_wrt_center_tuple(mat_dim,
num_aos,
block_length,
buffer_len,
ao,
ao_centers,
use_gradient,
use_tau,
f,
get_geo_offset,
k_coor,
l_coor,
density,
mat);
k_coor.clear();
l_coor.clear();
break;
case 4:
k_coor.push_back(coor[0]);
k_coor.push_back(coor[1]);
k_coor.push_back(coor[2]);
k_coor.push_back(coor[3]);
diff_u_wrt_center_tuple(mat_dim,
num_aos,
block_length,
buffer_len,
ao,
ao_centers,
use_gradient,
use_tau,
f,
get_geo_offset,
k_coor,
l_coor,
density,
mat);
k_coor.clear();
l_coor.clear();
k_coor.push_back(coor[0]);
k_coor.push_back(coor[1]);
k_coor.push_back(coor[2]);
l_coor.push_back(coor[3]);
diff_u_wrt_center_tuple(mat_dim,
num_aos,
block_length,
buffer_len,
ao,
ao_centers,
use_gradient,
use_tau,
f,
get_geo_offset,
k_coor,
l_coor,
density,
mat);
k_coor.clear();
l_coor.clear();
k_coor.push_back(coor[0]);
k_coor.push_back(coor[1]);
l_coor.push_back(coor[2]);
l_coor.push_back(coor[3]);
diff_u_wrt_center_tuple(mat_dim,
num_aos,
block_length,
buffer_len,
ao,
ao_centers,
use_gradient,
use_tau,
f,
get_geo_offset,
k_coor,
l_coor,
density,
mat);
k_coor.clear();
l_coor.clear();
k_coor.push_back(coor[0]);
l_coor.push_back(coor[1]);
l_coor.push_back(coor[2]);
l_coor.push_back(coor[3]);
diff_u_wrt_center_tuple(mat_dim,
num_aos,
block_length,
buffer_len,
ao,
ao_centers,
use_gradient,
use_tau,
f,
get_geo_offset,
k_coor,
l_coor,
density,
mat);
k_coor.clear();
l_coor.clear();
k_coor.push_back(coor[0]);
k_coor.push_back(coor[1]);
k_coor.push_back(coor[3]);
l_coor.push_back(coor[2]);
diff_u_wrt_center_tuple(mat_dim,
num_aos,
block_length,
buffer_len,
ao,
ao_centers,
use_gradient,
use_tau,
f,
get_geo_offset,
k_coor,
l_coor,
density,
mat);
k_coor.clear();
l_coor.clear();
k_coor.push_back(coor[0]);
k_coor.push_back(coor[2]);
k_coor.push_back(coor[3]);
l_coor.push_back(coor[1]);
diff_u_wrt_center_tuple(mat_dim,
num_aos,
block_length,
buffer_len,
ao,
ao_centers,
use_gradient,
use_tau,
f,
get_geo_offset,
k_coor,
l_coor,
density,
mat);
k_coor.clear();
l_coor.clear();
k_coor.push_back(coor[0]);
k_coor.push_back(coor[2]);
l_coor.push_back(coor[1]);
l_coor.push_back(coor[3]);
diff_u_wrt_center_tuple(mat_dim,
num_aos,
block_length,
buffer_len,
ao,
ao_centers,
use_gradient,
use_tau,
f,
get_geo_offset,
k_coor,
l_coor,
density,
mat);
k_coor.clear();
l_coor.clear();
k_coor.push_back(coor[0]);
k_coor.push_back(coor[3]);
l_coor.push_back(coor[1]);
l_coor.push_back(coor[2]);
diff_u_wrt_center_tuple(mat_dim,
num_aos,
block_length,
buffer_len,
ao,
ao_centers,
use_gradient,
use_tau,
f,
get_geo_offset,
k_coor,
l_coor,
density,
mat);
k_coor.clear();
l_coor.clear();
break;
default:
std::cout << "ERROR: get_dens_geo_derv coor.size() too high\n";
exit(1);
break;
}
}
void get_mat_geo_derv(const int mat_dim,
const int num_aos,
const int block_length,
const int buffer_len,
const double ao[],
const int ao_centers[],
const bool use_gradient,
const bool use_tau,
const std::vector<int> &coor,
std::function<int(int, int, int)> get_geo_offset,
const double density[],
double mat[])
{
/*
1st a,0
2nd ab,0 a,b
/ \ / \
/ \ / \
3rd abc,0 ab,c ac,b a,bc
/ \ / \ / \ / \
4th abcd,0 abc,d abd,c ab,cd acd,b ac,bd ad,bc a,bcd
*/
for (unsigned int i = 0; i < coor.size(); i++)
{
if (coor[i] == 0)
return;
}
// there is a factor 2 because center-a
// differentiation can be left or right
double f = 2.0 * pow(-1.0, (int)coor.size());
std::vector<int> k_coor;
std::vector<int> l_coor;
switch (coor.size())
{
// FIXME implement shortcuts
case 1:
k_coor.push_back(coor[0]);
diff_M_wrt_center_tuple(mat_dim,
num_aos,
block_length,
buffer_len,
ao,
ao_centers,
use_gradient,
use_tau,
f,
get_geo_offset,
k_coor,
l_coor,
density,
mat);
k_coor.clear();
l_coor.clear();
break;
case 2:
k_coor.push_back(coor[0]);
k_coor.push_back(coor[1]);
diff_M_wrt_center_tuple(mat_dim,
num_aos,
block_length,
buffer_len,
ao,
ao_centers,
use_gradient,
use_tau,
f,
get_geo_offset,
k_coor,
l_coor,
density,
mat);
k_coor.clear();
l_coor.clear();
k_coor.push_back(coor[0]);
l_coor.push_back(coor[1]);
diff_M_wrt_center_tuple(mat_dim,
num_aos,
block_length,
buffer_len,
ao,
ao_centers,
use_gradient,
use_tau,
f,
get_geo_offset,
k_coor,
l_coor,
density,
mat);
k_coor.clear();
l_coor.clear();
break;
case 3:
k_coor.push_back(coor[0]);
k_coor.push_back(coor[1]);
k_coor.push_back(coor[2]);
diff_M_wrt_center_tuple(mat_dim,
num_aos,
block_length,
buffer_len,
ao,
ao_centers,
use_gradient,
use_tau,
f,
get_geo_offset,
k_coor,
l_coor,
density,
mat);
k_coor.clear();
l_coor.clear();
k_coor.push_back(coor[0]);
k_coor.push_back(coor[1]);
l_coor.push_back(coor[2]);
diff_M_wrt_center_tuple(mat_dim,
num_aos,
block_length,
buffer_len,
ao,
ao_centers,
use_gradient,
use_tau,
f,
get_geo_offset,
k_coor,
l_coor,
density,
mat);
k_coor.clear();
l_coor.clear();
k_coor.push_back(coor[0]);
l_coor.push_back(coor[1]);
l_coor.push_back(coor[2]);
diff_M_wrt_center_tuple(mat_dim,
num_aos,
block_length,
buffer_len,
ao,
ao_centers,
use_gradient,
use_tau,
f,
get_geo_offset,
k_coor,
l_coor,
density,
mat);
k_coor.clear();
l_coor.clear();
k_coor.push_back(coor[0]);
k_coor.push_back(coor[2]);
l_coor.push_back(coor[1]);
diff_M_wrt_center_tuple(mat_dim,
num_aos,
block_length,
buffer_len,
ao,
ao_centers,
use_gradient,
use_tau,
f,
get_geo_offset,
k_coor,
l_coor,
density,
mat);
k_coor.clear();
l_coor.clear();
break;
case 4:
k_coor.push_back(coor[0]);
k_coor.push_back(coor[1]);
k_coor.push_back(coor[2]);
k_coor.push_back(coor[3]);
diff_M_wrt_center_tuple(mat_dim,
num_aos,
block_length,
buffer_len,
ao,
ao_centers,
use_gradient,
use_tau,
f,
get_geo_offset,
k_coor,
l_coor,
density,
mat);
k_coor.clear();
l_coor.clear();
k_coor.push_back(coor[0]);
k_coor.push_back(coor[1]);
k_coor.push_back(coor[2]);
l_coor.push_back(coor[3]);
diff_M_wrt_center_tuple(mat_dim,
num_aos,
block_length,
buffer_len,
ao,
ao_centers,
use_gradient,
use_tau,
f,
get_geo_offset,
k_coor,
l_coor,
density,
mat);
k_coor.clear();
l_coor.clear();
k_coor.push_back(coor[0]);
k_coor.push_back(coor[1]);
l_coor.push_back(coor[2]);
l_coor.push_back(coor[3]);
diff_M_wrt_center_tuple(mat_dim,
num_aos,
block_length,
buffer_len,
ao,
ao_centers,
use_gradient,
use_tau,
f,
get_geo_offset,
k_coor,
l_coor,
density,
mat);
k_coor.clear();
l_coor.clear();
k_coor.push_back(coor[0]);
l_coor.push_back(coor[1]);
l_coor.push_back(coor[2]);
l_coor.push_back(coor[3]);
diff_M_wrt_center_tuple(mat_dim,
num_aos,
block_length,
buffer_len,
ao,
ao_centers,
use_gradient,
use_tau,
f,
get_geo_offset,
k_coor,
l_coor,
density,
mat);
k_coor.clear();
l_coor.clear();
k_coor.push_back(coor[0]);
k_coor.push_back(coor[1]);
k_coor.push_back(coor[3]);
l_coor.push_back(coor[2]);
diff_M_wrt_center_tuple(mat_dim,
num_aos,
block_length,
buffer_len,
ao,
ao_centers,
use_gradient,
use_tau,
f,
get_geo_offset,
k_coor,
l_coor,
density,
mat);
k_coor.clear();
l_coor.clear();
k_coor.push_back(coor[0]);
k_coor.push_back(coor[2]);
k_coor.push_back(coor[3]);
l_coor.push_back(coor[1]);
diff_M_wrt_center_tuple(mat_dim,
num_aos,
block_length,
buffer_len,
ao,
ao_centers,
use_gradient,
use_tau,
f,
get_geo_offset,
k_coor,
l_coor,
density,
mat);
k_coor.clear();
l_coor.clear();
k_coor.push_back(coor[0]);
k_coor.push_back(coor[2]);
l_coor.push_back(coor[1]);
l_coor.push_back(coor[3]);
diff_M_wrt_center_tuple(mat_dim,
num_aos,
block_length,
buffer_len,
ao,
ao_centers,
use_gradient,
use_tau,
f,
get_geo_offset,
k_coor,
l_coor,
density,
mat);
k_coor.clear();
l_coor.clear();
k_coor.push_back(coor[0]);
k_coor.push_back(coor[3]);
l_coor.push_back(coor[1]);
l_coor.push_back(coor[2]);
diff_M_wrt_center_tuple(mat_dim,
num_aos,
block_length,
buffer_len,
ao,
ao_centers,
use_gradient,
use_tau,
f,
get_geo_offset,
k_coor,
l_coor,
density,
mat);
k_coor.clear();
l_coor.clear();
break;
default:
std::cout << "ERROR: get_dens_geo_derv coor.size() too high\n";
exit(1);
break;
}
}
void diff_u_wrt_center_tuple(const int mat_dim,
const int num_aos,
const int block_length,
const int buffer_len,
const double ao[],
const int ao_centers[],
const bool use_gradient,
const bool use_tau,
const double f,
std::function<int(int, int, int)> get_geo_offset,
const std::vector<int> &k_coor,
const std::vector<int> &l_coor,
double u[],
const double M[])
{
double *k_ao_compressed = new double[buffer_len];
int *k_ao_compressed_index = new int[buffer_len];
int k_ao_compressed_num;
double *l_ao_compressed = new double[buffer_len];
int *l_ao_compressed_index = new int[buffer_len];
int l_ao_compressed_num;
int slice_offsets[4];
compute_slice_offsets(get_geo_offset, k_coor, slice_offsets);
compress(use_gradient,
block_length,
k_ao_compressed_num,
k_ao_compressed_index,
k_ao_compressed,
num_aos,
ao,
ao_centers,
k_coor,
slice_offsets);
compute_slice_offsets(get_geo_offset, l_coor, slice_offsets);
compress(use_gradient,
block_length,
l_ao_compressed_num,
l_ao_compressed_index,
l_ao_compressed,
num_aos,
ao,
ao_centers,
l_coor,
slice_offsets);
double prefactors[5] = {f, f, f, f, 0.5 * f};
// evaluate density dervs
get_density(mat_dim,
block_length,
use_gradient,
use_tau,
prefactors,
u,
M,
false,
false,
k_ao_compressed_num,
k_ao_compressed_index,
k_ao_compressed,
l_ao_compressed_num,
l_ao_compressed_index,
l_ao_compressed);
if (use_gradient)
{
prefactors[0] = 0.0;
get_density(mat_dim,
block_length,
use_gradient,
false,
prefactors,
u,
M,
false,
false,
l_ao_compressed_num,
l_ao_compressed_index,
l_ao_compressed,
k_ao_compressed_num,
k_ao_compressed_index,
k_ao_compressed);
}
delete[] k_ao_compressed;
delete[] k_ao_compressed_index;
delete[] l_ao_compressed;
delete[] l_ao_compressed_index;
}
void diff_M_wrt_center_tuple(const int mat_dim,
const int num_aos,
const int block_length,
const int buffer_len,
const double ao[],
const int ao_centers[],
const bool use_gradient,
const bool use_tau,
const double f,
std::function<int(int, int, int)> get_geo_offset,
const std::vector<int> &k_coor,
const std::vector<int> &l_coor,
const double u[],
double M[])
{
double *k_ao_compressed = new double[buffer_len];
int *k_ao_compressed_index = new int[buffer_len];
int k_ao_compressed_num;
double *l_ao_compressed = new double[buffer_len];
int *l_ao_compressed_index = new int[buffer_len];
int l_ao_compressed_num;
int slice_offsets[4];
compute_slice_offsets(get_geo_offset, k_coor, slice_offsets);
compress(use_gradient,
block_length,
k_ao_compressed_num,
k_ao_compressed_index,
k_ao_compressed,
num_aos,
ao,
ao_centers,
k_coor,
slice_offsets);
compute_slice_offsets(get_geo_offset, l_coor, slice_offsets);
compress(use_gradient,
block_length,
l_ao_compressed_num,
l_ao_compressed_index,
l_ao_compressed,
num_aos,
ao,
ao_centers,
l_coor,
slice_offsets);
double prefactors[5] = {f, f, f, f, 0.5 * f};
// distribute over XC potential derivative matrix
distribute_matrix(mat_dim,
block_length,
use_gradient,
use_tau,
prefactors,
u,
M,
k_ao_compressed_num,
k_ao_compressed_index,
k_ao_compressed,
l_ao_compressed_num,
l_ao_compressed_index,
l_ao_compressed);
if (use_gradient)
{
prefactors[0] = 0.0;
distribute_matrix(mat_dim,
block_length,
use_gradient,
false,
prefactors,
u,
M,
l_ao_compressed_num,
l_ao_compressed_index,
l_ao_compressed,
k_ao_compressed_num,
k_ao_compressed_index,
k_ao_compressed);
}
delete[] k_ao_compressed;
delete[] k_ao_compressed_index;
delete[] l_ao_compressed;
delete[] l_ao_compressed_index;
}
void compute_slice_offsets(std::function<int(int, int, int)> get_geo_offset,
const std::vector<int> &coor,
int off[])
{
int kp[3] = {0, 0, 0};
for (size_t j = 0; j < coor.size(); j++)
{
kp[(coor[j] - 1) % 3]++;
}
off[0] = get_geo_offset(kp[0], kp[1], kp[2]);
off[1] = get_geo_offset(kp[0] + 1, kp[1], kp[2]);
off[2] = get_geo_offset(kp[0], kp[1] + 1, kp[2]);
off[3] = get_geo_offset(kp[0], kp[1], kp[2] + 1);
}
| bsd-3-clause |
pyannote/pyannote-banyan | docs/find_local_performance.html | 8202 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Local-Find Performance — Banyan 0.1.5 documentation</title>
<link rel="stylesheet" href="_static/default.css" type="text/css" />
<link rel="stylesheet" href="_static/pygments.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: '',
VERSION: '0.1.5',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true
};
</script>
<script type="text/javascript" src="_static/jquery.js"></script>
<script type="text/javascript" src="_static/underscore.js"></script>
<script type="text/javascript" src="_static/doctools.js"></script>
<link rel="top" title="Banyan 0.1.5 documentation" href="index.html" />
</head>
<body>
<div class="related">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="General Index"
accesskey="I">index</a></li>
<li class="right" >
<a href="py-modindex.html" title="Python Module Index"
>modules</a> |</li>
<li><a href="index.html">Banyan 0.1.5 documentation</a> »</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body">
<div class="section" id="local-find-performance">
<h1>Local-Find Performance<a class="headerlink" href="#local-find-performance" title="Permalink to this headline">¶</a></h1>
<p>The tests measure the performance of sets and dicts with integer keys. The following implementation are compared:</p>
<ul class="simple">
<li>banyan_red_black_tree - <a class="reference internal" href="reference.html#sorted-set-class"><em>banyan.SortedSet</em></a> or <a class="reference internal" href="reference.html#sorted-dict-class"><em>banyan.SortedDict</em></a> with <tt class="docutils literal"><span class="pre">key_type</span> <span class="pre">=</span> <span class="pre">int</span></tt> or <tt class="docutils literal"><span class="pre">key_type</span> <span class="pre">=</span> <span class="pre">str</span></tt> and <tt class="docutils literal"><span class="pre">alg</span> <span class="pre">=</span> <span class="pre">banyan.RED_BLACK_TREE</span></tt></li>
<li>banyan_splay_tree - <a class="reference internal" href="reference.html#sorted-set-class"><em>banyan.SortedSet</em></a> or <a class="reference internal" href="reference.html#sorted-dict-class"><em>banyan.SortedDict</em></a> with <tt class="docutils literal"><span class="pre">key_type</span> <span class="pre">=</span> <span class="pre">int</span></tt> or <tt class="docutils literal"><span class="pre">key_type</span> <span class="pre">=</span> <span class="pre">str</span></tt> and <tt class="docutils literal"><span class="pre">alg</span> <span class="pre">=</span> <span class="pre">banyan.SPLAY_TREE</span></tt></li>
<li>banyan_sorted_list - <a class="reference internal" href="reference.html#sorted-set-class"><em>banyan.SortedSet</em></a> or <a class="reference internal" href="reference.html#sorted-dict-class"><em>banyan.SortedDict</em></a> with <tt class="docutils literal"><span class="pre">key_type</span> <span class="pre">=</span> <span class="pre">int</span></tt> or <tt class="docutils literal"><span class="pre">key_type</span> <span class="pre">=</span> <span class="pre">str</span></tt> and <tt class="docutils literal"><span class="pre">alg</span> <span class="pre">=</span> <span class="pre">banyan.SORTEDLISt</span></tt></li>
<li>banyan_red_black_tree_gen - <a class="reference internal" href="reference.html#sorted-set-class"><em>banyan.SortedSet</em></a> or <a class="reference internal" href="reference.html#sorted-dict-class"><em>banyan.SortedDict</em></a> without key-type specification and <tt class="docutils literal"><span class="pre">alg</span> <span class="pre">=</span> <span class="pre">banyan.RED_BLACK_TREE</span></tt></li>
<li>banyan_splay_tree_gen - <a class="reference internal" href="reference.html#sorted-set-class"><em>banyan.SortedSet</em></a> or <a class="reference internal" href="reference.html#sorted-dict-class"><em>banyan.SortedDict</em></a> without key-type specification and <tt class="docutils literal"><span class="pre">alg</span> <span class="pre">=</span> <span class="pre">banyan.SPLAY_TREE</span></tt></li>
<li>banyan_sorted_list_gen - <a class="reference internal" href="reference.html#sorted-set-class"><em>banyan.SortedSet</em></a> or <a class="reference internal" href="reference.html#sorted-dict-class"><em>banyan.SortedDict</em></a> without key-type specification <tt class="docutils literal"><span class="pre">alg</span> <span class="pre">=</span> <span class="pre">banyan.SORTEDLISt</span></tt></li>
<li>bintrees - A <a class="reference external" href="https://pypi.python.org/pypi/bintrees/1.0.1/">bintrees.FastRBTree</a> (V 1.0.1) red-black tree.</li>
<li>blist - A <a class="reference external" href="http://stutzbachenterprises.com/blist/sortedset.html">blist.sortedset</a> (V 1.3.4) BTree</li>
<li>btrees - A <a class="reference external" href="https://pypi.python.org/pypi/BTrees/4.0.5/">BTrees.OOBTree</a> (V 4.0.5) BTree</li>
<li>bx - A <a class="reference external" href="https://pypi.python.org/pypi/bx-python">bx</a> (V 0.7.1) tree</li>
<li>dict - <a class="reference external" href="http://docs.python.org/2/library/stdtypes.html#mapping-types-dict">Python’s (hash-based) dict</a></li>
<li>set - <a class="reference external" href="http://docs.python.org/2/library/stdtypes.html#set-types-set-frozenset">Python’s (hash-based) set</a></li>
</ul>
<p>The following figures show the running time of finding integers such that first one integer is found repeatedly, then the next one, and so forth, as a function of the number of integers (see <a class="reference download internal" href="_downloads/_set_find_local.py"><tt class="xref download docutils literal"><span class="pre">_set_find_local.py</span></tt></a> for the source).</p>
<p>The following figure shows the performance of all the implementations:</p>
<div class="figure">
<img alt="_images/IntSetFindLocalAll.png" src="_images/IntSetFindLocalAll.png" />
</div>
<p>The following figure shows the performance of all implementations with similar performance:</p>
<div class="figure">
<img alt="_images/IntSetFindLocalAllNoBList.png" src="_images/IntSetFindLocalAllNoBList.png" />
</div>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar">
<div class="sphinxsidebarwrapper">
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="_sources/find_local_performance.txt"
rel="nofollow">Show Source</a></li>
</ul>
<div id="searchbox" style="display: none">
<h3>Quick search</h3>
<form class="search" action="search.html" method="get">
<input type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
<p class="searchtip" style="font-size: 90%">
Enter search terms or a module, class or function name.
</p>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="related">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="General Index"
>index</a></li>
<li class="right" >
<a href="py-modindex.html" title="Python Module Index"
>modules</a> |</li>
<li><a href="index.html">Banyan 0.1.5 documentation</a> »</li>
</ul>
</div>
<div class="footer">
© Copyright 2013, Ami Tavory.
Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.1.3.
</div>
</body>
</html> | bsd-3-clause |
krisgiesing/sky_engine | lib/ui/window/window.cc | 10895 | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/lib/ui/window/window.h"
#include "flutter/lib/ui/compositing/scene.h"
#include "flutter/lib/ui/ui_dart_state.h"
#include "flutter/lib/ui/window/platform_message_response_dart.h"
#include "third_party/tonic/converter/dart_converter.h"
#include "third_party/tonic/dart_args.h"
#include "third_party/tonic/dart_library_natives.h"
#include "third_party/tonic/dart_microtask_queue.h"
#include "third_party/tonic/logging/dart_invoke.h"
#include "third_party/tonic/typed_data/dart_byte_data.h"
using tonic::DartInvokeField;
using tonic::DartState;
using tonic::StdStringToDart;
using tonic::ToDart;
namespace blink {
namespace {
void DefaultRouteName(Dart_NativeArguments args) {
std::string routeName =
UIDartState::Current()->window()->client()->DefaultRouteName();
Dart_SetReturnValue(args, StdStringToDart(routeName));
}
void ScheduleFrame(Dart_NativeArguments args) {
UIDartState::Current()->window()->client()->ScheduleFrame();
}
void Render(Dart_NativeArguments args) {
Dart_Handle exception = nullptr;
Scene* scene =
tonic::DartConverter<Scene*>::FromArguments(args, 1, exception);
if (exception) {
Dart_ThrowException(exception);
return;
}
UIDartState::Current()->window()->client()->Render(scene);
}
void UpdateSemantics(Dart_NativeArguments args) {
Dart_Handle exception = nullptr;
SemanticsUpdate* update =
tonic::DartConverter<SemanticsUpdate*>::FromArguments(args, 1, exception);
if (exception) {
Dart_ThrowException(exception);
return;
}
UIDartState::Current()->window()->client()->UpdateSemantics(update);
}
void SetIsolateDebugName(Dart_NativeArguments args) {
Dart_Handle exception = nullptr;
const std::string name =
tonic::DartConverter<std::string>::FromArguments(args, 1, exception);
if (exception) {
Dart_ThrowException(exception);
return;
}
UIDartState::Current()->window()->client()->SetIsolateDebugName(name);
}
Dart_Handle SendPlatformMessage(Dart_Handle window,
const std::string& name,
Dart_Handle callback,
const tonic::DartByteData& data) {
UIDartState* dart_state = UIDartState::Current();
if (!dart_state->window()) {
// Must release the TypedData buffer before allocating other Dart objects.
data.Release();
return ToDart("Platform messages can only be sent from the main isolate");
}
fml::RefPtr<PlatformMessageResponse> response;
if (!Dart_IsNull(callback)) {
response = fml::MakeRefCounted<PlatformMessageResponseDart>(
tonic::DartPersistentValue(dart_state, callback),
dart_state->GetTaskRunners().GetUITaskRunner());
}
if (Dart_IsNull(data.dart_handle())) {
dart_state->window()->client()->HandlePlatformMessage(
fml::MakeRefCounted<PlatformMessage>(name, response));
} else {
const uint8_t* buffer = static_cast<const uint8_t*>(data.data());
dart_state->window()->client()->HandlePlatformMessage(
fml::MakeRefCounted<PlatformMessage>(
name, std::vector<uint8_t>(buffer, buffer + data.length_in_bytes()),
response));
}
return Dart_Null();
}
void _SendPlatformMessage(Dart_NativeArguments args) {
tonic::DartCallStatic(&SendPlatformMessage, args);
}
void RespondToPlatformMessage(Dart_Handle window,
int response_id,
const tonic::DartByteData& data) {
if (Dart_IsNull(data.dart_handle())) {
UIDartState::Current()->window()->CompletePlatformMessageEmptyResponse(
response_id);
} else {
// TODO(engine): Avoid this copy.
const uint8_t* buffer = static_cast<const uint8_t*>(data.data());
UIDartState::Current()->window()->CompletePlatformMessageResponse(
response_id,
std::vector<uint8_t>(buffer, buffer + data.length_in_bytes()));
}
}
void _RespondToPlatformMessage(Dart_NativeArguments args) {
tonic::DartCallStatic(&RespondToPlatformMessage, args);
}
} // namespace
Dart_Handle ToByteData(const std::vector<uint8_t>& buffer) {
Dart_Handle data_handle =
Dart_NewTypedData(Dart_TypedData_kByteData, buffer.size());
if (Dart_IsError(data_handle))
return data_handle;
Dart_TypedData_Type type;
void* data = nullptr;
intptr_t num_bytes = 0;
FML_CHECK(!Dart_IsError(
Dart_TypedDataAcquireData(data_handle, &type, &data, &num_bytes)));
memcpy(data, buffer.data(), num_bytes);
Dart_TypedDataReleaseData(data_handle);
return data_handle;
}
WindowClient::~WindowClient() {}
Window::Window(WindowClient* client) : client_(client) {}
Window::~Window() {}
void Window::DidCreateIsolate() {
library_.Set(DartState::Current(), Dart_LookupLibrary(ToDart("dart:ui")));
}
void Window::UpdateWindowMetrics(const ViewportMetrics& metrics) {
viewport_metrics_ = metrics;
std::shared_ptr<tonic::DartState> dart_state = library_.dart_state().lock();
if (!dart_state)
return;
tonic::DartState::Scope scope(dart_state);
DartInvokeField(library_.value(), "_updateWindowMetrics",
{
ToDart(metrics.device_pixel_ratio),
ToDart(metrics.physical_width),
ToDart(metrics.physical_height),
ToDart(metrics.physical_padding_top),
ToDart(metrics.physical_padding_right),
ToDart(metrics.physical_padding_bottom),
ToDart(metrics.physical_padding_left),
ToDart(metrics.physical_view_inset_top),
ToDart(metrics.physical_view_inset_right),
ToDart(metrics.physical_view_inset_bottom),
ToDart(metrics.physical_view_inset_left),
});
}
void Window::UpdateLocales(const std::vector<std::string>& locales) {
std::shared_ptr<tonic::DartState> dart_state = library_.dart_state().lock();
if (!dart_state)
return;
tonic::DartState::Scope scope(dart_state);
DartInvokeField(library_.value(), "_updateLocales",
{
tonic::ToDart<std::vector<std::string>>(locales),
});
}
void Window::UpdateUserSettingsData(const std::string& data) {
std::shared_ptr<tonic::DartState> dart_state = library_.dart_state().lock();
if (!dart_state)
return;
tonic::DartState::Scope scope(dart_state);
DartInvokeField(library_.value(), "_updateUserSettingsData",
{
StdStringToDart(data),
});
}
void Window::UpdateSemanticsEnabled(bool enabled) {
std::shared_ptr<tonic::DartState> dart_state = library_.dart_state().lock();
if (!dart_state)
return;
tonic::DartState::Scope scope(dart_state);
DartInvokeField(library_.value(), "_updateSemanticsEnabled",
{ToDart(enabled)});
}
void Window::UpdateAccessibilityFeatures(int32_t values) {
std::shared_ptr<tonic::DartState> dart_state = library_.dart_state().lock();
if (!dart_state)
return;
tonic::DartState::Scope scope(dart_state);
DartInvokeField(library_.value(), "_updateAccessibilityFeatures",
{ToDart(values)});
}
void Window::DispatchPlatformMessage(fml::RefPtr<PlatformMessage> message) {
std::shared_ptr<tonic::DartState> dart_state = library_.dart_state().lock();
if (!dart_state)
return;
tonic::DartState::Scope scope(dart_state);
Dart_Handle data_handle =
(message->hasData()) ? ToByteData(message->data()) : Dart_Null();
if (Dart_IsError(data_handle))
return;
int response_id = 0;
if (auto response = message->response()) {
response_id = next_response_id_++;
pending_responses_[response_id] = response;
}
DartInvokeField(
library_.value(), "_dispatchPlatformMessage",
{ToDart(message->channel()), data_handle, ToDart(response_id)});
}
void Window::DispatchPointerDataPacket(const PointerDataPacket& packet) {
std::shared_ptr<tonic::DartState> dart_state = library_.dart_state().lock();
if (!dart_state)
return;
tonic::DartState::Scope scope(dart_state);
Dart_Handle data_handle = ToByteData(packet.data());
if (Dart_IsError(data_handle))
return;
DartInvokeField(library_.value(), "_dispatchPointerDataPacket",
{data_handle});
}
void Window::DispatchSemanticsAction(int32_t id,
SemanticsAction action,
std::vector<uint8_t> args) {
std::shared_ptr<tonic::DartState> dart_state = library_.dart_state().lock();
if (!dart_state)
return;
tonic::DartState::Scope scope(dart_state);
Dart_Handle args_handle = (args.empty()) ? Dart_Null() : ToByteData(args);
if (Dart_IsError(args_handle))
return;
DartInvokeField(
library_.value(), "_dispatchSemanticsAction",
{ToDart(id), ToDart(static_cast<int32_t>(action)), args_handle});
}
void Window::BeginFrame(fml::TimePoint frameTime) {
std::shared_ptr<tonic::DartState> dart_state = library_.dart_state().lock();
if (!dart_state)
return;
tonic::DartState::Scope scope(dart_state);
int64_t microseconds = (frameTime - fml::TimePoint()).ToMicroseconds();
DartInvokeField(library_.value(), "_beginFrame",
{
Dart_NewInteger(microseconds),
});
UIDartState::Current()->FlushMicrotasksNow();
DartInvokeField(library_.value(), "_drawFrame", {});
}
void Window::CompletePlatformMessageEmptyResponse(int response_id) {
if (!response_id)
return;
auto it = pending_responses_.find(response_id);
if (it == pending_responses_.end())
return;
auto response = std::move(it->second);
pending_responses_.erase(it);
response->CompleteEmpty();
}
void Window::CompletePlatformMessageResponse(int response_id,
std::vector<uint8_t> data) {
if (!response_id)
return;
auto it = pending_responses_.find(response_id);
if (it == pending_responses_.end())
return;
auto response = std::move(it->second);
pending_responses_.erase(it);
response->Complete(std::make_unique<fml::DataMapping>(std::move(data)));
}
void Window::RegisterNatives(tonic::DartLibraryNatives* natives) {
natives->Register({
{"Window_defaultRouteName", DefaultRouteName, 1, true},
{"Window_scheduleFrame", ScheduleFrame, 1, true},
{"Window_sendPlatformMessage", _SendPlatformMessage, 4, true},
{"Window_respondToPlatformMessage", _RespondToPlatformMessage, 3, true},
{"Window_render", Render, 2, true},
{"Window_updateSemantics", UpdateSemantics, 2, true},
{"Window_setIsolateDebugName", SetIsolateDebugName, 2, true},
});
}
} // namespace blink
| bsd-3-clause |
DeepDiver1975/sabre-dav | examples/calendarserver.php | 1682 | <?php
/*
CalendarServer example
This server features CalDAV support
*/
// settings
date_default_timezone_set('Canada/Eastern');
// If you want to run the SabreDAV server in a custom location (using mod_rewrite for instance)
// You can override the baseUri here.
// $baseUri = '/';
/* Database */
$pdo = new PDO('sqlite:data/db.sqlite');
$pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
//Mapping PHP errors to exceptions
function exception_error_handler($errno, $errstr, $errfile, $errline ) {
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
set_error_handler("exception_error_handler");
// Files we need
require_once 'vendor/autoload.php';
// Backends
$authBackend = new Sabre\DAV\Auth\Backend\PDO($pdo);
$calendarBackend = new Sabre\CalDAV\Backend\PDO($pdo);
$principalBackend = new Sabre\DAVACL\PrincipalBackend\PDO($pdo);
// Directory structure
$tree = [
new Sabre\CalDAV\Principal\Collection($principalBackend),
new Sabre\CalDAV\CalendarRootNode($principalBackend, $calendarBackend),
];
$server = new Sabre\DAV\Server($tree);
if (isset($baseUri))
$server->setBaseUri($baseUri);
/* Server Plugins */
$authPlugin = new Sabre\DAV\Auth\Plugin($authBackend,'SabreDAV');
$server->addPlugin($authPlugin);
$aclPlugin = new Sabre\DAVACL\Plugin();
$server->addPlugin($aclPlugin);
/* CalDAV support */
$caldavPlugin = new Sabre\CalDAV\Plugin();
$server->addPlugin($caldavPlugin);
/* Calendar subscription support */
$server->addPlugin(
new Sabre\CalDAV\Subscription\Plugin()
);
// Support for html frontend
$browser = new Sabre\DAV\Browser\Plugin();
$server->addPlugin($browser);
// And off we go!
$server->exec();
| bsd-3-clause |
tanerkuc/shineisp | application/modules/default/views/helpers/Logo.php | 588 | <?php
/**
* Logo helper
*/
class Zend_View_Helper_Logo extends Zend_View_Helper_Abstract {
public $view;
public function setView(Zend_View_Interface $view) {
$this->view = $view;
}
public function logo($data = array()) {
$isp = Shineisp_Registry::get('ISP');
if (! empty ( $isp->logo )) {
if (file_exists ( PUBLIC_PATH . "/documents/isp/" . $isp->logo )) {
$this->view->file = "/documents/isp/" . $isp->logo;
}
}
$this->view->logotitle = $isp->company;
$this->view->slogan = $isp->slogan;
return $this->view->render ( 'partials/logo.phtml' );
}
} | bsd-3-clause |
pbalcer/pbalcer.github.io | content/libpmemobj-cpp/master/doxygen/search/typedefs_7.js | 592 | var searchData=
[
['native_5fhandle_5ftype_928',['native_handle_type',['../classpmem_1_1obj_1_1condition__variable.html#a5d6f2b49f88a03db9e9f3a2b49f6bf6d',1,'pmem::obj::condition_variable::native_handle_type()'],['../classpmem_1_1obj_1_1mutex.html#a746ecab28758da55f241b0f7b76ced36',1,'pmem::obj::mutex::native_handle_type()'],['../classpmem_1_1obj_1_1shared__mutex.html#ad4c7fd0b2addf9babd42dc3827585c87',1,'pmem::obj::shared_mutex::native_handle_type()'],['../classpmem_1_1obj_1_1timed__mutex.html#ac561c19b42016f409ae142395645f99b',1,'pmem::obj::timed_mutex::native_handle_type()']]]
];
| bsd-3-clause |
carlohamalainen/ghc-mod | Language/Haskell/GhcMod/PkgDoc.hs | 1012 | module Language.Haskell.GhcMod.PkgDoc (packageDoc) where
import Language.Haskell.GhcMod.Types
import Language.Haskell.GhcMod.GhcPkg
import Control.Applicative ((<$>))
import System.Process (readProcess)
-- | Obtaining the package name and the doc path of a module.
packageDoc :: Options
-> Cradle
-> ModuleString
-> IO String
packageDoc _ cradle mdl = pkgDoc cradle mdl
pkgDoc :: Cradle -> String -> IO String
pkgDoc cradle mdl = do
pkg <- trim <$> readProcess "ghc-pkg" toModuleOpts []
if pkg == "" then
return "\n"
else do
htmlpath <- readProcess "ghc-pkg" (toDocDirOpts pkg) []
let ret = pkg ++ " " ++ drop 14 htmlpath
return ret
where
toModuleOpts = ["find-module", mdl, "--simple-output"]
++ ghcPkgDbStackOpts (cradlePkgDbStack cradle)
toDocDirOpts pkg = ["field", pkg, "haddock-html"]
++ ghcPkgDbStackOpts (cradlePkgDbStack cradle)
trim = takeWhile (`notElem` " \n")
| bsd-3-clause |
JianpingZeng/xcc | xcc/test/juliet/testcases/CWE195_Signed_to_Unsigned_Conversion_Error/s02/CWE195_Signed_to_Unsigned_Conversion_Error__negative_memmove_21.c | 4813 | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE195_Signed_to_Unsigned_Conversion_Error__negative_memmove_21.c
Label Definition File: CWE195_Signed_to_Unsigned_Conversion_Error.label.xml
Template File: sources-sink-21.tmpl.c
*/
/*
* @description
* CWE: 195 Signed to Unsigned Conversion Error
* BadSource: negative Set data to a fixed negative number
* GoodSource: Positive integer
* Sink: memmove
* BadSink : Copy strings using memmove() with the length of data
* Flow Variant: 21 Control flow: Flow controlled by value of a static global variable. All functions contained in one file.
*
* */
#include "std_testcase.h"
#ifndef OMITBAD
/* The static variable below is used to drive control flow in the source function */
static int badStatic = 0;
static int badSource(int data)
{
if(badStatic)
{
/* FLAW: Use a negative number */
data = -1;
}
return data;
}
void CWE195_Signed_to_Unsigned_Conversion_Error__negative_memmove_21_bad()
{
int data;
/* Initialize data */
data = -1;
badStatic = 1; /* true */
data = badSource(data);
{
char source[100];
char dest[100] = "";
memset(source, 'A', 100-1);
source[100-1] = '\0';
if (data < 100)
{
/* POTENTIAL FLAW: data is interpreted as an unsigned int - if its value is negative,
* the sign conversion could result in a very large number */
memmove(dest, source, data);
dest[data] = '\0'; /* NULL terminate */
}
printLine(dest);
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* The static variables below are used to drive control flow in the source functions. */
static int goodG2B1Static = 0;
static int goodG2B2Static = 0;
/* goodG2B1() - use goodsource and badsink by setting the static variable to false instead of true */
static int goodG2B1Source(int data)
{
if(goodG2B1Static)
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
printLine("Benign, fixed string");
}
else
{
/* FIX: Use a positive integer less than &InitialDataSize&*/
data = 100-1;
}
return data;
}
static void goodG2B1()
{
int data;
/* Initialize data */
data = -1;
goodG2B1Static = 0; /* false */
data = goodG2B1Source(data);
{
char source[100];
char dest[100] = "";
memset(source, 'A', 100-1);
source[100-1] = '\0';
if (data < 100)
{
/* POTENTIAL FLAW: data is interpreted as an unsigned int - if its value is negative,
* the sign conversion could result in a very large number */
memmove(dest, source, data);
dest[data] = '\0'; /* NULL terminate */
}
printLine(dest);
}
}
/* goodG2B2() - use goodsource and badsink by reversing the blocks in the if in the source function */
static int goodG2B2Source(int data)
{
if(goodG2B2Static)
{
/* FIX: Use a positive integer less than &InitialDataSize&*/
data = 100-1;
}
return data;
}
static void goodG2B2()
{
int data;
/* Initialize data */
data = -1;
goodG2B2Static = 1; /* true */
data = goodG2B2Source(data);
{
char source[100];
char dest[100] = "";
memset(source, 'A', 100-1);
source[100-1] = '\0';
if (data < 100)
{
/* POTENTIAL FLAW: data is interpreted as an unsigned int - if its value is negative,
* the sign conversion could result in a very large number */
memmove(dest, source, data);
dest[data] = '\0'; /* NULL terminate */
}
printLine(dest);
}
}
void CWE195_Signed_to_Unsigned_Conversion_Error__negative_memmove_21_good()
{
goodG2B1();
goodG2B2();
}
#endif /* OMITGOOD */
/* Below is the main(). It is only used when building this testcase on
* its own for testing or for building a binary to use in testing binary
* analysis tools. It is not used when compiling all the testcases as one
* application, which is how source code analysis tools are tested.
*/
#ifdef INCLUDEMAIN
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
CWE195_Signed_to_Unsigned_Conversion_Error__negative_memmove_21_good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
CWE195_Signed_to_Unsigned_Conversion_Error__negative_memmove_21_bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| bsd-3-clause |
tavoot/cysdusac | module/Centro/src/Centro/Model/Data/Item.php | 5949 | <?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
namespace Centro\Model\Data;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilterInterface;
use Zend\Validator\NotEmpty;
class Item
{
public $id;
public $titulo;
public $enlace;
public $descripcion;
public $fecha_publicacion;
public $canal_id;
protected $inputFilter;
public function exchangeArray($data)
{
$this->id = (!empty($data['id'])) ? $data['id'] : null;
$this->titulo = (!empty($data['titulo'])) ? $data['titulo'] : null;
$this->enlace = (!empty($data['enlace'])) ? $data['enlace'] : null;
$this->descripcion = (!empty($data['descripcion'])) ? $data['descripcion'] : null;
$this->fecha_publicacion = (!empty($data['fecha_publicacion'])) ? $data['fecha_publicacion'] : null;
$this->canal_id = (!empty($data['canal_id'])) ? $data['canal_id'] : null;
}
public function getArrayCopy() {
return get_object_vars($this);
}
public function setInputFilter(InputFilterInterface $inputFilter) {
throw new \Exception("Not used");
}
public function getInputFilter() {
if (!$this->inputFilter) {
$inputFilter = new InputFilter();
$inputFilter->add(array(
'name' => 'id',
'required' => true,
'filters' => array(
array('name' => 'Int'),
),
));
$inputFilter->add(array(
'name' => 'canal_id',
'required' => true,
'filters' => array(
array('name' => 'Int'),
),
));
$inputFilter->add(array(
'name' => 'titulo',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'NotEmpty',
'options' => array(
'setMessages' => array(
NotEmpty::IS_EMPTY => 'Campo obligatorio',
),
),
'break_chain_on_failure' => true,
),
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 1,
'max' => 200,
'setMessages' => array(
'stringLengthTooLong' => 'La cadena ingresada es mayor al limite permitido',
),
),
'break_chain_on_failure' => true,
),
),
));
$inputFilter->add(array(
'name' => 'enlace',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'NotEmpty',
'options' => array(
'setMessages' => array(
NotEmpty::IS_EMPTY => 'Campo obligatorio',
),
),
'break_chain_on_failure' => true,
),
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 1,
'max' => 200,
'setMessages' => array(
'stringLengthTooLong' => 'Cadena de caracteres mayor al limite permitido',
),
),
'break_chain_on_failure' => true,
),
array(
'name' => 'Regex',
'options' => array(
'pattern' => '#(http://|https://).+#',
'message' => 'Formato del url ingresada no valido',
),
'break_chain_on_failure' => true,
),
),
));
$inputFilter->add(array(
'name' => 'descripcion',
'required' => false,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 1,
'max' => 500,
'setMessages' => array(
'stringLengthTooLong' => 'Cadena de caracteres mayor al limite permitido',
),
),
'break_chain_on_failure' => true,
),
),
));
$this->inputFilter = $inputFilter;
}
return $this->inputFilter;
}
} | bsd-3-clause |
koodaamo/yadifa | lib/dnscore/include/dnscore/clone_input_output_stream.h | 2669 | /*------------------------------------------------------------------------------
*
* Copyright (c) 2011, EURid. All rights reserved.
* The YADIFA TM software product is provided under the BSD 3-clause license:
*
* 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 EURid 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.
*
*------------------------------------------------------------------------------
*
* DOCUMENTATION */
/** @defgroup streaming Streams
* @ingroup dnscore
* @brief
*
*
*
* @{
*
*----------------------------------------------------------------------------*/
#ifndef _CLONE_INPUT_OUTPUT_STREAM_H
#define _CLONE_INPUT_OUTPUT_STREAM_H
#include <dnscore/input_stream.h>
#include <dnscore/output_stream.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* Can only fail if in_filtered has not been set
*/
ya_result clone_input_output_stream_init(input_stream *cis, input_stream* in_cloned, output_stream* out_copy);
input_stream *clone_input_output_stream_get_cloned(input_stream* cis);
output_stream *clone_input_output_stream_get_copy(input_stream* cis);
#ifdef __cplusplus
}
#endif
#endif /* _clone_OUTPUT_STREAM_H */
/** @} */
/*----------------------------------------------------------------------------*/
| bsd-3-clause |
JianpingZeng/xcc | xcc/test/juliet/testcases/CWE122_Heap_Based_Buffer_Overflow/s04/CWE122_Heap_Based_Buffer_Overflow__cpp_CWE806_char_snprintf_53d.cpp | 1666 | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE806_char_snprintf_53d.cpp
Label Definition File: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE806.label.xml
Template File: sources-sink-53d.tmpl.cpp
*/
/*
* @description
* CWE: 122 Heap Based Buffer Overflow
* BadSource: Initialize data as a large string
* GoodSource: Initialize data as a small string
* Sink: snprintf
* BadSink : Copy data to string using snprintf
* Flow Variant: 53 Data flow: data passed as an argument from one function through two others to a fourth; all four functions are in different source files
*
* */
#include "std_testcase.h"
#include <wchar.h>
#ifdef _WIN32
#define SNPRINTF _snprintf
#else
#define SNPRINTF snprintf
#endif
namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE806_char_snprintf_53
{
/* all the sinks are the same, we just want to know where the hit originated if a tool flags one */
#ifndef OMITBAD
void badSink_d(char * data)
{
{
char dest[50] = "";
/* POTENTIAL FLAW: Possible buffer overflow if data is larger than dest */
SNPRINTF(dest, strlen(data), "%s", data);
printLine(data);
delete [] data;
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
void goodG2BSink_d(char * data)
{
{
char dest[50] = "";
/* POTENTIAL FLAW: Possible buffer overflow if data is larger than dest */
SNPRINTF(dest, strlen(data), "%s", data);
printLine(data);
delete [] data;
}
}
#endif /* OMITGOOD */
} /* close namespace */
| bsd-3-clause |
gentnerlab/klusta-pipeline | klusta_pipeline/merge_stim_kwik.py | 7008 |
# Merge stimuli information from spike2 mat file into Kwik file
import h5py as h5
import tables
import os
import numpy as np
import argparse
import glob
try: import simplejson as json
except ImportError: import json
from klusta_pipeline.dataio import load_recordings, save_info, load_digmark, load_stim_info
from klusta_pipeline.utils import get_import_list, validate_merge, realign
def get_args():
parser = argparse.ArgumentParser(description='Compile Spike2 epoch .mat files into KlustaKwik KWD file.')
parser.add_argument('path', default = './', nargs='?',
help='directory containing all of the mat files to compile')
parser.add_argument('dest', default = './', nargs='?',
help='destination directory for kwd and other files')
return parser.parse_args()
def get_rec_samples(kwd_file,index):
with h5.File(kwd_file, 'r') as kwd:
return kwd['/recordings/{}/data'.format(index)].shape[0]
def merge_recording_info(klu_path,mat_path):
batch = klu_path.split('__')[-1]
with open(os.path.join(klu_path,batch+'_info.json')) as f:
info = json.load(f)
assert 'recordings' not in info
import_list = get_import_list(mat_path,info['exports'])
for item in import_list:
assert os.path.exists(item), item
mat_data = validate_merge(import_list,info['omit'])
fs = info['params']['fs']
chans = set(mat_data[0]['chans'])
for d2 in mat_data[1:]:
chans = chans.intersection(d2['chans'])
chans = list(chans)
for i,m in zip(info['exports'],mat_data):
i['chans'] = chans
rec_list = []
for import_file in import_list:
recordings = load_recordings(import_file,chans)
for r in recordings:
rec = realign(r,chans,fs,'spline')
del rec['data']
rec_list.append(rec)
info['recordings'] = [{k:v for k,v in rec.items() if k is not 'data'} for rec in rec_list]
save_info(klu_path,info)
return info
def merge(spike2mat_folder, kwik_folder):
info_json = glob.glob(os.path.join(kwik_folder,'*_info.json'))[0]
with open(info_json, 'r') as f:
info = json.load(f)
kwik_data_file = os.path.join(kwik_folder,info['name']+'.kwik')
kwd_raw_file = os.path.join(kwik_folder,info['name']+'.raw.kwd')\
with tables.open_file(kwik_data_file, 'r+') as kkfile:
digmark_timesamples = []
digmark_recording = []
digmark_codes = []
stimulus_timesamples = []
stimulus_recording = []
stimulus_codes = []
stimulus_names = []
spike_recording_obj = kkfile.get_node('/channel_groups/0/spikes','recording')
spike_time_samples_obj = kkfile.get_node('/channel_groups/0/spikes','time_samples')
spike_recording = spike_recording_obj.read()
spike_time_samples = spike_time_samples_obj.read()
try:
assert 'recordings' in info
except AssertionError:
info = merge_recording_info(kwik_folder,spike2mat_folder)
order = np.sort([str(ii) for ii in range(len(info['recordings']))])
print order
print len(spike_recording)
is_done = np.zeros(spike_recording.shape,np.bool_)
for rr,rid_str in enumerate(order):
# rr: index of for-loop
# rid: recording id
# rid_str: string form of recording id
rid = int(rid_str)
rec = info['recordings'][rid]
n_samps = get_rec_samples(kwd_raw_file,rid)
#is_done = np.vectorize(lambda x: x not in done)
todo = ~is_done & (spike_time_samples >= n_samps)
print "rec {}: {} spikes done".format(rid,is_done.sum())
print "setting {} spikes to next cluster".format(todo.sum())
if todo.sum()>0:
spike_recording[todo] = int(order[rr+1])
spike_time_samples[todo] -= n_samps
is_done = is_done | ~todo
print is_done.sum()
t0 = rec['start_time']
fs = rec['fs']
dur = float(n_samps) / fs
s2mat = os.path.split(rec['file_origin'])[-1]
s2mat = os.path.join(spike2mat_folder, s2mat)
codes, times = load_digmark(s2mat)
rec_mask = (times >= t0) * (times < (t0+dur))
codes = codes[rec_mask]
times = times[rec_mask] - t0
time_samples = (times * fs).round().astype(np.uint64)
recording = rid * np.ones(codes.shape,np.uint16)
digmark_timesamples.append(time_samples)
digmark_recording.append(recording)
digmark_codes.append(codes)
codes, times, names = load_stim_info(s2mat)
rec_mask = (times >= t0) * (times < (t0+dur))
codes = codes[rec_mask]
names = names[rec_mask]
times = times[rec_mask] - t0
time_samples = (times * fs).round().astype(np.uint64)
recording = rid * np.ones(codes.shape,np.uint16)
stimulus_timesamples.append(time_samples)
stimulus_recording.append(recording)
stimulus_codes.append(codes)
stimulus_names.append(names)
digmark_timesamples = np.concatenate(digmark_timesamples)
digmark_recording = np.concatenate(digmark_recording)
digmark_codes = np.concatenate(digmark_codes)
stimulus_timesamples = np.concatenate(stimulus_timesamples)
stimulus_recording = np.concatenate(stimulus_recording)
stimulus_codes = np.concatenate(stimulus_codes)
stimulus_names = np.concatenate(stimulus_names)
print digmark_timesamples.dtype
print digmark_recording.dtype
print digmark_codes.dtype
print stimulus_timesamples.dtype
print stimulus_recording.dtype
print stimulus_codes.dtype
print stimulus_names.dtype
kkfile.create_group("/", "event_types", "event_types")
kkfile.create_group("/event_types", "DigMark")
kkfile.create_earray("/event_types/DigMark", 'time_samples', obj=digmark_timesamples)
kkfile.create_earray("/event_types/DigMark", 'recording', obj=digmark_recording)
kkfile.create_earray("/event_types/DigMark", 'codes', obj=digmark_codes)
kkfile.create_group("/event_types", "Stimulus")
kkfile.create_earray("/event_types/Stimulus", 'time_samples', obj=stimulus_timesamples)
kkfile.create_earray("/event_types/Stimulus", 'recording', obj=stimulus_recording)
kkfile.create_earray("/event_types/Stimulus", 'codes', obj=stimulus_codes)
kkfile.create_earray("/event_types/Stimulus", 'text', obj=stimulus_names)
spike_recording_obj[:] = spike_recording
spike_time_samples_obj[:] = spike_time_samples
def main():
args = get_args()
spike2mat_folder = os.path.abspath(args.path)
kwik_folder = os.path.abspath(args.dest)
merge(spike2mat_folder, kwik_folder)
if __name__ == '__main__':
main()
| bsd-3-clause |
JosefMeixner/opentoonz | toonz/sources/toonz/studiopaletteviewer.cpp | 31411 |
#include "studiopaletteviewer.h"
#include "palettesscanpopup.h"
#include "toonz/studiopalettecmd.h"
#include "toonzqt/menubarcommand.h"
#include "floatingpanelcommand.h"
#include "toonzqt/gutil.h"
#include "toonz/tpalettehandle.h"
#include "toonz/txshlevelhandle.h"
#include "toonzqt/paletteviewer.h"
#include "toonzutil.h"
#include "tconvert.h"
#include "toonz/txshsimplelevel.h"
#include <QHeaderView>
#include <QContextMenuEvent>
#include <QMenu>
#include <QUrl>
#include <QPainter>
#include <QVBoxLayout>
#include <QToolBar>
#include <QSplitter>
#include "toonz/tscenehandle.h"
#include "toonz/toonzscene.h"
#include "toonz/sceneproperties.h"
using namespace std;
using namespace PaletteViewerGUI;
//=============================================================================
namespace
{
//-----------------------------------------------------------------------------
/*! Return true if path is in folder \b rootPath of \b StudioPalette.
*/
bool isInStudioPaletteFolder(TFilePath path, TFilePath rootPath)
{
if (path.getType() != "tpl")
return false;
StudioPalette *studioPlt = StudioPalette::instance();
std::vector<TFilePath> childrenPath;
studioPlt->getChildren(childrenPath, rootPath);
int i;
for (i = 0; i < (int)childrenPath.size(); i++) {
if (path == childrenPath[i])
return true;
else if (isInStudioPaletteFolder(path, childrenPath[i]))
return true;
}
return false;
}
//-----------------------------------------------------------------------------
/*! Return true if path is in a \b StudioPalette folder.
*/
bool isInStudioPalette(TFilePath path)
{
if (path.getType() != "tpl")
return false;
StudioPalette *studioPlt = StudioPalette::instance();
if (isInStudioPaletteFolder(path, studioPlt->getLevelPalettesRoot()))
return true;
if (isInStudioPaletteFolder(path, studioPlt->getCleanupPalettesRoot()))
return true;
if (isInStudioPaletteFolder(path, TFilePath("C:\\Toonz 6.0 stuff\\projects\\Project Palettes"))) //DAFARE studioPlt->getProjectPalettesRoot(); Per ora lo fisso))
return true;
return false;
}
//-----------------------------------------------------------------------------
} //namespace
//-----------------------------------------------------------------------------
//=============================================================================
/*! \class StudioPaletteTreeViewer
\brief The StudioPaletteTreeViewer class provides an object to view and manage
palettes files.
Inherits \b QTreeWidget and \b StudioPalette::Listener.
This object provides interface for class \b StudioPalette.
StudioPaletteTreeViewer is a \b QTreeWidget with three root item related to
level palette folder, cleanup palette folder and current project palette folder,
the three root folder of \b StudioPalette.
*/
/*! \fn void StudioPaletteTreeViewer::onStudioPaletteTreeChange()
Overriden from StudioPalette::Listener.
\fn void StudioPaletteTreeViewer::onStudioPaletteMove(const TFilePath &dstPath, const TFilePath &srcPath)
Overriden from StudioPalette::Listener.
\fn void StudioPaletteTreeViewer::onStudioPaletteChange(const TFilePath &palette)
Overriden from StudioPalette::Listener.
*/
StudioPaletteTreeViewer::StudioPaletteTreeViewer(QWidget *parent,
TPaletteHandle *studioPaletteHandle,
TPaletteHandle *levelPaletteHandle)
: QTreeWidget(parent), m_dropItem(0), m_stdPltHandle(studioPaletteHandle), m_levelPltHandle(levelPaletteHandle), m_sceneHandle(0), m_levelHandle(0)
{
header()->close();
setIconSize(QSize(20, 20));
//Da sistemare le icone dei tre folder principali
static QPixmap PaletteIconPxmp(":Resources/icon.png");
QList<QTreeWidgetItem *> paletteItems;
StudioPalette *studioPlt = StudioPalette::instance();
//static QPixmap PaletteLevelIconPxmp(":Resources/studio_plt_toonz.png");
TFilePath levelPltPath = studioPlt->getLevelPalettesRoot();
paletteItems.append(createRootItem(levelPltPath, PaletteIconPxmp));
//static QPixmap PaletteCleanupIconPxmp(":Resources/studio_plt_cleanup.png");
TFilePath cleanupPltPath = studioPlt->getCleanupPalettesRoot();
paletteItems.append(createRootItem(cleanupPltPath, PaletteIconPxmp));
//DAFARE
//Oss.: se il folder non c'e' non fa nulla, non si aprono neanche i menu' da tasto destro!
//static QPixmap PaletteProjectIconPxmp(":Resources/studio_plt_project.png");
TFilePath projectPltPath = TFilePath("C:\\Toonz 6.0 stuff\\projects\\Project Palettes"); //studioPlt->getProjectPalettesRoot(); Per ora lo fisso
paletteItems.append(createRootItem(projectPltPath, PaletteIconPxmp));
insertTopLevelItems(0, paletteItems);
connect(this, SIGNAL(itemChanged(QTreeWidgetItem *, int)),
this, SLOT(onItemChanged(QTreeWidgetItem *, int)));
connect(this, SIGNAL(itemExpanded(QTreeWidgetItem *)),
this, SLOT(onItemExpanded(QTreeWidgetItem *)));
connect(this, SIGNAL(itemCollapsed(QTreeWidgetItem *)),
this, SLOT(onItemCollapsed(QTreeWidgetItem *)));
connect(this, SIGNAL(itemSelectionChanged()),
this, SLOT(onItemSelectionChanged()));
m_palettesScanPopup = new PalettesScanPopup();
setAcceptDrops(true);
}
//-----------------------------------------------------------------------------
StudioPaletteTreeViewer::~StudioPaletteTreeViewer()
{
}
//-----------------------------------------------------------------------------
void StudioPaletteTreeViewer::setLevelPaletteHandle(TPaletteHandle *paletteHandle)
{
m_levelPltHandle = paletteHandle;
}
//-----------------------------------------------------------------------------
void StudioPaletteTreeViewer::setStdPaletteHandle(TPaletteHandle *stdPltHandle)
{
m_stdPltHandle = stdPltHandle;
}
//-----------------------------------------------------------------------------
void StudioPaletteTreeViewer::setSceneHandle(TSceneHandle *sceneHandle)
{
m_sceneHandle = sceneHandle;
}
//-----------------------------------------------------------------------------
void StudioPaletteTreeViewer::setLevelHandle(TXshLevelHandle *levelHandle)
{
m_levelHandle = levelHandle;
}
//-----------------------------------------------------------------------------
/*! Create root item related to path \b path.
*/
QTreeWidgetItem *StudioPaletteTreeViewer::createRootItem(TFilePath path, const QPixmap pix)
{
QString rootName = QString(path.getName().c_str());
QTreeWidgetItem *rootItem = new QTreeWidgetItem((QTreeWidget *)0, QStringList(rootName));
rootItem->setIcon(0, pix);
rootItem->setData(1, Qt::UserRole, toQString(path));
refreshItem(rootItem);
return rootItem;
}
//-----------------------------------------------------------------------------
/*! Return true if \b item is a root item; false otherwis.
*/
bool StudioPaletteTreeViewer::isRootItem(QTreeWidgetItem *item)
{
assert(item);
TFilePath path = getFolderPath(item);
//DAFARE
//Oss.: se il folder non c'e' non fa nulla, non si aprono neanche i menu' da tasto destro!
//static QPixmap PaletteProjectIconPxmp(":Resources/studio_plt_project.png");
TFilePath projectPltPath = TFilePath("C:\\Toonz 6.0 stuff\\projects\\Project Palettes"); //studioPlt->getProjectPalettesRoot(); Per ora lo fisso
StudioPalette *stdPalette = StudioPalette::instance();
if (path == stdPalette->getCleanupPalettesRoot() ||
path == stdPalette->getLevelPalettesRoot() ||
path == projectPltPath)
return true;
return false;
}
//-----------------------------------------------------------------------------
/*! Create a new item related to path \b path.
*/
QTreeWidgetItem *StudioPaletteTreeViewer::createItem(const TFilePath path)
{
static QPixmap PaletteIconPxmp(":Resources/icon.png");
static QPixmap FolderIconPxmp(":Resources/newfolder_over.png");
StudioPalette *studioPlt = StudioPalette::instance();
QString itemName = QString(path.getName().c_str());
QTreeWidgetItem *item = new QTreeWidgetItem((QTreeWidget *)0, QStringList(itemName));
if (studioPlt->isPalette(path))
item->setIcon(0, PaletteIconPxmp);
else if (studioPlt->isFolder(path))
item->setIcon(0, FolderIconPxmp);
item->setData(1, Qt::UserRole, toQString(path));
item->setFlags(item->flags() | Qt::ItemIsEditable);
return item;
}
//-----------------------------------------------------------------------------
/*! Return path related to item \b item if \b item exist, otherwise return an
empty path \b TFilePath.
*/
TFilePath StudioPaletteTreeViewer::getFolderPath(QTreeWidgetItem *item)
{
TFilePath path = (item) ? TFilePath(item->data(1, Qt::UserRole).toString().toStdWString())
: TFilePath();
return path;
}
//-----------------------------------------------------------------------------
/*! Return current item path.
*/
TFilePath StudioPaletteTreeViewer::getCurrentFolderPath()
{
return getFolderPath(currentItem());
}
//-----------------------------------------------------------------------------
/*! Return item identified by \b path; if it doesn't exist return 0.
*/
QTreeWidgetItem *StudioPaletteTreeViewer::getItem(const TFilePath path)
{
QList<QTreeWidgetItem *> oldItems = findItems(QString(""), Qt::MatchContains, 0);
if (oldItems.isEmpty())
return 0;
int i;
for (i = 0; i < (int)oldItems.size(); i++) {
TFilePath oldItemPath(oldItems[i]->data(1, Qt::UserRole).toString().toStdWString());
if (oldItemPath == path)
return oldItems[i];
else {
QTreeWidgetItem *item = getFolderItem(oldItems[i], path);
if (item)
return item;
}
}
return 0;
}
//-----------------------------------------------------------------------------
/*! Return item child of \b parent identified by \b path; if it doesn't exist return 0.
*/
QTreeWidgetItem *StudioPaletteTreeViewer::getFolderItem(QTreeWidgetItem *parent, const TFilePath path)
{
int childrenCount = parent->childCount();
int i;
for (i = 0; i < childrenCount; i++) {
QTreeWidgetItem *item = parent->child(i);
if (getFolderPath(item) == path)
return item;
else {
item = getFolderItem(item, path);
if (item)
return item;
}
}
return 0;
}
//-----------------------------------------------------------------------------
/*! Refresh all item of three root item in tree and preserve current item.
*/
void StudioPaletteTreeViewer::refresh()
{
StudioPalette *studioPlt = StudioPalette::instance();
TFilePath levelPltPath = studioPlt->getLevelPalettesRoot();
refreshItem(getItem(levelPltPath));
TFilePath cleanupPltPath = studioPlt->getCleanupPalettesRoot();
refreshItem(getItem(cleanupPltPath));
//DAFARE
TFilePath projectPltPath = TFilePath("C:\\Toonz 6.0 stuff\\projects\\Project Palettes"); //studioPlt->getProjectPalettesRoot(); Per ora lo fisso
refreshItem(getItem(projectPltPath));
}
//-----------------------------------------------------------------------------
/*! Refresh item \b item and its children; take path concerning \b item and
compare \b StudioPalette folder in path with folder in item.
If are not equal add or remove child to current \b item. Recall itself
for each item child.
*/
void StudioPaletteTreeViewer::refreshItem(QTreeWidgetItem *item)
{
TFilePath folderPath = getFolderPath(item);
assert(folderPath != TFilePath());
std::vector<TFilePath> childrenPath;
StudioPalette::instance()->getChildren(childrenPath, folderPath);
int currentChildCount = item->childCount();
std::vector<QTreeWidgetItem *> currentChildren;
int i;
for (i = 0; i < currentChildCount; i++)
currentChildren.push_back(item->child(i));
int childrenPathCount = childrenPath.size();
int itemIndex = 0;
int pathIndex = 0;
while (itemIndex < currentChildCount || pathIndex < childrenPathCount) {
TFilePath path = (pathIndex < childrenPathCount) ? childrenPath[pathIndex] : TFilePath();
QTreeWidgetItem *currentItem = (itemIndex < currentChildCount) ? currentChildren[itemIndex] : 0;
TFilePath currentItemPath = getFolderPath(currentItem);
if (path == currentItemPath) {
itemIndex++;
pathIndex++;
refreshItem(currentItem);
} else if ((!path.isEmpty() && path < currentItemPath) ||
currentItemPath.isEmpty()) {
currentItem = createItem(path);
item->insertChild(pathIndex, currentItem);
refreshItem(currentItem);
pathIndex++;
} else {
assert(currentItemPath < path || path.isEmpty());
assert(currentItem);
item->removeChild(currentItem);
itemIndex++;
}
}
}
//-----------------------------------------------------------------------------
/*! If item \b item name changed update name item related path name in \b StudioPalette.
*/
void StudioPaletteTreeViewer::onItemChanged(QTreeWidgetItem *item, int column)
{
if (item != currentItem())
return;
string name = item->text(column).toStdString();
TFilePath oldPath = getCurrentFolderPath();
if (oldPath.isEmpty() || name.empty() || oldPath.getName() == name)
return;
TFilePath newPath(oldPath.getParentDir() + TFilePath(name + oldPath.getDottedType()));
try {
StudioPaletteCmd::movePalette(newPath, oldPath);
} catch (TException &e) {
error("Can't rename palette: " + QString(toString(e.getMessage()).c_str()));
} catch (...) {
error("Can't rename palette");
}
setCurrentItem(getItem(newPath));
}
//-----------------------------------------------------------------------------
/*! If item \b item is expanded change item icon.
*/
void StudioPaletteTreeViewer::onItemExpanded(QTreeWidgetItem *item)
{
if (!item || isRootItem(item))
return;
static QPixmap FolderIconExpandedPxmp(":Resources/folder_open.png");
item->setIcon(0, FolderIconExpandedPxmp);
}
//-----------------------------------------------------------------------------
/*! If item \b item is collapsed change item icon.
*/
void StudioPaletteTreeViewer::onItemCollapsed(QTreeWidgetItem *item)
{
if (!item || isRootItem(item))
return;
static QPixmap FolderIconPxmp(":Resources/newfolder_over.png");
item->setIcon(0, FolderIconPxmp);
}
//-----------------------------------------------------------------------------
/*! If current item is a palette set current studioPalette to it.
*/
void StudioPaletteTreeViewer::onItemSelectionChanged()
{
TFilePath path = getCurrentFolderPath();
if (!m_stdPltHandle || path.getType() != "tpl")
return;
if (m_stdPltHandle->getPalette() && m_stdPltHandle->getPalette()->getDirtyFlag()) {
QString question;
question = "Current Studio Palette has been modified.\n"
"Do you want to save your changes?";
int ret = MsgBox(0, question, QObject::tr("Save"), QObject::tr("Don't Save"), QObject::tr("Cancel"), 0);
TPaletteP oldPalette = m_stdPltHandle->getPalette();
TFilePath oldPath = StudioPalette::instance()->getPalettePath(oldPalette->getGlobalName());
if (ret == 3) {
setCurrentItem(getItem(oldPath));
return;
}
if (ret == 1)
StudioPalette::instance()->save(oldPath, oldPalette.getPointer());
oldPalette->setDirtyFlag(false);
}
m_stdPltHandle->setPalette(StudioPalette::instance()->getPalette(path, true));
m_stdPltHandle->notifyPaletteSwitched();
}
//-----------------------------------------------------------------------------
/*! Create a new \b StudioPalette palette in current item path.
*/
void StudioPaletteTreeViewer::addNewPlt()
{
if (!currentItem()) {
error("Error: No folder selected.");
return;
}
TFilePath newPath;
try {
newPath = StudioPaletteCmd::createPalette(getCurrentFolderPath(), "", 0);
} catch (TException &e) {
error("Can't create palette: " + QString(toString(e.getMessage()).c_str()));
} catch (...) {
error("Can't create palette");
}
setCurrentItem(getItem(newPath));
}
//-----------------------------------------------------------------------------
/*! Create a new \b StudioPalette folder in current item path.
*/
void StudioPaletteTreeViewer::addNewFolder()
{
if (!currentItem()) {
error("Error: No folder selected.");
return;
}
TFilePath newPath;
try {
newPath = StudioPaletteCmd::addFolder(getCurrentFolderPath());
} catch (TException &e) {
error("Can't create palette folder: " + QString(toString(e.getMessage()).c_str()));
} catch (...) {
error("Can't create palette folder");
}
setCurrentItem(getItem(newPath));
}
//-----------------------------------------------------------------------------
/*! Delete current item path from \b StudioPalette. If item is a not empty
folder send a question to know if must delete item or not.
*/
void StudioPaletteTreeViewer::deleteItem()
{
if (!currentItem()) {
error("Nothing to delete");
return;
}
QTreeWidgetItem *parent = currentItem()->parent();
if (!parent)
return;
if (currentItem()->childCount() > 0) {
QString question;
question = tr("This folder is not empty. Delete anyway?");
int ret = MsgBox(0, question, QObject::tr("Yes"), QObject::tr("No"));
if (ret == 0 || ret == 2)
return;
}
TFilePath path = getCurrentFolderPath();
StudioPalette *studioPlt = StudioPalette::instance();
if (studioPlt->isFolder(path)) {
try {
StudioPaletteCmd::deleteFolder(path);
} catch (TException &e) {
error("Can't delete palette: " + QString(toString(e.getMessage()).c_str()));
} catch (...) {
error("Can't delete palette");
}
} else {
assert(studioPlt->isPalette(path));
try {
StudioPaletteCmd::deletePalette(path);
} catch (TException &e) {
error("Can't delete palette: " + QString(toString(e.getMessage()).c_str()));
} catch (...) {
error("Can't delete palette");
}
}
}
//-----------------------------------------------------------------------------
/*! Open a \b PalettesScanPopup.
*/
void StudioPaletteTreeViewer::searchForPlt()
{
m_palettesScanPopup->setCurrentFolder(getCurrentFolderPath());
int ret = m_palettesScanPopup->exec();
if (ret == QDialog::Accepted)
refresh();
}
//-----------------------------------------------------------------------------
/*! Recall \b StudioPaletteCmd::loadIntoCleanupPalette.
*/
void StudioPaletteTreeViewer::loadInCurrentCleanupPlt()
{
StudioPaletteCmd::loadIntoCleanupPalette(m_levelPltHandle, m_sceneHandle, getCurrentFolderPath());
}
//-----------------------------------------------------------------------------
/*! Recall \b StudioPaletteCmd::replaceWithCleanupPalette.
*/
void StudioPaletteTreeViewer::replaceCurrentCleanupPlt()
{
StudioPaletteCmd::replaceWithCleanupPalette(m_levelPltHandle, m_stdPltHandle,
m_sceneHandle, getCurrentFolderPath());
}
//-----------------------------------------------------------------------------
/*! Recall \b StudioPaletteCmd::loadIntoCurrentPalette.
*/
void StudioPaletteTreeViewer::loadInCurrentPlt()
{
StudioPaletteCmd::loadIntoCurrentPalette(m_levelPltHandle, m_sceneHandle,
getCurrentFolderPath());
}
//-----------------------------------------------------------------------------
/*! Recall \b StudioPaletteCmd::replaceWithCurrentPalette.
*/
void StudioPaletteTreeViewer::replaceCurrentPlt()
{
StudioPaletteCmd::replaceWithCurrentPalette(m_levelPltHandle, m_stdPltHandle,
m_sceneHandle, getCurrentFolderPath());
}
//-----------------------------------------------------------------------------
/*! Recall \b StudioPaletteCmd::mergeIntoCurrentPalette.
*/
void StudioPaletteTreeViewer::mergeToCurrentPlt()
{
StudioPaletteCmd::mergeIntoCurrentPalette(m_levelPltHandle, m_sceneHandle,
getCurrentFolderPath());
}
//-----------------------------------------------------------------------------
void StudioPaletteTreeViewer::paintEvent(QPaintEvent *event)
{
QTreeWidget::paintEvent(event);
QPainter p(viewport());
if (m_dropItem) {
QRect rect = visualItemRect(m_dropItem).adjusted(0, 0, -5, 0);
p.setPen(Qt::red);
p.drawRect(rect);
}
}
//-----------------------------------------------------------------------------
/*! Open a context menu considering current item data role \b Qt::UserRole.
*/
void StudioPaletteTreeViewer::contextMenuEvent(QContextMenuEvent *event)
{
TFilePath path = getCurrentFolderPath();
StudioPalette *studioPlt = StudioPalette::instance();
// Verify if click position is in a row containing an item.
QRect rect = visualItemRect(currentItem());
if (!QRect(0, rect.y(), width(), rect.height()).contains(event->pos()))
return;
bool isLevelFolder = (studioPlt->isFolder(path) && !studioPlt->isCleanupFolder(path));
QMenu menu(this);
if (isLevelFolder) {
createMenuAction(menu, tr("New Palette"), "addNewPlt()");
createMenuAction(menu, tr("New Folder"), "addNewFolder()");
} else if (studioPlt->isCleanupFolder(path)) {
createMenuAction(menu, tr("New Cleanup Palette"), "addNewPlt()");
createMenuAction(menu, tr("New Folder"), "addNewFolder()");
}
if (studioPlt->isFolder(path) &&
studioPlt->getLevelPalettesRoot() != path &&
studioPlt->getCleanupPalettesRoot() != path &&
TFilePath("C:\\Toonz 6.0 stuff\\projects\\Project Palettes") != path) //DAFARE studioPlt->getProjectPalettesRoot(); Per ora lo fisso)
{
menu.addSeparator();
createMenuAction(menu, tr("Delete Folder"), "deleteItem()");
} else if (studioPlt->isPalette(path)) {
if (studioPlt->isCleanupPalette(path)) {
createMenuAction(menu, tr("Load into Current Cleaunp Palette"), "loadInCurrentCleanupPlt()");
createMenuAction(menu, tr("Replace with Current Cleaunp Palette"), "replaceCurrentCleanupPlt()");
menu.addSeparator();
} else if (m_stdPltHandle->getPalette()) {
createMenuAction(menu, tr("Load into Current Palette"), "loadInCurrentPlt()");
createMenuAction(menu, tr("Merge to Current Palette"), "mergeToCurrentPlt()");
createMenuAction(menu, tr("Replace with Current Palette"), "replaceCurrentPlt()");
menu.addSeparator();
}
createMenuAction(menu, tr("Delete Palette"), "deleteItem()");
menu.addSeparator();
menu.addAction(CommandManager::instance()->getAction("MI_LoadColorModelInStdPlt"));
}
if (isLevelFolder) {
menu.addSeparator();
createMenuAction(menu, tr("Search for Palettes"), "searchForPlt()");
}
menu.exec(event->globalPos());
}
//-----------------------------------------------------------------------------
/*! Add an action to menu \b menu; the action has text \b name and its
\b triggered() signal is connetted with \b slot.
*/
void StudioPaletteTreeViewer::createMenuAction(QMenu &menu, QString name, const char *slot)
{
QAction *act = menu.addAction(name);
string slotName(slot);
slotName = string("1") + slotName;
connect(act, SIGNAL(triggered()), slotName.c_str());
}
//-----------------------------------------------------------------------------
/*! If button left is pressed start drag and drop.
*/
void StudioPaletteTreeViewer::mouseMoveEvent(QMouseEvent *event)
{
// If left button is not pressed return; is not drag event.
if (!(event->buttons() & Qt::LeftButton))
return;
startDragDrop();
}
//-----------------------------------------------------------------------------
/*! If path related to current item exist and is a palette execute drag.
*/
void StudioPaletteTreeViewer::startDragDrop()
{
TFilePath path = getCurrentFolderPath();
if (!path.isEmpty() &&
(path.getType() == "tpl" || path.getType() == "pli" ||
path.getType() == "tlv" || path.getType() == "tnz")) {
QDrag *drag = new QDrag(this);
QMimeData *mimeData = new QMimeData;
QList<QUrl> urls;
urls.append(pathToUrl(path));
mimeData->setUrls(urls);
drag->setMimeData(mimeData);
Qt::DropAction dropAction = drag->exec(Qt::CopyAction | Qt::MoveAction);
}
viewport()->update();
}
//-----------------------------------------------------------------------------
/*! Verify drag enter data, if it has an url and it's path is a palette or data
is a PaletteData accept drag event.
*/
void StudioPaletteTreeViewer::dragEnterEvent(QDragEnterEvent *event)
{
const QMimeData *mimeData = event->mimeData();
const PaletteData *paletteData = dynamic_cast<const PaletteData *>(mimeData);
if (mimeData->hasUrls()) {
if (mimeData->urls().size() != 1)
return;
QUrl url = mimeData->urls()[0];
TFilePath path(url.toLocalFile().toStdWString());
if (path.isEmpty() ||
(path.getType() != "tpl" && path.getType() != "pli" &&
path.getType() != "tlv" && path.getType() != "tnz"))
return;
event->acceptProposedAction();
} else if (paletteData && !paletteData->hasStyleIndeces())
event->acceptProposedAction();
viewport()->update();
}
//-----------------------------------------------------------------------------
/*! Find item folder nearest to current position.
*/
void StudioPaletteTreeViewer::dragMoveEvent(QDragMoveEvent *event)
{
QTreeWidgetItem *item = itemAt(event->pos());
TFilePath newPath = getFolderPath(item);
if (newPath.getType() == "tpl") {
m_dropItem = 0;
event->ignore();
} else {
m_dropItem = item;
event->acceptProposedAction();
}
viewport()->update();
}
//-----------------------------------------------------------------------------
/*! Execute drop event. If dropped palette is in studio palette folder move
palette, otherwise copy palette in current folder.
*/
void StudioPaletteTreeViewer::dropEvent(QDropEvent *event)
{
TFilePath path;
const QMimeData *mimeData = event->mimeData();
if (!mimeData->hasUrls())
return;
if (mimeData->urls().size() != 1)
return;
QUrl url = mimeData->urls()[0];
path = TFilePath(url.toLocalFile().toStdWString());
event->setDropAction(Qt::CopyAction);
event->accept();
TFilePath newPath = getFolderPath(m_dropItem);
StudioPalette *studioPlt = StudioPalette::instance();
if (path == newPath || path.getParentDir() == newPath)
return;
if (isInStudioPalette(path)) {
newPath += TFilePath(path.getName() + path.getDottedType());
try {
StudioPaletteCmd::movePalette(newPath, path);
} catch (TException &e) {
error("Can't rename palette: " + QString(toString(e.getMessage()).c_str()));
} catch (...) {
error("Can't rename palette");
}
} else {
TPalette *palette = studioPlt->getPalette(path);
//Se non trova palette sto importando: - la palette del livello corrente o - la cleanupPalette!
if (!palette) {
if (path.getType() == "pli" || path.getType() == "tlv") {
TXshLevel *level = m_levelHandle->getLevel();
assert(level && level->getSimpleLevel());
palette = level->getSimpleLevel()->getPalette();
path = level->getPath();
} else if (path.getType() == "tnz") {
palette = m_sceneHandle->getScene()->getProperties()->getCleanupPalette();
path = TFilePath();
}
}
try {
StudioPaletteCmd::createPalette(newPath, path.getName(), palette);
} catch (TException &e) {
error("Can't create palette: " + QString(toString(e.getMessage()).c_str()));
} catch (...) {
error("Can't create palette");
}
}
m_dropItem = 0;
}
//-----------------------------------------------------------------------------
/*! Set dropItem to 0 and update the tree.
*/
void StudioPaletteTreeViewer::dragLeaveEvent(QDragLeaveEvent *event)
{
m_dropItem = 0;
update();
}
//-----------------------------------------------------------------------------
/*! Receive widget hide events. Remove this listener from \b StudioPalette.
*/
void StudioPaletteTreeViewer::hideEvent(QHideEvent *event)
{
StudioPalette::instance()->removeListener(this);
}
//-----------------------------------------------------------------------------
/*! Receive widget show events. Add this listener to \b StudioPalette and
refresh tree.
*/
void StudioPaletteTreeViewer::showEvent(QShowEvent *event)
{
StudioPalette::instance()->addListener(this);
refresh();
}
//=============================================================================
/*! \class StudioPaletteViewer
\brief The StudioPaletteViewer class provides an object to view and manage
studio palettes.
Inherits \b QFrame.
This object is composed of a splitter \b QSplitter that contain a vertical
layout and a \b PaletteViewer. Vertical layout contain a \b StudioPaletteTreeViewer
and a toolbar, this object allows to manage the palettes in studio palette folders.
\b PaletteViewer is set to fixed view type: \b PaletteViewerGUI::STUDIO_PALETTE
allows to show and modify current studio palette selected in tree.
*/
StudioPaletteViewer::StudioPaletteViewer(QWidget *parent,
TPaletteHandle *studioPaletteHandle,
TPaletteHandle *levelPaletteHandle,
TSceneHandle *sceneHandle,
TXshLevelHandle *levelHandle,
TFrameHandle *frameHandle)
: QFrame(parent)
{
setObjectName("studiopalette");
setFrameStyle(QFrame::StyledPanel);
setAcceptDrops(true);
QVBoxLayout *layout = new QVBoxLayout(this);
layout->setMargin(0);
QSplitter *splitter = new QSplitter(this);
splitter->setOrientation(Qt::Vertical);
//First Splitter Widget
QWidget *treeWidget = new QWidget(this);
QVBoxLayout *treeVLayout = new QVBoxLayout(treeWidget);
treeVLayout->setMargin(0);
treeVLayout->setSpacing(0);
StudioPaletteTreeViewer *studioPltTreeViewer = new StudioPaletteTreeViewer(treeWidget,
studioPaletteHandle,
levelPaletteHandle);
studioPltTreeViewer->setSceneHandle(sceneHandle);
studioPltTreeViewer->setLevelHandle(levelHandle);
treeVLayout->addWidget(studioPltTreeViewer);
//Create toolbar. It is an horizontal layout with three internal toolbar.
QWidget *treeToolbarWidget = new QWidget(this);
treeToolbarWidget->setFixedHeight(22);
QHBoxLayout *treeToolbarLayout = new QHBoxLayout(treeToolbarWidget);
treeToolbarLayout->setMargin(0);
treeToolbarLayout->setSpacing(0);
QToolBar *newToolbar = new QToolBar(treeToolbarWidget);
//New folder action
QIcon newFolderIcon = createQIconPNG("newfolder");
QAction *addFolder = new QAction(newFolderIcon, tr("&New Folder"), newToolbar);
connect(addFolder, SIGNAL(triggered()), studioPltTreeViewer, SLOT(addNewFolder()));
newToolbar->addAction(addFolder);
//New palette action
QIcon newPaletteIcon = createQIconPNG("newpalette");
QAction *addPalette = new QAction(newPaletteIcon, tr("&New Palette"), newToolbar);
connect(addPalette, SIGNAL(triggered()), studioPltTreeViewer, SLOT(addNewPlt()));
newToolbar->addAction(addPalette);
newToolbar->addSeparator();
QToolBar *spacingToolBar = new QToolBar(treeToolbarWidget);
spacingToolBar->setMinimumHeight(22);
QToolBar *deleteToolbar = new QToolBar(treeToolbarWidget);
//Delete folder and palette action
QIcon deleteFolderIcon = createQIconPNG("delete");
QAction *deleteFolder = new QAction(deleteFolderIcon, tr("&Delete"), deleteToolbar);
connect(deleteFolder, SIGNAL(triggered()), studioPltTreeViewer, SLOT(deleteItem()));
deleteToolbar->addSeparator();
deleteToolbar->addAction(deleteFolder);
treeToolbarLayout->addWidget(newToolbar, 0, Qt::AlignLeft);
treeToolbarLayout->addWidget(spacingToolBar, 1);
treeToolbarLayout->addWidget(deleteToolbar, 0, Qt::AlignRight);
treeToolbarWidget->setLayout(treeToolbarLayout);
treeVLayout->addWidget(treeToolbarWidget);
treeWidget->setLayout(treeVLayout);
//Second Splitter Widget
PaletteViewer *studioPltViewer = new PaletteViewer(this, PaletteViewerGUI::STUDIO_PALETTE);
studioPltViewer->setPaletteHandle(studioPaletteHandle);
studioPltViewer->setFrameHandle(frameHandle);
studioPltViewer->setLevelHandle(levelHandle);
studioPltViewer->setSceneHandle(sceneHandle);
splitter->addWidget(treeWidget);
splitter->addWidget(studioPltViewer);
layout->addWidget(splitter);
setLayout(layout);
}
//-----------------------------------------------------------------------------
StudioPaletteViewer::~StudioPaletteViewer()
{
}
//=============================================================================
OpenFloatingPanel openStudioPaletteCommand("MI_OpenStudioPalette",
"StudioPalette",
"Studio Palette");
| bsd-3-clause |
diofeher/django-nfa | django/core/serializers/base.py | 5533 | """
Module for abstract serializer/unserializer base classes.
"""
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
from django.db import models
from django.utils.encoding import smart_str, smart_unicode
class SerializationError(Exception):
"""Something bad happened during serialization."""
pass
class DeserializationError(Exception):
"""Something bad happened during deserialization."""
pass
class Serializer(object):
"""
Abstract serializer base class.
"""
# Indicates if the implemented serializer is only available for
# internal Django use.
internal_use_only = False
def serialize(self, queryset, **options):
"""
Serialize a queryset.
"""
self.options = options
self.stream = options.get("stream", StringIO())
self.selected_fields = options.get("fields")
self.start_serialization()
for obj in queryset:
self.start_object(obj)
for field in obj._meta.local_fields:
if field.serialize:
if field.rel is None:
if self.selected_fields is None or field.attname in self.selected_fields:
self.handle_field(obj, field)
else:
if self.selected_fields is None or field.attname[:-3] in self.selected_fields:
self.handle_fk_field(obj, field)
for field in obj._meta.many_to_many:
if field.serialize:
if self.selected_fields is None or field.attname in self.selected_fields:
self.handle_m2m_field(obj, field)
self.end_object(obj)
self.end_serialization()
return self.getvalue()
def get_string_value(self, obj, field):
"""
Convert a field's value to a string.
"""
if isinstance(field, models.DateTimeField):
value = getattr(obj, field.name).strftime("%Y-%m-%d %H:%M:%S")
else:
value = field.flatten_data(follow=None, obj=obj).get(field.name, "")
return smart_unicode(value)
def start_serialization(self):
"""
Called when serializing of the queryset starts.
"""
raise NotImplementedError
def end_serialization(self):
"""
Called when serializing of the queryset ends.
"""
pass
def start_object(self, obj):
"""
Called when serializing of an object starts.
"""
raise NotImplementedError
def end_object(self, obj):
"""
Called when serializing of an object ends.
"""
pass
def handle_field(self, obj, field):
"""
Called to handle each individual (non-relational) field on an object.
"""
raise NotImplementedError
def handle_fk_field(self, obj, field):
"""
Called to handle a ForeignKey field.
"""
raise NotImplementedError
def handle_m2m_field(self, obj, field):
"""
Called to handle a ManyToManyField.
"""
raise NotImplementedError
def getvalue(self):
"""
Return the fully serialized queryset (or None if the output stream is
not seekable).
"""
if callable(getattr(self.stream, 'getvalue', None)):
return self.stream.getvalue()
class Deserializer(object):
"""
Abstract base deserializer class.
"""
def __init__(self, stream_or_string, **options):
"""
Init this serializer given a stream or a string
"""
self.options = options
if isinstance(stream_or_string, basestring):
self.stream = StringIO(stream_or_string)
else:
self.stream = stream_or_string
# hack to make sure that the models have all been loaded before
# deserialization starts (otherwise subclass calls to get_model()
# and friends might fail...)
models.get_apps()
def __iter__(self):
return self
def next(self):
"""Iteration iterface -- return the next item in the stream"""
raise NotImplementedError
class DeserializedObject(object):
"""
A deserialized model.
Basically a container for holding the pre-saved deserialized data along
with the many-to-many data saved with the object.
Call ``save()`` to save the object (with the many-to-many data) to the
database; call ``save(save_m2m=False)`` to save just the object fields
(and not touch the many-to-many stuff.)
"""
def __init__(self, obj, m2m_data=None):
self.object = obj
self.m2m_data = m2m_data
def __repr__(self):
return "<DeserializedObject: %s>" % smart_str(self.object)
def save(self, save_m2m=True):
# Call save on the Model baseclass directly. This bypasses any
# model-defined save. The save is also forced to be raw.
# This ensures that the data that is deserialized is literally
# what came from the file, not post-processed by pre_save/save
# methods.
models.Model.save_base(self.object, raw=True)
if self.m2m_data and save_m2m:
for accessor_name, object_list in self.m2m_data.items():
setattr(self.object, accessor_name, object_list)
# prevent a second (possibly accidental) call to save() from saving
# the m2m data twice.
self.m2m_data = None
| bsd-3-clause |
captainsafia/nteract | applications/desktop/__tests__/renderer/native-window-spec.js | 3118 | import Immutable from "immutable";
import { remote } from "electron";
import { from } from "rxjs/observable/from";
import * as nativeWindow from "../../src/notebook/native-window";
import { makeAppRecord, makeDocumentRecord } from "@nteract/types/core/records";
const path = require("path");
describe("tildify", () => {
test("returns an empty string if given no path", () => {
expect(nativeWindow.tildify()).toBe("");
});
test("replaces the user directory with ~", () => {
const fixture = path.join(remote.app.getPath("home"), "test-notebooks");
const result = nativeWindow.tildify(fixture);
if (process.platform === "win32") {
expect(result).toBe(fixture);
} else {
expect(result).toContain("~");
}
});
});
describe("setTitleFromAttributes", () => {
test("sets the window title", () => {
// Set up our "Electron window"
const win = {
setRepresentedFilename: jest.fn(),
setDocumentEdited: jest.fn(),
setTitle: jest.fn()
};
remote.getCurrentWindow = jest.fn();
remote.getCurrentWindow.mockReturnValue(win);
const titleObject = {
fullpath: "/tmp/test.ipynb",
kernelStatus: "busy",
modified: true
};
nativeWindow.setTitleFromAttributes(titleObject);
expect(win.setTitle).toBeCalled();
});
});
describe("createTitleFeed", () => {
test("creates an observable that updates title attributes for modified notebook", done => {
const notebook = new Immutable.Map().setIn(
["metadata", "kernelspec", "display_name"],
"python3000"
);
const state = {
document: makeDocumentRecord({
notebook,
filename: "titled.ipynb"
}),
app: makeAppRecord({
kernelStatus: "not connected"
})
};
const state$ = from([state]);
const allAttributes = [];
nativeWindow.createTitleFeed(state$).subscribe(
attributes => {
allAttributes.push(attributes);
},
null,
() => {
expect(allAttributes).toEqual([
{
modified: process.platform === "darwin" ? true : false,
fullpath: "titled.ipynb",
kernelStatus: "not connected"
}
]);
done();
}
);
});
test("creates an observable that updates title attributes", done => {
const notebook = new Immutable.Map().setIn(
["metadata", "kernelspec", "display_name"],
"python3000"
);
const state = {
document: makeDocumentRecord({
notebook,
savedNotebook: notebook,
filename: "titled.ipynb"
}),
app: makeAppRecord({
kernelStatus: "not connected"
})
};
const state$ = from([state]);
const allAttributes = [];
nativeWindow.createTitleFeed(state$).subscribe(
attributes => {
allAttributes.push(attributes);
},
null,
() => {
expect(allAttributes).toEqual([
{
modified: false,
fullpath: "titled.ipynb",
kernelStatus: "not connected"
}
]);
done();
}
);
});
});
| bsd-3-clause |
jlmadurga/permabots | permabots/test/testcases.py | 16025 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.test import TestCase
from permabots.models import TelegramUpdate
from telegram import User
from permabots.test import factories
from django.core.urlresolvers import reverse
from rest_framework import status
from telegram.replykeyboardhide import ReplyKeyboardHide
from permabots.models import KikMessage
from permabots.models import MessengerMessage
from messengerbot.elements import PostbackButton, WebUrlButton
import json
try:
from unittest import mock
except ImportError:
import mock # noqa
class BaseTestBot(TestCase):
def _gen_token(self, token):
return 'Token %s' % str(token)
def _create_kik_api_message(self):
self.kik_message = factories.KikTextMessageLibFactory()
self.kik_message.participants = [self.kik_message.from_user]
self.kik_messages = {'messages': [self.kik_message]}
def _create_messenger_api_message(self):
self.messenger_text_message = factories.MessengerMessagingFactory()
self.messenger_entry = factories.MessengerEntryFactory()
self.messenger_entry.messaging = [self.messenger_text_message]
self.messenger_webhook_message = factories.MessengerWebhookFactory()
self.messenger_webhook_message.entries = [self.messenger_entry]
def setUp(self):
with mock.patch("telegram.bot.Bot.set_webhook", callable=mock.MagicMock()):
with mock.patch("kik.api.KikApi.set_configuration", callable=mock.MagicMock()):
with mock.patch("messengerbot.MessengerClient.subscribe_app", callable=mock.MagicMock()):
with mock.patch("telegram.bot.Bot.get_me", callable=mock.MagicMock()) as mock_get_me:
user_dict = {'username': u'Microbot_test_bot', 'first_name': u'Microbot_test', 'id': 204840063}
mock_get_me.return_value = User(**user_dict)
self.bot = factories.BotFactory()
self.telegram_webhook_url = reverse('permabots:telegrambot', kwargs={'hook_id': self.bot.telegram_bot.hook_id})
self.kik_webhook_url = reverse('permabots:kikbot', kwargs={'hook_id': self.bot.kik_bot.hook_id})
self.messenger_webhook_url = reverse('permabots:messengerbot', kwargs={'hook_id': self.bot.messenger_bot.hook_id})
self.telegram_update = factories.TelegramUpdateLibFactory()
self._create_kik_api_message()
self._create_messenger_api_message()
self.kwargs = {'content_type': 'application/json', }
def _test_message(self, action, message_api=None, number=1, no_handler=False):
if not message_api:
message_api = self.message_api
with mock.patch(self.send_message_to_patch, callable=mock.MagicMock()) as mock_send:
if 'in' in action:
self.set_text(action['in'], message_api)
response = self.client.post(self.webhook_url, self.to_send(message_api), **self.kwargs)
# Check response 200 OK
self.assertEqual(response.status_code, status.HTTP_200_OK)
# Check
if no_handler:
self.assertEqual(0, mock_send.call_count)
else:
self.assertBotResponse(mock_send, action, number)
self.assertAPI(number, message_api)
def _test_hook(self, action, data, no_hook=False, num_recipients=1, recipients=[], auth=None, status_to_check=None,
error_to_check=None):
with mock.patch(self.send_message_to_patch, callable=mock.MagicMock()) as mock_send:
hook_url = reverse('permabots:hook', kwargs={'key': action['in']})
if auth:
response = self.client.post(hook_url, data, HTTP_AUTHORIZATION=auth, **self.kwargs)
else:
response = self.client.post(hook_url, data, **self.kwargs)
if no_hook:
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
else:
if status_to_check:
self.assertEqual(response.status_code, status_to_check)
if error_to_check:
self.assertIn(error_to_check, response.data)
else:
# Check response 200 OK
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertBotResponse(mock_send, action, num=num_recipients, recipients=recipients)
class TelegramTestBot(BaseTestBot):
def setUp(self):
super(TelegramTestBot, self).setUp()
self.send_message_to_patch = 'telegram.bot.Bot.send_message'
self.webhook_url = self.telegram_webhook_url
self.message_api = self.telegram_update
def set_text(self, text, update):
if update.message:
update.message.text = text
elif update.callback_query:
update.callback_query.data = text
def to_send(self, update):
if update.callback_query:
update_dict = update.to_dict()
user = update_dict['callback_query'].pop('from_user')
update_dict['callback_query']['from'] = user
return json.dumps(update_dict)
return update.to_json()
def assertTelegramUser(self, model_user, user):
self.assertEqual(model_user.id, user.id)
self.assertEqual(model_user.first_name, user.first_name)
self.assertEqual(model_user.last_name, user.last_name)
self.assertEqual(model_user.username, user.username)
def assertTelegramChat(self, model_chat, chat):
self.assertEqual(model_chat.id, chat.id)
self.assertEqual(model_chat.type, chat.type)
self.assertEqual(model_chat.title, chat.title)
self.assertEqual(model_chat.username, chat.username)
self.assertEqual(model_chat.first_name, chat.first_name)
self.assertEqual(model_chat.last_name, chat.last_name)
def assertTelegramMessage(self, model_message, message):
self.assertEqual(model_message.message_id, message.message_id)
self.assertTelegramUser(model_message.from_user, message.from_user)
self.assertTelegramChat(model_message.chat, message.chat)
# TODO: problems with UTCs
# self.assertEqual(model_message.date, message.date)
self.assertEqual(model_message.text, message.text)
def assertTelegramCallbackQuery(self, model_callback_query, callback_query):
self.assertEqual(model_callback_query.callback_id, callback_query.id)
self.assertTelegramUser(model_callback_query.from_user, callback_query.from_user)
self.assertTelegramChat(model_callback_query.message.chat, callback_query.message.chat)
# TODO: problems with UTCs
# self.assertEqual(model_message.date, message.date)
self.assertEqual(model_callback_query.data, callback_query.data)
def assertTelegramUpdate(self, model_update, update):
self.assertEqual(model_update.update_id, update.update_id)
if update.message:
self.assertTelegramMessage(model_update.message, update.message)
elif update.callback_query:
self.assertTelegramCallbackQuery(model_update.callback_query, update.callback_query)
def assertInTelegramKeyboard(self, button, keyboard):
found = False
for line in keyboard:
if button in line[0].text:
found = True
break
elif line[0].url:
if button in line[0].url:
found = True
break
elif line[0].callback_data:
if button in line[0].callback_data:
found = True
break
self.assertTrue(found)
def assertBotResponse(self, mock_send, command, num=1, recipients=[]):
self.assertEqual(num, mock_send.call_count)
for call_args in mock_send.call_args_list:
args, kwargs = call_args
if not recipients:
if self.telegram_update.message:
self.assertEqual(kwargs['chat_id'], self.telegram_update.message.chat.id)
elif self.telegram_update.callback_query:
self.assertEqual(kwargs['chat_id'], self.telegram_update.callback_query.message.chat.id)
else:
recipients.remove(kwargs['chat_id'])
self.assertEqual(kwargs['parse_mode'], command['out']['parse_mode'])
if not command['out']['reply_markup']:
self.assertTrue(isinstance(kwargs['reply_markup'], ReplyKeyboardHide))
else:
if isinstance(command['out']['reply_markup'], list):
for keyboard in command['out']['reply_markup']:
self.assertInTelegramKeyboard(keyboard, kwargs['reply_markup'].inline_keyboard)
else:
self.assertInTelegramKeyboard(command['out']['reply_markup'], kwargs['reply_markup'].inline_keyboard)
self.assertIn(command['out']['text'], kwargs['text'])
self.assertEqual([], recipients)
def assertAPI(self, number, message_api):
self.assertEqual(number, TelegramUpdate.objects.count())
self.assertTelegramUpdate(TelegramUpdate.objects.get(update_id=message_api.update_id), message_api)
class KikTestBot(BaseTestBot):
def setUp(self):
super(KikTestBot, self).setUp()
self.send_message_to_patch = 'kik.api.KikApi.send_messages'
self.webhook_url = self.kik_webhook_url
self.message_api = self.kik_messages
def set_text(self, text, update):
update['messages'][0].body = text
def to_send(self, messages):
from time import mktime
message = messages['messages'][0]
if message.timestamp:
message.timestamp = int(mktime(message.timestamp.timetuple()))
message.id = str(message.id)
return json.dumps({'messages': [message.to_json()]})
def assertKikMessage(self, model_message, message):
self.assertEqual(str(model_message.message_id), message.id)
self.assertEqual(model_message.from_user.username, message.from_user)
self.assertEqual(model_message.chat.id, message.chat_id)
if message.participants:
self.assertEqual([participant.username for participant in model_message.chat.participants.all()], message.participants)
else:
self.assertEqual(model_message.chat.participants.count(), 0)
# TODO: problems with UTCs
# self.assertEqual(model_message.date, message.date)
if message.type == "text":
body = message.body
if message.type == "start-chatting":
body = "/start"
self.assertEqual(model_message.body, body)
def assertInKikKeyboard(self, button, keyboard):
found = False
for response in keyboard.responses:
if button in response.body:
found = True
break
self.assertTrue(found)
def assertBotResponse(self, mock_send, command, num=1, recipients=[]):
self.assertEqual(num, mock_send.call_count)
for call_args in mock_send.call_args_list:
args, kwargs = call_args
message = args[0][0]
if not recipients:
self.assertEqual(message.chat_id, self.kik_message.chat_id)
else:
recipients.remove(kwargs['chat_id'])
if not command['out']['reply_markup']:
self.assertEqual(message.keyboards, [])
else:
if isinstance(command['out']['reply_markup'], list):
for keyboard in command['out']['reply_markup']:
self.assertInKikKeyboard(keyboard, message.keyboards[0])
else:
self.assertInKikKeyboard(command['out']['reply_markup'], message.keyboards[0])
self.assertIn(command['out']['body'], message.body)
self.assertEqual([], recipients)
def assertAPI(self, number, message_api):
self.assertEqual(number, KikMessage.objects.count())
self.assertKikMessage(KikMessage.objects.get(message_id=message_api['messages'][0].id), message_api['messages'][0])
class MessengerTestBot(BaseTestBot):
def setUp(self):
super(MessengerTestBot, self).setUp()
self.send_message_to_patch = 'messengerbot.MessengerClient.send'
self.webhook_url = self.messenger_webhook_url
self.message_api = self.messenger_webhook_message
def set_text(self, text, update):
if update.entries[0].messaging[0].type == 'message':
update.entries[0].messaging[0].message.text = text
else:
update.entries[0].messaging[0].message.payload = text
def to_send(self, update):
return json.dumps(update.to_json())
def assertMessengerMessage(self, model_message, message):
message = message.entries[0].messaging[0]
self.assertEqual(model_message.sender, message.sender)
self.assertEqual(model_message.recipient, message.recipient)
if model_message.type == MessengerMessage.MESSAGE:
self.assertEqual(model_message.text, message.message.text)
else:
self.assertEqual(model_message.postback, message.message.payload)
def assertInMessengerKeyboard(self, button, keyboard):
found = False
for element in keyboard.elements:
for keyboard_button in element.buttons:
if button in keyboard_button.title:
found = True
break
elif isinstance(keyboard_button, PostbackButton):
if button in keyboard_button.payload:
found = True
break
elif isinstance(keyboard_button, WebUrlButton):
if button in keyboard_button.url:
found = True
break
self.assertTrue(found)
def assertBotResponse(self, mock_send, command, num=1, recipients=[]):
self.assertEqual(num, mock_send.call_count)
for call_args in mock_send.call_args_list:
args, kwargs = call_args
message = args[0]
if not recipients:
self.assertEqual(message.recipient.recipient_id, self.messenger_entry.messaging[0].sender)
else:
recipients.remove(message.recipient.recipient_id)
if not command['out']['reply_markup']:
self.assertEqual(message.message.attachment, None)
text = message.message.text
self.assertIn(command['out']['body'], text)
else:
if isinstance(command['out']['reply_markup'], list):
for keyboard in command['out']['reply_markup']:
self.assertInMessengerKeyboard(keyboard, message.message.attachment.template)
else:
self.assertInMessengerKeyboard(command['out']['reply_markup'], message.message.attachment.template)
self.assertIn(message.message.attachment.template.elements[0].title, command['out']['body'])
self.assertEqual([], recipients)
def assertAPI(self, number, message_api):
self.assertEqual(number, MessengerMessage.objects.count())
self.assertMessengerMessage(MessengerMessage.objects.all()[0], message_api)
| bsd-3-clause |
innaDa/Rcm | src/Factory/ResponseHandlerFactory.php | 1430 | <?php
namespace Rcm\Factory;
use Rcm\Service\ResponseHandler;
use Zend\Mvc\ResponseSender\HttpResponseSender;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
/**
* Service Factory for the Container Manager
*
* Factory for the Container Manager.
*
* @category Reliv
* @package Rcm
* @author Westin Shafer <[email protected]>
* @copyright 2012 Reliv International
* @license License.txt New BSD License
* @version Release: 1.0
* @link https://github.com/reliv
*
*/
class ResponseHandlerFactory implements FactoryInterface
{
/**
* Creates Service
*
* @param ServiceLocatorInterface $serviceLocator Zend Service Locator
*
* @return ResponseHandler
*/
public function createService(ServiceLocatorInterface $serviceLocator)
{
/** @var \Rcm\Entity\Site $currentSite */
$currentSite = $serviceLocator->get('Rcm\Service\CurrentSite');
/** @var \RcmUser\Service\RcmUserService $rcmUserService */
$rcmUserService = $serviceLocator->get('RcmUser\Service\RcmUserService');
/** @var \Zend\Stdlib\Request $request */
$request = $serviceLocator->get('request');
$responseSender = new HttpResponseSender();
return new ResponseHandler(
$request,
$currentSite,
$responseSender,
$rcmUserService
);
}
}
| bsd-3-clause |
cuavas/mFAST | src/mfast/instructions/byte_vector_instruction.h | 1593 | // Copyright (c) 2016, Huang-Ming Huang, Object Computing, Inc.
// All rights reserved.
//
// This file is part of mFAST.
// See the file license.txt for licensing information.
#pragma once
#include "string_instructions.h"
namespace mfast {
class MFAST_EXPORT byte_vector_field_instruction
: public unicode_field_instruction {
public:
byte_vector_field_instruction(operator_enum_t operator_id,
presence_enum_t optional, uint32_t id,
const char *name, const char *ns,
const op_context_t *context,
string_value_storage initial_value,
uint32_t length_id, const char *length_name,
const char *length_ns,
instruction_tag tag = instruction_tag())
: unicode_field_instruction(operator_id, optional, id, name, ns, context,
initial_value, length_id, length_name,
length_ns, tag, field_type_byte_vector) {}
byte_vector_field_instruction(const byte_vector_field_instruction &other)
: unicode_field_instruction(other) {}
virtual void accept(field_instruction_visitor &visitor,
void *context) const override;
virtual byte_vector_field_instruction *
clone(arena_allocator &alloc) const override;
static std::ptrdiff_t hex2binary(const char *src, unsigned char *target);
static const byte_vector_field_instruction *default_instruction();
};
} /* mfast */
| bsd-3-clause |
JianpingZeng/xcc | xcc/test/juliet/testcases/CWE415_Double_Free/s01/CWE415_Double_Free__malloc_free_int_53c.c | 1532 | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE415_Double_Free__malloc_free_int_53c.c
Label Definition File: CWE415_Double_Free__malloc_free.label.xml
Template File: sources-sinks-53c.tmpl.c
*/
/*
* @description
* CWE: 415 Double Free
* BadSource: Allocate data using malloc() and Deallocate data using free()
* GoodSource: Allocate data using malloc()
* Sinks:
* GoodSink: do nothing
* BadSink : Deallocate data using free()
* Flow Variant: 53 Data flow: data passed as an argument from one function through two others to a fourth; all four functions are in different source files
*
* */
#include "std_testcase.h"
#include <wchar.h>
#ifndef OMITBAD
/* bad function declaration */
void CWE415_Double_Free__malloc_free_int_53d_badSink(int * data);
void CWE415_Double_Free__malloc_free_int_53c_badSink(int * data)
{
CWE415_Double_Free__malloc_free_int_53d_badSink(data);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
void CWE415_Double_Free__malloc_free_int_53d_goodG2BSink(int * data);
void CWE415_Double_Free__malloc_free_int_53c_goodG2BSink(int * data)
{
CWE415_Double_Free__malloc_free_int_53d_goodG2BSink(data);
}
/* goodB2G uses the BadSource with the GoodSink */
void CWE415_Double_Free__malloc_free_int_53d_goodB2GSink(int * data);
void CWE415_Double_Free__malloc_free_int_53c_goodB2GSink(int * data)
{
CWE415_Double_Free__malloc_free_int_53d_goodB2GSink(data);
}
#endif /* OMITGOOD */
| bsd-3-clause |
arisona/ether | ether-core/src/main/java/ch/fhnw/util/ClassUtilities.java | 19598 | /*
* Copyright (c) 2013 - 2016 Stefan Muller Arisona, Simon Schubiger
* Copyright (c) 2013 - 2016 FHNW & ETH Zurich
* All rights reserved.
*
* Contributions by: Filip Schramka, Samuel von Stachelski
*
* 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 FHNW / 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 OWNER 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.
*/
package ch.fhnw.util;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicLong;
public final class ClassUtilities {
public static final Class<Object> CLS_Object = Object.class;
public static final Class<Object[]> CLS_ObjectA = Object[].class;
public static final Object[] EMPTY_ObjectA = new Object[0];
public static final Class<?> CLS_void = void.class;
public static final Class<?> CLS_Class = Class.class;
public static final Class<?>[] EMPTY_ClassA = new Class[0];
public static final Class<?> CLS_boolean = boolean.class;
public static final Class<boolean[]> CLS_booleanA = boolean[].class;
public static final Class<Boolean> CLS_Boolean = Boolean.class;
public static final boolean[] EMPTY_booleanA = new boolean[0];
public static final Class<?> CLS_byte = byte.class;
public static final Class<byte[]> CLS_byteA = byte[].class;
public static final byte[] EMPTY_byteA = new byte[0];
public static final Class<Byte> CLS_Byte = Byte.class;
public static final Class<?> CLS_char = char.class;
public static final Class<char[]> CLS_charA = char[].class;
public static final char[] EMPTY_charA = new char[0];
public static final Class<Character> CLS_Character = Character.class;
public static final Class<?> CLS_short = short.class;
public static final Class<short[]> CLS_shortA = short[].class;
public static final Class<Short> CLS_Short = Short.class;
public static final Class<?> CLS_int = int.class;
public static final Class<int[]> CLS_intA = int[].class;
public static final int[] EMPTY_intA = new int[0];
public static final Class<Integer> CLS_Integer = Integer.class;
public static final Class<?> CLS_long = long.class;
public static final Class<long[]> CLS_longA = long[].class;
public static final long[] EMPTY_longA = new long[0];
public static final Class<Long> CLS_Long = Long.class;
public static final Class<?> CLS_float = float.class;
public static final Class<float[]> CLS_floatA = float[].class;
public static final float[] EMPTY_floatA = new float[0];
public static final Class<Float> CLS_Float = Float.class;
public static final Class<?> CLS_double = double.class;
public static final double[] EMPTY_doubleA = new double[0];
public static final Class<double[]> CLS_doubleA = double[].class;
public static final Class<Double> CLS_Double = Double.class;
public static final Class<String> CLS_String = String.class;
public static final Class<String[]> CLS_StringA = String[].class;
public static final String EMPTY_String = "";
public static final String[] EMPTY_StringA = new String[0];
public static final Class<BitSet> CLS_BitSet = BitSet.class;
public static final Class<UUID> CLS_UUID = UUID.class;
public static final UUID[] EMPTY_UUIDA = new UUID[0];
public static final Class<File> CLS_File = File.class;
public static final File[] EMPTY_FileA = new File[0];
@SuppressWarnings("rawtypes")
public static final Class<Enum> CLS_Enum = Enum.class;
@SuppressWarnings("rawtypes")
public static final Class<Map> CLS_Map = Map.class;
@SuppressWarnings("rawtypes")
public static final Class<List> CLS_List = List.class;
@SuppressWarnings("rawtypes")
public static final Class<HashMap> CLS_HashMap = HashMap.class;
@SuppressWarnings("rawtypes")
public static final Class<IdentityHashMap> CLS_IdentityHashMap = IdentityHashMap.class;
@SuppressWarnings("rawtypes")
public static final Class<ArrayList> CLS_ArrayList = ArrayList.class;
static final Hashtable<Class<?>, byte[]> cls2md5 = new Hashtable<>();
static final Hashtable<String, Class<?>> clsMap = new Hashtable<>();
static final Set<Class<?>> IS_INTEGRAL = new IdentityHashSet<>();
static final Set<Class<?>> IS_FLOAT = new IdentityHashSet<>();
static final Set<Class<?>> IS_PRIMITIVE = new IdentityHashSet<>();
static final Set<Class<?>> IS_WRAPPER = new IdentityHashSet<>();
static final Map<Class<?>, HashMap<String, Field>> fieldMap = new IdentityHashMap<>();
static final Map<Class<?>, Field[]> cls2fields = new IdentityHashMap<>();
static final Map<Class<?>, Method[]> cls2methods = new IdentityHashMap<>();
static final Map<Class<?>, Map<Class<?>, Field[]>> clsAnnotation2fields = new IdentityHashMap<>();
static final Map<Class<?>, Map<Class<?>, Method[]>> clsAnnotation2methods = new IdentityHashMap<>();
static final Map<Class<?>, Class<?>> inner2outer = new IdentityHashMap<>();
static {
clsMap.put("boolean", CLS_boolean);
clsMap.put("byte", CLS_byte);
clsMap.put("char", CLS_char);
clsMap.put("short", CLS_short);
clsMap.put("int", CLS_int);
clsMap.put("long", CLS_long);
clsMap.put("float", CLS_float);
clsMap.put("double", CLS_double);
IS_INTEGRAL.add(CLS_byte);
IS_INTEGRAL.add(CLS_Byte);
IS_INTEGRAL.add(CLS_char);
IS_INTEGRAL.add(CLS_Character);
IS_INTEGRAL.add(CLS_short);
IS_INTEGRAL.add(CLS_Short);
IS_INTEGRAL.add(CLS_int);
IS_INTEGRAL.add(CLS_Integer);
IS_INTEGRAL.add(CLS_long);
IS_INTEGRAL.add(CLS_Long);
IS_FLOAT.add(CLS_float);
IS_FLOAT.add(CLS_Float);
IS_FLOAT.add(CLS_double);
IS_FLOAT.add(CLS_Double);
IS_PRIMITIVE.add(CLS_boolean);
IS_PRIMITIVE.add(CLS_void);
IS_PRIMITIVE.add(CLS_byte);
IS_PRIMITIVE.add(CLS_char);
IS_PRIMITIVE.add(CLS_short);
IS_PRIMITIVE.add(CLS_int);
IS_PRIMITIVE.add(CLS_long);
IS_PRIMITIVE.add(CLS_float);
IS_PRIMITIVE.add(CLS_double);
IS_WRAPPER.add(CLS_Boolean);
IS_WRAPPER.add(CLS_Byte);
IS_WRAPPER.add(CLS_Character);
IS_WRAPPER.add(CLS_Short);
IS_WRAPPER.add(CLS_Integer);
IS_WRAPPER.add(CLS_Long);
IS_WRAPPER.add(CLS_Float);
IS_WRAPPER.add(CLS_Double);
}
public static byte[] getMD5(Class<?> cls) throws NoSuchAlgorithmException, IOException {
byte[] result = cls2md5.get(cls);
if(result == null) {
MessageDigest md = MessageDigest.getInstance("MD5");
String name = cls.getName();
name = name.substring(name.lastIndexOf('.') + 1) + ".class";
try (InputStream in = cls.getResourceAsStream(name)) {
byte[] buffer = new byte[8192];
while(true) {
int r = in.read(buffer);
if(r == -1) break;
md.update(buffer, 0, r);
}
}
result = md.digest();
cls2md5.put(cls, result);
}
return result;
}
public static Class<?> toPrimitiveType(Class<?> type) {
if(type == Boolean.class)
return Boolean.TYPE;
else if(type == Byte.class)
return Byte.TYPE;
else if(type == Short.class)
return Short.TYPE;
else if(type == Integer.class)
return Integer.TYPE;
else if(type == Long.class)
return Long.TYPE;
else if(type == Float.class)
return Float.TYPE;
else if(type == Double.class)
return Double.TYPE;
else
return type;
}
public static Class<?> forName(String name) throws ClassNotFoundException {
Class<?> result = clsMap.get(name);
return result == null ? getGlobalClassloader().loadClass(name) : result;
}
public static Class<?>[] getGenericTypes(Type genericType) throws ClassNotFoundException {
String[] gtypes = genericType.toString().split("[<>]");
Class<?>[] result = new Class<?>[gtypes.length - 1];
for(int i = 0; i < result.length; i++) {
String cls = gtypes[i + 1];
int dimension = TextUtilities.count(cls, '[');
if(dimension == 0)
result[i] = forName(cls);
else {
cls = cls.substring(0, cls.indexOf('['));
int[] dims = new int[dimension];
result[i] = Array.newInstance(forName(cls), dims).getClass();
}
}
return result;
}
public static boolean isBoolean(Class<?> cls) {
return CLS_boolean == cls || CLS_Boolean == cls;
}
public static boolean isIntegral(Class<?> cls) {
return IS_INTEGRAL.contains(cls);
}
public static boolean isFloat(Class<?> cls) {
return IS_FLOAT.contains(cls);
}
public static boolean isPrimitiveOrWrapper(Class<?> cls) {
return IS_PRIMITIVE.contains(cls) || IS_WRAPPER.contains(cls);
}
public static Class<?> getComponentType(Class<?> type) {
if(type.isArray()) return getComponentType(type.getComponentType());
return type;
}
public static Field[] getAllFields(Class<?> type) {
Field[] result = cls2fields.get(type);
if(result == null) {
Collection<Field> fields = getAllFields(type, new ArrayList<>());
result = fields.toArray(new Field[fields.size()]);
cls2fields.put(type, result);
AccessibleObject.setAccessible(result, true);
}
return result;
}
private static Collection<Field> getAllFields(Class<?> type, List<Field> result) {
if(type == CLS_Object) return result;
try {
Collections.addAll(result, type.getDeclaredFields());
} catch(Throwable t) {
t.printStackTrace();
}
return getAllFields(type.getSuperclass(), result);
}
public static Method[] getAllMethods(Class<?> type) {
Method[] result = cls2methods.get(type);
if(result == null) {
Collection<Method> methods = getAllMethods(type, new ArrayList<>());
result = methods.toArray(new Method[methods.size()]);
cls2methods.put(type, result);
AccessibleObject.setAccessible(result, true);
}
return result;
}
public static Method getMethod(String type, String method, Class<?> ... argTypes) throws ClassNotFoundException {
return getMethod(getGlobalClassloader().loadClass(type), method, argTypes);
}
public static Method getMethod(Class<?> type, String method, Class<?> ... argTypes) {
for(Method m : getAllMethods(type)) {
if(m.getName().equals(method) && Arrays.equals(m.getParameterTypes(), argTypes))
return m;
}
throw new NoSuchMethodError(method + TextUtilities.toString("(", ",", ")", argTypes));
}
private static Collection<Method> getAllMethods(Class<?> type, List<Method> result) {
if(type == CLS_Object) return result;
Collections.addAll(result, type.getDeclaredMethods());
return getAllMethods(type.getSuperclass(), result);
}
public static String getCurrentMethodName() {
return Thread.currentThread().getStackTrace()[2].getMethodName();
}
public static String getCallerMethodName() {
return Thread.currentThread().getStackTrace()[3].getMethodName();
}
public static String getCallerClassName() {
return Thread.currentThread().getStackTrace()[3].getClassName();
}
public static String getCallerClassAndMethodName(int n) {
StackTraceElement[] elements = Thread.currentThread().getStackTrace();
if (n + 4 >= elements.length)
return "none";
return elements[n + 3].getClassName() + "." + elements[n + 3].getMethodName();
}
public static Field getField(Class<?> type, String field) {
HashMap<String, Field> fields = fieldMap.get(type);
if(fields == null) {
fields = new HashMap<>();
Field[] fieldsa = getAllFields(type);
for(int i = fieldsa.length; --i >= 0;)
fields.put(fieldsa[i].getName(), fieldsa[i]);
fieldMap.put(type, fields);
}
Field result = fields.get(field);
if(result == null)
throw new NoSuchFieldError(type.getName() + "." + field);
return result;
}
public static Field[] getAllAnotatedFields(Class<?> cls, Class<? extends Annotation> annotationCls) {
Map<Class<?>, Field[]> annotation2field = clsAnnotation2fields.get(cls);
if(annotation2field == null) {
annotation2field = new IdentityHashMap<>();
clsAnnotation2fields.put(cls, annotation2field);
}
Field[] result = annotation2field.get(annotationCls);
if(result == null) {
List<Field> fields = new LinkedList<>();
for(Field field : getAllFields(cls)) {
if(field.getAnnotation(annotationCls) != null)
fields.add(field);
}
result = fields.toArray(new Field[fields.size()]);
annotation2field.put(annotationCls, result);
}
return result;
}
public static Method[] getAllAnnotatedMethods(Class<?> cls, Class<? extends Annotation> annotationCls) {
Map<Class<?>, Method[]> annotation2method = clsAnnotation2methods.get(cls);
if(annotation2method == null) {
annotation2method = new IdentityHashMap<>();
clsAnnotation2methods.put(cls, annotation2method);
}
Method[] result = annotation2method.get(annotationCls);
if(result == null) {
List<Method> methods = new LinkedList<>();
for(Method method : getAllMethods(cls)) {
if(method.getAnnotation(annotationCls) != null)
methods.add(method);
}
result = methods.toArray(new Method[methods.size()]);
annotation2method.put(annotationCls, result);
}
return result;
}
private static final Map<Method, Class<?>[]> method2paramTypes = new IdentityHashMap<>();
public synchronized static Class<?>[] getParameterTypes(Method m) {
Class<?>[] result = method2paramTypes.get(m);
if(result == null) {
result = m.getParameterTypes();
method2paramTypes.put(m, result);
}
return result;
}
public synchronized static ClassLoader getGlobalClassloader() {
return ClassUtilities.class.getClassLoader();
}
public static Class<?>[] getTypeHierarchy(Class<?> cls) {
ArrayList<Class<?>> result = getTypeHierarchy(cls, new ArrayList<>());
return result.toArray(new Class<?>[result.size()]);
}
private static ArrayList<Class<?>> getTypeHierarchy(Class<?> cls, ArrayList<Class<?>> result) {
result.add(cls);
if(cls == CLS_Object)
return result;
return getTypeHierarchy(cls.getSuperclass(), result);
}
@SuppressWarnings("unchecked")
public static <T> Class<T> forNameOrNull(String cls) {
try {
return (Class<T>) forName(cls);
} catch (Throwable t) {
return null;
}
}
/**
* Returns the class of the specified object, or {@code null} if {@code object} is null.
* This method is also useful for fetching the class of an object known only by its bound
* type. As of Java 6, the usual pattern:
*
* <blockquote><pre>
* Number n = 0;
* Class<? extends Number> c = n.getClass();
* </pre></blockquote>
*
* doesn't seem to work if {@link Number} is replaced by a parametirez type {@code T}.
*
* @param <T> The type of the given object.
* @param object The object for which to get the class, or {@code null}.
* @return The class of the given object, or {@code null} if the given object was null.
*/
@SuppressWarnings("unchecked")
public static <T> Class<? extends T> getClass(final T object) {
return (object != null) ? (Class<? extends T>) object.getClass() : null;
}
public static int getDimension(Class<?> cls) {
return cls.getComponentType() == null ? 0 : 1 + getDimension(cls.getComponentType());
}
private static final AtomicLong ID_COUNTER = new AtomicLong();
public static long createObjectID() {
return ID_COUNTER.addAndGet(1);
}
public static int identityHashCode(Object x) {
if(x instanceof IObjectID)
return (int) ((IObjectID) x).getObjectID();
else if(x instanceof String || x instanceof Number || x instanceof UUID)
return x.hashCode();
return System.identityHashCode(x);
}
/**
* Value representing null keys inside tables.
*/
private static final Object NULL_KEY = new IObjectID() {
@Override
public long getObjectID() {
return 0;
}
};
/**
* Use NULL_KEY for key if it is null.
*/
public static Object maskNull(Object key) {
return (key == null ? NULL_KEY : key);
}
/**
* Returns internal representation of null key back to caller as null.
*/
public static Object unmaskNull(Object key) {
return (key == NULL_KEY ? null : key);
}
@SuppressWarnings("unchecked")
public static <T> T newInstance(String cls, Class<?>[] types, Object ... args) {
try {
return (T) getGlobalClassloader().loadClass(cls).getConstructor(types).newInstance(args);
} catch(Throwable t) {
t.printStackTrace();
}
return null;
}
public static <T> T newInstance(Class<? extends T> cls, Class<?>[] types, Object ... args) {
try {
return cls.getConstructor(types).newInstance(args);
} catch(Throwable t) {
t.printStackTrace();
}
return null;
}
public static Class<?> getEnclosingClass(Class<?> cls) {
Class<?> result = inner2outer.get(cls);
if(result == null) {
result = cls.getEnclosingClass();
inner2outer.put(cls, result);
}
return result;
}
}
| bsd-3-clause |
mathjazz/pontoon | pontoon/urls.py | 2791 | from django.urls import include, path, register_converter
from django.urls.converters import StringConverter
from django.contrib import admin
from django.contrib.auth import logout
from django.views.generic import RedirectView, TemplateView
from pontoon.teams.views import team
class LocaleConverter(StringConverter):
regex = r"[A-Za-z0-9\-\@\.]+"
register_converter(LocaleConverter, "locale")
pontoon_js_view = TemplateView.as_view(
template_name="js/pontoon.js", content_type="text/javascript"
)
permission_denied_view = TemplateView.as_view(template_name="403.html")
page_not_found_view = TemplateView.as_view(template_name="404.html")
server_error_view = TemplateView.as_view(template_name="500.html")
urlpatterns = [
# Accounts
path("accounts/", include("pontoon.allauth_urls")),
# Admin
path("admin/", include("pontoon.administration.urls")),
# Django admin: Disable the login form
path("a/login/", permission_denied_view),
# Django admin
path("a/", admin.site.urls),
# Logout
path("signout/", logout, {"next_page": "/"}, name="signout"),
# Error pages
path("403/", permission_denied_view),
path("404/", page_not_found_view),
path("500/", server_error_view),
# Robots.txt
path(
"robots.txt",
TemplateView.as_view(template_name="robots.txt", content_type="text/plain"),
),
# contribute.json
path(
"contribute.json",
TemplateView.as_view(
template_name="contribute.json", content_type="text/plain"
),
),
# Favicon
path(
"favicon.ico",
RedirectView.as_view(url="/static/img/favicon.ico", permanent=True),
),
# Include script
path("pontoon.js", pontoon_js_view),
path("static/js/pontoon.js", pontoon_js_view),
# Include URL configurations from installed apps
path("terminology/", include("pontoon.terminology.urls")),
path("translations/", include("pontoon.translations.urls")),
path("", include("pontoon.teams.urls")),
path("", include("pontoon.tour.urls")),
path("", include("pontoon.tags.urls")),
path("", include("pontoon.sync.urls")),
path("", include("pontoon.projects.urls")),
path("", include("pontoon.machinery.urls")),
path("", include("pontoon.contributors.urls")),
path("", include("pontoon.localizations.urls")),
path("", include("pontoon.base.urls")),
path("", include("pontoon.translate.urls")),
path("", include("pontoon.batch.urls")),
path("", include("pontoon.api.urls")),
path("", include("pontoon.homepage.urls")),
path("", include("pontoon.in_context.urls")),
path("", include("pontoon.uxactionlog.urls")),
# Team page: Must be at the end
path("<locale:locale>/", team, name="pontoon.teams.team"),
]
| bsd-3-clause |
JianpingZeng/xcc | xcc/test/juliet/testcases/CWE191_Integer_Underflow/s01/CWE191_Integer_Underflow__char_rand_multiply_22b.c | 3725 | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE191_Integer_Underflow__char_rand_multiply_22b.c
Label Definition File: CWE191_Integer_Underflow.label.xml
Template File: sources-sinks-22b.tmpl.c
*/
/*
* @description
* CWE: 191 Integer Underflow
* BadSource: rand Set data to result of rand()
* GoodSource: Set data to a small, non-zero number (negative two)
* Sinks: multiply
* GoodSink: Ensure there will not be an underflow before multiplying data by 2
* BadSink : If data is negative, multiply by 2, which can cause an underflow
* Flow Variant: 22 Control flow: Flow controlled by value of a global variable. Sink functions are in a separate file from sources.
*
* */
#include "std_testcase.h"
#ifndef OMITBAD
/* The global variable below is used to drive control flow in the sink function */
extern int CWE191_Integer_Underflow__char_rand_multiply_22_badGlobal;
void CWE191_Integer_Underflow__char_rand_multiply_22_badSink(char data)
{
if(CWE191_Integer_Underflow__char_rand_multiply_22_badGlobal)
{
if(data < 0) /* ensure we won't have an overflow */
{
/* POTENTIAL FLAW: if (data * 2) < CHAR_MIN, this will underflow */
char result = data * 2;
printHexCharLine(result);
}
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* The global variables below are used to drive control flow in the sink functions. */
extern int CWE191_Integer_Underflow__char_rand_multiply_22_goodB2G1Global;
extern int CWE191_Integer_Underflow__char_rand_multiply_22_goodB2G2Global;
extern int CWE191_Integer_Underflow__char_rand_multiply_22_goodG2BGlobal;
/* goodB2G1() - use badsource and goodsink by setting the static variable to false instead of true */
void CWE191_Integer_Underflow__char_rand_multiply_22_goodB2G1Sink(char data)
{
if(CWE191_Integer_Underflow__char_rand_multiply_22_goodB2G1Global)
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
printLine("Benign, fixed string");
}
else
{
if(data < 0) /* ensure we won't have an overflow */
{
/* FIX: Add a check to prevent an underflow from occurring */
if (data > (CHAR_MIN/2))
{
char result = data * 2;
printHexCharLine(result);
}
else
{
printLine("data value is too small to perform multiplication.");
}
}
}
}
/* goodB2G2() - use badsource and goodsink by reversing the blocks in the if in the sink function */
void CWE191_Integer_Underflow__char_rand_multiply_22_goodB2G2Sink(char data)
{
if(CWE191_Integer_Underflow__char_rand_multiply_22_goodB2G2Global)
{
if(data < 0) /* ensure we won't have an overflow */
{
/* FIX: Add a check to prevent an underflow from occurring */
if (data > (CHAR_MIN/2))
{
char result = data * 2;
printHexCharLine(result);
}
else
{
printLine("data value is too small to perform multiplication.");
}
}
}
}
/* goodG2B() - use goodsource and badsink */
void CWE191_Integer_Underflow__char_rand_multiply_22_goodG2BSink(char data)
{
if(CWE191_Integer_Underflow__char_rand_multiply_22_goodG2BGlobal)
{
if(data < 0) /* ensure we won't have an overflow */
{
/* POTENTIAL FLAW: if (data * 2) < CHAR_MIN, this will underflow */
char result = data * 2;
printHexCharLine(result);
}
}
}
#endif /* OMITGOOD */
| bsd-3-clause |
ondra-novak/blink | Source/core/svg/SVGAnimateElement.h | 3322 | /*
* Copyright (C) 2004, 2005 Nikolas Zimmermann <[email protected]>
* Copyright (C) 2004, 2005 Rob Buis <[email protected]>
* Copyright (C) 2008 Apple Inc. All rights reserved.
* Copyright (C) Research In Motion Limited 2011. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#ifndef SVGAnimateElement_h
#define SVGAnimateElement_h
#include "core/SVGNames.h"
#include "core/svg/SVGAnimatedTypeAnimator.h"
#include "core/svg/SVGAnimationElement.h"
#include "wtf/OwnPtr.h"
namespace blink {
class SVGAnimatedTypeAnimator;
class SVGAnimateElement : public SVGAnimationElement {
public:
static PassRefPtrWillBeRawPtr<SVGAnimateElement> create(Document&);
virtual ~SVGAnimateElement();
virtual void trace(Visitor*) OVERRIDE;
AnimatedPropertyType animatedPropertyType();
bool animatedPropertyTypeSupportsAddition();
protected:
SVGAnimateElement(const QualifiedName&, Document&);
virtual void resetAnimatedType() OVERRIDE FINAL;
virtual void clearAnimatedType(SVGElement* targetElement) OVERRIDE FINAL;
virtual bool calculateToAtEndOfDurationValue(const String& toAtEndOfDurationString) OVERRIDE FINAL;
virtual bool calculateFromAndToValues(const String& fromString, const String& toString) OVERRIDE FINAL;
virtual bool calculateFromAndByValues(const String& fromString, const String& byString) OVERRIDE FINAL;
virtual void calculateAnimatedValue(float percentage, unsigned repeatCount, SVGSMILElement* resultElement) OVERRIDE FINAL;
virtual void applyResultsToTarget() OVERRIDE FINAL;
virtual float calculateDistance(const String& fromString, const String& toString) OVERRIDE FINAL;
virtual bool isAdditive() OVERRIDE FINAL;
virtual void setTargetElement(SVGElement*) OVERRIDE FINAL;
virtual void setAttributeName(const QualifiedName&) OVERRIDE FINAL;
private:
void resetAnimatedPropertyType();
SVGAnimatedTypeAnimator* ensureAnimator();
virtual bool hasValidAttributeType() OVERRIDE;
RefPtr<SVGPropertyBase> m_fromProperty;
RefPtr<SVGPropertyBase> m_toProperty;
RefPtr<SVGPropertyBase> m_toAtEndOfDurationProperty;
RefPtr<SVGPropertyBase> m_animatedProperty;
OwnPtrWillBeMember<SVGAnimatedTypeAnimator> m_animator;
};
inline bool isSVGAnimateElement(const SVGElement& element)
{
return element.hasTagName(SVGNames::animateTag)
|| element.hasTagName(SVGNames::animateTransformTag)
|| element.hasTagName(SVGNames::setTag);
}
DEFINE_SVGELEMENT_TYPE_CASTS_WITH_FUNCTION(SVGAnimateElement);
} // namespace blink
#endif // SVGAnimateElement_h
| bsd-3-clause |
BernhardDenner/libelektra | src/plugins/yanlr/yanlr/map-list-plain_scalars.hpp | 365 | // clang-format off
CppKeySet { 10,
keyNew (PREFIX "primes", KEY_META, "array", "#3", KEY_END),
keyNew (PREFIX "primes/#0", KEY_VALUE, "two", KEY_END),
keyNew (PREFIX "primes/#1", KEY_VALUE, "three", KEY_END),
keyNew (PREFIX "primes/#2", KEY_VALUE, "five", KEY_END),
keyNew (PREFIX "primes/#3", KEY_VALUE, "seven", KEY_END),
KS_END }
| bsd-3-clause |
upliu/getyii | common/services/UserService.php | 6118 | <?php
/**
* author : forecho <[email protected]>
* createTime : 15/4/19 下午3:20
* description:
*/
namespace common\services;
use common\models\Post;
use common\models\PostComment;
use common\models\User;
use common\models\UserInfo;
use DevGroup\TagDependencyHelper\NamingHelper;
use frontend\modules\topic\models\Topic;
use frontend\modules\user\models\UserMeta;
use yii\caching\TagDependency;
class UserService
{
/**
* 获取通知条数
* @return mixed
*/
public static function findNotifyCount()
{
$user = \Yii::$app->getUser()->getIdentity();
return $user ? $user->notification_count : null;
}
/**
* 清除通知数
* @return mixed
*/
public static function clearNotifyCount()
{
return User::updateAll(['notification_count' => '0'], ['id' => \Yii::$app->user->id]);
}
/**
* 赞话题(如果已经赞,则取消赞)
* @param User $user
* @param Topic $topic
* @param $action 动作
* @return array
*/
public static function TopicActionA(User $user, Topic $topic, $action)
{
return self::toggleType($user, $topic, $action);
}
/**
* 用户对话题其他动作
* @param User $user
* @param Post $model
* @param $action fa
* @return array
*/
public static function TopicActionB(User $user, Post $model, $action)
{
$data = [
'target_id' => $model->id,
'target_type' => $model->type,
'user_id' => $user->id,
'value' => '1',
];
if (!UserMeta::deleteOne($data + ['type' => $action])) { // 删除数据有行数则代表有数据,无行数则添加数据
$userMeta = new UserMeta();
$userMeta->setAttributes($data + ['type' => $action]);
$result = $userMeta->save();
if ($result) {
$model->updateCounters([$action . '_count' => 1]);
if ($action == 'thanks') {
UserInfo::updateAllCounters([$action . '_count' => 1], ['user_id' => $model->user_id]);
}
}
return [$result, $userMeta];
}
$model->updateCounters([$action . '_count' => -1]);
if ($action == 'thanks') {
UserInfo::updateAllCounters([$action . '_count' => -1], ['user_id' => $model->user_id]);
}
return [true, null];
}
/**
* 对评论点赞
* @param User $user
* @param PostComment $comment
* @param $action
* @return array
*/
public static function CommentAction(User $user, PostComment $comment, $action)
{
$data = [
'target_id' => $comment->id,
'target_type' => $comment::TYPE,
'user_id' => $user->id,
'value' => '1',
];
if (!UserMeta::deleteOne($data + ['type' => $action])) { // 删除数据有行数则代表有数据,无行数则添加数据
$userMeta = new UserMeta();
$userMeta->setAttributes($data + ['type' => $action]);
$result = $userMeta->save();
if ($result) {
$comment->updateCounters([$action . '_count' => 1]);
// 更新个人总统计
UserInfo::updateAllCounters([$action . '_count' => 1], ['user_id' => $comment->user_id]);
}
return [$result, $userMeta];
}
$comment->updateCounters([$action . '_count' => -1]);
// 更新个人总统计
UserInfo::updateAllCounters([$action . '_count' => -1], ['user_id' => $comment->user_id]);
return [true, null];
}
/**
* 喝倒彩或者赞
* @param User $user
* @param Post $model
* @param $action 动作
* @return array
*/
protected static function toggleType(User $user, Post $model, $action)
{
$data = [
'target_id' => $model->id,
'target_type' => $model->type,
'user_id' => $user->id,
'value' => '1',
];
if (!UserMeta::deleteOne($data + ['type' => $action])) { // 删除数据有行数则代表有数据,无行数则添加数据
$userMeta = new UserMeta();
$userMeta->setAttributes($data + ['type' => $action]);
$result = $userMeta->save();
if ($result) { // 如果是新增数据, 删除掉Hate的同类型数据
$attributeName = ($action == 'like' ? 'hate' : 'like');
$attributes = [$action . '_count' => 1];
if (UserMeta::deleteOne($data + ['type' => $attributeName])) { // 如果有删除hate数据, hate_count也要-1
$attributes[$attributeName . '_count'] = -1;
}
//更新版块统计
$model->updateCounters($attributes);
// 更新个人总统计
UserInfo::updateAllCounters($attributes, ['user_id' => $model->user_id]);
}
return [$result, $userMeta];
}
$model->updateCounters([$action . '_count' => -1]);
UserInfo::updateAllCounters([$action . '_count' => -1], ['user_id' => $model->user_id]);
return [true, null];
}
/**
* 查找活跃用户
* @param int $limit
* @return array|\yii\db\ActiveRecord[]
*/
public static function findActiveUser($limit = 12)
{
$cacheKey = md5(__METHOD__ . $limit);
if (false === $items = \Yii::$app->cache->get($cacheKey)) {
$items = User::find()
->joinWith(['merit', 'userInfo'])
->where([User::tableName() . '.status' => 10])
->orderBy(['merit' => SORT_DESC, '(like_count+thanks_count)' => SORT_DESC])
->limit($limit)
->all();
//一天缓存
\Yii::$app->cache->set($cacheKey, $items, 86400,
new TagDependency([
'tags' => [NamingHelper::getCommonTag(User::className())]
])
);
}
return $items;
}
} | bsd-3-clause |
j-po/django-brambling | brambling/templates/registration/sign_up.html | 420 | {% extends 'brambling/layouts/12_xs.html' %}
{% load floppyforms %}
{% block title %}Sign up – {{ block.super }}{% endblock %}
{% block main %}
<h2>Sign up</h2>
<form action="{{ request.path }}?{{ request.GET.urlencode }}" method="post">
{% csrf_token %}
{% form form using "brambling/forms/signup.html" %}
<button class='btn btn-primary' type="submit">Create your account!</button>
</form>
{% endblock %}
| bsd-3-clause |
JianpingZeng/xcc | xcc/test/juliet/testcases/CWE680_Integer_Overflow_to_Buffer_Overflow/CWE680_Integer_Overflow_to_Buffer_Overflow__malloc_fixed_73a.cpp | 2932 | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE680_Integer_Overflow_to_Buffer_Overflow__malloc_fixed_73a.cpp
Label Definition File: CWE680_Integer_Overflow_to_Buffer_Overflow__malloc.label.xml
Template File: sources-sink-73a.tmpl.cpp
*/
/*
* @description
* CWE: 680 Integer Overflow to Buffer Overflow
* BadSource: fixed Fixed value that will cause an integer overflow in the sink
* GoodSource: Small number greater than zero that will not cause an integer overflow in the sink
* Sinks:
* BadSink : Attempt to allocate array using length value from source
* Flow Variant: 73 Data flow: data passed in a list from one function to another in different source files
*
* */
#include "std_testcase.h"
#include <list>
using namespace std;
namespace CWE680_Integer_Overflow_to_Buffer_Overflow__malloc_fixed_73
{
#ifndef OMITBAD
/* bad function declaration */
void badSink(list<int> dataList);
void bad()
{
int data;
list<int> dataList;
/* Initialize data */
data = -1;
/* FLAW: Set data to a value that will cause an integer overflow in the call to malloc() in the sink */
data = INT_MAX / 2 + 2; /* 1073741825 */
/* NOTE: This value will cause the sink to only allocate 4 bytes of memory, however
* the for loop will attempt to access indices 0-1073741824 */
/* Put data in a list */
dataList.push_back(data);
dataList.push_back(data);
dataList.push_back(data);
badSink(dataList);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* good function declarations */
/* goodG2B uses the GoodSource with the BadSink */
void goodG2BSink(list<int> dataList);
static void goodG2B()
{
int data;
list<int> dataList;
/* Initialize data */
data = -1;
/* FIX: Set data to a relatively small number greater than zero */
data = 20;
/* Put data in a list */
dataList.push_back(data);
dataList.push_back(data);
dataList.push_back(data);
goodG2BSink(dataList);
}
void good()
{
goodG2B();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
* its own for testing or for building a binary to use in testing binary
* analysis tools. It is not used when compiling all the testcases as one
* application, which is how source code analysis tools are tested.
*/
#ifdef INCLUDEMAIN
using namespace CWE680_Integer_Overflow_to_Buffer_Overflow__malloc_fixed_73; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| bsd-3-clause |
chicoxyzzy/fbjs | packages/fbjs/src/core/TouchEventUtils.js | 1271 | /**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule TouchEventUtils
*/
const TouchEventUtils = {
/**
* Utility function for common case of extracting out the primary touch from a
* touch event.
* - `touchEnd` events usually do not have the `touches` property.
* http://stackoverflow.com/questions/3666929/
* mobile-sarai-touchend-event-not-firing-when-last-touch-is-removed
*
* @param {Event} nativeEvent Native event that may or may not be a touch.
* @return {TouchesObject?} an object with pageX and pageY or null.
*/
extractSingleTouch: function(nativeEvent) {
const touches = nativeEvent.touches;
const changedTouches = nativeEvent.changedTouches;
const hasTouches = touches && touches.length > 0;
const hasChangedTouches = changedTouches && changedTouches.length > 0;
return !hasTouches && hasChangedTouches ? changedTouches[0] :
hasTouches ? touches[0] :
nativeEvent;
}
};
module.exports = TouchEventUtils;
| bsd-3-clause |
CUBRID/cubrid-testcases | sql/_23_apricot_qa/_02_performance/_02_function_based_index/cases/function_based_index_function_CHARACTER_LENGTH.sql | 2522 | --+ holdcas on;
set system parameters 'dont_reuse_heap_file=yes';
create table t1( a char(1200), b varchar(1200), c nchar(1200), d NCHAR VARYING(1200), e BIT(1200), f BIT VARYING(1200), g int, h SMALLINT, i BIGINT, j NUMERIC, k FLOAT, l DOUBLE, m MONETARY, n DATE, o TIME, p TIMESTAMP, q DATETIME);
insert into t1 values (
'1234567890',
'1234567890',
N'abc',
N'ABC',
B'1111111111',
B'1111111111',
10,
255,
9223372036854775807,
0,
0,
0,
-100,
DATE '2008-10-31',
TIME '00:00:00',
TIMESTAMP '2010-10-31 01:15:45',
DATETIME '2008-10-31 13:15:45');
insert into t1 values (null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null);
--TEST Create successfully
create index i_t1_a2q on t1(CHARACTER_LENGTH(a));
--TEST: should use index i_t1_a2q
select /*+ RECOMPILE */* from t1 where CHARACTER_LENGTH(a)=3 using index i_t1_a2q(+);
--TEST Create successfully
create index i_t1_a2p on t1(CHARACTER_LENGTH(b));
--TEST: should use index i_t1_a2p
select /*+ RECOMPILE */* from t1 where CHARACTER_LENGTH(b)>3 using index i_t1_a2p(+);
--TEST Create successfully
create index i_t1_a2o on t1(CHARACTER_LENGTH(c));
--TEST: should use index i_t1_a2o
select /*+ RECOMPILE */* from t1 where CHARACTER_LENGTH(c)>=3 using index i_t1_a2o(+);
--TEST Create successfully
create index i_t1_a2n on t1(CHARACTER_LENGTH(d));
--TEST: should use index i_t1_a2n
select /*+ RECOMPILE */* from t1 where CHARACTER_LENGTH(d)=-1 using index i_t1_a2n(+);
--TEST Create failed
create index i_t1_a2m on t1(CHARACTER_LENGTH(e));
--TEST Create failed
create index i_t1_a2l on t1(CHARACTER_LENGTH(f));
--TEST Create failed
create index i_t1_a2k on t1(CHARACTER_LENGTH(g));
--TEST Create failed
create index i_t1_a2j on t1(CHARACTER_LENGTH(h));
--TEST Create failed
create index i_t1_a2i on t1(CHARACTER_LENGTH(i));
--TEST Create failed
create index i_t1_a2h on t1(CHARACTER_LENGTH(j));
--TEST Create failed
create index i_t1_a2g on t1(CHARACTER_LENGTH(k));
--TEST Create failed
create index i_t1_a2f on t1(CHARACTER_LENGTH(l));
--TEST Create failed
create index i_t1_a2e on t1(CHARACTER_LENGTH(m));
--TEST Create failed
create index i_t1_a2d on t1(CHARACTER_LENGTH(n));
--TEST Create failed
create index i_t1_a2c on t1(CHARACTER_LENGTH(o));
--TEST Create failed
create index i_t1_a2b on t1(CHARACTER_LENGTH(p));
--TEST Create failed
create index i_t1_a2a on t1(CHARACTER_LENGTH(q));
drop table t1;
set system parameters 'dont_reuse_heap_file=no';
commit;
--+ holdcas off;
| bsd-3-clause |
UniStuttgart-VISUS/megamol | plugins/protein_cuda/src/tables.h | 18374 | /*
* Copyright 1993-2010 NVIDIA Corporation. All rights reserved.
*
* Please refer to the NVIDIA end user license agreement (EULA) associated
* with this source code for terms and conditions that govern your use of
* this software. Any use, reproduction, disclosure, or distribution of
* this software and related documentation outside the terms of the EULA
* is strictly prohibited.
*
*/
/*
Tables for Marching Cubes
http://local.wasp.uwa.edu.au/~pbourke/geometry/polygonise/
*/
// edge table maps 8-bit flag representing which cube vertices are inside
// the isosurface to 12-bit number indicating which edges are intersected
uint edgeTable[256] = {0x0, 0x109, 0x203, 0x30a, 0x406, 0x50f, 0x605, 0x70c, 0x80c, 0x905, 0xa0f, 0xb06, 0xc0a, 0xd03,
0xe09, 0xf00, 0x190, 0x99, 0x393, 0x29a, 0x596, 0x49f, 0x795, 0x69c, 0x99c, 0x895, 0xb9f, 0xa96, 0xd9a, 0xc93,
0xf99, 0xe90, 0x230, 0x339, 0x33, 0x13a, 0x636, 0x73f, 0x435, 0x53c, 0xa3c, 0xb35, 0x83f, 0x936, 0xe3a, 0xf33,
0xc39, 0xd30, 0x3a0, 0x2a9, 0x1a3, 0xaa, 0x7a6, 0x6af, 0x5a5, 0x4ac, 0xbac, 0xaa5, 0x9af, 0x8a6, 0xfaa, 0xea3,
0xda9, 0xca0, 0x460, 0x569, 0x663, 0x76a, 0x66, 0x16f, 0x265, 0x36c, 0xc6c, 0xd65, 0xe6f, 0xf66, 0x86a, 0x963,
0xa69, 0xb60, 0x5f0, 0x4f9, 0x7f3, 0x6fa, 0x1f6, 0xff, 0x3f5, 0x2fc, 0xdfc, 0xcf5, 0xfff, 0xef6, 0x9fa, 0x8f3,
0xbf9, 0xaf0, 0x650, 0x759, 0x453, 0x55a, 0x256, 0x35f, 0x55, 0x15c, 0xe5c, 0xf55, 0xc5f, 0xd56, 0xa5a, 0xb53,
0x859, 0x950, 0x7c0, 0x6c9, 0x5c3, 0x4ca, 0x3c6, 0x2cf, 0x1c5, 0xcc, 0xfcc, 0xec5, 0xdcf, 0xcc6, 0xbca, 0xac3,
0x9c9, 0x8c0, 0x8c0, 0x9c9, 0xac3, 0xbca, 0xcc6, 0xdcf, 0xec5, 0xfcc, 0xcc, 0x1c5, 0x2cf, 0x3c6, 0x4ca, 0x5c3,
0x6c9, 0x7c0, 0x950, 0x859, 0xb53, 0xa5a, 0xd56, 0xc5f, 0xf55, 0xe5c, 0x15c, 0x55, 0x35f, 0x256, 0x55a, 0x453,
0x759, 0x650, 0xaf0, 0xbf9, 0x8f3, 0x9fa, 0xef6, 0xfff, 0xcf5, 0xdfc, 0x2fc, 0x3f5, 0xff, 0x1f6, 0x6fa, 0x7f3,
0x4f9, 0x5f0, 0xb60, 0xa69, 0x963, 0x86a, 0xf66, 0xe6f, 0xd65, 0xc6c, 0x36c, 0x265, 0x16f, 0x66, 0x76a, 0x663,
0x569, 0x460, 0xca0, 0xda9, 0xea3, 0xfaa, 0x8a6, 0x9af, 0xaa5, 0xbac, 0x4ac, 0x5a5, 0x6af, 0x7a6, 0xaa, 0x1a3,
0x2a9, 0x3a0, 0xd30, 0xc39, 0xf33, 0xe3a, 0x936, 0x83f, 0xb35, 0xa3c, 0x53c, 0x435, 0x73f, 0x636, 0x13a, 0x33,
0x339, 0x230, 0xe90, 0xf99, 0xc93, 0xd9a, 0xa96, 0xb9f, 0x895, 0x99c, 0x69c, 0x795, 0x49f, 0x596, 0x29a, 0x393,
0x99, 0x190, 0xf00, 0xe09, 0xd03, 0xc0a, 0xb06, 0xa0f, 0x905, 0x80c, 0x70c, 0x605, 0x50f, 0x406, 0x30a, 0x203,
0x109, 0x0};
// triangle table maps same cube vertex index to a list of up to 5 triangles
// which are built from the interpolated edge vertices
#define X 255
int triTable[256][16] = {{X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X},
{0, 8, 3, X, X, X, X, X, X, X, X, X, X, X, X, X}, {0, 1, 9, X, X, X, X, X, X, X, X, X, X, X, X, X},
{1, 8, 3, 9, 8, 1, X, X, X, X, X, X, X, X, X, X}, {1, 2, 10, X, X, X, X, X, X, X, X, X, X, X, X, X},
{0, 8, 3, 1, 2, 10, X, X, X, X, X, X, X, X, X, X}, {9, 2, 10, 0, 2, 9, X, X, X, X, X, X, X, X, X, X},
{2, 8, 3, 2, 10, 8, 10, 9, 8, X, X, X, X, X, X, X}, {3, 11, 2, X, X, X, X, X, X, X, X, X, X, X, X, X},
{0, 11, 2, 8, 11, 0, X, X, X, X, X, X, X, X, X, X}, {1, 9, 0, 2, 3, 11, X, X, X, X, X, X, X, X, X, X},
{1, 11, 2, 1, 9, 11, 9, 8, 11, X, X, X, X, X, X, X}, {3, 10, 1, 11, 10, 3, X, X, X, X, X, X, X, X, X, X},
{0, 10, 1, 0, 8, 10, 8, 11, 10, X, X, X, X, X, X, X}, {3, 9, 0, 3, 11, 9, 11, 10, 9, X, X, X, X, X, X, X},
{9, 8, 10, 10, 8, 11, X, X, X, X, X, X, X, X, X, X}, {4, 7, 8, X, X, X, X, X, X, X, X, X, X, X, X, X},
{4, 3, 0, 7, 3, 4, X, X, X, X, X, X, X, X, X, X}, {0, 1, 9, 8, 4, 7, X, X, X, X, X, X, X, X, X, X},
{4, 1, 9, 4, 7, 1, 7, 3, 1, X, X, X, X, X, X, X}, {1, 2, 10, 8, 4, 7, X, X, X, X, X, X, X, X, X, X},
{3, 4, 7, 3, 0, 4, 1, 2, 10, X, X, X, X, X, X, X}, {9, 2, 10, 9, 0, 2, 8, 4, 7, X, X, X, X, X, X, X},
{2, 10, 9, 2, 9, 7, 2, 7, 3, 7, 9, 4, X, X, X, X}, {8, 4, 7, 3, 11, 2, X, X, X, X, X, X, X, X, X, X},
{11, 4, 7, 11, 2, 4, 2, 0, 4, X, X, X, X, X, X, X}, {9, 0, 1, 8, 4, 7, 2, 3, 11, X, X, X, X, X, X, X},
{4, 7, 11, 9, 4, 11, 9, 11, 2, 9, 2, 1, X, X, X, X}, {3, 10, 1, 3, 11, 10, 7, 8, 4, X, X, X, X, X, X, X},
{1, 11, 10, 1, 4, 11, 1, 0, 4, 7, 11, 4, X, X, X, X}, {4, 7, 8, 9, 0, 11, 9, 11, 10, 11, 0, 3, X, X, X, X},
{4, 7, 11, 4, 11, 9, 9, 11, 10, X, X, X, X, X, X, X}, {9, 5, 4, X, X, X, X, X, X, X, X, X, X, X, X, X},
{9, 5, 4, 0, 8, 3, X, X, X, X, X, X, X, X, X, X}, {0, 5, 4, 1, 5, 0, X, X, X, X, X, X, X, X, X, X},
{8, 5, 4, 8, 3, 5, 3, 1, 5, X, X, X, X, X, X, X}, {1, 2, 10, 9, 5, 4, X, X, X, X, X, X, X, X, X, X},
{3, 0, 8, 1, 2, 10, 4, 9, 5, X, X, X, X, X, X, X}, {5, 2, 10, 5, 4, 2, 4, 0, 2, X, X, X, X, X, X, X},
{2, 10, 5, 3, 2, 5, 3, 5, 4, 3, 4, 8, X, X, X, X}, {9, 5, 4, 2, 3, 11, X, X, X, X, X, X, X, X, X, X},
{0, 11, 2, 0, 8, 11, 4, 9, 5, X, X, X, X, X, X, X}, {0, 5, 4, 0, 1, 5, 2, 3, 11, X, X, X, X, X, X, X},
{2, 1, 5, 2, 5, 8, 2, 8, 11, 4, 8, 5, X, X, X, X}, {10, 3, 11, 10, 1, 3, 9, 5, 4, X, X, X, X, X, X, X},
{4, 9, 5, 0, 8, 1, 8, 10, 1, 8, 11, 10, X, X, X, X}, {5, 4, 0, 5, 0, 11, 5, 11, 10, 11, 0, 3, X, X, X, X},
{5, 4, 8, 5, 8, 10, 10, 8, 11, X, X, X, X, X, X, X}, {9, 7, 8, 5, 7, 9, X, X, X, X, X, X, X, X, X, X},
{9, 3, 0, 9, 5, 3, 5, 7, 3, X, X, X, X, X, X, X}, {0, 7, 8, 0, 1, 7, 1, 5, 7, X, X, X, X, X, X, X},
{1, 5, 3, 3, 5, 7, X, X, X, X, X, X, X, X, X, X}, {9, 7, 8, 9, 5, 7, 10, 1, 2, X, X, X, X, X, X, X},
{10, 1, 2, 9, 5, 0, 5, 3, 0, 5, 7, 3, X, X, X, X}, {8, 0, 2, 8, 2, 5, 8, 5, 7, 10, 5, 2, X, X, X, X},
{2, 10, 5, 2, 5, 3, 3, 5, 7, X, X, X, X, X, X, X}, {7, 9, 5, 7, 8, 9, 3, 11, 2, X, X, X, X, X, X, X},
{9, 5, 7, 9, 7, 2, 9, 2, 0, 2, 7, 11, X, X, X, X}, {2, 3, 11, 0, 1, 8, 1, 7, 8, 1, 5, 7, X, X, X, X},
{11, 2, 1, 11, 1, 7, 7, 1, 5, X, X, X, X, X, X, X}, {9, 5, 8, 8, 5, 7, 10, 1, 3, 10, 3, 11, X, X, X, X},
{5, 7, 0, 5, 0, 9, 7, 11, 0, 1, 0, 10, 11, 10, 0, X}, {11, 10, 0, 11, 0, 3, 10, 5, 0, 8, 0, 7, 5, 7, 0, X},
{11, 10, 5, 7, 11, 5, X, X, X, X, X, X, X, X, X, X}, {10, 6, 5, X, X, X, X, X, X, X, X, X, X, X, X, X},
{0, 8, 3, 5, 10, 6, X, X, X, X, X, X, X, X, X, X}, {9, 0, 1, 5, 10, 6, X, X, X, X, X, X, X, X, X, X},
{1, 8, 3, 1, 9, 8, 5, 10, 6, X, X, X, X, X, X, X}, {1, 6, 5, 2, 6, 1, X, X, X, X, X, X, X, X, X, X},
{1, 6, 5, 1, 2, 6, 3, 0, 8, X, X, X, X, X, X, X}, {9, 6, 5, 9, 0, 6, 0, 2, 6, X, X, X, X, X, X, X},
{5, 9, 8, 5, 8, 2, 5, 2, 6, 3, 2, 8, X, X, X, X}, {2, 3, 11, 10, 6, 5, X, X, X, X, X, X, X, X, X, X},
{11, 0, 8, 11, 2, 0, 10, 6, 5, X, X, X, X, X, X, X}, {0, 1, 9, 2, 3, 11, 5, 10, 6, X, X, X, X, X, X, X},
{5, 10, 6, 1, 9, 2, 9, 11, 2, 9, 8, 11, X, X, X, X}, {6, 3, 11, 6, 5, 3, 5, 1, 3, X, X, X, X, X, X, X},
{0, 8, 11, 0, 11, 5, 0, 5, 1, 5, 11, 6, X, X, X, X}, {3, 11, 6, 0, 3, 6, 0, 6, 5, 0, 5, 9, X, X, X, X},
{6, 5, 9, 6, 9, 11, 11, 9, 8, X, X, X, X, X, X, X}, {5, 10, 6, 4, 7, 8, X, X, X, X, X, X, X, X, X, X},
{4, 3, 0, 4, 7, 3, 6, 5, 10, X, X, X, X, X, X, X}, {1, 9, 0, 5, 10, 6, 8, 4, 7, X, X, X, X, X, X, X},
{10, 6, 5, 1, 9, 7, 1, 7, 3, 7, 9, 4, X, X, X, X}, {6, 1, 2, 6, 5, 1, 4, 7, 8, X, X, X, X, X, X, X},
{1, 2, 5, 5, 2, 6, 3, 0, 4, 3, 4, 7, X, X, X, X}, {8, 4, 7, 9, 0, 5, 0, 6, 5, 0, 2, 6, X, X, X, X},
{7, 3, 9, 7, 9, 4, 3, 2, 9, 5, 9, 6, 2, 6, 9, X}, {3, 11, 2, 7, 8, 4, 10, 6, 5, X, X, X, X, X, X, X},
{5, 10, 6, 4, 7, 2, 4, 2, 0, 2, 7, 11, X, X, X, X}, {0, 1, 9, 4, 7, 8, 2, 3, 11, 5, 10, 6, X, X, X, X},
{9, 2, 1, 9, 11, 2, 9, 4, 11, 7, 11, 4, 5, 10, 6, X}, {8, 4, 7, 3, 11, 5, 3, 5, 1, 5, 11, 6, X, X, X, X},
{5, 1, 11, 5, 11, 6, 1, 0, 11, 7, 11, 4, 0, 4, 11, X}, {0, 5, 9, 0, 6, 5, 0, 3, 6, 11, 6, 3, 8, 4, 7, X},
{6, 5, 9, 6, 9, 11, 4, 7, 9, 7, 11, 9, X, X, X, X}, {10, 4, 9, 6, 4, 10, X, X, X, X, X, X, X, X, X, X},
{4, 10, 6, 4, 9, 10, 0, 8, 3, X, X, X, X, X, X, X}, {10, 0, 1, 10, 6, 0, 6, 4, 0, X, X, X, X, X, X, X},
{8, 3, 1, 8, 1, 6, 8, 6, 4, 6, 1, 10, X, X, X, X}, {1, 4, 9, 1, 2, 4, 2, 6, 4, X, X, X, X, X, X, X},
{3, 0, 8, 1, 2, 9, 2, 4, 9, 2, 6, 4, X, X, X, X}, {0, 2, 4, 4, 2, 6, X, X, X, X, X, X, X, X, X, X},
{8, 3, 2, 8, 2, 4, 4, 2, 6, X, X, X, X, X, X, X}, {10, 4, 9, 10, 6, 4, 11, 2, 3, X, X, X, X, X, X, X},
{0, 8, 2, 2, 8, 11, 4, 9, 10, 4, 10, 6, X, X, X, X}, {3, 11, 2, 0, 1, 6, 0, 6, 4, 6, 1, 10, X, X, X, X},
{6, 4, 1, 6, 1, 10, 4, 8, 1, 2, 1, 11, 8, 11, 1, X}, {9, 6, 4, 9, 3, 6, 9, 1, 3, 11, 6, 3, X, X, X, X},
{8, 11, 1, 8, 1, 0, 11, 6, 1, 9, 1, 4, 6, 4, 1, X}, {3, 11, 6, 3, 6, 0, 0, 6, 4, X, X, X, X, X, X, X},
{6, 4, 8, 11, 6, 8, X, X, X, X, X, X, X, X, X, X}, {7, 10, 6, 7, 8, 10, 8, 9, 10, X, X, X, X, X, X, X},
{0, 7, 3, 0, 10, 7, 0, 9, 10, 6, 7, 10, X, X, X, X}, {10, 6, 7, 1, 10, 7, 1, 7, 8, 1, 8, 0, X, X, X, X},
{10, 6, 7, 10, 7, 1, 1, 7, 3, X, X, X, X, X, X, X}, {1, 2, 6, 1, 6, 8, 1, 8, 9, 8, 6, 7, X, X, X, X},
{2, 6, 9, 2, 9, 1, 6, 7, 9, 0, 9, 3, 7, 3, 9, X}, {7, 8, 0, 7, 0, 6, 6, 0, 2, X, X, X, X, X, X, X},
{7, 3, 2, 6, 7, 2, X, X, X, X, X, X, X, X, X, X}, {2, 3, 11, 10, 6, 8, 10, 8, 9, 8, 6, 7, X, X, X, X},
{2, 0, 7, 2, 7, 11, 0, 9, 7, 6, 7, 10, 9, 10, 7, X}, {1, 8, 0, 1, 7, 8, 1, 10, 7, 6, 7, 10, 2, 3, 11, X},
{11, 2, 1, 11, 1, 7, 10, 6, 1, 6, 7, 1, X, X, X, X}, {8, 9, 6, 8, 6, 7, 9, 1, 6, 11, 6, 3, 1, 3, 6, X},
{0, 9, 1, 11, 6, 7, X, X, X, X, X, X, X, X, X, X}, {7, 8, 0, 7, 0, 6, 3, 11, 0, 11, 6, 0, X, X, X, X},
{7, 11, 6, X, X, X, X, X, X, X, X, X, X, X, X, X}, {7, 6, 11, X, X, X, X, X, X, X, X, X, X, X, X, X},
{3, 0, 8, 11, 7, 6, X, X, X, X, X, X, X, X, X, X}, {0, 1, 9, 11, 7, 6, X, X, X, X, X, X, X, X, X, X},
{8, 1, 9, 8, 3, 1, 11, 7, 6, X, X, X, X, X, X, X}, {10, 1, 2, 6, 11, 7, X, X, X, X, X, X, X, X, X, X},
{1, 2, 10, 3, 0, 8, 6, 11, 7, X, X, X, X, X, X, X}, {2, 9, 0, 2, 10, 9, 6, 11, 7, X, X, X, X, X, X, X},
{6, 11, 7, 2, 10, 3, 10, 8, 3, 10, 9, 8, X, X, X, X}, {7, 2, 3, 6, 2, 7, X, X, X, X, X, X, X, X, X, X},
{7, 0, 8, 7, 6, 0, 6, 2, 0, X, X, X, X, X, X, X}, {2, 7, 6, 2, 3, 7, 0, 1, 9, X, X, X, X, X, X, X},
{1, 6, 2, 1, 8, 6, 1, 9, 8, 8, 7, 6, X, X, X, X}, {10, 7, 6, 10, 1, 7, 1, 3, 7, X, X, X, X, X, X, X},
{10, 7, 6, 1, 7, 10, 1, 8, 7, 1, 0, 8, X, X, X, X}, {0, 3, 7, 0, 7, 10, 0, 10, 9, 6, 10, 7, X, X, X, X},
{7, 6, 10, 7, 10, 8, 8, 10, 9, X, X, X, X, X, X, X}, {6, 8, 4, 11, 8, 6, X, X, X, X, X, X, X, X, X, X},
{3, 6, 11, 3, 0, 6, 0, 4, 6, X, X, X, X, X, X, X}, {8, 6, 11, 8, 4, 6, 9, 0, 1, X, X, X, X, X, X, X},
{9, 4, 6, 9, 6, 3, 9, 3, 1, 11, 3, 6, X, X, X, X}, {6, 8, 4, 6, 11, 8, 2, 10, 1, X, X, X, X, X, X, X},
{1, 2, 10, 3, 0, 11, 0, 6, 11, 0, 4, 6, X, X, X, X}, {4, 11, 8, 4, 6, 11, 0, 2, 9, 2, 10, 9, X, X, X, X},
{10, 9, 3, 10, 3, 2, 9, 4, 3, 11, 3, 6, 4, 6, 3, X}, {8, 2, 3, 8, 4, 2, 4, 6, 2, X, X, X, X, X, X, X},
{0, 4, 2, 4, 6, 2, X, X, X, X, X, X, X, X, X, X}, {1, 9, 0, 2, 3, 4, 2, 4, 6, 4, 3, 8, X, X, X, X},
{1, 9, 4, 1, 4, 2, 2, 4, 6, X, X, X, X, X, X, X}, {8, 1, 3, 8, 6, 1, 8, 4, 6, 6, 10, 1, X, X, X, X},
{10, 1, 0, 10, 0, 6, 6, 0, 4, X, X, X, X, X, X, X}, {4, 6, 3, 4, 3, 8, 6, 10, 3, 0, 3, 9, 10, 9, 3, X},
{10, 9, 4, 6, 10, 4, X, X, X, X, X, X, X, X, X, X}, {4, 9, 5, 7, 6, 11, X, X, X, X, X, X, X, X, X, X},
{0, 8, 3, 4, 9, 5, 11, 7, 6, X, X, X, X, X, X, X}, {5, 0, 1, 5, 4, 0, 7, 6, 11, X, X, X, X, X, X, X},
{11, 7, 6, 8, 3, 4, 3, 5, 4, 3, 1, 5, X, X, X, X}, {9, 5, 4, 10, 1, 2, 7, 6, 11, X, X, X, X, X, X, X},
{6, 11, 7, 1, 2, 10, 0, 8, 3, 4, 9, 5, X, X, X, X}, {7, 6, 11, 5, 4, 10, 4, 2, 10, 4, 0, 2, X, X, X, X},
{3, 4, 8, 3, 5, 4, 3, 2, 5, 10, 5, 2, 11, 7, 6, X}, {7, 2, 3, 7, 6, 2, 5, 4, 9, X, X, X, X, X, X, X},
{9, 5, 4, 0, 8, 6, 0, 6, 2, 6, 8, 7, X, X, X, X}, {3, 6, 2, 3, 7, 6, 1, 5, 0, 5, 4, 0, X, X, X, X},
{6, 2, 8, 6, 8, 7, 2, 1, 8, 4, 8, 5, 1, 5, 8, X}, {9, 5, 4, 10, 1, 6, 1, 7, 6, 1, 3, 7, X, X, X, X},
{1, 6, 10, 1, 7, 6, 1, 0, 7, 8, 7, 0, 9, 5, 4, X}, {4, 0, 10, 4, 10, 5, 0, 3, 10, 6, 10, 7, 3, 7, 10, X},
{7, 6, 10, 7, 10, 8, 5, 4, 10, 4, 8, 10, X, X, X, X}, {6, 9, 5, 6, 11, 9, 11, 8, 9, X, X, X, X, X, X, X},
{3, 6, 11, 0, 6, 3, 0, 5, 6, 0, 9, 5, X, X, X, X}, {0, 11, 8, 0, 5, 11, 0, 1, 5, 5, 6, 11, X, X, X, X},
{6, 11, 3, 6, 3, 5, 5, 3, 1, X, X, X, X, X, X, X}, {1, 2, 10, 9, 5, 11, 9, 11, 8, 11, 5, 6, X, X, X, X},
{0, 11, 3, 0, 6, 11, 0, 9, 6, 5, 6, 9, 1, 2, 10, X}, {11, 8, 5, 11, 5, 6, 8, 0, 5, 10, 5, 2, 0, 2, 5, X},
{6, 11, 3, 6, 3, 5, 2, 10, 3, 10, 5, 3, X, X, X, X}, {5, 8, 9, 5, 2, 8, 5, 6, 2, 3, 8, 2, X, X, X, X},
{9, 5, 6, 9, 6, 0, 0, 6, 2, X, X, X, X, X, X, X}, {1, 5, 8, 1, 8, 0, 5, 6, 8, 3, 8, 2, 6, 2, 8, X},
{1, 5, 6, 2, 1, 6, X, X, X, X, X, X, X, X, X, X}, {1, 3, 6, 1, 6, 10, 3, 8, 6, 5, 6, 9, 8, 9, 6, X},
{10, 1, 0, 10, 0, 6, 9, 5, 0, 5, 6, 0, X, X, X, X}, {0, 3, 8, 5, 6, 10, X, X, X, X, X, X, X, X, X, X},
{10, 5, 6, X, X, X, X, X, X, X, X, X, X, X, X, X}, {11, 5, 10, 7, 5, 11, X, X, X, X, X, X, X, X, X, X},
{11, 5, 10, 11, 7, 5, 8, 3, 0, X, X, X, X, X, X, X}, {5, 11, 7, 5, 10, 11, 1, 9, 0, X, X, X, X, X, X, X},
{10, 7, 5, 10, 11, 7, 9, 8, 1, 8, 3, 1, X, X, X, X}, {11, 1, 2, 11, 7, 1, 7, 5, 1, X, X, X, X, X, X, X},
{0, 8, 3, 1, 2, 7, 1, 7, 5, 7, 2, 11, X, X, X, X}, {9, 7, 5, 9, 2, 7, 9, 0, 2, 2, 11, 7, X, X, X, X},
{7, 5, 2, 7, 2, 11, 5, 9, 2, 3, 2, 8, 9, 8, 2, X}, {2, 5, 10, 2, 3, 5, 3, 7, 5, X, X, X, X, X, X, X},
{8, 2, 0, 8, 5, 2, 8, 7, 5, 10, 2, 5, X, X, X, X}, {9, 0, 1, 5, 10, 3, 5, 3, 7, 3, 10, 2, X, X, X, X},
{9, 8, 2, 9, 2, 1, 8, 7, 2, 10, 2, 5, 7, 5, 2, X}, {1, 3, 5, 3, 7, 5, X, X, X, X, X, X, X, X, X, X},
{0, 8, 7, 0, 7, 1, 1, 7, 5, X, X, X, X, X, X, X}, {9, 0, 3, 9, 3, 5, 5, 3, 7, X, X, X, X, X, X, X},
{9, 8, 7, 5, 9, 7, X, X, X, X, X, X, X, X, X, X}, {5, 8, 4, 5, 10, 8, 10, 11, 8, X, X, X, X, X, X, X},
{5, 0, 4, 5, 11, 0, 5, 10, 11, 11, 3, 0, X, X, X, X}, {0, 1, 9, 8, 4, 10, 8, 10, 11, 10, 4, 5, X, X, X, X},
{10, 11, 4, 10, 4, 5, 11, 3, 4, 9, 4, 1, 3, 1, 4, X}, {2, 5, 1, 2, 8, 5, 2, 11, 8, 4, 5, 8, X, X, X, X},
{0, 4, 11, 0, 11, 3, 4, 5, 11, 2, 11, 1, 5, 1, 11, X}, {0, 2, 5, 0, 5, 9, 2, 11, 5, 4, 5, 8, 11, 8, 5, X},
{9, 4, 5, 2, 11, 3, X, X, X, X, X, X, X, X, X, X}, {2, 5, 10, 3, 5, 2, 3, 4, 5, 3, 8, 4, X, X, X, X},
{5, 10, 2, 5, 2, 4, 4, 2, 0, X, X, X, X, X, X, X}, {3, 10, 2, 3, 5, 10, 3, 8, 5, 4, 5, 8, 0, 1, 9, X},
{5, 10, 2, 5, 2, 4, 1, 9, 2, 9, 4, 2, X, X, X, X}, {8, 4, 5, 8, 5, 3, 3, 5, 1, X, X, X, X, X, X, X},
{0, 4, 5, 1, 0, 5, X, X, X, X, X, X, X, X, X, X}, {8, 4, 5, 8, 5, 3, 9, 0, 5, 0, 3, 5, X, X, X, X},
{9, 4, 5, X, X, X, X, X, X, X, X, X, X, X, X, X}, {4, 11, 7, 4, 9, 11, 9, 10, 11, X, X, X, X, X, X, X},
{0, 8, 3, 4, 9, 7, 9, 11, 7, 9, 10, 11, X, X, X, X}, {1, 10, 11, 1, 11, 4, 1, 4, 0, 7, 4, 11, X, X, X, X},
{3, 1, 4, 3, 4, 8, 1, 10, 4, 7, 4, 11, 10, 11, 4, X}, {4, 11, 7, 9, 11, 4, 9, 2, 11, 9, 1, 2, X, X, X, X},
{9, 7, 4, 9, 11, 7, 9, 1, 11, 2, 11, 1, 0, 8, 3, X}, {11, 7, 4, 11, 4, 2, 2, 4, 0, X, X, X, X, X, X, X},
{11, 7, 4, 11, 4, 2, 8, 3, 4, 3, 2, 4, X, X, X, X}, {2, 9, 10, 2, 7, 9, 2, 3, 7, 7, 4, 9, X, X, X, X},
{9, 10, 7, 9, 7, 4, 10, 2, 7, 8, 7, 0, 2, 0, 7, X}, {3, 7, 10, 3, 10, 2, 7, 4, 10, 1, 10, 0, 4, 0, 10, X},
{1, 10, 2, 8, 7, 4, X, X, X, X, X, X, X, X, X, X}, {4, 9, 1, 4, 1, 7, 7, 1, 3, X, X, X, X, X, X, X},
{4, 9, 1, 4, 1, 7, 0, 8, 1, 8, 7, 1, X, X, X, X}, {4, 0, 3, 7, 4, 3, X, X, X, X, X, X, X, X, X, X},
{4, 8, 7, X, X, X, X, X, X, X, X, X, X, X, X, X}, {9, 10, 8, 10, 11, 8, X, X, X, X, X, X, X, X, X, X},
{3, 0, 9, 3, 9, 11, 11, 9, 10, X, X, X, X, X, X, X}, {0, 1, 10, 0, 10, 8, 8, 10, 11, X, X, X, X, X, X, X},
{3, 1, 10, 11, 3, 10, X, X, X, X, X, X, X, X, X, X}, {1, 2, 11, 1, 11, 9, 9, 11, 8, X, X, X, X, X, X, X},
{3, 0, 9, 3, 9, 11, 1, 2, 9, 2, 11, 9, X, X, X, X}, {0, 2, 11, 8, 0, 11, X, X, X, X, X, X, X, X, X, X},
{3, 2, 11, X, X, X, X, X, X, X, X, X, X, X, X, X}, {2, 3, 8, 2, 8, 10, 10, 8, 9, X, X, X, X, X, X, X},
{9, 10, 2, 0, 9, 2, X, X, X, X, X, X, X, X, X, X}, {2, 3, 8, 2, 8, 10, 0, 1, 8, 1, 10, 8, X, X, X, X},
{1, 10, 2, X, X, X, X, X, X, X, X, X, X, X, X, X}, {1, 3, 8, 9, 1, 8, X, X, X, X, X, X, X, X, X, X},
{0, 9, 1, X, X, X, X, X, X, X, X, X, X, X, X, X}, {0, 3, 8, X, X, X, X, X, X, X, X, X, X, X, X, X},
{X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X}};
#undef X
// number of vertices for each case above
uint numVertsTable[256] = {
0,
3,
3,
6,
3,
6,
6,
9,
3,
6,
6,
9,
6,
9,
9,
6,
3,
6,
6,
9,
6,
9,
9,
12,
6,
9,
9,
12,
9,
12,
12,
9,
3,
6,
6,
9,
6,
9,
9,
12,
6,
9,
9,
12,
9,
12,
12,
9,
6,
9,
9,
6,
9,
12,
12,
9,
9,
12,
12,
9,
12,
15,
15,
6,
3,
6,
6,
9,
6,
9,
9,
12,
6,
9,
9,
12,
9,
12,
12,
9,
6,
9,
9,
12,
9,
12,
12,
15,
9,
12,
12,
15,
12,
15,
15,
12,
6,
9,
9,
12,
9,
12,
6,
9,
9,
12,
12,
15,
12,
15,
9,
6,
9,
12,
12,
9,
12,
15,
9,
6,
12,
15,
15,
12,
15,
6,
12,
3,
3,
6,
6,
9,
6,
9,
9,
12,
6,
9,
9,
12,
9,
12,
12,
9,
6,
9,
9,
12,
9,
12,
12,
15,
9,
6,
12,
9,
12,
9,
15,
6,
6,
9,
9,
12,
9,
12,
12,
15,
9,
12,
12,
15,
12,
15,
15,
12,
9,
12,
12,
9,
12,
15,
15,
12,
12,
9,
15,
6,
15,
12,
6,
3,
6,
9,
9,
12,
9,
12,
12,
15,
9,
12,
12,
15,
6,
9,
9,
6,
9,
12,
12,
15,
12,
15,
15,
6,
12,
9,
15,
12,
9,
6,
12,
3,
9,
12,
12,
15,
12,
15,
9,
12,
12,
15,
15,
6,
9,
12,
6,
3,
6,
9,
9,
6,
9,
12,
6,
3,
9,
6,
12,
3,
6,
3,
3,
0,
};
| bsd-3-clause |
JianpingZeng/xcc | xcc/test/juliet/testcases/CWE134_Uncontrolled_Format_String/s01/CWE134_Uncontrolled_Format_String__char_console_printf_72a.cpp | 5028 | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE134_Uncontrolled_Format_String__char_console_printf_72a.cpp
Label Definition File: CWE134_Uncontrolled_Format_String.label.xml
Template File: sources-sinks-72a.tmpl.cpp
*/
/*
* @description
* CWE: 134 Uncontrolled Format String
* BadSource: console Read input from the console
* GoodSource: Copy a fixed string into data
* Sinks: printf
* GoodSink: printf with "%s" as the first argument and data as the second
* BadSink : printf with only data as an argument
* Flow Variant: 72 Data flow: data passed in a vector from one function to another in different source files
*
* */
#include "std_testcase.h"
#include <vector>
#ifndef _WIN32
#include <wchar.h>
#endif
using namespace std;
namespace CWE134_Uncontrolled_Format_String__char_console_printf_72
{
#ifndef OMITBAD
/* bad function declaration */
void badSink(vector<char *> dataVector);
void bad()
{
char * data;
vector<char *> dataVector;
char dataBuffer[100] = "";
data = dataBuffer;
{
/* Read input from the console */
size_t dataLen = strlen(data);
/* if there is room in data, read into it from the console */
if (100-dataLen > 1)
{
/* POTENTIAL FLAW: Read data from the console */
if (fgets(data+dataLen, (int)(100-dataLen), stdin) != NULL)
{
/* The next few lines remove the carriage return from the string that is
* inserted by fgets() */
dataLen = strlen(data);
if (dataLen > 0 && data[dataLen-1] == '\n')
{
data[dataLen-1] = '\0';
}
}
else
{
printLine("fgets() failed");
/* Restore NUL terminator if fgets fails */
data[dataLen] = '\0';
}
}
}
/* Put data in a vector */
dataVector.insert(dataVector.end(), 1, data);
dataVector.insert(dataVector.end(), 1, data);
dataVector.insert(dataVector.end(), 1, data);
badSink(dataVector);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
void goodG2BSink(vector<char *> dataVector);
static void goodG2B()
{
char * data;
vector<char *> dataVector;
char dataBuffer[100] = "";
data = dataBuffer;
/* FIX: Use a fixed string that does not contain a format specifier */
strcpy(data, "fixedstringtest");
/* Put data in a vector */
dataVector.insert(dataVector.end(), 1, data);
dataVector.insert(dataVector.end(), 1, data);
dataVector.insert(dataVector.end(), 1, data);
goodG2BSink(dataVector);
}
/* goodB2G uses the BadSource with the GoodSink */
void goodB2GSink(vector<char *> dataVector);
static void goodB2G()
{
char * data;
vector<char *> dataVector;
char dataBuffer[100] = "";
data = dataBuffer;
{
/* Read input from the console */
size_t dataLen = strlen(data);
/* if there is room in data, read into it from the console */
if (100-dataLen > 1)
{
/* POTENTIAL FLAW: Read data from the console */
if (fgets(data+dataLen, (int)(100-dataLen), stdin) != NULL)
{
/* The next few lines remove the carriage return from the string that is
* inserted by fgets() */
dataLen = strlen(data);
if (dataLen > 0 && data[dataLen-1] == '\n')
{
data[dataLen-1] = '\0';
}
}
else
{
printLine("fgets() failed");
/* Restore NUL terminator if fgets fails */
data[dataLen] = '\0';
}
}
}
dataVector.insert(dataVector.end(), 1, data);
dataVector.insert(dataVector.end(), 1, data);
dataVector.insert(dataVector.end(), 1, data);
goodB2GSink(dataVector);
}
void good()
{
goodG2B();
goodB2G();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE134_Uncontrolled_Format_String__char_console_printf_72; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| bsd-3-clause |
tweag/network-transport-zeromq | tests/TestZMQ.hs | 1973 | -- |
-- Copyright: (C) 2014-2015 EURL Tweag
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Control.Applicative ((<$>))
import Network.Transport
import Network.Transport.ZMQ
import Network.Transport.Tests
import Network.Transport.Tests.Auxiliary (runTests)
main :: IO ()
main = testTransport' (Right <$> createTransport defaultZMQParameters "127.0.0.1")
testTransport' :: IO (Either String Transport) -> IO ()
testTransport' newTransport = do
Right transport <- newTransport
runTests
[ ("PingPong", testPingPong transport numPings)
, ("EndPoints", testEndPoints transport numPings)
, ("Connections", testConnections transport numPings)
, ("CloseOneConnection", testCloseOneConnection transport numPings)
, ("CloseOneDirection", testCloseOneDirection transport numPings)
, ("CloseReopen", testCloseReopen transport numPings)
, ("ParallelConnects", testParallelConnects transport 10)
, ("SendAfterClose", testSendAfterClose transport 100)
, ("Crossing", testCrossing transport 10)
, ("CloseTwice", testCloseTwice transport 100)
, ("ConnectToSelf", testConnectToSelf transport numPings)
, ("ConnectToSelfTwice", testConnectToSelfTwice transport numPings)
, ("CloseSelf", testCloseSelf newTransport)
, ("CloseEndPoint", testCloseEndPoint transport numPings)
, ("CloseTransport", testCloseTransport newTransport)
, ("ExceptionOnReceive", testExceptionOnReceive newTransport)
, ("SendException", testSendException newTransport)
, ("Kill", testKill newTransport 80)
-- testKill test have a timeconstraint so n-t-zmq
-- fails to work with required speed, we need to
-- reduce a number of tests here
]
where
numPings = 500 :: Int
| bsd-3-clause |
xianyi/OpenBLAS | lapack-netlib/SRC/slaed8.f | 15954 | *> \brief \b SLAED8 used by sstedc. Merges eigenvalues and deflates secular equation. Used when the original matrix is dense.
*
* =========== DOCUMENTATION ===========
*
* Online html documentation available at
* http://www.netlib.org/lapack/explore-html/
*
*> \htmlonly
*> Download SLAED8 + dependencies
*> <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/slaed8.f">
*> [TGZ]</a>
*> <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/slaed8.f">
*> [ZIP]</a>
*> <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/slaed8.f">
*> [TXT]</a>
*> \endhtmlonly
*
* Definition:
* ===========
*
* SUBROUTINE SLAED8( ICOMPQ, K, N, QSIZ, D, Q, LDQ, INDXQ, RHO,
* CUTPNT, Z, DLAMDA, Q2, LDQ2, W, PERM, GIVPTR,
* GIVCOL, GIVNUM, INDXP, INDX, INFO )
*
* .. Scalar Arguments ..
* INTEGER CUTPNT, GIVPTR, ICOMPQ, INFO, K, LDQ, LDQ2, N,
* $ QSIZ
* REAL RHO
* ..
* .. Array Arguments ..
* INTEGER GIVCOL( 2, * ), INDX( * ), INDXP( * ),
* $ INDXQ( * ), PERM( * )
* REAL D( * ), DLAMDA( * ), GIVNUM( 2, * ),
* $ Q( LDQ, * ), Q2( LDQ2, * ), W( * ), Z( * )
* ..
*
*
*> \par Purpose:
* =============
*>
*> \verbatim
*>
*> SLAED8 merges the two sets of eigenvalues together into a single
*> sorted set. Then it tries to deflate the size of the problem.
*> There are two ways in which deflation can occur: when two or more
*> eigenvalues are close together or if there is a tiny element in the
*> Z vector. For each such occurrence the order of the related secular
*> equation problem is reduced by one.
*> \endverbatim
*
* Arguments:
* ==========
*
*> \param[in] ICOMPQ
*> \verbatim
*> ICOMPQ is INTEGER
*> = 0: Compute eigenvalues only.
*> = 1: Compute eigenvectors of original dense symmetric matrix
*> also. On entry, Q contains the orthogonal matrix used
*> to reduce the original matrix to tridiagonal form.
*> \endverbatim
*>
*> \param[out] K
*> \verbatim
*> K is INTEGER
*> The number of non-deflated eigenvalues, and the order of the
*> related secular equation.
*> \endverbatim
*>
*> \param[in] N
*> \verbatim
*> N is INTEGER
*> The dimension of the symmetric tridiagonal matrix. N >= 0.
*> \endverbatim
*>
*> \param[in] QSIZ
*> \verbatim
*> QSIZ is INTEGER
*> The dimension of the orthogonal matrix used to reduce
*> the full matrix to tridiagonal form. QSIZ >= N if ICOMPQ = 1.
*> \endverbatim
*>
*> \param[in,out] D
*> \verbatim
*> D is REAL array, dimension (N)
*> On entry, the eigenvalues of the two submatrices to be
*> combined. On exit, the trailing (N-K) updated eigenvalues
*> (those which were deflated) sorted into increasing order.
*> \endverbatim
*>
*> \param[in,out] Q
*> \verbatim
*> Q is REAL array, dimension (LDQ,N)
*> If ICOMPQ = 0, Q is not referenced. Otherwise,
*> on entry, Q contains the eigenvectors of the partially solved
*> system which has been previously updated in matrix
*> multiplies with other partially solved eigensystems.
*> On exit, Q contains the trailing (N-K) updated eigenvectors
*> (those which were deflated) in its last N-K columns.
*> \endverbatim
*>
*> \param[in] LDQ
*> \verbatim
*> LDQ is INTEGER
*> The leading dimension of the array Q. LDQ >= max(1,N).
*> \endverbatim
*>
*> \param[in] INDXQ
*> \verbatim
*> INDXQ is INTEGER array, dimension (N)
*> The permutation which separately sorts the two sub-problems
*> in D into ascending order. Note that elements in the second
*> half of this permutation must first have CUTPNT added to
*> their values in order to be accurate.
*> \endverbatim
*>
*> \param[in,out] RHO
*> \verbatim
*> RHO is REAL
*> On entry, the off-diagonal element associated with the rank-1
*> cut which originally split the two submatrices which are now
*> being recombined.
*> On exit, RHO has been modified to the value required by
*> SLAED3.
*> \endverbatim
*>
*> \param[in] CUTPNT
*> \verbatim
*> CUTPNT is INTEGER
*> The location of the last eigenvalue in the leading
*> sub-matrix. min(1,N) <= CUTPNT <= N.
*> \endverbatim
*>
*> \param[in] Z
*> \verbatim
*> Z is REAL array, dimension (N)
*> On entry, Z contains the updating vector (the last row of
*> the first sub-eigenvector matrix and the first row of the
*> second sub-eigenvector matrix).
*> On exit, the contents of Z are destroyed by the updating
*> process.
*> \endverbatim
*>
*> \param[out] DLAMDA
*> \verbatim
*> DLAMDA is REAL array, dimension (N)
*> A copy of the first K eigenvalues which will be used by
*> SLAED3 to form the secular equation.
*> \endverbatim
*>
*> \param[out] Q2
*> \verbatim
*> Q2 is REAL array, dimension (LDQ2,N)
*> If ICOMPQ = 0, Q2 is not referenced. Otherwise,
*> a copy of the first K eigenvectors which will be used by
*> SLAED7 in a matrix multiply (SGEMM) to update the new
*> eigenvectors.
*> \endverbatim
*>
*> \param[in] LDQ2
*> \verbatim
*> LDQ2 is INTEGER
*> The leading dimension of the array Q2. LDQ2 >= max(1,N).
*> \endverbatim
*>
*> \param[out] W
*> \verbatim
*> W is REAL array, dimension (N)
*> The first k values of the final deflation-altered z-vector and
*> will be passed to SLAED3.
*> \endverbatim
*>
*> \param[out] PERM
*> \verbatim
*> PERM is INTEGER array, dimension (N)
*> The permutations (from deflation and sorting) to be applied
*> to each eigenblock.
*> \endverbatim
*>
*> \param[out] GIVPTR
*> \verbatim
*> GIVPTR is INTEGER
*> The number of Givens rotations which took place in this
*> subproblem.
*> \endverbatim
*>
*> \param[out] GIVCOL
*> \verbatim
*> GIVCOL is INTEGER array, dimension (2, N)
*> Each pair of numbers indicates a pair of columns to take place
*> in a Givens rotation.
*> \endverbatim
*>
*> \param[out] GIVNUM
*> \verbatim
*> GIVNUM is REAL array, dimension (2, N)
*> Each number indicates the S value to be used in the
*> corresponding Givens rotation.
*> \endverbatim
*>
*> \param[out] INDXP
*> \verbatim
*> INDXP is INTEGER array, dimension (N)
*> The permutation used to place deflated values of D at the end
*> of the array. INDXP(1:K) points to the nondeflated D-values
*> and INDXP(K+1:N) points to the deflated eigenvalues.
*> \endverbatim
*>
*> \param[out] INDX
*> \verbatim
*> INDX is INTEGER array, dimension (N)
*> The permutation used to sort the contents of D into ascending
*> order.
*> \endverbatim
*>
*> \param[out] INFO
*> \verbatim
*> INFO is INTEGER
*> = 0: successful exit.
*> < 0: if INFO = -i, the i-th argument had an illegal value.
*> \endverbatim
*
* Authors:
* ========
*
*> \author Univ. of Tennessee
*> \author Univ. of California Berkeley
*> \author Univ. of Colorado Denver
*> \author NAG Ltd.
*
*> \date December 2016
*
*> \ingroup auxOTHERcomputational
*
*> \par Contributors:
* ==================
*>
*> Jeff Rutter, Computer Science Division, University of California
*> at Berkeley, USA
*
* =====================================================================
SUBROUTINE SLAED8( ICOMPQ, K, N, QSIZ, D, Q, LDQ, INDXQ, RHO,
$ CUTPNT, Z, DLAMDA, Q2, LDQ2, W, PERM, GIVPTR,
$ GIVCOL, GIVNUM, INDXP, INDX, INFO )
*
* -- LAPACK computational routine (version 3.7.0) --
* -- LAPACK is a software package provided by Univ. of Tennessee, --
* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..--
* December 2016
*
* .. Scalar Arguments ..
INTEGER CUTPNT, GIVPTR, ICOMPQ, INFO, K, LDQ, LDQ2, N,
$ QSIZ
REAL RHO
* ..
* .. Array Arguments ..
INTEGER GIVCOL( 2, * ), INDX( * ), INDXP( * ),
$ INDXQ( * ), PERM( * )
REAL D( * ), DLAMDA( * ), GIVNUM( 2, * ),
$ Q( LDQ, * ), Q2( LDQ2, * ), W( * ), Z( * )
* ..
*
* =====================================================================
*
* .. Parameters ..
REAL MONE, ZERO, ONE, TWO, EIGHT
PARAMETER ( MONE = -1.0E0, ZERO = 0.0E0, ONE = 1.0E0,
$ TWO = 2.0E0, EIGHT = 8.0E0 )
* ..
* .. Local Scalars ..
*
INTEGER I, IMAX, J, JLAM, JMAX, JP, K2, N1, N1P1, N2
REAL C, EPS, S, T, TAU, TOL
* ..
* .. External Functions ..
INTEGER ISAMAX
REAL SLAMCH, SLAPY2
EXTERNAL ISAMAX, SLAMCH, SLAPY2
* ..
* .. External Subroutines ..
EXTERNAL SCOPY, SLACPY, SLAMRG, SROT, SSCAL, XERBLA
* ..
* .. Intrinsic Functions ..
INTRINSIC ABS, MAX, MIN, SQRT
* ..
* .. Executable Statements ..
*
* Test the input parameters.
*
INFO = 0
*
IF( ICOMPQ.LT.0 .OR. ICOMPQ.GT.1 ) THEN
INFO = -1
ELSE IF( N.LT.0 ) THEN
INFO = -3
ELSE IF( ICOMPQ.EQ.1 .AND. QSIZ.LT.N ) THEN
INFO = -4
ELSE IF( LDQ.LT.MAX( 1, N ) ) THEN
INFO = -7
ELSE IF( CUTPNT.LT.MIN( 1, N ) .OR. CUTPNT.GT.N ) THEN
INFO = -10
ELSE IF( LDQ2.LT.MAX( 1, N ) ) THEN
INFO = -14
END IF
IF( INFO.NE.0 ) THEN
CALL XERBLA( 'SLAED8', -INFO )
RETURN
END IF
*
* Need to initialize GIVPTR to O here in case of quick exit
* to prevent an unspecified code behavior (usually sigfault)
* when IWORK array on entry to *stedc is not zeroed
* (or at least some IWORK entries which used in *laed7 for GIVPTR).
*
GIVPTR = 0
*
* Quick return if possible
*
IF( N.EQ.0 )
$ RETURN
*
N1 = CUTPNT
N2 = N - N1
N1P1 = N1 + 1
*
IF( RHO.LT.ZERO ) THEN
CALL SSCAL( N2, MONE, Z( N1P1 ), 1 )
END IF
*
* Normalize z so that norm(z) = 1
*
T = ONE / SQRT( TWO )
DO 10 J = 1, N
INDX( J ) = J
10 CONTINUE
CALL SSCAL( N, T, Z, 1 )
RHO = ABS( TWO*RHO )
*
* Sort the eigenvalues into increasing order
*
DO 20 I = CUTPNT + 1, N
INDXQ( I ) = INDXQ( I ) + CUTPNT
20 CONTINUE
DO 30 I = 1, N
DLAMDA( I ) = D( INDXQ( I ) )
W( I ) = Z( INDXQ( I ) )
30 CONTINUE
I = 1
J = CUTPNT + 1
CALL SLAMRG( N1, N2, DLAMDA, 1, 1, INDX )
DO 40 I = 1, N
D( I ) = DLAMDA( INDX( I ) )
Z( I ) = W( INDX( I ) )
40 CONTINUE
*
* Calculate the allowable deflation tolerance
*
IMAX = ISAMAX( N, Z, 1 )
JMAX = ISAMAX( N, D, 1 )
EPS = SLAMCH( 'Epsilon' )
TOL = EIGHT*EPS*ABS( D( JMAX ) )
*
* If the rank-1 modifier is small enough, no more needs to be done
* except to reorganize Q so that its columns correspond with the
* elements in D.
*
IF( RHO*ABS( Z( IMAX ) ).LE.TOL ) THEN
K = 0
IF( ICOMPQ.EQ.0 ) THEN
DO 50 J = 1, N
PERM( J ) = INDXQ( INDX( J ) )
50 CONTINUE
ELSE
DO 60 J = 1, N
PERM( J ) = INDXQ( INDX( J ) )
CALL SCOPY( QSIZ, Q( 1, PERM( J ) ), 1, Q2( 1, J ), 1 )
60 CONTINUE
CALL SLACPY( 'A', QSIZ, N, Q2( 1, 1 ), LDQ2, Q( 1, 1 ),
$ LDQ )
END IF
RETURN
END IF
*
* If there are multiple eigenvalues then the problem deflates. Here
* the number of equal eigenvalues are found. As each equal
* eigenvalue is found, an elementary reflector is computed to rotate
* the corresponding eigensubspace so that the corresponding
* components of Z are zero in this new basis.
*
K = 0
K2 = N + 1
DO 70 J = 1, N
IF( RHO*ABS( Z( J ) ).LE.TOL ) THEN
*
* Deflate due to small z component.
*
K2 = K2 - 1
INDXP( K2 ) = J
IF( J.EQ.N )
$ GO TO 110
ELSE
JLAM = J
GO TO 80
END IF
70 CONTINUE
80 CONTINUE
J = J + 1
IF( J.GT.N )
$ GO TO 100
IF( RHO*ABS( Z( J ) ).LE.TOL ) THEN
*
* Deflate due to small z component.
*
K2 = K2 - 1
INDXP( K2 ) = J
ELSE
*
* Check if eigenvalues are close enough to allow deflation.
*
S = Z( JLAM )
C = Z( J )
*
* Find sqrt(a**2+b**2) without overflow or
* destructive underflow.
*
TAU = SLAPY2( C, S )
T = D( J ) - D( JLAM )
C = C / TAU
S = -S / TAU
IF( ABS( T*C*S ).LE.TOL ) THEN
*
* Deflation is possible.
*
Z( J ) = TAU
Z( JLAM ) = ZERO
*
* Record the appropriate Givens rotation
*
GIVPTR = GIVPTR + 1
GIVCOL( 1, GIVPTR ) = INDXQ( INDX( JLAM ) )
GIVCOL( 2, GIVPTR ) = INDXQ( INDX( J ) )
GIVNUM( 1, GIVPTR ) = C
GIVNUM( 2, GIVPTR ) = S
IF( ICOMPQ.EQ.1 ) THEN
CALL SROT( QSIZ, Q( 1, INDXQ( INDX( JLAM ) ) ), 1,
$ Q( 1, INDXQ( INDX( J ) ) ), 1, C, S )
END IF
T = D( JLAM )*C*C + D( J )*S*S
D( J ) = D( JLAM )*S*S + D( J )*C*C
D( JLAM ) = T
K2 = K2 - 1
I = 1
90 CONTINUE
IF( K2+I.LE.N ) THEN
IF( D( JLAM ).LT.D( INDXP( K2+I ) ) ) THEN
INDXP( K2+I-1 ) = INDXP( K2+I )
INDXP( K2+I ) = JLAM
I = I + 1
GO TO 90
ELSE
INDXP( K2+I-1 ) = JLAM
END IF
ELSE
INDXP( K2+I-1 ) = JLAM
END IF
JLAM = J
ELSE
K = K + 1
W( K ) = Z( JLAM )
DLAMDA( K ) = D( JLAM )
INDXP( K ) = JLAM
JLAM = J
END IF
END IF
GO TO 80
100 CONTINUE
*
* Record the last eigenvalue.
*
K = K + 1
W( K ) = Z( JLAM )
DLAMDA( K ) = D( JLAM )
INDXP( K ) = JLAM
*
110 CONTINUE
*
* Sort the eigenvalues and corresponding eigenvectors into DLAMDA
* and Q2 respectively. The eigenvalues/vectors which were not
* deflated go into the first K slots of DLAMDA and Q2 respectively,
* while those which were deflated go into the last N - K slots.
*
IF( ICOMPQ.EQ.0 ) THEN
DO 120 J = 1, N
JP = INDXP( J )
DLAMDA( J ) = D( JP )
PERM( J ) = INDXQ( INDX( JP ) )
120 CONTINUE
ELSE
DO 130 J = 1, N
JP = INDXP( J )
DLAMDA( J ) = D( JP )
PERM( J ) = INDXQ( INDX( JP ) )
CALL SCOPY( QSIZ, Q( 1, PERM( J ) ), 1, Q2( 1, J ), 1 )
130 CONTINUE
END IF
*
* The deflated eigenvalues and their corresponding vectors go back
* into the last N - K slots of D and Q respectively.
*
IF( K.LT.N ) THEN
IF( ICOMPQ.EQ.0 ) THEN
CALL SCOPY( N-K, DLAMDA( K+1 ), 1, D( K+1 ), 1 )
ELSE
CALL SCOPY( N-K, DLAMDA( K+1 ), 1, D( K+1 ), 1 )
CALL SLACPY( 'A', QSIZ, N-K, Q2( 1, K+1 ), LDQ2,
$ Q( 1, K+1 ), LDQ )
END IF
END IF
*
RETURN
*
* End of SLAED8
*
END
| bsd-3-clause |
bartoszrychlicki/MainBrain.pl | payment/code/ChequePayment/ChequePayment.php | 1059 | <?php
/**
* Payment object representing a cheque payment.
*
* @package payment
*/
class ChequePayment extends Payment {
/**
* Process the Cheque payment method
*/
function processPayment($data, $form) {
$this->Status = 'Pending';
$this->Message = '<p class="warningMessage">' . _t('ChequePayment.MESSAGE', 'Payment accepted via Cheque. Please note : products will not be shipped until payment has been received.') . '</p>';
$this->write();
return new Payment_Success();
}
function getPaymentFormFields() {
return new FieldSet(
// retrieve cheque content from the ChequeContent() method on this class
new LiteralField("Chequeblurb", '<div id="Cheque" class="typography">' . $this->ChequeContent() . '</div>'),
new HiddenField("Cheque", "Cheque", 0)
);
}
function getPaymentFormRequirements() {
return null;
}
/**
* Returns the Cheque content from the CheckoutPage
*/
function ChequeContent() {
if(class_exists('CheckoutPage')) {
return DataObject::get_one('CheckoutPage')->ChequeMessage;
}
}
}
| bsd-3-clause |
gmimano/commcaretest | corehq/apps/adm/urls.py | 691 | from django.conf.urls.defaults import *
from corehq.apps.adm.dispatcher import ADMAdminInterfaceDispatcher, ADMSectionDispatcher
from corehq.apps.adm.views import ADMAdminCRUDFormView
adm_admin_interface_urls = patterns('corehq.apps.adm.views',
url(r'^$', 'default_adm_admin', name="default_adm_admin_interface"),
url(r'^form/(?P<form_type>[\w_]+)/(?P<action>[(update)|(new)|(delete)]+)/((?P<item_id>[\w_]+)/)?$',
ADMAdminCRUDFormView.as_view(), name="adm_item_form"),
ADMAdminInterfaceDispatcher.url_pattern(),
)
urlpatterns = patterns('corehq.apps.adm.views',
url(r'^$', 'default_adm_report', name="default_adm_report"),
ADMSectionDispatcher.url_pattern(),
)
| bsd-3-clause |
stlankes/HermitCore | usr/ircce/iRCCE_irecv.c | 20676 | //***************************************************************************************
// Synchronized receive routines.
//***************************************************************************************
//
// Author: Rob F. Van der Wijngaart
// Intel Corporation
// Date: 008/30/2010
//
//***************************************************************************************
//
// Copyright 2010 Intel Corporation
//
// 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.
//
// [2010-10-25] added support for non-blocking send/recv operations
// - iRCCE_isend(), ..._test(), ..._wait(), ..._push()
// - iRCCE_irecv(), ..._test(), ..._wait(), ..._push()
// by Carsten Clauss, Chair for Operating Systems,
// RWTH Aachen University
//
// [2010-11-12] extracted non-blocking code into separate library
// by Carsten Scholtes
//
// [2010-12-09] added cancel functions for non-blocking send/recv requests
// by Carsten Clauss
//
// [2011-02-21] added support for multiple incoming queues
// (one recv queue per remote rank)
//
// [2011-04-19] added wildcard mechanism (iRCCE_ANY_SOURCE) for receiving
// a message from an arbitrary remote rank
// by Simon Pickartz, Chair for Operating Systems,
// RWTH Aachen University
//
// [2011-06-27] merged iRCCE_ANY_SOURCE branch with trunk (iRCCE_ANY_LENGTH)
//
// [2011-08-02] added iRCCE_iprobe() function for probing for incomming messages
//
// [2011-11-03] added non-blocking by synchronous send/recv functions:
// iRCCE_issend() / iRCCE_isrecv()
//
#include "iRCCE_lib.h"
#ifdef __hermit__
#include "rte_memcpy.h"
#define memcpy_scc rte_memcpy
#elif defined COPPERRIDGE || defined SCC
#include "scc_memcpy.h"
#else
#define memcpy_scc memcpy
#endif
#ifdef SINGLEBITFLAGS
#warning iRCCE_ANY_LENGTH: for using this wildcard, SINGLEBITFLAGS must be disabled! (make SINGLEBITFLAGS=0)
#endif
#ifdef RCCE_VERSION
#warning iRCCE_ANY_LENGTH: for using this wildcard, iRCCE must be built against RCCE release V1.0.13!
#endif
static int iRCCE_push_recv_request(iRCCE_RECV_REQUEST *request) {
char padline[RCCE_LINE_SIZE]; // copy buffer, used if message not multiple of line size
int test; // flag for calling iRCCE_test_flag()
if(request->finished) return(iRCCE_SUCCESS);
if(request->sync) return iRCCE_push_srecv_request(request);
if(request->label == 1) goto label1;
if(request->label == 2) goto label2;
if(request->label == 3) goto label3;
#ifdef _iRCCE_ANY_LENGTH_
RCCE_flag_read(*(request->sent), &(request->flag_set_value), RCCE_IAM);
if(request->flag_set_value == 0) {
return(iRCCE_PENDING);
}
request->size = (size_t)request->flag_set_value;
#endif
// receive data in units of available chunk size of MPB
for (; request->wsize < (request->size / request->chunk) * request->chunk; request->wsize += request->chunk) {
request->bufptr = request->privbuf + request->wsize;
request->nbytes = request->chunk;
label1:
iRCCE_test_flag(*(request->sent), request->flag_set_value, &test);
if(!test) {
request->label = 1;
return(iRCCE_PENDING);
}
request->started = 1;
RCCE_flag_write(request->sent, RCCE_FLAG_UNSET, RCCE_IAM);
// copy data from source's MPB space to private memory
iRCCE_get((t_vcharp)request->bufptr, request->combuf, request->nbytes, request->source);
// tell the source I have moved data out of its comm buffer
RCCE_flag_write(request->ready, request->flag_set_value, request->source);
}
request->remainder = request->size % request->chunk;
// if nothing is left over, we are done
if (!request->remainder) {
if(iRCCE_recent_source != request->source) iRCCE_recent_source = request->source;
if(iRCCE_recent_length != request->size) iRCCE_recent_length = request->size;
request->finished = 1;
return(iRCCE_SUCCESS);
}
// receive remainder of data--whole cache lines
request->bufptr = request->privbuf + (request->size / request->chunk) * request->chunk;
request->nbytes = request->remainder - request->remainder % RCCE_LINE_SIZE;
if (request->nbytes) {
label2:
iRCCE_test_flag(*(request->sent), request->flag_set_value, &test);
if(!test) {
request->label = 2;
return(iRCCE_PENDING);
}
request->started = 1;
RCCE_flag_write(request->sent, RCCE_FLAG_UNSET, RCCE_IAM);
// copy data from source's MPB space to private memory
iRCCE_get((t_vcharp)request->bufptr, request->combuf, request->nbytes, request->source);
// tell the source I have moved data out of its comm buffer
RCCE_flag_write(request->ready, request->flag_set_value, request->source);
}
request->remainder = request->size % request->chunk;
request->remainder = request->remainder % RCCE_LINE_SIZE;
if (!request->remainder) {
if(iRCCE_recent_source != request->source) iRCCE_recent_source = request->source;
if(iRCCE_recent_length != request->size) iRCCE_recent_length = request->size;
request->finished = 1;
return(iRCCE_SUCCESS);
}
// remainder is less than cache line. This must be copied into appropriately sized
// intermediate space before exact number of bytes get copied to the final destination
request->bufptr = request->privbuf + (request->size / request->chunk) * request->chunk + request->nbytes;
request->nbytes = RCCE_LINE_SIZE;
label3:
iRCCE_test_flag(*(request->sent), request->flag_set_value, &test);
if(!test) {
request->label = 3;
return(iRCCE_PENDING);
}
request->started = 1;
RCCE_flag_write(request->sent, RCCE_FLAG_UNSET, RCCE_IAM);
// copy data from source's MPB space to private memory
iRCCE_get((t_vcharp)padline, request->combuf, request->nbytes, request->source);
memcpy_scc(request->bufptr,padline,request->remainder);
// tell the source I have moved data out of its comm buffer
RCCE_flag_write(request->ready, request->flag_set_value, request->source);
if(iRCCE_recent_source != request->source) iRCCE_recent_source = request->source;
if(iRCCE_recent_length != request->size) iRCCE_recent_length = request->size;
request->finished = 1;
return(iRCCE_SUCCESS);
}
static void iRCCE_init_recv_request(
char *privbuf, // source buffer in local private memory (send buffer)
t_vcharp combuf, // intermediate buffer in MPB
size_t chunk, // size of MPB available for this message (bytes)
RCCE_FLAG *ready, // flag indicating whether receiver is ready
RCCE_FLAG *sent, // flag indicating whether message has been sent by source
size_t size, // size of message (bytes)
int source, // UE that will send the message
int sync, // flag indicating whether recv is synchronous or not
iRCCE_RECV_REQUEST *request
) {
request->privbuf = privbuf;
request->combuf = combuf;
request->chunk = chunk;
request->ready = ready;
request->sent = sent;
request->size = size;
request->source = source;
request->sync = sync;
request->subchunk1 = chunk / 2;
request->subchunk1 = ( (chunk / 2) / RCCE_LINE_SIZE ) * RCCE_LINE_SIZE;
request->subchunk2 = chunk - request->subchunk1;
request->wsize = 0;
request->remainder = 0;
request->nbytes = 0;
request->bufptr = NULL;
request->label = 0;
request->finished = 0;
request->started = 0;
request->next = NULL;
#ifndef _iRCCE_ANY_LENGTH_
request->flag_set_value = RCCE_FLAG_SET;
#else
request->flag_set_value = (RCCE_FLAG_STATUS)size;
#endif
return;
}
static int iRCCE_irecv_search_source() {
int i, j;
int res = iRCCE_ANY_SOURCE;
for( i=0; i<RCCE_NP*3; ++i ){
j =i%RCCE_NP;
if ( j == RCCE_IAM )
continue;
// only take source if recv-queue is empty
if(!iRCCE_irecv_queue[j]) {
int test;
iRCCE_test_flag(RCCE_sent_flag[j], 0, &test);
if(!test) {
res = j;
break;
}
}
}
return res;
}
//--------------------------------------------------------------------------------------
// FUNCTION: iRCCE_irecv
//--------------------------------------------------------------------------------------
// non-blocking recv function; returns an handle of type iRCCE_RECV_REQUEST
//--------------------------------------------------------------------------------------
static iRCCE_RECV_REQUEST blocking_irecv_request;
#ifdef _OPENMP
#pragma omp threadprivate (blocking_irecv_request)
#endif
inline static int iRCCE_irecv_generic(char *privbuf, ssize_t size, int source, iRCCE_RECV_REQUEST *request, int sync) {
if(request == NULL){
request = &blocking_irecv_request;
// find source (blocking)
if( source == iRCCE_ANY_SOURCE ){
int i;
for( i=0;;i=(i+1)%RCCE_NP ){
if( (!iRCCE_irecv_queue[i]) && (i != RCCE_IAM) ) {
int test;
iRCCE_test_flag(RCCE_sent_flag[i], 0, &test);
if(!test) {
source = i;
break;
}
}
}
}
}
if(size == 0) {
if(sync) {
// just synchronize:
size = 1;
privbuf = (char*)&size;
} else
size = -1;
}
if(size <= 0) {
#ifdef _iRCCE_ANY_LENGTH_
if(size != iRCCE_ANY_LENGTH)
#endif
{
iRCCE_init_recv_request(privbuf, RCCE_buff_ptr, RCCE_chunk,
&RCCE_ready_flag[RCCE_IAM], &RCCE_sent_flag[source],
size, source, sync, request);
request->finished = 1;
return(iRCCE_SUCCESS);
}
}
if( source == iRCCE_ANY_SOURCE ) {
source = iRCCE_irecv_search_source(); // first try to find a source
if( source == iRCCE_ANY_SOURCE ){ // queue request if no source available
iRCCE_init_recv_request(privbuf, RCCE_buff_ptr, RCCE_chunk,
&RCCE_ready_flag[RCCE_IAM], NULL,
size, iRCCE_ANY_SOURCE, sync, request);
// put anysource-request in irecv_any_source_queue
if( iRCCE_irecv_any_source_queue == NULL ){
iRCCE_irecv_any_source_queue = request;
}
else {
if( iRCCE_irecv_any_source_queue->next == NULL ) {
iRCCE_irecv_any_source_queue->next = request;
}
else {
iRCCE_RECV_REQUEST* run = iRCCE_irecv_any_source_queue;
while( run->next != NULL ) run = run->next;
run->next = request;
}
}
return iRCCE_RESERVED;
}
}
if (source<0 || source >= RCCE_NP)
return(RCCE_error_return(RCCE_debug_comm,RCCE_ERROR_ID));
else {
iRCCE_init_recv_request(privbuf, RCCE_buff_ptr, RCCE_chunk,
&RCCE_ready_flag[RCCE_IAM], &RCCE_sent_flag[source],
size, source, sync, request);
if(iRCCE_irecv_queue[source] == NULL) {
if(iRCCE_push_recv_request(request) == iRCCE_SUCCESS) {
return(iRCCE_SUCCESS);
}
else {
iRCCE_irecv_queue[source] = request;
if(request == &blocking_irecv_request) {
iRCCE_irecv_wait(request);
return(iRCCE_SUCCESS);
}
return(iRCCE_PENDING);
}
}
else {
if(iRCCE_irecv_queue[source]->next == NULL) {
iRCCE_irecv_queue[source]->next = request;
}
else {
iRCCE_RECV_REQUEST *run = iRCCE_irecv_queue[source];
while(run->next != NULL) run = run->next;
run->next = request;
}
if(request == &blocking_irecv_request) {
iRCCE_irecv_wait(request);
return(iRCCE_SUCCESS);
}
return(iRCCE_RESERVED);
}
}
}
int iRCCE_irecv(char *privbuf, ssize_t size, int dest, iRCCE_RECV_REQUEST *request) {
return iRCCE_irecv_generic(privbuf, size, dest, request, 0);
}
int iRCCE_isrecv(char *privbuf, ssize_t size, int dest, iRCCE_RECV_REQUEST *request) {
return iRCCE_irecv_generic(privbuf, size, dest, request, 1);
}
//--------------------------------------------------------------------------------------
// FUNCTION: iRCCE_probe
//--------------------------------------------------------------------------------------
// probe for incomming messages (non-blocking / does not receive)
//--------------------------------------------------------------------------------------
int iRCCE_iprobe(int source, int* test_rank, int* test_flag)
{
// determine source of request if given source = iRCCE_ANY_SOURCE
if( source == iRCCE_ANY_SOURCE ) {
source = iRCCE_irecv_search_source(); // first try to find a source
}
else {
int res;
iRCCE_test_flag(RCCE_sent_flag[source], RCCE_FLAG_SET, &res);
if(!res) source = iRCCE_ANY_SOURCE;
}
if(source != iRCCE_ANY_SOURCE) { // message found:
if (test_rank != NULL) (*test_rank) = source;
if (test_flag != NULL) (*test_flag) = 1;
#ifdef _iRCCE_ANY_LENGTH_
{
ssize_t size = iRCCE_ANY_LENGTH;
RCCE_flag_read(RCCE_sent_flag[source], &size, RCCE_IAM);
if(iRCCE_recent_length != size) iRCCE_recent_length = size;
}
#endif
if(iRCCE_recent_source != source) iRCCE_recent_source = source;
}
else {
if (test_rank != NULL) (*test_rank) = iRCCE_ANY_SOURCE;
if (test_flag != NULL) (*test_flag) = 0;
}
return iRCCE_SUCCESS;
}
//--------------------------------------------------------------------------------------
// FUNCTION: iRCCE_irecv_test
//--------------------------------------------------------------------------------------
// test function for completion of the requestes non-blocking recv operation
// Just provide NULL instead of the testvar if you don't need it
//--------------------------------------------------------------------------------------
int iRCCE_irecv_test(iRCCE_RECV_REQUEST *request, int *test) {
int source;
if(request == NULL) {
if(iRCCE_irecv_push() == iRCCE_SUCCESS) {
if (test) (*test) = 1;
return(iRCCE_SUCCESS);
}
else {
if (test) (*test) = 0;
return(iRCCE_PENDING);
}
}
// does request still have no source?
if( request->source == iRCCE_ANY_SOURCE ) {
request->source = iRCCE_irecv_search_source();
if( request->source == iRCCE_ANY_SOURCE ) {
if (test) (*test) = 0;
return iRCCE_RESERVED;
}
else { // take request out of wait_any_source-list
// find request in queue
if( request == iRCCE_irecv_any_source_queue ) {
iRCCE_irecv_any_source_queue = iRCCE_irecv_any_source_queue->next;
}
else {
iRCCE_RECV_REQUEST* run = iRCCE_irecv_any_source_queue;
while( run->next != request ) run = run->next;
run->next = request->next;
}
request->next = NULL;
request->sent = &RCCE_sent_flag[request->source]; // set senders flag
source = request->source;
// queue request in iRCCE_irecv_queue
if(iRCCE_irecv_queue[source] == NULL) {
if(iRCCE_push_recv_request(request) == iRCCE_SUCCESS) {
if (test) (*test) = 1;
return(iRCCE_SUCCESS);
}
else {
iRCCE_irecv_queue[source] = request;
if(request == &blocking_irecv_request) {
iRCCE_irecv_wait(request);
if (test) (*test) = 1;
return(iRCCE_SUCCESS);
}
if (test) (*test) = 0;
return(iRCCE_PENDING);
}
}
else {
if(iRCCE_irecv_queue[source]->next == NULL) {
iRCCE_irecv_queue[source]->next = request;
}
else {
iRCCE_RECV_REQUEST *run = iRCCE_irecv_queue[source];
while(run->next != NULL) run = run->next;
run->next = request;
}
if(request == &blocking_irecv_request) {
iRCCE_irecv_wait(request);
if (test) (*test) = 1;
return(iRCCE_SUCCESS);
}
if (test) (*test) = 1;
return(iRCCE_RESERVED);
}
}
}
else {
source = request->source;
if(request->finished) {
if (test) (*test) = 1;
return(iRCCE_SUCCESS);
}
if(iRCCE_irecv_queue[source] != request) {
if (test) (*test) = 0;
return(iRCCE_RESERVED);
}
iRCCE_push_recv_request(request);
if(request->finished) {
iRCCE_irecv_queue[source] = request->next;
if (test) (*test) = 1;
return(iRCCE_SUCCESS);
}
if (test) (*test) = 0;
return(iRCCE_PENDING);
}
}
//--------------------------------------------------------------------------------------
// FUNCTION: iRCCE_irecv_push
//--------------------------------------------------------------------------------------
// progress function for pending requests in the irecv queue
//--------------------------------------------------------------------------------------
static int iRCCE_irecv_push_source(int source) {
iRCCE_RECV_REQUEST *request = iRCCE_irecv_queue[source];
if(request == NULL) {
return(iRCCE_SUCCESS);
}
if(request->finished) {
return(iRCCE_SUCCESS);
}
iRCCE_push_recv_request(request);
if(request->finished) {
iRCCE_irecv_queue[source] = request->next;
return(iRCCE_SUCCESS);
}
return(iRCCE_PENDING);
}
int iRCCE_irecv_push(void) {
iRCCE_RECV_REQUEST* help_request;
// first check sourceless requests
if( iRCCE_irecv_any_source_queue != NULL) {
while( iRCCE_irecv_any_source_queue != NULL ) {
iRCCE_irecv_any_source_queue->source = iRCCE_irecv_search_source();
if( iRCCE_irecv_any_source_queue->source == iRCCE_ANY_SOURCE ) {
break;
}
// source found for first request in iRCCE_irecv_any_source_queue
else {
// set senders flag
iRCCE_irecv_any_source_queue->sent = &RCCE_sent_flag[iRCCE_irecv_any_source_queue->source];
// take request out of irecv_any_source_queue
help_request = iRCCE_irecv_any_source_queue;
iRCCE_irecv_any_source_queue = iRCCE_irecv_any_source_queue->next;
help_request->next = NULL;
// put request into irecv_queue
if(iRCCE_irecv_queue[help_request->source] == NULL) {
iRCCE_irecv_queue[help_request->source] = help_request;
}
else {
iRCCE_RECV_REQUEST *run = iRCCE_irecv_queue[help_request->source];
while(run->next != NULL) run = run->next;
run->next = help_request;
}
}
}
}
int i, j;
int retval = iRCCE_SUCCESS;
for(i=0; i<RCCE_NP; i++) {
j = iRCCE_irecv_push_source(i);
if(j != iRCCE_SUCCESS) {
retval = j;
}
}
return (iRCCE_irecv_any_source_queue == NULL)? retval : iRCCE_RESERVED;
}
//--------------------------------------------------------------------------------------
// FUNCTION: iRCCE_irecv_wait
//--------------------------------------------------------------------------------------
// just wait for completion of the requested non-blocking send operation
//--------------------------------------------------------------------------------------
int iRCCE_irecv_wait(iRCCE_RECV_REQUEST *request) {
if(request != NULL) {
while(!request->finished) {
iRCCE_irecv_push();
iRCCE_isend_push();
}
}
else {
do {
iRCCE_isend_push();
}
while( iRCCE_irecv_push() != iRCCE_SUCCESS );
}
return(iRCCE_SUCCESS);
}
//--------------------------------------------------------------------------------------
// FUNCTION: iRCCE_irecv_cancel
//--------------------------------------------------------------------------------------
// try to cancel a pending non-blocking recv request
//--------------------------------------------------------------------------------------
int iRCCE_irecv_cancel(iRCCE_RECV_REQUEST *request, int *test) {
int source;
iRCCE_RECV_REQUEST *run;
if( (request == NULL) || (request->finished) ) {
if (test) (*test) = 0;
return iRCCE_NOT_ENQUEUED;
}
// does request have any source specified?
if( request->source == iRCCE_ANY_SOURCE ) {
for( run = iRCCE_irecv_any_source_queue; run->next != NULL; run = run->next ) {
if( run->next == request ) {
run->next = run->next->next;
if (test) (*test) = 1;
return iRCCE_SUCCESS;
}
}
if (test) (*test) = 0;
return iRCCE_NOT_ENQUEUED;
}
source = request->source;
if(iRCCE_irecv_queue[source] == NULL) {
if (test) (*test) = 0;
return iRCCE_NOT_ENQUEUED;
}
if(iRCCE_irecv_queue[source] == request) {
// have parts of the message already been received?
if(request->started) {
if (test) (*test) = 0;
return iRCCE_PENDING;
}
else {
// no, thus request can be canceld just in time:
iRCCE_irecv_queue[source] = request->next;
if (test) (*test) = 1;
return iRCCE_SUCCESS;
}
}
for(run = iRCCE_irecv_queue[source]; run->next != NULL; run = run->next) {
// request found --> remove it from recv queue:
if(run->next == request) {
run->next = run->next->next;
if (test) (*test) = 1;
return iRCCE_SUCCESS;
}
}
if (test) (*test) = 0;
return iRCCE_NOT_ENQUEUED;
}
| bsd-3-clause |
youtube/cobalt | third_party/crashpad/util/file/output_stream_file_writer.cc | 1982 | // Copyright 2020 The Crashpad Authors. 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.
#include "util/file/output_stream_file_writer.h"
#include "base/logging.h"
#include "util/stream/output_stream_interface.h"
namespace crashpad {
OutputStreamFileWriter::OutputStreamFileWriter(
std::unique_ptr<OutputStreamInterface> output_stream)
: output_stream_(std::move(output_stream)),
flush_needed_(false),
flushed_(false) {}
OutputStreamFileWriter::~OutputStreamFileWriter() {
DCHECK(!flush_needed_);
}
bool OutputStreamFileWriter::Write(const void* data, size_t size) {
DCHECK(!flushed_);
flush_needed_ =
output_stream_->Write(static_cast<const uint8_t*>(data), size);
return flush_needed_;
}
bool OutputStreamFileWriter::WriteIoVec(std::vector<WritableIoVec>* iovecs) {
DCHECK(!flushed_);
flush_needed_ = true;
if (iovecs->empty()) {
LOG(ERROR) << "no iovecs";
flush_needed_ = false;
return false;
}
for (const WritableIoVec& iov : *iovecs) {
if (!output_stream_->Write(static_cast<const uint8_t*>(iov.iov_base),
iov.iov_len)) {
flush_needed_ = false;
return false;
}
}
return true;
}
FileOffset OutputStreamFileWriter::Seek(FileOffset offset, int whence) {
NOTREACHED();
return -1;
}
bool OutputStreamFileWriter::Flush() {
flush_needed_ = false;
flushed_ = true;
return output_stream_->Flush();
}
} // namespace crashpad
| bsd-3-clause |
JianpingZeng/xcc | xcc/test/juliet/testcases/CWE36_Absolute_Path_Traversal/s01/CWE36_Absolute_Path_Traversal__char_connect_socket_ofstream_73a.cpp | 5444 | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE36_Absolute_Path_Traversal__char_connect_socket_ofstream_73a.cpp
Label Definition File: CWE36_Absolute_Path_Traversal.label.xml
Template File: sources-sink-73a.tmpl.cpp
*/
/*
* @description
* CWE: 36 Absolute Path Traversal
* BadSource: connect_socket Read data using a connect socket (client side)
* GoodSource: Full path and file name
* Sinks: ofstream
* BadSink : Open the file named in data using ofstream::open()
* Flow Variant: 73 Data flow: data passed in a list from one function to another in different source files
*
* */
#include "std_testcase.h"
#include <list>
#ifndef _WIN32
#include <wchar.h>
#endif
#ifdef _WIN32
#include <winsock2.h>
#include <windows.h>
#include <direct.h>
#pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */
#define CLOSE_SOCKET closesocket
#else /* NOT _WIN32 */
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define INVALID_SOCKET -1
#define SOCKET_ERROR -1
#define CLOSE_SOCKET close
#define SOCKET int
#endif
#define TCP_PORT 27015
#define IP_ADDRESS "127.0.0.1"
using namespace std;
namespace CWE36_Absolute_Path_Traversal__char_connect_socket_ofstream_73
{
#ifndef OMITBAD
/* bad function declaration */
void badSink(list<char *> dataList);
void bad()
{
char * data;
list<char *> dataList;
char dataBuffer[FILENAME_MAX] = "";
data = dataBuffer;
{
#ifdef _WIN32
WSADATA wsaData;
int wsaDataInit = 0;
#endif
int recvResult;
struct sockaddr_in service;
char *replace;
SOCKET connectSocket = INVALID_SOCKET;
size_t dataLen = strlen(data);
do
{
#ifdef _WIN32
if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
{
break;
}
wsaDataInit = 1;
#endif
/* POTENTIAL FLAW: Read data using a connect socket */
connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (connectSocket == INVALID_SOCKET)
{
break;
}
memset(&service, 0, sizeof(service));
service.sin_family = AF_INET;
service.sin_addr.s_addr = inet_addr(IP_ADDRESS);
service.sin_port = htons(TCP_PORT);
if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
{
break;
}
/* Abort on error or the connection was closed, make sure to recv one
* less char than is in the recv_buf in order to append a terminator */
/* Abort on error or the connection was closed */
recvResult = recv(connectSocket, (char *)(data + dataLen), sizeof(char) * (FILENAME_MAX - dataLen - 1), 0);
if (recvResult == SOCKET_ERROR || recvResult == 0)
{
break;
}
/* Append null terminator */
data[dataLen + recvResult / sizeof(char)] = '\0';
/* Eliminate CRLF */
replace = strchr(data, '\r');
if (replace)
{
*replace = '\0';
}
replace = strchr(data, '\n');
if (replace)
{
*replace = '\0';
}
}
while (0);
if (connectSocket != INVALID_SOCKET)
{
CLOSE_SOCKET(connectSocket);
}
#ifdef _WIN32
if (wsaDataInit)
{
WSACleanup();
}
#endif
}
/* Put data in a list */
dataList.push_back(data);
dataList.push_back(data);
dataList.push_back(data);
badSink(dataList);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* good function declarations */
/* goodG2B uses the GoodSource with the BadSink */
void goodG2BSink(list<char *> dataList);
static void goodG2B()
{
char * data;
list<char *> dataList;
char dataBuffer[FILENAME_MAX] = "";
data = dataBuffer;
#ifdef _WIN32
/* FIX: Use a fixed, full path and file name */
strcat(data, "c:\\temp\\file.txt");
#else
/* FIX: Use a fixed, full path and file name */
strcat(data, "/tmp/file.txt");
#endif
/* Put data in a list */
dataList.push_back(data);
dataList.push_back(data);
dataList.push_back(data);
goodG2BSink(dataList);
}
void good()
{
goodG2B();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE36_Absolute_Path_Traversal__char_connect_socket_ofstream_73; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| bsd-3-clause |
JianpingZeng/xcc | xcc/test/juliet/testcases/CWE400_Resource_Exhaustion/s01/CWE400_Resource_Exhaustion__connect_socket_sleep_06.c | 11509 | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE400_Resource_Exhaustion__connect_socket_sleep_06.c
Label Definition File: CWE400_Resource_Exhaustion.label.xml
Template File: sources-sinks-06.tmpl.c
*/
/*
* @description
* CWE: 400 Resource Exhaustion
* BadSource: connect_socket Read data using a connect socket (client side)
* GoodSource: Assign count to be a relatively small number
* Sinks: sleep
* GoodSink: Validate count before using it as a parameter in sleep function
* BadSink : Use count as the parameter for sleep withhout checking it's size first
* Flow Variant: 06 Control flow: if(STATIC_CONST_FIVE==5) and if(STATIC_CONST_FIVE!=5)
*
* */
#include "std_testcase.h"
#ifdef _WIN32
#include <winsock2.h>
#include <windows.h>
#include <direct.h>
#pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */
#define CLOSE_SOCKET closesocket
#else /* NOT _WIN32 */
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define INVALID_SOCKET -1
#define SOCKET_ERROR -1
#define CLOSE_SOCKET close
#define SOCKET int
#endif
#define TCP_PORT 27015
#define IP_ADDRESS "127.0.0.1"
#define CHAR_ARRAY_SIZE (3 * sizeof(count) + 2)
#ifdef _WIN32
#define SLEEP Sleep
#else
#define SLEEP usleep
#endif
/* The variable below is declared "const", so a tool should be able
to identify that reads of this will always give its initialized
value. */
static const int STATIC_CONST_FIVE = 5;
#ifndef OMITBAD
void CWE400_Resource_Exhaustion__connect_socket_sleep_06_bad()
{
int count;
/* Initialize count */
count = -1;
if(STATIC_CONST_FIVE==5)
{
{
#ifdef _WIN32
WSADATA wsaData;
int wsaDataInit = 0;
#endif
int recvResult;
struct sockaddr_in service;
SOCKET connectSocket = INVALID_SOCKET;
char inputBuffer[CHAR_ARRAY_SIZE];
do
{
#ifdef _WIN32
if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
{
break;
}
wsaDataInit = 1;
#endif
/* POTENTIAL FLAW: Read count using a connect socket */
connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (connectSocket == INVALID_SOCKET)
{
break;
}
memset(&service, 0, sizeof(service));
service.sin_family = AF_INET;
service.sin_addr.s_addr = inet_addr(IP_ADDRESS);
service.sin_port = htons(TCP_PORT);
if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
{
break;
}
/* Abort on error or the connection was closed, make sure to recv one
* less char than is in the recv_buf in order to append a terminator */
recvResult = recv(connectSocket, inputBuffer, CHAR_ARRAY_SIZE - 1, 0);
if (recvResult == SOCKET_ERROR || recvResult == 0)
{
break;
}
/* NUL-terminate the string */
inputBuffer[recvResult] = '\0';
/* Convert to int */
count = atoi(inputBuffer);
}
while (0);
if (connectSocket != INVALID_SOCKET)
{
CLOSE_SOCKET(connectSocket);
}
#ifdef _WIN32
if (wsaDataInit)
{
WSACleanup();
}
#endif
}
}
if(STATIC_CONST_FIVE==5)
{
/* POTENTIAL FLAW: Sleep function using count as the parameter with no validation */
SLEEP(count);
printLine("Sleep time possibly too long");
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodB2G1() - use badsource and goodsink by changing the second STATIC_CONST_FIVE==5 to STATIC_CONST_FIVE!=5 */
static void goodB2G1()
{
int count;
/* Initialize count */
count = -1;
if(STATIC_CONST_FIVE==5)
{
{
#ifdef _WIN32
WSADATA wsaData;
int wsaDataInit = 0;
#endif
int recvResult;
struct sockaddr_in service;
SOCKET connectSocket = INVALID_SOCKET;
char inputBuffer[CHAR_ARRAY_SIZE];
do
{
#ifdef _WIN32
if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
{
break;
}
wsaDataInit = 1;
#endif
/* POTENTIAL FLAW: Read count using a connect socket */
connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (connectSocket == INVALID_SOCKET)
{
break;
}
memset(&service, 0, sizeof(service));
service.sin_family = AF_INET;
service.sin_addr.s_addr = inet_addr(IP_ADDRESS);
service.sin_port = htons(TCP_PORT);
if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
{
break;
}
/* Abort on error or the connection was closed, make sure to recv one
* less char than is in the recv_buf in order to append a terminator */
recvResult = recv(connectSocket, inputBuffer, CHAR_ARRAY_SIZE - 1, 0);
if (recvResult == SOCKET_ERROR || recvResult == 0)
{
break;
}
/* NUL-terminate the string */
inputBuffer[recvResult] = '\0';
/* Convert to int */
count = atoi(inputBuffer);
}
while (0);
if (connectSocket != INVALID_SOCKET)
{
CLOSE_SOCKET(connectSocket);
}
#ifdef _WIN32
if (wsaDataInit)
{
WSACleanup();
}
#endif
}
}
if(STATIC_CONST_FIVE!=5)
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
printLine("Benign, fixed string");
}
else
{
/* FIX: Validate count before using it as a parameter in the sleep function */
if (count > 0 && count <= 2000)
{
SLEEP(count);
printLine("Sleep time OK");
}
else
{
printLine("Sleep time too long");
}
}
}
/* goodB2G2() - use badsource and goodsink by reversing the blocks in the second if */
static void goodB2G2()
{
int count;
/* Initialize count */
count = -1;
if(STATIC_CONST_FIVE==5)
{
{
#ifdef _WIN32
WSADATA wsaData;
int wsaDataInit = 0;
#endif
int recvResult;
struct sockaddr_in service;
SOCKET connectSocket = INVALID_SOCKET;
char inputBuffer[CHAR_ARRAY_SIZE];
do
{
#ifdef _WIN32
if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
{
break;
}
wsaDataInit = 1;
#endif
/* POTENTIAL FLAW: Read count using a connect socket */
connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (connectSocket == INVALID_SOCKET)
{
break;
}
memset(&service, 0, sizeof(service));
service.sin_family = AF_INET;
service.sin_addr.s_addr = inet_addr(IP_ADDRESS);
service.sin_port = htons(TCP_PORT);
if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
{
break;
}
/* Abort on error or the connection was closed, make sure to recv one
* less char than is in the recv_buf in order to append a terminator */
recvResult = recv(connectSocket, inputBuffer, CHAR_ARRAY_SIZE - 1, 0);
if (recvResult == SOCKET_ERROR || recvResult == 0)
{
break;
}
/* NUL-terminate the string */
inputBuffer[recvResult] = '\0';
/* Convert to int */
count = atoi(inputBuffer);
}
while (0);
if (connectSocket != INVALID_SOCKET)
{
CLOSE_SOCKET(connectSocket);
}
#ifdef _WIN32
if (wsaDataInit)
{
WSACleanup();
}
#endif
}
}
if(STATIC_CONST_FIVE==5)
{
/* FIX: Validate count before using it as a parameter in the sleep function */
if (count > 0 && count <= 2000)
{
SLEEP(count);
printLine("Sleep time OK");
}
else
{
printLine("Sleep time too long");
}
}
}
/* goodG2B1() - use goodsource and badsink by changing the first STATIC_CONST_FIVE==5 to STATIC_CONST_FIVE!=5 */
static void goodG2B1()
{
int count;
/* Initialize count */
count = -1;
if(STATIC_CONST_FIVE!=5)
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
printLine("Benign, fixed string");
}
else
{
/* FIX: Use a relatively small number */
count = 20;
}
if(STATIC_CONST_FIVE==5)
{
/* POTENTIAL FLAW: Sleep function using count as the parameter with no validation */
SLEEP(count);
printLine("Sleep time possibly too long");
}
}
/* goodG2B2() - use goodsource and badsink by reversing the blocks in the first if */
static void goodG2B2()
{
int count;
/* Initialize count */
count = -1;
if(STATIC_CONST_FIVE==5)
{
/* FIX: Use a relatively small number */
count = 20;
}
if(STATIC_CONST_FIVE==5)
{
/* POTENTIAL FLAW: Sleep function using count as the parameter with no validation */
SLEEP(count);
printLine("Sleep time possibly too long");
}
}
void CWE400_Resource_Exhaustion__connect_socket_sleep_06_good()
{
goodB2G1();
goodB2G2();
goodG2B1();
goodG2B2();
}
#endif /* OMITGOOD */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
CWE400_Resource_Exhaustion__connect_socket_sleep_06_good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
CWE400_Resource_Exhaustion__connect_socket_sleep_06_bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| bsd-3-clause |
manolama/asynchbase | src/MultiColumnAtomicIncrementRequest.java | 11947 | /*
* Copyright (C) 2010-2012 The Async HBase Authors. All rights reserved.
* This file is part of Async HBase.
*
* 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 StumbleUpon 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.
*/
package org.hbase.async;
import com.google.common.base.Joiner;
import com.google.common.collect.Maps;
import org.hbase.async.generated.ClientPB.MutateRequest;
import org.hbase.async.generated.ClientPB.MutateResponse;
import org.hbase.async.generated.ClientPB.MutationProto;
import org.jboss.netty.buffer.ChannelBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;
/**
* Atomically increments several column values in HBase.
*
* <h1>A note on passing {@code byte} arrays in argument</h1>
* None of the method that receive a {@code byte[]} in argument will copy it.
* For more info, please refer to the documentation of {@link HBaseRpc}.
* <h1>A note on passing {@code String}s in argument</h1>
* All strings are assumed to use the platform's default charset.
*/
public final class MultiColumnAtomicIncrementRequest extends HBaseRpc
implements HBaseRpc.HasTable, HBaseRpc.HasKey,
HBaseRpc.HasFamily, HBaseRpc.HasQualifiers, HBaseRpc.IsEdit {
private static byte[][] toByteArrays(String[] strArray) {
byte[][] converted = new byte[strArray.length][];
for(int i = 0; i < strArray.length; i++) {
converted[i] = strArray[i].getBytes();
}
return converted;
}
private static final byte[] INCREMENT_COLUMN_VALUE = new byte[] {
'i', 'n', 'c', 'r', 'e', 'm', 'e', 'n', 't',
'C', 'o', 'l', 'u', 'm', 'n',
'V', 'a', 'l', 'u', 'e'
};
private static final Joiner AMOUNT_JOINER = Joiner.on(",");
private final byte[] family;
private final byte[][] qualifiers;
private long[] amounts;
private boolean durable = true;
/**
* Constructor.
* <strong>These byte arrays will NOT be copied.</strong>
* @param table The non-empty name of the table to use.
* @param key The row key of the value to increment.
* @param family The column family of the value to increment.
* @param qualifiers The column qualifier of the value to increment.
* @param amounts Amount by which to increment the value in HBase.
* If negative, the value in HBase will be decremented.
*/
public MultiColumnAtomicIncrementRequest(final byte[] table,
final byte[] key,
final byte[] family,
final byte[][] qualifiers,
final long[] amounts) {
super(table, key);
KeyValue.checkFamily(family);
this.family = family;
if (qualifiers == null || qualifiers.length == 0) {
throw new IllegalArgumentException("qualifiers must be provided for MultiColumnAtomicIncrementRequest");
}
for (byte[] qualifier : qualifiers) {
KeyValue.checkQualifier(qualifier);
}
this.qualifiers = qualifiers;
if (amounts != null) {
if (amounts.length == 0) {
throw new IllegalArgumentException("amounts must be provided for MultiColumnAtomicIncrementRequest");
}
if (qualifiers.length != amounts.length) {
throw new IllegalArgumentException("Number of amounts must be equal to the number of qualifiers provided for MultiColumnAtomicIncrementRequest");
}
this.amounts = amounts;
} else {
this.amounts = new long[qualifiers.length];
Arrays.fill(this.amounts, 1L);
}
}
/**
* Constructor. This is equivalent to:
* {@link #MultiColumnAtomicIncrementRequest(byte[], byte[], byte[], byte[][], long[])
* MultiColumnAtomicIncrementRequest}{@code (table, key, family, qualifiers, new long[] {1, ..})}
* <p>
* <strong>These byte arrays will NOT be copied.</strong>
* @param table The non-empty name of the table to use.
* @param key The row key of the value to increment.
* @param family The column family of the value to increment.
* @param qualifiers The column qualifier of the value to increment.
*/
public MultiColumnAtomicIncrementRequest(final byte[] table,
final byte[] key,
final byte[] family,
final byte[][] qualifiers) {
this(table, key, family, qualifiers, null);
}
/**
* Constructor.
* All strings are assumed to use the platform's default charset.
* @param table The non-empty name of the table to use.
* @param key The row key of the value to increment.
* @param family The column family of the value to increment.
* @param qualifiers The column qualifier of the value to increment.
* @param amounts Amount by which to increment the value in HBase.
* If negative, the value in HBase will be decremented.
*/
public MultiColumnAtomicIncrementRequest(final String table,
final String key,
final String family,
final String[] qualifiers,
final long[] amounts) {
this(table.getBytes(), key.getBytes(), family.getBytes(),
toByteArrays(qualifiers), amounts);
}
/**
* Constructor. This is equivalent to:
* All strings are assumed to use the platform's default charset.
* {@link #MultiColumnAtomicIncrementRequest(String, String, String, String[], long[])
* MultiColumnAtomicIncrementRequest}{@code (table, key, family, qualifiers, new long[]{ 1, ..})}
* @param table The non-empty name of the table to use.
* @param key The row key of the value to increment.
* @param family The column family of the value to increment.
* @param qualifiers The column qualifier of the value to increment.
*/
public MultiColumnAtomicIncrementRequest(final String table,
final String key,
final String family,
final String[] qualifiers) {
this(table.getBytes(), key.getBytes(), family.getBytes(),
toByteArrays(qualifiers), null);
}
/**
* Returns the amount by which the value is going to be incremented.
*/
public long[] getAmounts() {
return amounts;
}
/**
* Changes the amounts by which the values are going to be incremented.
* @param amounts The new amounts. If negative, the value will be decremented.
*/
public void setAmounts(final long[] amounts) {
this.amounts = amounts;
}
@Override
byte[] method(final byte server_version) {
return (server_version >= RegionClient.SERVER_VERSION_095_OR_ABOVE
? MUTATE
: INCREMENT_COLUMN_VALUE);
}
@Override
public byte[] table() {
return table;
}
@Override
public byte[] key() {
return key;
}
@Override
public byte[] family() {
return family;
}
@Override
public byte[][] qualifiers() {
return qualifiers;
}
public String toString() {
return super.toStringWithQualifiers("MultiColumnAtomicIncrementRequest",
family, qualifiers, null, ", amounts=" + AMOUNT_JOINER.join(Arrays.asList(amounts)));
}
// ---------------------- //
// Package private stuff. //
// ---------------------- //
/**
* Changes whether or not this atomic increment should use the WAL.
* @param durable {@code true} to use the WAL, {@code false} otherwise.
*/
void setDurable(final boolean durable) {
this.durable = durable;
}
private int predictSerializedSize() {
int size = 0;
size += 4; // int: Number of parameters.
size += 1; // byte: Type of the 1st parameter.
size += 3; // vint: region name length (3 bytes => max length = 32768).
size += region.name().length; // The region name.
size += 1; // byte: Type of the 2nd parameter.
size += 3; // vint: row key length (3 bytes => max length = 32768).
size += key.length; // The row key.
size += 1; // byte: Type of the 3rd parameter.
size += 1; // vint: Family length (guaranteed on 1 byte).
size += family.length; // The family.
size += 1; // byte: Type of the 4th parameter.
size += 3; // vint: Qualifier length.
for(byte[] qualifier : qualifiers) {
size += qualifier.length; // The qualifier.
}
size += 1; // byte: Type of the 5th parameter.
size += 8 * amounts.length; // long: Amount.
size += 1; // byte: Type of the 6th parameter.
size += 1; // bool: Whether or not to write to the WAL.
return size;
}
/** Serializes this request. */
ChannelBuffer serialize(final byte server_version) {
if (server_version < RegionClient.SERVER_VERSION_095_OR_ABOVE) {
throw new UnsupportedOperationException(server_version + " is not supported by " + this.getClass().getName());
}
MutationProto.Builder incr = MutationProto.newBuilder()
.setRow(Bytes.wrap(key))
.setMutateType(MutationProto.MutationType.INCREMENT);
for (int i = 0; i < qualifiers.length; i++) {
final MutationProto.ColumnValue.QualifierValue qualifier =
MutationProto.ColumnValue.QualifierValue.newBuilder()
.setQualifier(Bytes.wrap(this.qualifiers[i]))
.setValue(Bytes.wrap(Bytes.fromLong(this.amounts[i])))
.build();
final MutationProto.ColumnValue column =
MutationProto.ColumnValue.newBuilder()
.setFamily(Bytes.wrap(family))
.addQualifierValue(qualifier)
.build();
incr.addColumnValue(column);
}
if (!durable) {
incr.setDurability(MutationProto.Durability.SKIP_WAL);
}
final MutateRequest req = MutateRequest.newBuilder()
.setRegion(region.toProtobuf())
.setMutation(incr.build())
.build();
return toChannelBuffer(MUTATE, req);
}
@Override
Object deserialize(final ChannelBuffer buf, int cell_size) {
final MutateResponse resp = readProtobuf(buf, MutateResponse.PARSER);
// An increment must always produce a result, so we shouldn't need to
// check whether the `result' field is set here.
final ArrayList<KeyValue> kvs = GetRequest.convertResult(resp.getResult(),
buf, cell_size);
Map<byte[], Long> updatedValues = Maps.newHashMap();
for (KeyValue kv : kvs) {
updatedValues.put(kv.qualifier(), Bytes.getLong(kv.value()));
}
return updatedValues;
}
}
| bsd-3-clause |
assetgraph/assetgraph-builder | testdata/transforms/buildProduction/issue114/index.html | 114 | <!DOCTYPE html>
<html>
<head>
<script src="a.js"></script>
</head>
<body>
<div>Text</div>
</body>
</html>
| bsd-3-clause |
JianpingZeng/xcc | xcc/test/juliet/testcases/CWE197_Numeric_Truncation_Error/s01/CWE197_Numeric_Truncation_Error__int_connect_socket_to_short_74a.cpp | 4835 | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE197_Numeric_Truncation_Error__int_connect_socket_to_short_74a.cpp
Label Definition File: CWE197_Numeric_Truncation_Error__int.label.xml
Template File: sources-sink-74a.tmpl.cpp
*/
/*
* @description
* CWE: 197 Numeric Truncation Error
* BadSource: connect_socket Read data using a connect socket (client side)
* GoodSource: Less than CHAR_MAX
* Sinks: to_short
* BadSink : Convert data to a short
* Flow Variant: 74 Data flow: data passed in a map from one function to another in different source files
*
* */
#include "std_testcase.h"
#include <map>
#ifdef _WIN32
#include <winsock2.h>
#include <windows.h>
#include <direct.h>
#pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */
#define CLOSE_SOCKET closesocket
#else /* NOT _WIN32 */
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define INVALID_SOCKET -1
#define SOCKET_ERROR -1
#define CLOSE_SOCKET close
#define SOCKET int
#endif
#define TCP_PORT 27015
#define IP_ADDRESS "127.0.0.1"
#define CHAR_ARRAY_SIZE (3 * sizeof(data) + 2)
using namespace std;
namespace CWE197_Numeric_Truncation_Error__int_connect_socket_to_short_74
{
#ifndef OMITBAD
/* bad function declaration */
void badSink(map<int, int> dataMap);
void bad()
{
int data;
map<int, int> dataMap;
/* Initialize data */
data = -1;
{
#ifdef _WIN32
WSADATA wsaData;
int wsaDataInit = 0;
#endif
int recvResult;
struct sockaddr_in service;
SOCKET connectSocket = INVALID_SOCKET;
char inputBuffer[CHAR_ARRAY_SIZE];
do
{
#ifdef _WIN32
if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
{
break;
}
wsaDataInit = 1;
#endif
/* POTENTIAL FLAW: Read data using a connect socket */
connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (connectSocket == INVALID_SOCKET)
{
break;
}
memset(&service, 0, sizeof(service));
service.sin_family = AF_INET;
service.sin_addr.s_addr = inet_addr(IP_ADDRESS);
service.sin_port = htons(TCP_PORT);
if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
{
break;
}
/* Abort on error or the connection was closed, make sure to recv one
* less char than is in the recv_buf in order to append a terminator */
recvResult = recv(connectSocket, inputBuffer, CHAR_ARRAY_SIZE - 1, 0);
if (recvResult == SOCKET_ERROR || recvResult == 0)
{
break;
}
/* NUL-terminate the string */
inputBuffer[recvResult] = '\0';
/* Convert to int */
data = atoi(inputBuffer);
}
while (0);
if (connectSocket != INVALID_SOCKET)
{
CLOSE_SOCKET(connectSocket);
}
#ifdef _WIN32
if (wsaDataInit)
{
WSACleanup();
}
#endif
}
/* Put data in a map */
dataMap[0] = data;
dataMap[1] = data;
dataMap[2] = data;
badSink(dataMap);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* good function declarations */
/* goodG2B uses the GoodSource with the BadSink */
void goodG2BSink(map<int, int> dataMap);
static void goodG2B()
{
int data;
map<int, int> dataMap;
/* Initialize data */
data = -1;
/* FIX: Use a positive integer less than CHAR_MAX*/
data = CHAR_MAX-5;
/* Put data in a map */
dataMap[0] = data;
dataMap[1] = data;
dataMap[2] = data;
goodG2BSink(dataMap);
}
void good()
{
goodG2B();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
* its own for testing or for building a binary to use in testing binary
* analysis tools. It is not used when compiling all the testcases as one
* application, which is how source code analysis tools are tested.
*/
#ifdef INCLUDEMAIN
using namespace CWE197_Numeric_Truncation_Error__int_connect_socket_to_short_74; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| bsd-3-clause |
nwjs/chromium.src | ui/gfx/geometry/vector2d_f.h | 4239 | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Defines a simple float vector class. This class is used to indicate a
// distance in two dimensions between two points. Subtracting two points should
// produce a vector, and adding a vector to a point produces the point at the
// vector's distance from the original point.
#ifndef UI_GFX_GEOMETRY_VECTOR2D_F_H_
#define UI_GFX_GEOMETRY_VECTOR2D_F_H_
#include <iosfwd>
#include <string>
#include "ui/gfx/geometry/geometry_export.h"
namespace gfx {
class GEOMETRY_EXPORT Vector2dF {
public:
constexpr Vector2dF() : x_(0), y_(0) {}
constexpr Vector2dF(float x, float y) : x_(x), y_(y) {}
constexpr float x() const { return x_; }
void set_x(float x) { x_ = x; }
constexpr float y() const { return y_; }
void set_y(float y) { y_ = y; }
// True if both components of the vector are 0.
bool IsZero() const;
// Add the components of the |other| vector to the current vector.
void Add(const Vector2dF& other);
// Subtract the components of the |other| vector from the current vector.
void Subtract(const Vector2dF& other);
void operator+=(const Vector2dF& other) { Add(other); }
void operator-=(const Vector2dF& other) { Subtract(other); }
void SetToMin(const Vector2dF& other) {
x_ = std::min(x_, other.x_);
y_ = std::min(y_, other.y_);
}
void SetToMax(const Vector2dF& other) {
x_ = std::max(x_, other.x_);
y_ = std::max(y_, other.y_);
}
// Gives the square of the diagonal length, i.e. the square of magnitude, of
// the vector.
double LengthSquared() const;
// Gives the diagonal length (i.e. the magnitude) of the vector.
float Length() const;
float AspectRatio() const { return x_ / y_; }
// Gives the slope angle in radians of the vector from the positive x axis,
// in the range of (-pi, pi]. The sign of the result is the same as the sign
// of y(), except that the result is pi for Vector2dF(negative-x, zero-y).
float SlopeAngleRadians() const;
// Scale the x and y components of the vector by |scale|.
void Scale(float scale) { Scale(scale, scale); }
// Scale the x and y components of the vector by |x_scale| and |y_scale|
// respectively.
void Scale(float x_scale, float y_scale);
void Transpose() { std::swap(x_, y_); }
std::string ToString() const;
private:
float x_;
float y_;
};
inline constexpr bool operator==(const Vector2dF& lhs, const Vector2dF& rhs) {
return lhs.x() == rhs.x() && lhs.y() == rhs.y();
}
inline constexpr bool operator!=(const Vector2dF& lhs, const Vector2dF& rhs) {
return !(lhs == rhs);
}
inline constexpr Vector2dF operator-(const Vector2dF& v) {
return Vector2dF(-v.x(), -v.y());
}
inline Vector2dF operator+(const Vector2dF& lhs, const Vector2dF& rhs) {
Vector2dF result = lhs;
result.Add(rhs);
return result;
}
inline Vector2dF operator-(const Vector2dF& lhs, const Vector2dF& rhs) {
Vector2dF result = lhs;
result.Add(-rhs);
return result;
}
// Return the cross product of two vectors, i.e. the determinant.
GEOMETRY_EXPORT double CrossProduct(const Vector2dF& lhs, const Vector2dF& rhs);
// Return the dot product of two vectors.
GEOMETRY_EXPORT double DotProduct(const Vector2dF& lhs, const Vector2dF& rhs);
// Return a vector that is |v| scaled by the given scale factors along each
// axis.
GEOMETRY_EXPORT Vector2dF ScaleVector2d(const Vector2dF& v,
float x_scale,
float y_scale);
// Return a vector that is |v| scaled by the given scale factor.
inline Vector2dF ScaleVector2d(const Vector2dF& v, float scale) {
return ScaleVector2d(v, scale, scale);
}
inline Vector2dF TransposeVector2d(const Vector2dF& v) {
return Vector2dF(v.y(), v.x());
}
// This is declared here for use in gtest-based unit tests but is defined in
// the //ui/gfx:test_support target. Depend on that to use this in your unit
// test. This should not be used in production code - call ToString() instead.
void PrintTo(const Vector2dF& vector, ::std::ostream* os);
} // namespace gfx
#endif // UI_GFX_GEOMETRY_VECTOR2D_F_H_
| bsd-3-clause |
JianpingZeng/xcc | xcc/test/juliet/testcases/CWE121_Stack_Based_Buffer_Overflow/s01/CWE121_Stack_Based_Buffer_Overflow__CWE131_loop_66b.c | 1625 | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE121_Stack_Based_Buffer_Overflow__CWE131_loop_66b.c
Label Definition File: CWE121_Stack_Based_Buffer_Overflow__CWE131.label.xml
Template File: sources-sink-66b.tmpl.c
*/
/*
* @description
* CWE: 121 Stack Based Buffer Overflow
* BadSource: Allocate memory without using sizeof(int)
* GoodSource: Allocate memory using sizeof(int)
* Sinks: loop
* BadSink : Copy array to data using a loop
* Flow Variant: 66 Data flow: data passed in an array from one function to another in different source files
*
* */
#include "std_testcase.h"
#ifndef OMITBAD
void CWE121_Stack_Based_Buffer_Overflow__CWE131_loop_66b_badSink(int * dataArray[])
{
/* copy data out of dataArray */
int * data = dataArray[2];
{
int source[10] = {0};
size_t i;
/* POTENTIAL FLAW: Possible buffer overflow if data was not allocated correctly in the source */
for (i = 0; i < 10; i++)
{
data[i] = source[i];
}
printIntLine(data[0]);
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
void CWE121_Stack_Based_Buffer_Overflow__CWE131_loop_66b_goodG2BSink(int * dataArray[])
{
int * data = dataArray[2];
{
int source[10] = {0};
size_t i;
/* POTENTIAL FLAW: Possible buffer overflow if data was not allocated correctly in the source */
for (i = 0; i < 10; i++)
{
data[i] = source[i];
}
printIntLine(data[0]);
}
}
#endif /* OMITGOOD */
| bsd-3-clause |
JianpingZeng/xcc | xcc/test/juliet/testcases/CWE272_Least_Privilege_Violation/CWE272_Least_Privilege_Violation__w32_char_RegCreateKey_12.c | 4262 | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE272_Least_Privilege_Violation__w32_char_RegCreateKey_12.c
Label Definition File: CWE272_Least_Privilege_Violation__w32.label.xml
Template File: point-flaw-12.tmpl.c
*/
/*
* @description
* CWE: 272 Least Privilege Violation
* Sinks: RegCreateKey
* GoodSink: Create a registry key using RegCreateKeyA() and HKEY_CURRENT_USER
* BadSink : Create a registry key using RegCreateKeyA() and HKEY_LOCAL_MACHINE
* Flow Variant: 12 Control flow: if(globalReturnsTrueOrFalse())
*
* */
#include "std_testcase.h"
#include <windows.h>
#pragma comment( lib, "advapi32" )
#ifndef OMITBAD
void CWE272_Least_Privilege_Violation__w32_char_RegCreateKey_12_bad()
{
if(globalReturnsTrueOrFalse())
{
{
char * keyName = "TEST\\TestKey";
HKEY hKey;
/* FLAW: Call RegCreateKeyA() with HKEY_LOCAL_MACHINE violating the least privilege principal */
if (RegCreateKeyA(
HKEY_LOCAL_MACHINE,
keyName,
&hKey) != ERROR_SUCCESS)
{
printLine("Registry key could not be created");
}
else
{
printLine("Registry key created successfully");
RegCloseKey(hKey);
}
}
}
else
{
{
char * keyName = "TEST\\TestKey";
HKEY hKey;
/* FIX: Call RegCreateKeyA() with HKEY_CURRENT_USER */
if (RegCreateKeyA(
HKEY_CURRENT_USER,
keyName,
&hKey) != ERROR_SUCCESS)
{
printLine("Registry key could not be created");
}
else
{
printLine("Registry key created successfully");
RegCloseKey(hKey);
}
}
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* good1() uses the GoodSink on both sides of the "if" statement */
static void good1()
{
if(globalReturnsTrueOrFalse())
{
{
char * keyName = "TEST\\TestKey";
HKEY hKey;
/* FIX: Call RegCreateKeyA() with HKEY_CURRENT_USER */
if (RegCreateKeyA(
HKEY_CURRENT_USER,
keyName,
&hKey) != ERROR_SUCCESS)
{
printLine("Registry key could not be created");
}
else
{
printLine("Registry key created successfully");
RegCloseKey(hKey);
}
}
}
else
{
{
char * keyName = "TEST\\TestKey";
HKEY hKey;
/* FIX: Call RegCreateKeyA() with HKEY_CURRENT_USER */
if (RegCreateKeyA(
HKEY_CURRENT_USER,
keyName,
&hKey) != ERROR_SUCCESS)
{
printLine("Registry key could not be created");
}
else
{
printLine("Registry key created successfully");
RegCloseKey(hKey);
}
}
}
}
void CWE272_Least_Privilege_Violation__w32_char_RegCreateKey_12_good()
{
good1();
}
#endif /* OMITGOOD */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
CWE272_Least_Privilege_Violation__w32_char_RegCreateKey_12_good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
CWE272_Least_Privilege_Violation__w32_char_RegCreateKey_12_bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| bsd-3-clause |
alunys/ApigilityAngularTest | vendor/zfcampus/zf-apigility-doctrine/src/Server/Query/Provider/QueryProviderInterface.php | 1172 | <?php
namespace ZF\Apigility\Doctrine\Server\Query\Provider;
use DoctrineModule\Persistence\ObjectManagerAwareInterface;
use Zend\Paginator\Adapter\AdapterInterface;
use Zend\ServiceManager\AbstractPluginManager;
use ZF\Rest\ResourceEvent;
interface QueryProviderInterface extends ObjectManagerAwareInterface
{
/**
* @param string $entityClass
* @param array $parameters
*
* @return mixed This will return an ORM or ODM Query\Builder
*/
public function createQuery(ResourceEvent $event, $entityClass, $parameters);
/**
* This function is not necessary for any but fetch-all queries
* In order to provide a single QueryProvider service this is
* included in this interface.
*
* @param $queryBuilder
*
* @return AdapterInterface
*/
public function getPaginatedQuery($queryBuilder);
/**
* This function is not necessary for any but fetch-all queries
* In order to provide a single QueryProvider service this is
* included in this interface.
*
* @param $entityClass
*
* @return int
*/
public function getCollectionTotal($entityClass);
}
| bsd-3-clause |
MalcolmD/CloudCVPlusDetection | src/modules/cameraCalibration/CameraCalibrationBinding.cpp | 10211 | #include <cloudcv.hpp>
#include <framework/marshal/marshal.hpp>
#include <framework/marshal/node_object_builder.hpp>
#include <framework/Job.hpp>
#include <framework/NanCheck.hpp>
#include <framework/Logger.h>
#include "framework/ImageSource.hpp"
#include "CameraCalibrationAlgorithm.hpp"
using namespace v8;
using namespace node;
namespace cloudcv
{
class DetectPatternTask : public Job
{
public:
DetectPatternTask(ImageSourcePtr imageSource, cv::Size patternSize, PatternType type, NanCallback * callback)
: Job(callback)
, m_imageSource(imageSource)
, m_algorithm(patternSize, type)
{
TRACE_FUNCTION;
}
virtual ~DetectPatternTask()
{
TRACE_FUNCTION;
}
protected:
void ExecuteNativeCode()
{
TRACE_FUNCTION;
cv::Mat frame = m_imageSource->getImage(cv::IMREAD_GRAYSCALE);
if (frame.empty())
{
SetErrorMessage("Cannot decode input image");
return;
}
try
{
m_patternfound = m_algorithm.detectCorners(frame, m_corners2d);
}
catch (...)
{
SetErrorMessage("Internal exception");
}
}
virtual Local<Value> CreateCallbackResult()
{
TRACE_FUNCTION;
NanEscapableScope();
Local<Object> res = NanNew<Object>(); //(Object::New());
NodeObject resultWrapper(res);
resultWrapper["patternFound"] = m_patternfound;
if (m_patternfound)
{
resultWrapper["corners"] = m_corners2d;
}
return NanEscapeScope(res);
}
private:
ImageSourcePtr m_imageSource;
CameraCalibrationAlgorithm m_algorithm;
CameraCalibrationAlgorithm::VectorOf2DPoints m_corners2d;
bool m_patternfound;
bool m_returnImage;
};
class ComputeIntrinsicParametersTask : public Job
{
public:
typedef CameraCalibrationAlgorithm::VectorOfVectorOf3DPoints VectorOfVectorOf3DPoints;
typedef CameraCalibrationAlgorithm::VectorOfVectorOf2DPoints VectorOfVectorOf2DPoints;
typedef CameraCalibrationAlgorithm::VectorOfMat VectorOfMat;
ComputeIntrinsicParametersTask(
const std::vector<std::string>& files,
cv::Size boardSize,
PatternType type,
NanCallback * callback
)
: Job(callback)
, m_algorithm(boardSize, type)
, m_imageFiles(files)
{
}
ComputeIntrinsicParametersTask(
const VectorOfVectorOf2DPoints& v,
cv::Size imageSize,
cv::Size boardSize,
PatternType type,
NanCallback * callback
)
: Job(callback)
, m_algorithm(boardSize, type)
, m_imageSize(imageSize)
, m_gridCorners(v)
{
}
protected:
virtual void ExecuteNativeCode()
{
TRACE_FUNCTION;
if (!m_imageFiles.empty())
{
m_gridCorners.resize(m_imageFiles.size());
for (size_t i = 0; i < m_imageFiles.size(); i++)
{
cv::Mat image = CreateImageSource(m_imageFiles[i])->getImage(cv::IMREAD_GRAYSCALE);
if (image.empty())
{
SetErrorMessage(std::string("Cannot read image at index ") + lexical_cast(i) + ": " + m_imageFiles[i]);
return;
}
if (!m_algorithm.detectCorners(image, m_gridCorners[i]))
{
SetErrorMessage(std::string("Cannot detect calibration pattern on image at index ") + lexical_cast(i));
return;
}
m_imageSize = image.size();
}
}
if (!m_gridCorners.empty())
{
m_calibrationSuccess = m_algorithm.calibrateCamera(m_gridCorners, m_imageSize, m_cameraMatrix, m_distCoeffs);
LOG_TRACE_MESSAGE("m_calibrationSuccess = " << m_calibrationSuccess);
}
else
{
SetErrorMessage("Neither image files nor grid corners were passed");
return;
}
}
virtual Local<Value> CreateCallbackResult()
{
TRACE_FUNCTION;
NanEscapableScope();
Local<Object> res = NanNew<Object>(); //Local(Object::New());
NodeObject resultWrapper(res);
if (m_calibrationSuccess)
{
resultWrapper["intrinsic"] = m_cameraMatrix;
resultWrapper["distCoeffs"] = m_distCoeffs;
}
resultWrapper["calibrationSuccess"] = m_calibrationSuccess;
return NanEscapeScope(res);
}
private:
CameraCalibrationAlgorithm m_algorithm;
std::vector<std::string> m_imageFiles;
cv::Size m_imageSize;
VectorOfVectorOf2DPoints m_gridCorners;
cv::Mat m_cameraMatrix;
cv::Mat m_distCoeffs;
bool m_calibrationSuccess;
};
NAN_METHOD(calibrationPatternDetect)
{
TRACE_FUNCTION;
NanEscapableScope();
Local<Object> imageBuffer;
std::string imagePath;
Local<Function> callback;
cv::Size patternSize;
PatternType pattern;
std::string error;
LOG_TRACE_MESSAGE("Begin parsing arguments");
if (NanCheck(args)
.Error(&error)
.ArgumentsCount(4)
.Argument(0).IsBuffer().Bind(imageBuffer)
.Argument(1).Bind(patternSize)
.Argument(2).StringEnum<PatternType>({
{ "CHESSBOARD", PatternType::CHESSBOARD },
{ "CIRCLES_GRID", PatternType::CIRCLES_GRID },
{ "ACIRCLES_GRID", PatternType::ACIRCLES_GRID } }).Bind(pattern)
.Argument(3).IsFunction().Bind(callback))
{
LOG_TRACE_MESSAGE("Parsed function arguments");
NanCallback *nanCallback = new NanCallback(callback);
NanAsyncQueueWorker(new DetectPatternTask(
CreateImageSource(imageBuffer),
patternSize,
pattern,
nanCallback));
}
else if (NanCheck(args)
.Error(&error)
.ArgumentsCount(4)
.Argument(0).IsString().Bind(imagePath)
.Argument(1).Bind(patternSize)
.Argument(2).StringEnum<PatternType>({
{ "CHESSBOARD", PatternType::CHESSBOARD },
{ "CIRCLES_GRID", PatternType::CIRCLES_GRID },
{ "ACIRCLES_GRID", PatternType::ACIRCLES_GRID } }).Bind(pattern)
.Argument(3).IsFunction().Bind(callback))
{
LOG_TRACE_MESSAGE("Parsed function arguments");
NanCallback *nanCallback = new NanCallback(callback);
NanAsyncQueueWorker(new DetectPatternTask(
CreateImageSource(imagePath),
patternSize,
pattern,
nanCallback));
}
else if (!error.empty())
{
LOG_TRACE_MESSAGE(error);
NanThrowTypeError(error.c_str());
}
NanReturnUndefined();
}
NAN_METHOD(calibrateCamera)
{
TRACE_FUNCTION;
NanEscapableScope();
std::vector<std::string> imageFiles;
std::vector< std::vector<cv::Point2f> > imageCorners;
Local<Function> callback;
cv::Size patternSize;
cv::Size imageSize;
PatternType pattern;
std::string error;
if (NanCheck(args)
.Error(&error)
.ArgumentsCount(4)
.Argument(0).IsArray().Bind(imageFiles)
.Argument(1).Bind(patternSize)
.Argument(2).StringEnum<PatternType>({
{ "CHESSBOARD", PatternType::CHESSBOARD },
{ "CIRCLES_GRID", PatternType::CIRCLES_GRID },
{ "ACIRCLES_GRID", PatternType::ACIRCLES_GRID } }).Bind(pattern)
.Argument(3).IsFunction().Bind(callback))
{
LOG_TRACE_MESSAGE("Image files count: " << imageFiles.size());
NanCallback *nanCallback = new NanCallback(callback);
NanAsyncQueueWorker(new ComputeIntrinsicParametersTask(imageFiles, patternSize, pattern, nanCallback));
} else if (NanCheck(args)
.Error(&error)
.ArgumentsCount(6)
.Argument(0).IsArray().Bind(imageCorners)
.Argument(1).Bind(imageSize)
.Argument(2).Bind(patternSize)
.Argument(3).StringEnum<PatternType>({
{ "CHESSBOARD", PatternType::CHESSBOARD },
{ "CIRCLES_GRID", PatternType::CIRCLES_GRID },
{ "ACIRCLES_GRID", PatternType::ACIRCLES_GRID } }).Bind(pattern)
.Argument(4).IsFunction().Bind(callback))
{
NanCallback *nanCallback = new NanCallback(callback);
NanAsyncQueueWorker(new ComputeIntrinsicParametersTask(imageCorners, imageSize, patternSize, pattern, nanCallback));
}
else if (!error.empty())
{
NanThrowTypeError(error.c_str());
}
NanReturnUndefined();
}
}
| bsd-3-clause |
lockss/lockss-daemon | test/src/org/lockss/mbf/MockMemoryBoundFunctionVote.java | 5392 | /*
* $Id$
*/
/*
Copyright (c) 2000-2002 Board of Trustees of Leland Stanford Jr. University,
all rights reserved.
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
STANFORD UNIVERSITY 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.
Except as contained in this notice, the name of Stanford University shall not
be used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from Stanford University.
*/
package org.lockss.mbf;
import java.util.*;
import java.security.*;
import java.io.*;
import org.lockss.util.*;
import org.lockss.plugin.*;
import org.lockss.daemon.*;
import org.lockss.protocol.*;
/**
* @author David S. H. Rosenthal
* @version 1.0
*/
public class MockMemoryBoundFunctionVote extends MemoryBoundFunctionVote {
private byte[][] mockHashes;
private int[][] mockProofs;
private boolean[] mockVerifies;
private int stepLimit;
/**
* No-argument constructor for use with Class.newInstance().
*/
public MockMemoryBoundFunctionVote() {
mockHashes = null;
mockProofs = null;
mockVerifies = null;
stepLimit = 0;
}
/**
* Public constructor for an object that will compute a vote
* using hashing and memory bound functions.
* It accepts as input a nonce and a CachedUrlSet. It divides the
* content into i blocks of length <= 2**(i+1) and for each computes
* the MBF proof and the hash. The first proof depends on the nonce
* the AU name and the first bytes of the AU. Subsequent proofs
* depend on the preceeding hash and proof. The effort sizer e
* is constant for all rounds. The path length l is set equal to
* the block size for that round.
* @param nVal a byte array containing the nonce
* @param eVal the effort sizer (# of low-order zeros in destination)
* @param cusVal the CachedUrlSet containing the content to be voted on
* @param pollID the byte array ID for the poll
* @param voterID the PeerIdentity of the voter
*
*/
protected void setupGeneration(MemoryBoundFunctionFactory fact,
byte[] nVal,
int eVal,
CachedUrlSet cusVal,
byte[] pollID,
PeerIdentity voterID)
throws MemoryBoundFunctionException {
super.setupGeneration(fact, nVal, eVal, cusVal, pollID, voterID);
setup(nVal, eVal, cusVal);
}
/**
* Public constructor for an object that will verify a vote
* using hashing and memory bound functions. It accepts as
* input a nonce, a cachedUrlSet, and arrays of proofs
* and hashes.
* @param nVal a byte array containing the nonce
* @param eVal the effort sizer (# of low-order zeros in destination)
* @param cusVal the CachedUrlSet containing the content to be voted on
* @param sVals the starting points chosen by the prover for each block
* @param hashes the hashes of each block
* @param pollID the byte array ID for the poll
* @param voterID the PeerIdentity of the voter
*
*/
public void setupVerification(MemoryBoundFunctionFactory fact,
byte[] nVal,
int eVal,
CachedUrlSet cusVal,
int sVals[][],
byte[][] hashes,
byte[] pollID,
PeerIdentity voterID)
throws MemoryBoundFunctionException {
super.setupVerification(fact, nVal, eVal, cusVal, sVals, hashes,
pollID, voterID);
setup(nVal, eVal, cusVal);
}
private void setup(byte[] nVal, int eVal, CachedUrlSet cusVal) throws
MemoryBoundFunctionException {
finished = false;
}
/**
* Do "n" steps of the underlying hash or effort proof generation
* @param n number of steps to move.
* @return true if there is more work to do
*
*/
public boolean computeSteps(int n) throws MemoryBoundFunctionException {
stepLimit -= n;
if (stepLimit <= 0) {
logger.info("MockMemoryBoundFunctionVote: valid " + valid +
" agreeing " + agreeing);
finished = true;
}
return (!finished);
}
protected void setStepCount(int steps) {
stepLimit = steps;
}
protected void setHashes(byte[][] hshs) {
mockHashes = hshs;
for (int i = 0; i <mockHashes.length; i++)
saveHash(i, mockHashes[i]);
}
protected void setProofs(int[][] prfs) {
mockProofs = prfs;
for (int i = 0; i < mockProofs.length; i++)
saveProof(i , mockProofs[i]);
}
protected void setValid(boolean val) {
valid = val;
}
protected void setAgreeing(boolean val) {
agreeing = val;
}
protected void setFinished(boolean val) {
finished = val;
}
}
| bsd-3-clause |
jonathanihm/freeCodeCamp | curriculum/challenges/russian/01-responsive-web-design/css-flexbox/use-the-order-property-to-rearrange-items.russian.md | 2354 | ---
id: 587d78ae367417b2b2512aff
title: Use the order Property to Rearrange Items
challengeType: 0
videoUrl: https://scrimba.com/p/pVaDAv/cMbvNAG
forumTopicId: 301116
localeTitle: Используйте свойство Order для переупорядочения элементов
---
## Description
<section id='description'>
Свойство <code>order</code> используется для указания CSS порядка отображения элементов гибкости в контейнере flex. По умолчанию элементы будут отображаться в том же порядке, что и исходный HTML-код. Свойство принимает числа как значения, а отрицательные числа могут использоваться.
</section>
## Instructions
<section id='instructions'>
Добавьте <code>order</code> свойств CSS в <code>#box-1</code> и <code>#box-2</code> . Дайте <code>#box-1</code> значение 2 и дайте <code>#box-2</code> значение 1.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: The <code>#box-1</code> element should have the <code>order</code> property set to a value of 2.
testString: assert($('#box-1').css('order') == '2');
- text: The <code>#box-2</code> element should have the <code>order</code> property set to a value of 1.
testString: assert($('#box-2').css('order') == '1');
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='html-seed'>
```html
<style>
#box-container {
display: flex;
height: 500px;
}
#box-1 {
background-color: dodgerblue;
height: 200px;
width: 200px;
}
#box-2 {
background-color: orangered;
height: 200px;
width: 200px;
}
</style>
<div id="box-container">
<div id="box-1"></div>
<div id="box-2"></div>
</div>
```
</div>
</section>
## Solution
<section id='solution'>
```html
<style>
#box-container {
display: flex;
height: 500px;
}
#box-1 {
background-color: dodgerblue;
order: 2;
height: 200px;
width: 200px;
}
#box-2 {
background-color: orangered;
order: 1;
height: 200px;
width: 200px;
}
</style>
<div id="box-container">
<div id="box-1"></div>
<div id="box-2"></div>
</div>
```
</section>
| bsd-3-clause |
tekul/cryptonite | cbits/cryptonite_salsa.c | 8621 | /*
* Copyright (c) 2014-2015 Vincent Hanquez <[email protected]>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
* 3. Neither the name of the author nor the names of his contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 AUTHORS 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.
*/
#include <stdint.h>
#include <string.h>
#include <stdio.h>
#include "cryptonite_salsa.h"
#include "cryptonite_bitfn.h"
#include "cryptonite_align.h"
static const uint8_t sigma[16] = "expand 32-byte k";
static const uint8_t tau[16] = "expand 16-byte k";
#define QR(a,b,c,d) \
b ^= rol32(a+d, 7); \
c ^= rol32(b+a, 9); \
d ^= rol32(c+b, 13); \
a ^= rol32(d+c, 18);
#define ALIGNED64(PTR) \
(((uintptr_t)(const void *)(PTR)) % 8 == 0)
#define SALSA_CORE_LOOP \
for (i = rounds; i > 0; i -= 2) { \
QR (x0,x4,x8,x12); \
QR (x5,x9,x13,x1); \
QR (x10,x14,x2,x6); \
QR (x15,x3,x7,x11); \
QR (x0,x1,x2,x3); \
QR (x5,x6,x7,x4); \
QR (x10,x11,x8,x9); \
QR (x15,x12,x13,x14); \
}
static void salsa_core(int rounds, block *out, const cryptonite_salsa_state *in)
{
uint32_t x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15;
int i;
x0 = in->d[0]; x1 = in->d[1]; x2 = in->d[2]; x3 = in->d[3];
x4 = in->d[4]; x5 = in->d[5]; x6 = in->d[6]; x7 = in->d[7];
x8 = in->d[8]; x9 = in->d[9]; x10 = in->d[10]; x11 = in->d[11];
x12 = in->d[12]; x13 = in->d[13]; x14 = in->d[14]; x15 = in->d[15];
SALSA_CORE_LOOP;
x0 += in->d[0]; x1 += in->d[1]; x2 += in->d[2]; x3 += in->d[3];
x4 += in->d[4]; x5 += in->d[5]; x6 += in->d[6]; x7 += in->d[7];
x8 += in->d[8]; x9 += in->d[9]; x10 += in->d[10]; x11 += in->d[11];
x12 += in->d[12]; x13 += in->d[13]; x14 += in->d[14]; x15 += in->d[15];
out->d[0] = cpu_to_le32(x0);
out->d[1] = cpu_to_le32(x1);
out->d[2] = cpu_to_le32(x2);
out->d[3] = cpu_to_le32(x3);
out->d[4] = cpu_to_le32(x4);
out->d[5] = cpu_to_le32(x5);
out->d[6] = cpu_to_le32(x6);
out->d[7] = cpu_to_le32(x7);
out->d[8] = cpu_to_le32(x8);
out->d[9] = cpu_to_le32(x9);
out->d[10] = cpu_to_le32(x10);
out->d[11] = cpu_to_le32(x11);
out->d[12] = cpu_to_le32(x12);
out->d[13] = cpu_to_le32(x13);
out->d[14] = cpu_to_le32(x14);
out->d[15] = cpu_to_le32(x15);
}
void cryptonite_salsa_core_xor(int rounds, block *out, block *in)
{
uint32_t x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15;
int i;
#define LOAD(i) (out->d[i] ^= in->d[i])
x0 = LOAD(0); x1 = LOAD(1); x2 = LOAD(2); x3 = LOAD(3);
x4 = LOAD(4); x5 = LOAD(5); x6 = LOAD(6); x7 = LOAD(7);
x8 = LOAD(8); x9 = LOAD(9); x10 = LOAD(10); x11 = LOAD(11);
x12 = LOAD(12); x13 = LOAD(13); x14 = LOAD(14); x15 = LOAD(15);
#undef LOAD
SALSA_CORE_LOOP;
out->d[0] += x0; out->d[1] += x1; out->d[2] += x2; out->d[3] += x3;
out->d[4] += x4; out->d[5] += x5; out->d[6] += x6; out->d[7] += x7;
out->d[8] += x8; out->d[9] += x9; out->d[10] += x10; out->d[11] += x11;
out->d[12] += x12; out->d[13] += x13; out->d[14] += x14; out->d[15] += x15;
}
/* only 2 valid values for keylen are 256 (32) and 128 (16) */
void cryptonite_salsa_init_core(cryptonite_salsa_state *st,
uint32_t keylen, const uint8_t *key,
uint32_t ivlen, const uint8_t *iv)
{
const uint8_t *constants = (keylen == 32) ? sigma : tau;
int i;
st->d[0] = load_le32_aligned(constants + 0);
st->d[5] = load_le32_aligned(constants + 4);
st->d[10] = load_le32_aligned(constants + 8);
st->d[15] = load_le32_aligned(constants + 12);
st->d[1] = load_le32(key + 0);
st->d[2] = load_le32(key + 4);
st->d[3] = load_le32(key + 8);
st->d[4] = load_le32(key + 12);
/* we repeat the key on 128 bits */
if (keylen == 32)
key += 16;
st->d[11] = load_le32(key + 0);
st->d[12] = load_le32(key + 4);
st->d[13] = load_le32(key + 8);
st->d[14] = load_le32(key + 12);
st->d[9] = 0;
switch (ivlen) {
case 8:
st->d[6] = load_le32(iv + 0);
st->d[7] = load_le32(iv + 4);
st->d[8] = 0;
break;
case 12:
st->d[6] = load_le32(iv + 0);
st->d[7] = load_le32(iv + 4);
st->d[8] = load_le32(iv + 8);
default:
return;
}
}
void cryptonite_salsa_init(cryptonite_salsa_context *ctx, uint8_t nb_rounds,
uint32_t keylen, const uint8_t *key,
uint32_t ivlen, const uint8_t *iv)
{
memset(ctx, 0, sizeof(*ctx));
ctx->nb_rounds = nb_rounds;
cryptonite_salsa_init_core(&ctx->st, keylen, key, ivlen, iv);
}
void cryptonite_salsa_combine(uint8_t *dst, cryptonite_salsa_context *ctx, const uint8_t *src, uint32_t bytes)
{
block out;
cryptonite_salsa_state *st;
int i;
if (!bytes)
return;
/* xor the previous buffer first (if any) */
if (ctx->prev_len > 0) {
int to_copy = (ctx->prev_len < bytes) ? ctx->prev_len : bytes;
for (i = 0; i < to_copy; i++)
dst[i] = src[i] ^ ctx->prev[ctx->prev_ofs+i];
memset(ctx->prev + ctx->prev_ofs, 0, to_copy);
ctx->prev_len -= to_copy;
ctx->prev_ofs += to_copy;
src += to_copy;
dst += to_copy;
bytes -= to_copy;
}
if (bytes == 0)
return;
st = &ctx->st;
/* xor new 64-bytes chunks and store the left over if any */
for (; bytes >= 64; bytes -= 64, src += 64, dst += 64) {
/* generate new chunk and update state */
salsa_core(ctx->nb_rounds, &out, st);
st->d[8] += 1;
if (st->d[8] == 0)
st->d[9] += 1;
for (i = 0; i < 64; ++i)
dst[i] = src[i] ^ out.b[i];
}
if (bytes > 0) {
/* generate new chunk and update state */
salsa_core(ctx->nb_rounds, &out, st);
st->d[8] += 1;
if (st->d[8] == 0)
st->d[9] += 1;
/* xor as much as needed */
for (i = 0; i < bytes; i++)
dst[i] = src[i] ^ out.b[i];
/* copy the left over in the buffer */
ctx->prev_len = 64 - bytes;
ctx->prev_ofs = i;
for (; i < 64; i++) {
ctx->prev[i] = out.b[i];
}
}
}
void cryptonite_salsa_generate(uint8_t *dst, cryptonite_salsa_context *ctx, uint32_t bytes)
{
cryptonite_salsa_state *st;
block out;
int i;
if (!bytes)
return;
/* xor the previous buffer first (if any) */
if (ctx->prev_len > 0) {
int to_copy = (ctx->prev_len < bytes) ? ctx->prev_len : bytes;
for (i = 0; i < to_copy; i++)
dst[i] = ctx->prev[ctx->prev_ofs+i];
memset(ctx->prev + ctx->prev_ofs, 0, to_copy);
ctx->prev_len -= to_copy;
ctx->prev_ofs += to_copy;
dst += to_copy;
bytes -= to_copy;
}
if (bytes == 0)
return;
st = &ctx->st;
if (ALIGNED64(dst)) {
/* xor new 64-bytes chunks and store the left over if any */
for (; bytes >= 64; bytes -= 64, dst += 64) {
/* generate new chunk and update state */
salsa_core(ctx->nb_rounds, (block *) dst, st);
st->d[8] += 1;
if (st->d[8] == 0)
st->d[9] += 1;
}
} else {
/* xor new 64-bytes chunks and store the left over if any */
for (; bytes >= 64; bytes -= 64, dst += 64) {
/* generate new chunk and update state */
salsa_core(ctx->nb_rounds, &out, st);
st->d[8] += 1;
if (st->d[8] == 0)
st->d[9] += 1;
for (i = 0; i < 64; ++i)
dst[i] = out.b[i];
}
}
if (bytes > 0) {
/* generate new chunk and update state */
salsa_core(ctx->nb_rounds, &out, st);
st->d[8] += 1;
if (st->d[8] == 0)
st->d[9] += 1;
/* xor as much as needed */
for (i = 0; i < bytes; i++)
dst[i] = out.b[i];
/* copy the left over in the buffer */
ctx->prev_len = 64 - bytes;
ctx->prev_ofs = i;
for (; i < 64; i++)
ctx->prev[i] = out.b[i];
}
}
| bsd-3-clause |
Hackplayers/Empire-mod-Hpys-tests | lib/modules/powershell/collection/vaults/get_keepass_config_trigger.py | 3104 | from lib.common import helpers
class Module:
def __init__(self, mainMenu, params=[]):
# metadata info about the module, not modified during runtime
self.info = {
# name for the module that will appear in module menus
'Name': 'Get-KeePassconfig',
# list of one or more authors for the module
'Author': ['@tifkin_', '@harmj0y'],
# more verbose multi-line description of the module
'Description': ('This module extracts out the trigger specifications from a KeePass 2.X configuration XML file.'),
# True if the module needs to run in the background
'Background' : True,
# File extension to save the file as
'OutputExtension' : '',
# True if the module needs admin rights to run
'NeedsAdmin' : False,
# True if the method doesn't touch disk/is reasonably opsec safe
'OpsecSafe' : True,
'Language' : 'powershell',
'MinLanguageVersion' : '2',
# list of any references/other comments
'Comments': [
'https://github.com/adaptivethreat/KeeThief'
]
}
# any options needed by the module, settable during runtime
self.options = {
# format:
# value_name : {description, required, default_value}
'Agent' : {
# The 'Agent' option is the only one that MUST be in a module
'Description' : 'Agent to run the module on.',
'Required' : True,
'Value' : ''
}
}
# save off a copy of the mainMenu object to access external functionality
# like listeners/agent handlers/etc.
self.mainMenu = mainMenu
# During instantiation, any settable option parameters
# are passed as an object set to the module and the
# options dictionary is automatically set. This is mostly
# in case options are passed on the command line
if params:
for param in params:
# parameter format is [Name, Value]
option, value = param
if option in self.options:
self.options[option]['Value'] = value
def generate(self):
moduleName = self.info["Name"]
# read in the common powerview.ps1 module source code
moduleSource = self.mainMenu.installPath + "/data/module_source/collection/vaults/KeePassConfig.ps1"
try:
f = open(moduleSource, 'r')
except:
print helpers.color("[!] Could not read module source path at: " + str(moduleSource))
return ""
moduleCode = f.read()
f.close()
# get just the code needed for the specified function
script = moduleCode
script += "\nFind-KeePassconfig | Get-KeePassConfigTrigger "
script += ' | Format-List | Out-String | %{$_ + \"`n\"};"`n'+str(moduleName)+' completed!"'
return script
| bsd-3-clause |
gpedro/joy | config/adapters.js | 1463 | /**
* Global adapter config
*
* The `adapters` configuration object lets you create different global "saved settings"
* that you can mix and match in your models. The `default` option indicates which
* "saved setting" should be used if a model doesn't have an adapter specified.
*
* Keep in mind that options you define directly in your model definitions
* will override these settings.
*
* For more information on adapter configuration, check out:
* http://sailsjs.org/#documentation
*/
module.exports.adapters = {
// If you leave the adapter config unspecified
// in a model definition, 'default' will be used.
'default': 'mongo',
// Persistent adapter for DEVELOPMENT ONLY
// (data is preserved when the server shuts down)
disk: {
module: 'sails-disk'
},
mongo: {
module: 'sails-mongo',
url: process.env.MONGOLAB_URI || process.env.MONGOHQ_URL || 'mongodb://localhost/joydb'
},
// MySQL is the world's most popular relational database.
// Learn more: http://en.wikipedia.org/wiki/MySQL
myLocalMySQLDatabase: {
module: 'sails-mysql',
host: 'YOUR_MYSQL_SERVER_HOSTNAME_OR_IP_ADDRESS',
user: 'YOUR_MYSQL_USER',
// Psst.. You can put your password in config/local.js instead
// so you don't inadvertently push it up if you're using version control
password: 'YOUR_MYSQL_PASSWORD',
database: 'YOUR_MYSQL_DB'
}
};
| bsd-3-clause |
201528013359030/basic_pai | views/js/easyzoom.js | 8461 | (function ($) {
'use strict';
var dw, dh, rw, rh, lx, ly;
var defaults = {
// The text to display within the notice box while loading the zoom image.
loadingNotice: 'Loading image',
// The text to display within the notice box if an error occurs when loading the zoom image.
errorNotice: 'The image could not be loaded',
// The time (in milliseconds) to display the error notice.
errorDuration: 2500,
// Attribute to retrieve the zoom image URL from.
linkAttribute: 'href',
// Prevent clicks on the zoom image link.
preventClicks: true,
// Callback function to execute before the flyout is displayed.
beforeShow: $.noop,
// Callback function to execute before the flyout is removed.
beforeHide: $.noop,
// Callback function to execute when the flyout is displayed.
onShow: $.noop,
// Callback function to execute when the flyout is removed.
onHide: $.noop,
// Callback function to execute when the cursor is moved while over the image.
onMove: $.noop
};
/**
* EasyZoom
* @constructor
* @param {Object} target
* @param {Object} options (Optional)
*/
function EasyZoom(target, options) {
this.$target = $(target);
this.opts = $.extend({}, defaults, options, this.$target.data());
this.isOpen === undefined && this._init();
}
/**
* Init
* @private
*/
EasyZoom.prototype._init = function() {
this.$link = this.$target.find('a');
this.$image = this.$target.find('img');
this.$flyout = $('<div class="easyzoom-flyout" />');
this.$notice = $('<div class="easyzoom-notice" />');
this.$target.on({
'mousemove.easyzoom touchmove.easyzoom': $.proxy(this._onMove, this),
'mouseleave.easyzoom touchend.easyzoom': $.proxy(this._onLeave, this),
'mouseenter.easyzoom touchstart.easyzoom': $.proxy(this._onEnter, this)
});
this.opts.preventClicks && this.$target.on('click.easyzoom', function(e) {
e.preventDefault();
});
};
/**
* Show
* @param {MouseEvent|TouchEvent} e
* @param {Boolean} testMouseOver (Optional)
*/
EasyZoom.prototype.show = function(e, testMouseOver) {
var w1, h1, w2, h2;
var self = this;
if (this.opts.beforeShow.call(this) === false) return;
if (!this.isReady) {
return this._loadImage(this.$link.attr(this.opts.linkAttribute), function() {
if (self.isMouseOver || !testMouseOver) {
self.show(e);
}
});
}
this.$target.append(this.$flyout);
w1 = this.$target.width();
h1 = this.$target.height();
w2 = this.$flyout.width();
h2 = this.$flyout.height();
dw = this.$zoom.width() - w2;
dh = this.$zoom.height() - h2;
// For the case where the zoom image is actually smaller than
// the flyout.
if (dw < 0) dw = 0;
if (dh < 0) dh = 0;
rw = dw / w1;
rh = dh / h1;
this.isOpen = true;
this.opts.onShow.call(this);
e && this._move(e);
};
/**
* On enter
* @private
* @param {Event} e
*/
EasyZoom.prototype._onEnter = function(e) {
var touches = e.originalEvent.touches;
this.isMouseOver = true;
if (!touches || touches.length == 1) {
e.preventDefault();
this.show(e, true);
}
};
/**
* On move
* @private
* @param {Event} e
*/
EasyZoom.prototype._onMove = function(e) {
if (!this.isOpen) return;
e.preventDefault();
this._move(e);
};
/**
* On leave
* @private
*/
EasyZoom.prototype._onLeave = function() {
this.isMouseOver = false;
this.isOpen && this.hide();
};
/**
* On load
* @private
* @param {Event} e
*/
EasyZoom.prototype._onLoad = function(e) {
// IE may fire a load event even on error so test the image dimensions
if (!e.currentTarget.width) return;
this.isReady = true;
this.$notice.detach();
this.$flyout.html(this.$zoom);
this.$target.removeClass('is-loading').addClass('is-ready');
e.data.call && e.data();
};
/**
* On error
* @private
*/
EasyZoom.prototype._onError = function() {
var self = this;
this.$notice.text(this.opts.errorNotice);
this.$target.removeClass('is-loading').addClass('is-error');
this.detachNotice = setTimeout(function() {
self.$notice.detach();
self.detachNotice = null;
}, this.opts.errorDuration);
};
/**
* Load image
* @private
* @param {String} href
* @param {Function} callback
*/
EasyZoom.prototype._loadImage = function(href, callback) {
var zoom = new Image;
this.$target
.addClass('is-loading')
.append(this.$notice.text(this.opts.loadingNotice));
this.$zoom = $(zoom)
.on('error', $.proxy(this._onError, this))
.on('load', callback, $.proxy(this._onLoad, this));
zoom.style.position = 'absolute';
zoom.src = href;
};
/**
* Move
* @private
* @param {Event} e
*/
EasyZoom.prototype._move = function(e) {
if (e.type.indexOf('touch') === 0) {
var touchlist = e.touches || e.originalEvent.touches;
lx = touchlist[0].pageX;
ly = touchlist[0].pageY;
} else {
lx = e.pageX || lx;
ly = e.pageY || ly;
}
var offset = this.$target.offset();
var pt = ly - offset.top;
var pl = lx - offset.left;
var xt = Math.ceil(pt * rh);
var xl = Math.ceil(pl * rw);
// Close if outside
if (xl < 0 || xt < 0 || xl > dw || xt > dh) {
this.hide();
} else {
var top = xt * -1;
var left = xl * -1;
this.$zoom.css({
top: top,
left: left
});
this.opts.onMove.call(this, top, left);
}
};
/**
* Hide
*/
EasyZoom.prototype.hide = function() {
if (!this.isOpen) return;
if (this.opts.beforeHide.call(this) === false) return;
this.$flyout.detach();
this.isOpen = false;
this.opts.onHide.call(this);
};
/**
* Swap
* @param {String} standardSrc
* @param {String} zoomHref
* @param {String|Array} srcset (Optional)
*/
EasyZoom.prototype.swap = function(standardSrc, zoomHref, srcset) {
this.hide();
this.isReady = false;
this.detachNotice && clearTimeout(this.detachNotice);
this.$notice.parent().length && this.$notice.detach();
this.$target.removeClass('is-loading is-ready is-error');
this.$image.attr({
src: standardSrc,
srcset: $.isArray(srcset) ? srcset.join() : srcset
});
this.$link.attr(this.opts.linkAttribute, zoomHref);
};
/**
* Teardown
*/
EasyZoom.prototype.teardown = function() {
this.hide();
this.$target
.off('.easyzoom')
.removeClass('is-loading is-ready is-error');
this.detachNotice && clearTimeout(this.detachNotice);
delete this.$link;
delete this.$zoom;
delete this.$image;
delete this.$notice;
delete this.$flyout;
delete this.isOpen;
delete this.isReady;
};
// jQuery plugin wrapper
$.fn.easyZoom = function(options) {
return this.each(function() {
var api = $.data(this, 'easyZoom');
if (!api) {
$.data(this, 'easyZoom', new EasyZoom(this, options));
} else if (api.isOpen === undefined) {
api._init();
}
});
};
// AMD and CommonJS module compatibility
if (typeof define === 'function' && define.amd){
define(function() {
return EasyZoom;
});
} else if (typeof module !== 'undefined' && module.exports) {
module.exports = EasyZoom;
}
})(jQuery);
| bsd-3-clause |
bpsinc-native/src_third_party_chromite | lib/binpkg.py | 12642 | # Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
#
# Adapted from portage/getbinpkg.py -- Portage binary-package helper functions
# Copyright 2003-2004 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2
"""Helpers dealing with binpkg Packages index files"""
import collections
import cStringIO
import operator
import os
import tempfile
import time
import urllib2
from chromite.lib import cros_build_lib
from chromite.lib import gs
from chromite.lib import parallel
TWO_WEEKS = 60 * 60 * 24 * 7 * 2
HTTP_FORBIDDEN_CODES = (401, 403)
HTTP_NOT_FOUND_CODES = (404, 410)
_Package = collections.namedtuple('_Package', ['mtime', 'uri'])
class PackageIndex(object):
"""A parser for the Portage Packages index file.
The Portage Packages index file serves to keep track of what packages are
included in a tree. It contains the following sections:
1) The header. The header tracks general key/value pairs that don't apply
to any specific package. E.g., it tracks the base URL of the packages
file, and the number of packages included in the file. The header is
terminated by a blank line.
2) The body. The body is a list of packages. Each package contains a list
of key/value pairs. Packages are either terminated by a blank line or
by the end of the file. Every package has a CPV entry, which serves as
a unique identifier for the package.
"""
def __init__(self):
"""Constructor."""
# The header tracks general key/value pairs that don't apply to any
# specific package. E.g., it tracks the base URL of the packages.
self.header = {}
# A list of packages (stored as a list of dictionaries).
self.packages = []
# Whether or not the PackageIndex has been modified since the last time it
# was written.
self.modified = False
def _PopulateDuplicateDB(self, db, expires):
"""Populate db with SHA1 -> URL mapping for packages.
Args:
db: Dictionary to populate with SHA1 -> URL mapping for packages.
expires: The time at which prebuilts expire from the binhost.
"""
uri = gs.CanonicalizeURL(self.header['URI'])
for pkg in self.packages:
cpv, sha1, mtime = pkg['CPV'], pkg.get('SHA1'), pkg.get('MTIME')
oldpkg = db.get(sha1, _Package(0, None))
if sha1 and mtime and int(mtime) > max(expires, oldpkg.mtime):
path = pkg.get('PATH', cpv + '.tbz2')
db[sha1] = _Package(int(mtime), '%s/%s' % (uri.rstrip('/'), path))
def _ReadPkgIndex(self, pkgfile):
"""Read a list of key/value pairs from the Packages file into a dictionary.
Both header entries and package entries are lists of key/value pairs, so
they can both be read by this function. Entries can be terminated by empty
lines or by the end of the file.
This function will read lines from the specified file until it encounters
the a blank line or the end of the file.
Keys and values in the Packages file are separated by a colon and a space.
Keys may contain capital letters, numbers, and underscores, but may not
contain colons. Values may contain any character except a newline. In
particular, it is normal for values to contain colons.
Lines that have content, and do not contain a valid key/value pair, are
ignored. This is for compatibility with the Portage package parser, and
to allow for future extensions to the Packages file format.
All entries must contain at least one key/value pair. If the end of the
fils is reached, an empty dictionary is returned.
Args:
pkgfile: A python file object.
Returns:
The dictionary of key-value pairs that was read from the file.
"""
d = {}
for line in pkgfile:
line = line.rstrip('\n')
if not line:
assert d, 'Packages entry must contain at least one key/value pair'
break
line = line.split(': ', 1)
if len(line) == 2:
k, v = line
d[k] = v
return d
def _WritePkgIndex(self, pkgfile, entry):
"""Write header entry or package entry to packages file.
The keys and values will be separated by a colon and a space. The entry
will be terminated by a blank line.
Args:
pkgfile: A python file object.
entry: A dictionary of the key/value pairs to write.
"""
lines = ['%s: %s' % (k, v) for k, v in sorted(entry.items()) if v]
pkgfile.write('%s\n\n' % '\n'.join(lines))
def _ReadHeader(self, pkgfile):
"""Read header of packages file.
Args:
pkgfile: A python file object.
"""
assert not self.header, 'Should only read header once.'
self.header = self._ReadPkgIndex(pkgfile)
def _ReadBody(self, pkgfile):
"""Read body of packages file.
Before calling this function, you must first read the header (using
_ReadHeader).
Args:
pkgfile: A python file object.
"""
assert self.header, 'Should read header first.'
assert not self.packages, 'Should only read body once.'
# Read all of the sections in the body by looping until we reach the end
# of the file.
while True:
d = self._ReadPkgIndex(pkgfile)
if not d:
break
if 'CPV' in d:
self.packages.append(d)
def Read(self, pkgfile):
"""Read the entire packages file.
Args:
pkgfile: A python file object.
"""
self._ReadHeader(pkgfile)
self._ReadBody(pkgfile)
def RemoveFilteredPackages(self, filter_fn):
"""Remove packages which match filter_fn.
Args:
filter_fn: A function which operates on packages. If it returns True,
the package should be removed.
"""
filtered = [p for p in self.packages if not filter_fn(p)]
if filtered != self.packages:
self.modified = True
self.packages = filtered
def ResolveDuplicateUploads(self, pkgindexes):
"""Point packages at files that have already been uploaded.
For each package in our index, check if there is an existing package that
has already been uploaded to the same base URI, and that is no older than
two weeks. If so, point that package at the existing file, so that we don't
have to upload the file.
Args:
pkgindexes: A list of PackageIndex objects containing info about packages
that have already been uploaded.
Returns:
A list of the packages that still need to be uploaded.
"""
db = {}
now = int(time.time())
expires = now - TWO_WEEKS
base_uri = gs.CanonicalizeURL(self.header['URI'])
for pkgindex in pkgindexes:
if gs.CanonicalizeURL(pkgindex.header['URI']) == base_uri:
# pylint: disable=W0212
pkgindex._PopulateDuplicateDB(db, expires)
uploads = []
base_uri = self.header['URI']
for pkg in self.packages:
sha1 = pkg.get('SHA1')
dup = db.get(sha1)
if sha1 and dup and dup.uri.startswith(base_uri):
pkg['PATH'] = dup.uri[len(base_uri):].lstrip('/')
pkg['MTIME'] = str(dup.mtime)
else:
pkg['MTIME'] = str(now)
uploads.append(pkg)
return uploads
def SetUploadLocation(self, base_uri, path_prefix):
"""Set upload location to base_uri + path_prefix.
Args:
base_uri: Base URI for all packages in the file. We set
self.header['URI'] to this value, so all packages must live under
this directory.
path_prefix: Path prefix to use for all current packages in the file.
This will be added to the beginning of the path for every package.
"""
self.header['URI'] = base_uri
for pkg in self.packages:
path = pkg['CPV'] + '.tbz2'
pkg['PATH'] = '%s/%s' % (path_prefix.rstrip('/'), path)
def Write(self, pkgfile):
"""Write a packages file to disk.
If 'modified' flag is set, the TIMESTAMP and PACKAGES fields in the header
will be updated before writing to disk.
Args:
pkgfile: A python file object.
"""
if self.modified:
self.header['TIMESTAMP'] = str(long(time.time()))
self.header['PACKAGES'] = str(len(self.packages))
self.modified = False
self._WritePkgIndex(pkgfile, self.header)
for metadata in sorted(self.packages, key=operator.itemgetter('CPV')):
self._WritePkgIndex(pkgfile, metadata)
def WriteToNamedTemporaryFile(self):
"""Write pkgindex to a temporary file.
Args:
pkgindex: The PackageIndex object.
Returns:
A temporary file containing the packages from pkgindex.
"""
f = tempfile.NamedTemporaryFile(prefix='chromite.binpkg.pkgidx.')
self.Write(f)
f.flush()
f.seek(0)
return f
def _RetryUrlOpen(url, tries=3):
"""Open the specified url, retrying if we run into temporary errors.
We retry for both network errors and 5xx Server Errors. We do not retry
for HTTP errors with a non-5xx code.
Args:
url: The specified url.
tries: The number of times to try.
Returns:
The result of urllib2.urlopen(url).
"""
for i in range(tries):
try:
return urllib2.urlopen(url)
except urllib2.HTTPError as e:
if i + 1 >= tries or e.code < 500:
e.msg += ('\nwhile processing %s' % url)
raise
else:
print 'Cannot GET %s: %s' % (url, str(e))
except urllib2.URLError as e:
if i + 1 >= tries:
raise
else:
print 'Cannot GET %s: %s' % (url, str(e))
print 'Sleeping for 10 seconds before retrying...'
time.sleep(10)
def GrabRemotePackageIndex(binhost_url):
"""Grab the latest binary package database from the specified URL.
Args:
binhost_url: Base URL of remote packages (PORTAGE_BINHOST).
Returns:
A PackageIndex object, if the Packages file can be retrieved. If the
packages file cannot be retrieved, then None is returned.
"""
url = '%s/Packages' % binhost_url.rstrip('/')
pkgindex = PackageIndex()
if binhost_url.startswith('http'):
try:
f = _RetryUrlOpen(url)
except urllib2.HTTPError as e:
if e.code in HTTP_FORBIDDEN_CODES:
cros_build_lib.PrintBuildbotStepWarnings()
cros_build_lib.Error('Cannot GET %s: %s' % (url, str(e)))
return None
# Not found errors are normal if old prebuilts were cleaned out.
if e.code in HTTP_NOT_FOUND_CODES:
return None
raise
elif binhost_url.startswith('gs://'):
try:
gs_context = gs.GSContext()
output = gs_context.Cat(url).output
except (cros_build_lib.RunCommandError, gs.GSNoSuchKey) as e:
cros_build_lib.PrintBuildbotStepWarnings()
cros_build_lib.Error('Cannot GET %s: %s' % (url, str(e)))
return None
f = cStringIO.StringIO(output)
else:
return None
pkgindex.Read(f)
pkgindex.header.setdefault('URI', binhost_url)
f.close()
return pkgindex
def GrabLocalPackageIndex(package_path):
"""Read a local packages file from disk into a PackageIndex() object.
Args:
package_path: Directory containing Packages file.
Returns:
A PackageIndex object.
"""
packages_file = file(os.path.join(package_path, 'Packages'))
pkgindex = PackageIndex()
pkgindex.Read(packages_file)
packages_file.close()
return pkgindex
def _DownloadURLs(urls, dest_dir):
"""Copy URLs into the specified |dest_dir|.
Args:
urls: List of URLs to fetch.
dest_dir: Destination directory.
"""
gs_ctx = gs.GSContext()
cmd = ['cp'] + urls + [dest_dir]
gs_ctx.DoCommand(cmd, parallel=len(urls) > 1)
def FetchTarballs(binhost_urls, pkgdir):
"""Prefetch the specified |binhost_urls| to the specified |pkgdir|.
This function fetches the tarballs from the specified list of binhost
URLs to disk. It does not populate the Packages file -- we leave that
to Portage.
Args:
binhost_urls: List of binhost URLs to fetch.
pkgdir: Location to store the fetched packages.
"""
categories = {}
for binhost_url in binhost_urls:
pkgindex = GrabRemotePackageIndex(binhost_url)
base_uri = pkgindex.header['URI']
for pkg in pkgindex.packages:
cpv = pkg['CPV']
path = pkg.get('PATH', '%s.tbz2' % cpv)
uri = '/'.join([base_uri, path])
category = cpv.partition('/')[0]
fetches = categories.setdefault(category, {})
fetches[cpv] = uri
with parallel.BackgroundTaskRunner(_DownloadURLs) as queue:
for category, urls in categories.iteritems():
category_dir = os.path.join(pkgdir, category)
if not os.path.exists(category_dir):
os.makedirs(category_dir)
queue.put((urls.values(), category_dir))
| bsd-3-clause |
JianpingZeng/xcc | xcc/test/juliet/testcases/CWE122_Heap_Based_Buffer_Overflow/s02/CWE122_Heap_Based_Buffer_Overflow__cpp_CWE193_wchar_t_cpy_32.cpp | 3124 | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE193_wchar_t_cpy_32.cpp
Label Definition File: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE193.label.xml
Template File: sources-sink-32.tmpl.cpp
*/
/*
* @description
* CWE: 122 Heap Based Buffer Overflow
* BadSource: Allocate memory for a string, but do not allocate space for NULL terminator
* GoodSource: Allocate enough memory for a string and the NULL terminator
* Sink: cpy
* BadSink : Copy string to data using wcscpy()
* Flow Variant: 32 Data flow using two pointers to the same value within the same function
*
* */
#include "std_testcase.h"
#ifndef _WIN32
#include <wchar.h>
#endif
/* MAINTENANCE NOTE: The length of this string should equal the 10 */
#define SRC_STRING L"AAAAAAAAAA"
namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE193_wchar_t_cpy_32
{
#ifndef OMITBAD
void bad()
{
wchar_t * data;
wchar_t * *dataPtr1 = &data;
wchar_t * *dataPtr2 = &data;
data = NULL;
{
wchar_t * data = *dataPtr1;
/* FLAW: Did not leave space for a null terminator */
data = new wchar_t[10];
*dataPtr1 = data;
}
{
wchar_t * data = *dataPtr2;
{
wchar_t source[10+1] = SRC_STRING;
/* POTENTIAL FLAW: data may not have enough space to hold source */
wcscpy(data, source);
printWLine(data);
delete [] data;
}
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B() uses the GoodSource with the BadSink */
static void goodG2B()
{
wchar_t * data;
wchar_t * *dataPtr1 = &data;
wchar_t * *dataPtr2 = &data;
data = NULL;
{
wchar_t * data = *dataPtr1;
/* FIX: Allocate space for a null terminator */
data = new wchar_t[10+1];
*dataPtr1 = data;
}
{
wchar_t * data = *dataPtr2;
{
wchar_t source[10+1] = SRC_STRING;
/* POTENTIAL FLAW: data may not have enough space to hold source */
wcscpy(data, source);
printWLine(data);
delete [] data;
}
}
}
void good()
{
goodG2B();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE193_wchar_t_cpy_32; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| bsd-3-clause |
agungsijawir/yii2 | docs/guide-ja/db-migrations.md | 49975 | データベース・マイグレーション
============================
データベース駆動型のアプリケーションを開発し保守する途上で、ソース・コードが進化するのと同じように、使用されるデータベースの構造も進化していきます。
例えば、アプリケーションの開発中に、新しいテーブルが必要であることが分ったり、アプリケーションを配備した後に、クエリのパフォーマンスを向上させるためにインデックスを作成すべきことが発見されたりします。
データベースの構造の変更が何らかのソース・コードの変更を要求する場合はよくありますから、Yii はいわゆる *データベース・マイグレーション* 機能を提供して、ソース・コードとともにバージョン管理される *データベース・マイグレーション* の形式でデータベースの変更を追跡できるようにしています。
下記の一連のステップは、開発中にチームによってデータベース・マイグレーションがどのように使用されるかを示す例です。
1. Tim が新しいマイグレーション (例えば、新しいテーブルを作成したり、カラムの定義を変更したりなど) を作る。
2. Tim が新しいマイグレーションをソース・コントロール・システム (例えば Git や Mercurial) にコミットする。
3. Doug がソース・コントロール・システムから自分のレポジトリを更新して新しいマイグレーションを受け取る。
4. Doug がマイグレーションを彼のローカルの開発用データベースに適用して、自分のデータベースの同期を取り、Tim が行った変更を反映する。
そして、次の一連のステップは、本番環境でデータベース・マイグレーションとともに新しいリリースを配備する方法を示すものです。
1. Scott は新しいデータベース・マイグレーションをいくつか含むプロジェクトのレポジトリにリリース・タグを作成する。
2. Scott は本番サーバでソース・コードをリリース・タグまで更新する。
3. Scott は本番のデータベースに対して累積したデータベース・マイグレーションを全て適用する。
Yii は一連のマイグレーション・コマンドライン・ツールを提供して、以下の機能をサポートします。
* 新しいマイグレーションの作成
* マイグレーションの適用
* マイグレーションの取消
* マイグレーションの再適用
* マイグレーションの履歴と状態の表示
これらのツールは、全て、`yii migrate` コマンドからアクセスすることが出来ます。
このセクションでは、これらのツールを使用して、さまざまなタスクをどうやって達成するかを詳細に説明します。
各ツールの使用方法は、ヘルプコマンド `yii help migrate` によっても知ることが出来ます。
> Tip: マイグレーションはデータベース・スキーマに影響を及ぼすだけでなく、既存のデータを新しいスキーマに合うように修正したり、RBAC 階層を作成したり、
キャッシュをクリーンアップしたりするために使うことも出来ます。
## マイグレーションを作成する <span id="creating-migrations"></span>
新しいマイグレーションを作成するためには、次のコマンドを実行します。
```
yii migrate/create <name>
```
要求される `name` パラメータには、マイグレーションの非常に短い説明を指定します。
例えば、マイグレーションが *news* という名前のテーブルを作成するものである場合は、`create_news_table` という名前を使って、次のようにコマンドを実行すれば良いでしょう。
```
yii migrate/create create_news_table
```
> Note: この `name` 引数は、生成されるマイグレーション・クラス名の一部として使用されますので、アルファベット、数字、および/または、アンダースコアだけを含むものでなければなりません。
上記のコマンドは、`m150101_185401_create_news_table.php` という名前の新しい PHP クラス・ファイルを `@app/migrations` ディレクトリに作成します。
このファイルは次のようなコードを含み、主として、スケルトン・コードを持った `m150101_185401_create_news_table` というマイグレーション・クラスを宣言するためのものす。
```php
<?php
use yii\db\Migration;
class m150101_185401_create_news_table extends Migration
{
public function up()
{
}
public function down()
{
echo "m101129_185401_create_news_table cannot be reverted.\n";
return false;
}
/*
// Use safeUp/safeDown to run migration code within a transaction
public function safeUp()
{
}
public function safeDown()
{
}
*/
}
```
各データベース・マイグレーションは [[yii\db\Migration]] から拡張した PHP クラスとして定義されます。
マイグレーション・クラスの名前は、`m<YYMMDD_HHMMSS>_<Name>` という形式で自動的に生成されます。
ここで、
* `<YYMMDD_HHMMSS>` は、マイグレーション作成コマンドが実行された UTC 日時を表し、
* `<Name>` は、あなたがコマンドに与えた `name` 引数と同じ値になります。
マイグレーション・クラスにおいて、あなたがなすべき事は、データベースの構造に変更を加える `up()` メソッドにコードを書くことです。
また、`up()` によって加えられた変更を取り消すための `down()` メソッドにも、コードを書きたいと思うかもしれません。
`up()` メソッドは、このマイグレーションによってデータベースをアップグレードする際に呼び出され、`down()` メソッドはデータベースをダウングレードする際に呼び出されます。
下記のコードは、新しい `news` テーブルを作成するマイグレーション・クラスをどのようにして実装するかを示すものです。
```php
<?php
use yii\db\Schema;
use yii\db\Migration;
class m150101_185401_create_news_table extends Migration
{
public function up()
{
$this->createTable('news', [
'id' => Schema::TYPE_PK,
'title' => Schema::TYPE_STRING . ' NOT NULL',
'content' => Schema::TYPE_TEXT,
]);
}
public function down()
{
$this->dropTable('news');
}
}
```
> Info: 全てのマイグレーションが取り消し可能な訳ではありません。
例えば、`up()` メソッドがテーブルからある行を削除するものである場合、`down()` メソッドでその行を回復することは出来ません。
また、データベース・マイグレーションを取り消すことはあまり一般的ではありませんので、場合によっては、面倒くさいというだけの理由で `down()` を実装しないこともあるでしょう。
そういう場合は、マイグレーションが取り消し不可能であることを示すために、`down()` メソッドで false を返さなければなりません。
基底のマイグレーション・クラス [[yii\db\Migration]] は、[[yii\db\Migration::db|db]] プロパティによって、データベース接続にアクセスすることを可能にしています。
このデータベース接続によって、[データベース・スキーマを扱う](db-dao.md#database-schema) で説明されているメソッドを使い、データベース・スキーマを操作することが出来ます。
テーブルやカラムを作成するときは、物理的な型を使うのでなく、*抽象型* を使って、あなたのマイグレーションが特定の DBMS に依存しないようにします。
[[yii\db\Schema]] クラスが、サポートされている抽象型を表す一連の定数を定義しています。
これらの定数は `TYPE_<Name>` という形式の名前を持っています。
例えば、`TYPE_PK` は、オート・インクリメントのプライマリ・キー型であり、`TYPE_STRING` は文字列型です。
これらの抽象型は、マイグレーションが特定のデータベースに適用されるときに、対応する物理型に翻訳されます。
MySQL の場合は、`TYPE_PK` は `int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY` に変換され、`TYPE_STRING` は `varchar(255)` となります。
抽象型を使用するときに、付随的な制約を追加することが出来ます。
上記の例では、`Schema::TYPE_STRING` に ` NOT NULL` を追加して、このカラムが null を許容しないことを指定しています。
> Info: 抽象型と物理型の対応関係は、それぞれの `QueryBuilder` の具象クラスの [[yii\db\QueryBuilder::$typeMap|$typeMap]] プロパティによって定義されています。
バージョン 2.0.6 以降は、カラムのスキーマを定義するための更に便利な方法を提供するスキーマビルダが新たに導入されています。
したがって、上記のマイグレーションは次のように書くことが出来ます。
```php
<?php
use yii\db\Migration;
class m150101_185401_create_news_table extends Migration
{
public function up()
{
$this->createTable('news', [
'id' => $this->primaryKey(),
'title' => $this->string()->notNull(),
'content' => $this->text(),
]);
}
public function down()
{
$this->dropTable('news');
}
}
```
カラムの型を定義するために利用できる全てのメソッドのリストは、[[yii\db\SchemaBuilderTrait]] の API ドキュメントで参照することが出来ます。
## マイグレーションを生成する <span id="generating-migrations"></span>
バージョン 2.0.7 以降では、マイグレーション・コンソールがマイグレーションを生成する便利な方法を提供しています。
マイグレーションの名前が特別な形式である場合は、生成されるマイグレーション・ファイルに追加のコードが書き込まれます。
例えば、`create_xxx_table` や `drop_xxx_table` であれば、テーブルの作成や削除をするコードが追加されます。
以下で、この機能の全ての変種を説明します。
### テーブルの作成
```
yii migrate/create create_post_table
```
上記のコマンドは、次のコードを生成します。
```php
/**
* Handles the creation for table `post`.
*/
class m150811_220037_create_post_table extends Migration
{
/**
* {@inheritdoc}
*/
public function up()
{
$this->createTable('post', [
'id' => $this->primaryKey()
]);
}
/**
* {@inheritdoc}
*/
public function down()
{
$this->dropTable('post');
}
}
```
テーブルのフィールドも直接に生成したい場合は、`--fields` オプションでフィールドを指定します。
```
yii migrate/create create_post_table --fields="title:string,body:text"
```
これは、次のコードを生成します。
```php
/**
* Handles the creation for table `post`.
*/
class m150811_220037_create_post_table extends Migration
{
/**
* {@inheritdoc}
*/
public function up()
{
$this->createTable('post', [
'id' => $this->primaryKey(),
'title' => $this->string(),
'body' => $this->text(),
]);
}
/**
* {@inheritdoc}
*/
public function down()
{
$this->dropTable('post');
}
}
```
さらに多くのフィールド・パラメータを指定することも出来ます。
```
yii migrate/create create_post_table --fields="title:string(12):notNull:unique,body:text"
```
これは、次のコードを生成します。
```php
/**
* Handles the creation for table `post`.
*/
class m150811_220037_create_post_table extends Migration
{
/**
* {@inheritdoc}
*/
public function up()
{
$this->createTable('post', [
'id' => $this->primaryKey(),
'title' => $this->string(12)->notNull()->unique(),
'body' => $this->text()
]);
}
/**
* {@inheritdoc}
*/
public function down()
{
$this->dropTable('post');
}
}
```
> Note: プライマリ・キーが自動的に追加されて、デフォルトでは `id` と名付けられます。
> 別の名前を使いたい場合は、`--fields="name:primaryKey"` のように、明示的に指定してください。
#### 外部キー
バージョン 2.0.8 からは、`foreignKey` キーワードを使って外部キーを生成することができます。
```
yii migrate/create create_post_table --fields="author_id:integer:notNull:foreignKey(user),category_id:integer:defaultValue(1):foreignKey,title:string,body:text"
```
これは、次のコードを生成します。
```php
/**
* Handles the creation for table `post`.
* Has foreign keys to the tables:
*
* - `user`
* - `category`
*/
class m160328_040430_create_post_table extends Migration
{
/**
* {@inheritdoc}
*/
public function up()
{
$this->createTable('post', [
'id' => $this->primaryKey(),
'author_id' => $this->integer()->notNull(),
'category_id' => $this->integer()->defaultValue(1),
'title' => $this->string(),
'body' => $this->text(),
]);
// creates index for column `author_id`
$this->createIndex(
'idx-post-author_id',
'post',
'author_id'
);
// add foreign key for table `user`
$this->addForeignKey(
'fk-post-author_id',
'post',
'author_id',
'user',
'id',
'CASCADE'
);
// creates index for column `category_id`
$this->createIndex(
'idx-post-category_id',
'post',
'category_id'
);
// add foreign key for table `category`
$this->addForeignKey(
'fk-post-category_id',
'post',
'category_id',
'category',
'id',
'CASCADE'
);
}
/**
* {@inheritdoc}
*/
public function down()
{
// drops foreign key for table `user`
$this->dropForeignKey(
'fk-post-author_id',
'post'
);
// drops index for column `author_id`
$this->dropIndex(
'idx-post-author_id',
'post'
);
// drops foreign key for table `category`
$this->dropForeignKey(
'fk-post-category_id',
'post'
);
// drops index for column `category_id`
$this->dropIndex(
'idx-post-category_id',
'post'
);
$this->dropTable('post');
}
}
```
カラムの記述における `foreignKey` キーワードの位置によって、生成されるコードが変ることはありません。
つまり、
- `author_id:integer:notNull:foreignKey(user)`
- `author_id:integer:foreignKey(user):notNull`
- `author_id:foreignKey(user):integer:notNull`
これらはすべて同じコードを生成します。
`foreignKey` キーワードは括弧の中にパラメータを取ることが出来て、これが生成される外部キーの関連テーブルの名前になります。
パラメータが渡されなかった場合は、テーブル名はカラム名から推測されます。
上記の例で `author_id:integer:notNull:foreignKey(user)` は、`user` テーブルへの外部キーを持つ `author_id` という名前のカラムを生成します。
一方、`category_id:integer:defaultValue(1):foreignKey` は、`category` テーブルへの外部キーを持つ `category_id` というカラムを生成します。
2.0.11 以降では、`foreignKey` キーワードは空白で区切られた第二のパラメータを取ることが出来ます。
これは、生成される外部キーに関連づけられるカラム名を表します。
第二のパラメータが渡されなかった場合は、カラム名はテーブル・スキーマから取得されます。
スキーマが存在しない場合や、プライマリ・キーが設定されていなかったり、複合キーであったりする場合は、デフォルト名として `id` が使用されます。
### テーブルを削除する
```
yii migrate/create drop_post_table --fields="title:string(12):notNull:unique,body:text"
```
これは、次のコードを生成します。
```php
class m150811_220037_drop_post_table extends Migration
{
public function up()
{
$this->dropTable('post');
}
public function down()
{
$this->createTable('post', [
'id' => $this->primaryKey(),
'title' => $this->string(12)->notNull()->unique(),
'body' => $this->text()
]);
}
}
```
### カラムを追加する
マイグレーションの名前が `add_xxx_column_to_yyy_table` の形式である場合、ファイルの内容は、必要となる `addColumn` と `dropColumn` を含むことになります。
カラムを追加するためには、次のようにします。
```
yii migrate/create add_position_column_to_post_table --fields="position:integer"
```
これが次のコードを生成します。
```php
class m150811_220037_add_position_column_to_post_table extends Migration
{
public function up()
{
$this->addColumn('post', 'position', $this->integer());
}
public function down()
{
$this->dropColumn('post', 'position');
}
}
```
次のようにして複数のカラムを指定することも出来ます。
```
yii migrate/create add_xxx_column_yyy_column_to_zzz_table --fields="xxx:integer,yyy:text"
```
### カラムを削除する
マイグレーションの名前が `drop_xxx_column_from_yyy_table` の形式である場合、ファイルの内容は、必要となる `addColumn` と `dropColumn` を含むことになります。
```
yii migrate/create drop_position_column_from_post_table --fields="position:integer"
```
これは、次のコードを生成します。
```php
class m150811_220037_drop_position_column_from_post_table extends Migration
{
public function up()
{
$this->dropColumn('post', 'position');
}
public function down()
{
$this->addColumn('post', 'position', $this->integer());
}
}
```
### 中間テーブルを追加する
マイグレーションの名前が `create_junction_table_for_xxx_and_yyy_tables` の形式である場合は、中間テーブルを作成するのに必要となるコードが生成されます。
```
yii migrate/create create_junction_table_for_post_and_tag_tables --fields="created_at:dateTime"
```
これは、次のコードを生成します。
```php
/**
* Handles the creation for table `post_tag`.
* Has foreign keys to the tables:
*
* - `post`
* - `tag`
*/
class m160328_041642_create_junction_table_for_post_and_tag_tables extends Migration
{
/**
* {@inheritdoc}
*/
public function up()
{
$this->createTable('post_tag', [
'post_id' => $this->integer(),
'tag_id' => $this->integer(),
'created_at' => $this->dateTime(),
'PRIMARY KEY(post_id, tag_id)',
]);
// creates index for column `post_id`
$this->createIndex(
'idx-post_tag-post_id',
'post_tag',
'post_id'
);
// add foreign key for table `post`
$this->addForeignKey(
'fk-post_tag-post_id',
'post_tag',
'post_id',
'post',
'id',
'CASCADE'
);
// creates index for column `tag_id`
$this->createIndex(
'idx-post_tag-tag_id',
'post_tag',
'tag_id'
);
// add foreign key for table `tag`
$this->addForeignKey(
'fk-post_tag-tag_id',
'post_tag',
'tag_id',
'tag',
'id',
'CASCADE'
);
}
/**
* {@inheritdoc}
*/
public function down()
{
// drops foreign key for table `post`
$this->dropForeignKey(
'fk-post_tag-post_id',
'post_tag'
);
// drops index for column `post_id`
$this->dropIndex(
'idx-post_tag-post_id',
'post_tag'
);
// drops foreign key for table `tag`
$this->dropForeignKey(
'fk-post_tag-tag_id',
'post_tag'
);
// drops index for column `tag_id`
$this->dropIndex(
'idx-post_tag-tag_id',
'post_tag'
);
$this->dropTable('post_tag');
}
}
```
2.0.11 以降では、中間テーブルの外部キーのカラム名はテーブル・スキーマから取得されます。
スキーマでテーブルが定義されていない場合や、プライマリ・キーが設定されていなかったり複合キーであったりする場合は、デフォルト名 `id` が使われます。
### トランザクションを使うマイグレーション <span id="transactional-migrations"></span>
複雑な一連の DB マイグレーションを実行するときは、通常、データベースの一貫性と整合性を保つために、各マイグレーションが全体として成功または失敗することを保証する必要があります。
この目的を達成するために、各マイグレーションの DB 操作を [トランザクション](db-dao.md#performing-transactions) で囲むことが推奨されます。
トランザクションを使うマイグレーションを実装するためのもっと簡単な方法は、マイグレーションのコードを `safeUp()` と `safeDown()` のメソッドに入れることです。
この二つのメソッドが `up()` および `down()` と違う点は、これらが暗黙のうちにトランザクションに囲まれていることです。
結果として、これらのメソッドの中で何か操作が失敗した場合は、先行する全ての操作が自動的にロールバックされます。
次の例では、`news` テーブルを作成するだけでなく、このテーブルに初期値となる行を挿入しています。
```php
<?php
use yii\db\Migration;
class m150101_185401_create_news_table extends Migration
{
public function safeUp()
{
$this->createTable('news', [
'id' => $this->primaryKey(),
'title' => $this->string()->notNull(),
'content' => $this->text(),
]);
$this->insert('news', [
'title' => 'test 1',
'content' => 'content 1',
]);
}
public function safeDown()
{
$this->delete('news', ['id' => 1]);
$this->dropTable('news');
}
}
```
通常、`safeUp()` で複数の DB 操作を実行する場合は、`safeDown()` では実行の順序を逆にしなければならないことに注意してください。
上記の例では、`safeUp()` では、最初にテーブルを作って、次に行を挿入し、`safeDown()` では、先に行を削除して、次にテーブルを削除しています。
> Note: 全ての DBMS がトランザクションをサポートしている訳ではありません。
また、トランザクションに入れることが出来ない DB クエリもあります。
いくつかの例を [暗黙のコミット](http://dev.mysql.com/doc/refman/5.7/en/implicit-commit.html) で見ることが出来ます。
その場合には、代りに、`up()` と `down()` を実装しなければなりません。
### データベース・アクセス・メソッド <span id="db-accessing-methods"></span>
基底のマイグレーション・クラス [[yii\db\Migration]] は、データベースにアクセスして操作するための一連のメソッドを提供しています。
あなたは、これらのメソッドが、[[yii\db\Command]] クラスによって提供される [DAO メソッド](db-dao.md) と同じような名前を付けられていることに気付くでしょう。
例えば、[[yii\db\Migration::createTable()]] メソッドは、[[yii\db\Command::createTable()]] と全く同じように、新しいテーブルを作成します。
[[yii\db\Migration]] によって提供されているメソッドを使うことの利点は、[[yii\db\Command]] インスタンスを明示的に作成する必要がないこと、そして、各メソッドを実行すると、どのようなデータベース操作がどれだけの時間をかけて実行されたかを教えてくれる有益なメッセージが自動的に表示されることです。
以下がそういうデータベース・アクセス・メソッドの一覧です。
* [[yii\db\Migration::execute()|execute()]]: SQL 文を実行
* [[yii\db\Migration::insert()|insert()]]: 一行を挿入
* [[yii\db\Migration::batchInsert()|batchInsert()]]: 複数行を挿入
* [[yii\db\Migration::update()|update()]]: 行を更新
* [[yii\db\Migration::delete()|delete()]]: 行を削除
* [[yii\db\Migration::createTable()|createTable()]]: テーブルを作成
* [[yii\db\Migration::renameTable()|renameTable()]]: テーブルの名前を変更
* [[yii\db\Migration::dropTable()|dropTable()]]: テーブルを削除
* [[yii\db\Migration::truncateTable()|truncateTable()]]: テーブル中の全ての行を削除
* [[yii\db\Migration::addColumn()|addColumn()]]: カラムを追加
* [[yii\db\Migration::renameColumn()|renameColumn()]]: カラムの名前を変更
* [[yii\db\Migration::dropColumn()|dropColumn()]]: カラムを削除
* [[yii\db\Migration::alterColumn()|alterColumn()]]: カラムの定義を変更
* [[yii\db\Migration::addPrimaryKey()|addPrimaryKey()]]: プライマリ・キーを追加
* [[yii\db\Migration::dropPrimaryKey()|dropPrimaryKey()]]: プライマリ・キーを削除
* [[yii\db\Migration::addForeignKey()|addForeignKey()]]: 外部キーを追加
* [[yii\db\Migration::dropForeignKey()|dropForeignKey()]]: 外部キーを削除
* [[yii\db\Migration::createIndex()|createIndex()]]: インデックスを作成
* [[yii\db\Migration::dropIndex()|dropIndex()]]: インデックスを削除
* [[yii\db\Migration::addCommentOnColumn()|addCommentOnColumn()]]: カラムにコメントを追加
* [[yii\db\Migration::dropCommentFromColumn()|dropCommentFromColumn()]]: カラムからコメントを削除
* [[yii\db\Migration::addCommentOnTable()|addCommentOnTable()]]: テーブルにコメントを追加
* [[yii\db\Migration::dropCommentFromTable()|dropCommentFromTable()]]: テーブルからコメントを削除
> Info: [[yii\db\Migration]] は、データベース・クエリ・メソッドを提供しません。
これは、通常、データベースからのデータ取得については、メッセージを追加して表示する必要がないからです。
更にまた、複雑なクエリを構築して実行するためには、強力な [クエリ・ビルダ](db-query-builder.md) を使うことが出来るからです。
> Note: マイグレーションを使ってデータを操作する場合に、あなたは、あなたの [アクティブレコード](db-active-record.md) クラスをデータ操作に使えば便利じゃないか、と気付くかもしれません。
> なぜなら、いくつかのロジックは既にアクティブレコードで実装済みだから、と。
> しかしながら、マイグレーションの中で書かれるコードが永久に不変であることを本質とするのと対照的に、アプリケーションのロジックは変化にさらされるものであるということを心に留めなければなりません。
> 従って、マイグレーションのコードでアクティブレコードを使用していると、アクティブレコードのレイヤにおけるロジックの変更が思いがけず既存のマイグレーションを破壊することがあり得ます。
> このような理由のため、マイグレーションのコードはアクティブレコードのようなアプリケーションの他のロジックから独立を保つべきです。
## マイグレーションを適用する <span id="applying-migrations"></span>
データベースを最新の構造にアップグレードするためには、利用できる全ての新しいマイグレーションを適用するために、次のコマンドを使わなければなりません。
```
yii migrate
```
コマンドを実行すると、まだ適用されていない全てのマイグレーションが一覧表示されます。
リストされたマイグレーションを適用することをあなたが確認すると、タイムスタンプの値の順に、一つずつ、すべての新しいマイグレーション・クラスの `up()` または `safeUp()` メソッドが実行されます。
マイグレーションのどれかが失敗した場合は、コマンドは残りのマイグレーションを適用せずに終了します。
> Tip: あなたのサーバでコマンドラインを使用できない場合は
> [web shell](https://github.com/samdark/yii2-webshell) エクステンションを使ってみてください。
適用が成功したマイグレーションの一つ一つについて、`migration` という名前のデータベース・テーブルに行が挿入されて、マイグレーションの成功が記録されます。
この記録によって、マイグレーション・ツールは、どのマイグレーションが適用され、どのマイグレーションが適用されていないかを特定することが出来ます。
> Info: マイグレーション・ツールは、コマンドの [[yii\console\controllers\MigrateController::db|db]] オプションで指定されたデータベースに `migration` テーブルを自動的に作成します。
デフォルトでは、このデータベースは `db` [アプリケーション・コンポーネント](structure-application-components.md) によって指定されます。
時として、利用できる全てのマイグレーションではなく、一つまたは数個の新しいマイグレーションだけを適用したい場合があります。
コマンドを実行するときに、適用したいマイグレーションの数を指定することによって、そうすることが出来ます。
例えば、次のコマンドは、次の三個の利用できるマイグレーションを適用しようとするものです。
```
yii migrate 3
```
また、そのマイグレーションまでをデータベースに適用するという、特定のマイグレーションを明示的に指定することも出来ます。
そのためには、`migrate/to` コマンドを、次のどれかの形式で使います。
```
yii migrate/to 150101_185401 # タイムスタンプを使ってマイグレーションを指定
yii migrate/to "2015-01-01 18:54:01" # strtotime() によって解釈できる文字列を使用
yii migrate/to m150101_185401_create_news_table # フルネームを使用
yii migrate/to 1392853618 # UNIX タイムスタンプを使用
```
指定されたマイグレーションよりも古いものが適用されずに残っている場合は、指定されたものが適用される前に、すべて適用されます。
指定されたマイグレーションが既に適用済みである場合、それより新しいものが適用されていれば、すべて取り消されます。
## マイグレーションを取り消す <span id="reverting-migrations"></span>
適用済みのマイグレーションを一個または複数個取り消したい場合は、下記のコマンドを使うことが出来ます。
```
yii migrate/down # 最近に適用されたマイグレーション一個を取り消す
yii migrate/down 3 # 最近に適用されたマイグレーション三個を取り消す
```
> Note: 全てのマイグレーションが取り消せるとは限りません。
そのようなマイグレーションを取り消そうとするとエラーとなり、取り消しのプロセス全体が終了させられます。
## マイグレーションを再適用する <span id="redoing-migrations"></span>
マイグレーションの再適用とは、指定されたマイグレーションを最初に取り消してから、再度適用することを意味します。
これは次のコマンドによって実行することが出来ます。
```
yii migrate/redo # 最後に適用された一個のマイグレーションを再適用する
yii migrate/redo 3 # 最後に適用された三個のマイグレーションを再適用する
```
> Note: マイグレーションが取り消し不可能な場合は、それを再適用することは出来ません。
## マイグレーションをリスト表示する <span id="listing-migrations"></span>
どのマイグレーションが適用済みであり、どのマイグレーションが未適用であるかをリスト表示するために、次のコマンドを使うことが出来ます。
```
yii migrate/history # 最後に適用された 10 個のマイグレーションを表示
yii migrate/history 5 # 最後に適用された 5 個のマイグレーションを表示
yii migrate/history all # 適用された全てのマイグレーションを表示
yii migrate/new # 適用可能な最初の 10 個のマイグレーションを表示
yii migrate/new 5 # 適用可能な最初の 5 個のマイグレーションを表示
yii migrate/new all # 適用可能な全てのマイグレーションを表示
```
## マイグレーション履歴を修正する <span id="modifying-migration-history"></span>
時として、実際にマイグレーションを適用したり取り消したりするのではなく、データベースが特定のマイグレーションまでアップグレードされたとマークしたいだけ、という場合があります。
このようなことがよく起るのは、データベースを手作業で特定の状態に変更した後に、その変更のための一つまたは複数のマイグレーションを記録はするが再度適用はしたくない、という場合です。
次のコマンドでこの目的を達することが出来ます。
```
yii migrate/mark 150101_185401 # タイムスタンプを使ってマイグレーションを指定
yii migrate/mark "2015-01-01 18:54:01" # strtotime() によって解釈できる文字列を使用
yii migrate/mark m150101_185401_create_news_table # フルネームを使用
yii migrate/mark 1392853618 # UNIX タイムスタンプを使用
```
このコマンドは、一定の行を追加または削除して、`migration` テーブルを修正し、データベースが指定されたものまでマイグレーションが適用済みであることを示します。
このコマンドによってマイグレーションが適用されたり取り消されたりはしません。
## マイグレーションをカスタマイズする <span id="customizing-migrations"></span>
マイグレーションコマンドをカスタマイズする方法がいくつかあります。
### コマンドライン・オプションを使う <span id="using-command-line-options"></span>
マイグレーション・コマンドには、その動作をカスタマイズするために使うことが出来るコマンドライン・オプションがいくつかあります。
* `interactive`: 真偽値 (デフォルト値は true)。
マイグレーションを対話モードで実行するかどうかを指定します。
true である場合は、コマンドが何らかの操作を実行する前に、ユーザは確認を求められます。
コマンドがバックグラウンドのプロセスで使用される場合は、このオプションを false にセットします。
* `migrationPath`: 文字列 (デフォルト値は `@app/migrations`)。
全てのマイグレーション・クラス・ファイルを保存しているディレクトリを指定します。
この値は、ディレクトリ・パスか、パス・[エイリアス](concept-aliases.md) として指定することが出来ます。
ディレクトリが存在する必要があり、そうでなければコマンドがエラーを発生させることに注意してください。
* `migrationTable`: 文字列 (デフォルト値は `migration`)。
マイグレーション履歴の情報を保存するためのデータベース・テーブル名を指定します。
テーブルが存在しない場合は、コマンドによって自動的に作成されます。
`version varchar(255) primary key, apply_time integer` という構造のテーブルを手作業で作成しても構いません。
* `db`: 文字列 (デフォルト値は `db`)。
データベース [アプリケーション・コンポーネント](structure-application-components.md) の ID を指定します。
このコマンドによってマイグレーションを適用されるデータベースを表します。
* `templateFile`: 文字列 (デフォルト値は `@yii/views/migration.php`)。
スケルトンのマイグレーション・クラス・ファイルを生成するために使用されるテンプレート・ファイルのパスを指定します。
この値は、ファイル・パスか、パス [エイリアス](concept-aliases.md) として指定することが出来ます。
テンプレート・ファイルは PHP スクリプトであり、その中で、マイグレーション・クラスの名前を取得するための `$className` という事前定義された変数を使うことが出来ます。
* `generatorTemplateFiles`: 配列 (デフォルト値は `[
'create_table' => '@yii/views/createTableMigration.php',
'drop_table' => '@yii/views/dropTableMigration.php',
'add_column' => '@yii/views/addColumnMigration.php',
'drop_column' => '@yii/views/dropColumnMigration.php',
'create_junction' => '@yii/views/createTableMigration.php'
]`)。
マイグレーション・コードを生成するためのテンプレート・ファイルを指定します。
詳細は "[マイグレーションを生成する](#generating-migrations)" を参照してください。
* `fields`: マイグレーション・コードを生成するためのカラム定義文字列の配列。
デフォルト値は `[]`。個々の定義の書式は `COLUMN_NAME:COLUMN_TYPE:COLUMN_DECORATOR` です。
例えば、`--fields=name:string(12):notNull` は、サイズが 12 の null でない文字列カラムを作成します。
次の例は、これらのオプションの使い方を示すものです。
例えば、`forum` モジュールにマイグレーションを適用しようとしており、そのマイグレーション・ファイルがモジュールの `migrations` ディレクトリに配置されている場合、次のコマンドを使うことが出来ます。
```
# forum モジュールのマイグレーションを非対話的に適用する
yii migrate --migrationPath=@app/modules/forum/migrations --interactive=0
```
### コマンドをグローバルに構成する <span id="configuring-command-globally"></span>
マイグレーション・コマンドを実行するたびに同じオプションの値を入力する代りに、次のように、アプリケーションの構成情報でコマンドを一度だけ構成して済ませることが出来ます。
```php
return [
'controllerMap' => [
'migrate' => [
'class' => 'yii\console\controllers\MigrateController',
'migrationTable' => 'backend_migration',
],
],
];
```
上記のように構成しておくと、`migrate` コマンドを実行するたびに、`backend_migration` テーブルがマイグレーション履歴を記録するために使われるようになります。
もう、`migrationTable` のコマンドライン・オプションを使ってテーブルを指定する必要はなくなります。
### 名前空間を持つマイグレーション <span id="namespaced-migrations"></span>
2.0.10 以降では、マイグレーションのクラスに名前空間を適用することが出来ます。
マイグレーションの名前空間のリストをを [[yii\console\controllers\MigrateController::migrationNamespaces|migrationNamespaces]] によって指定することが出来ます。
マイグレーションのクラスに名前空間を使うと、マイグレーションのソースについて、複数の配置場所を使用することが出来ます。
例えば、
```php
return [
'controllerMap' => [
'migrate' => [
'class' => 'yii\console\controllers\MigrateController',
'migrationNamespaces' => [
'app\migrations', // アプリケーション全体のための共通のマイグレーション
'module\migrations', // プロジェクトの特定のモジュールのためのマイグレーション
'some\extension\migrations', // 特定のエクステンションのためのマイグレーション
],
],
],
];
```
> Note: 異なる名前空間に属するマイグレーションを適用しても、**単一の** マイグレーション履歴が生成されます。
> つまり、特定の名前空間に属するマイグレーションだけを適用したり元に戻したりすることは出来ません。
名前空間を持つマイグレーションを操作するときは、新規作成時も、元に戻すときも、マイグレーション名の前にフルパスの名前空間を指定しなければなりません。
バック・スラッシュ (`\`) のシンボルは、通常、シェルでは特殊文字として扱われますので、シェルのエラーや誤った動作を防止するために、適切にエスケープしなければならないことに注意して下さい。
例えば、
```
yii migrate/create 'app\\migrations\\createUserTable'
```
> Note: [[yii\console\controllers\MigrateController::migrationPath|migrationPath]] によって指定されたマイグレーションは、名前空間を持つことが出来ません。
名前空間を持つマイグレーションは [[yii\console\controllers\MigrateController::migrationNamespaces]] プロパティを通じてのみ適用可能です。
バージョン 2.0.12 以降は [[yii\console\controllers\MigrateController::migrationPath|migrationPath]] プロパティは
名前空間を持たないマイグレーションを含む複数のディレクトリを指定した配列を受け入れるようになりました。
この機能追加は、主として、いろんな場所にあるマイグレーションを使っている既存のプロジェクトによって使われることを意図しています。
これらのマイグレーションは、主として、他の開発者による Yii エクステンションなど、外部ソースに由来するものであり、
新しい手法を使い始めようとしても、名前空間を使うように変更することが簡単には出来ないものだからです。
### 分離されたマイグレーション <span id="separated-migrations"></span>
プロジェクトのマイグレーション全体に単一のマイグレーション履歴を使用することが望ましくない場合もあります。
例えば、完全に独立した機能性とそれ自身のためのマイグレーションを持つような 'blog' エクステンションをインストールする場合には、
メインのプロジェクトの機能専用のマイグレーションに影響を与えたくないでしょう。
これらをお互いに完全に分離して適用かつ追跡したい場合は、別々の名前空間とマイグレーション履歴テーブルを使う
複数のマイグレーションコマンドを構成することが出来ます。
```php
return [
'controllerMap' => [
// アプリケーション全体のための共通のマイグレーション
'migrate-app' => [
'class' => 'yii\console\controllers\MigrateController',
'migrationNamespaces' => ['app\migrations'],
'migrationTable' => 'migration_app',
],
// 特定のモジュールのためのマイグレーション
'migrate-module' => [
'class' => 'yii\console\controllers\MigrateController',
'migrationNamespaces' => ['module\migrations'],
'migrationTable' => 'migration_module',
],
// 特定のエクステンションのためのマイグレーション
'migrate-rbac' => [
'class' => 'yii\console\controllers\MigrateController',
'migrationPath' => '@yii/rbac/migrations',
'migrationTable' => 'migration_rbac',
],
],
];
```
データベースを同期するためには、一つではなく複数のコマンドを実行しなければならなくなることに注意してください。
```
yii migrate-app
yii migrate-module
yii migrate-rbac
```
## 複数のデータベースにマイグレーションを適用する <span id="migrating-multiple-databases"></span>
デフォルトでは、マイグレーションは `db` [アプリケーション・コンポーネント](structure-application-components.md) によって指定された同じデータベースに対して適用されます。
マイグレーションを別のデータベースに適用したい場合は、次のように、`db` コマンドライン・オプションを指定することが出来ます。
```
yii migrate --db=db2
```
上記のコマンドはマイグレーションを `db2` データベースに適用します。
場合によっては、*いくつかの* マイグレーションはあるデータベースに適用し、*別のいくつかの* マイグレーションはもう一つのデータベースに適用したい、ということがあります。
この目的を達するためには、マイグレーション・クラスを実装する時に、そのマイグレーションが使用する DB コンポーネントの ID を明示的に指定しなければなりません。
例えば、次のようにします。
```php
<?php
use yii\db\Migration;
class m150101_185401_create_news_table extends Migration
{
public function init()
{
$this->db = 'db2';
parent::init();
}
}
```
上記のマイグレーションは、`db` コマンドライン・オプションで別のデータベースを指定した場合でも、`db2` に対して適用されます。
ただし、マイグレーション履歴は、`db` コマンドライン・オプションで指定されたデータベースに記録されることに注意してください。
同じデータベースを使う複数のマイグレーションがある場合は、上記の `init()` コードを持つ基底のマイグレーション・クラスを作成することを推奨します。
そうすれば、個々のマイグレーション・クラスは、その基底クラスから拡張することが出来ます。
> Tip: 異なるデータベースを操作するためには、[[yii\db\Migration::db|db]] プロパティを設定する以外にも、マイグレーション・クラスの中で新しいデータベース接続を作成するという方法があります。
そうすれば、そのデータベース接続で [DAO メソッド](db-dao.md) を使って、違うデータベースを操作することが出来ます。
複数のデータベースに対してマイグレーションを適用するために採用できるもう一つの戦略としては、異なるデータベースに対するマイグレーションは異なるマイグレーションパスに保持する、というものがあります。
そうすれば、次のように、異なるデータベースのマイグレーションを別々のコマンドで適用することが出来ます。
```
yii migrate --migrationPath=@app/migrations/db1 --db=db1
yii migrate --migrationPath=@app/migrations/db2 --db=db2
...
```
最初のコマンドは `@app/migrations/db1` にあるマイグレーションを `db1` データベースに適用し、第二のコマンドは `@app/migrations/db2` にあるマイグレーションを `db2` データベースに適用する、という具合です。
| bsd-3-clause |
Workday/OpenFrame | third_party/WebKit/Source/modules/permissions/PermissionsCallback.cpp | 1871 | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "config.h"
#include "modules/permissions/PermissionsCallback.h"
#include "bindings/core/v8/ScriptPromiseResolver.h"
#include "modules/permissions/PermissionStatus.h"
namespace blink {
PermissionsCallback::PermissionsCallback(ScriptPromiseResolver* resolver, PassOwnPtr<Vector<WebPermissionType>> internalPermissions, PassOwnPtr<Vector<int>> callerIndexToInternalIndex)
: m_resolver(resolver),
m_internalPermissions(internalPermissions),
m_callerIndexToInternalIndex(callerIndexToInternalIndex)
{
ASSERT(m_resolver);
}
void PermissionsCallback::onSuccess(WebPassOwnPtr<WebVector<WebPermissionStatus>> permissionStatus)
{
if (!m_resolver->executionContext() || m_resolver->executionContext()->activeDOMObjectsAreStopped())
return;
OwnPtr<WebVector<WebPermissionStatus>> statusPtr = permissionStatus.release();
HeapVector<Member<PermissionStatus>> result(m_callerIndexToInternalIndex->size());
// Create the response vector by finding the status for each index by
// using the caller to internal index mapping and looking up the status
// using the internal index obtained.
for (size_t i = 0; i < m_callerIndexToInternalIndex->size(); ++i) {
int internalIndex = m_callerIndexToInternalIndex->operator[](i);
result[i] = PermissionStatus::createAndListen(m_resolver->executionContext(), statusPtr->operator[](internalIndex), m_internalPermissions->operator[](internalIndex));
}
m_resolver->resolve(result);
}
void PermissionsCallback::onError()
{
if (!m_resolver->executionContext() || m_resolver->executionContext()->activeDOMObjectsAreStopped())
return;
m_resolver->reject();
}
} // namespace blink
| bsd-3-clause |
kivi8/ars-poetica | vendor/nette/di/src/DI/ServiceDefinition.php | 4863 | <?php
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\DI;
use Nette;
/**
* Definition used by ContainerBuilder.
*/
class ServiceDefinition extends Nette\Object
{
/** @var string|NULL class or interface name */
private $class;
/** @var Statement|NULL */
private $factory;
/** @var Statement[] */
private $setup = array();
/** @var array */
public $parameters = array();
/** @var array */
private $tags = array();
/** @var bool */
private $autowired = TRUE;
/** @var bool */
private $dynamic = FALSE;
/** @var string|NULL interface name */
private $implement;
/** @var string|NULL create | get */
private $implementType;
/**
* @return self
*/
public function setClass($class, array $args = array())
{
$this->class = ltrim($class, '\\');
if ($args) {
$this->setFactory($class, $args);
}
return $this;
}
/**
* @return string|NULL
*/
public function getClass()
{
return $this->class;
}
/**
* @return self
*/
public function setFactory($factory, array $args = array())
{
$this->factory = $factory instanceof Statement ? $factory : new Statement($factory, $args);
return $this;
}
/**
* @return Statement|NULL
*/
public function getFactory()
{
return $this->factory;
}
/**
* @return string|array|ServiceDefinition|NULL
*/
public function getEntity()
{
return $this->factory ? $this->factory->getEntity() : NULL;
}
/**
* @return self
*/
public function setArguments(array $args = array())
{
if (!$this->factory) {
$this->factory = new Statement($this->class);
}
$this->factory->arguments = $args;
return $this;
}
/**
* @param Statement[]
* @return self
*/
public function setSetup(array $setup)
{
foreach ($setup as $v) {
if (!$v instanceof Statement) {
throw new Nette\InvalidArgumentException('Argument must be Nette\DI\Statement[].');
}
}
$this->setup = $setup;
return $this;
}
/**
* @return Statement[]
*/
public function getSetup()
{
return $this->setup;
}
/**
* @return self
*/
public function addSetup($entity, array $args = array())
{
$this->setup[] = $entity instanceof Statement ? $entity : new Statement($entity, $args);
return $this;
}
/**
* @return self
*/
public function setParameters(array $params)
{
$this->parameters = $params;
return $this;
}
/**
* @return array
*/
public function getParameters()
{
return $this->parameters;
}
/**
* @return self
*/
public function setTags(array $tags)
{
$this->tags = $tags;
return $this;
}
/**
* @return array
*/
public function getTags()
{
return $this->tags;
}
/**
* @return self
*/
public function addTag($tag, $attr = TRUE)
{
$this->tags[$tag] = $attr;
return $this;
}
/**
* @return mixed
*/
public function getTag($tag)
{
return isset($this->tags[$tag]) ? $this->tags[$tag] : NULL;
}
/**
* @param bool
* @return self
*/
public function setAutowired($state = TRUE)
{
$this->autowired = (bool) $state;
return $this;
}
/**
* @return bool
*/
public function isAutowired()
{
return $this->autowired;
}
/**
* @param bool
* @return self
*/
public function setDynamic($state = TRUE)
{
$this->dynamic = (bool) $state;
return $this;
}
/**
* @return bool
*/
public function isDynamic()
{
return $this->dynamic;
}
/**
* @param string
* @return self
*/
public function setImplement($interface)
{
$this->implement = ltrim($interface, '\\');
return $this;
}
/**
* @return string|NULL
*/
public function getImplement()
{
return $this->implement;
}
/**
* @param string
* @return self
*/
public function setImplementType($type)
{
if (!in_array($type, array('get', 'create'), TRUE)) {
throw new Nette\InvalidArgumentException('Argument must be get|create.');
}
$this->implementType = $type;
return $this;
}
/**
* @return string|NULL
*/
public function getImplementType()
{
return $this->implementType;
}
/** @deprecated */
public function setShared($on)
{
trigger_error(__METHOD__ . '() is deprecated.', E_USER_DEPRECATED);
$this->autowired = $on ? $this->autowired : FALSE;
return $this;
}
/** @deprecated */
public function isShared()
{
trigger_error(__METHOD__ . '() is deprecated.', E_USER_DEPRECATED);
}
/** @return self */
public function setInject($state = TRUE)
{
//trigger_error(__METHOD__ . '() is deprecated.', E_USER_DEPRECATED);
return $this->addTag(Extensions\InjectExtension::TAG_INJECT, $state);
}
/** @return bool|NULL */
public function getInject()
{
//trigger_error(__METHOD__ . '() is deprecated.', E_USER_DEPRECATED);
return $this->getTag(Extensions\InjectExtension::TAG_INJECT);
}
}
| bsd-3-clause |
gfxmonk/py-dataflow | setup.py | 694 | #!/usr/bin/env python
from setuptools import *
setup(
name='dataflow',
version='0.1.1',
description='a dataflow library for python',
author='Tim Cuthbertson',
author_email='[email protected]',
url='http://github.com/gfxmonk/py-dataflow/tree',
packages=find_packages(exclude=["test"]),
long_description=open('readme.rst').read(),
classifiers=[
"License :: OSI Approved :: BSD License",
"Programming Language :: Python",
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Topic :: Software Development :: Libraries :: Python Modules",
],
keywords='dataflow concurrent concurrency',
license='BSD',
install_requires=[
'setuptools',
],
)
| bsd-3-clause |
dhruvagarwal/http-request-translator | tests/test_input.py | 524 | import unittest
from hrt import input_handler
class TestCLIInput(unittest.TestCase):
def setUp(self):
pass
def test_stdin_input(self):
pass
def test_interactive_input(self):
pass
def test_file_input(self):
pass
def test_inline_input(self):
pass
def test_when_input_unicode(self):
pass
def test_multiple_input_methods_chosen(self):
pass
def test_empty_input(self):
pass
if __name__ == '__main__':
unittest.main()
| bsd-3-clause |
hainm/pythran | third_party/nt2/include/functions/scalar/store.hpp | 178 | #ifndef NT2_INCLUDE_FUNCTIONS_SCALAR_STORE_HPP_INCLUDED
#define NT2_INCLUDE_FUNCTIONS_SCALAR_STORE_HPP_INCLUDED
#include <nt2/memory/include/functions/scalar/store.hpp>
#endif
| bsd-3-clause |
mwillebrands/Platform | src/Platform.Xml.Serialization/SerializationContext.cs | 3632 | using System;
using System.Collections;
namespace Platform.Xml.Serialization
{
/// <summary>
/// Maintains state required to perform serialization.
/// </summary>
public sealed class SerializationContext
{
private readonly IList stack = new ArrayList();
public SerializationParameters Parameters { get; }
public SerializerOptions SerializerOptions { get; set; }
public SerializationContext(SerializerOptions options, SerializationParameters parameters)
{
this.Parameters = parameters;
SerializerOptions = options;
}
/// <summary>
/// Checks if see if an object should be serialized.
/// </summary>
/// <remarks>
/// <p>
/// An object shouldn't be serialized if it has already been serialized.
/// This method automatically checks if the object has been serialized
/// by examining the serialization stack. This stack is maintained by
/// the SerializationStart and SerializationEnd methods.
/// </p>
/// <p>
/// You should call SerializationStart and SerializationEnd when you start
/// and finish serializing an object.
/// </p>
/// </remarks>
/// <param name="obj"></param>
/// <returns></returns>
public bool ShouldSerialize(object obj, SerializationMemberInfo memberInfo)
{
IXmlSerializationShouldSerializeProvider shouldSerialize;
if (obj == null && !memberInfo.SerializeIfNull)
{
return false;
}
if ((shouldSerialize = obj as IXmlSerializationShouldSerializeProvider) != null)
{
if (!shouldSerialize.ShouldSerialize(this.SerializerOptions, this.Parameters))
{
return false;
}
}
for (var i = 0; i < stack.Count; i++)
{
if (stack[i] == obj)
{
return false;
}
}
return true;
}
private readonly Stack serializationMemberInfoStack = new Stack();
public void PushCurrentMemberInfo(SerializationMemberInfo memberInfo)
{
serializationMemberInfoStack.Push(memberInfo);
}
public void PopCurrentMemberInfo()
{
serializationMemberInfoStack.Pop();
}
public SerializationMemberInfo GetCurrentMemberInfo()
{
return (SerializationMemberInfo)serializationMemberInfoStack.Peek();
}
public void DeserializationStart(object obj)
{
var listener = obj as IXmlDeserializationStartListener;
listener?.XmlDeserializationStart(this.Parameters);
}
public void DeserializationEnd(object obj)
{
var listener = obj as IXmlDeserializationEndListener;
listener?.XmlDeserializationEnd(this.Parameters);
}
/// <summary>
/// Prepares an object for serialization/
/// </summary>
/// <remarks>
/// The object is pushed onto the serialization stack.
/// This prevents the object from being serialized in cycles.
/// </remarks>
/// <param name="obj"></param>
public void SerializationStart(object obj)
{
stack.Add(obj);
var listener = obj as IXmlSerializationStartListener;
listener?.XmlSerializationStart(this.Parameters);
}
/// <summary>
/// Call when an object has been serialized.
/// </summary>
/// <remarks>
/// The object is popped off the serialization stack.
/// </remarks>
/// <param name="obj"></param>
public void SerializationEnd(object obj)
{
if (stack[stack.Count - 1] != obj)
{
stack.RemoveAt(stack.Count - 1);
throw new InvalidOperationException("Push/Pop misalignment.");
}
stack.RemoveAt(stack.Count - 1);
var listener = obj as IXmlSerializationEndListener;
listener?.XmlSerializationEnd(this.Parameters);
}
}
}
| bsd-3-clause |
Klaudit/inbox2_desktop | ThirdParty/Src/Lumisoft.Net/DNS/Client/DNS_rr_A.cs | 1419 | using System;
using System.Net;
namespace LumiSoft.Net.Dns.Client
{
/// <summary>
/// A record class.
/// </summary>
[Serializable]
public class DNS_rr_A : DNS_rr_base
{
private IPAddress m_IP = null;
/// <summary>
/// Default constructor.
/// </summary>
/// <param name="ip">IP address.</param>
/// <param name="ttl">TTL value.</param>
public DNS_rr_A(IPAddress ip,int ttl) : base(QTYPE.A,ttl)
{
m_IP = ip;
}
#region static method Parse
/// <summary>
/// Parses resource record from reply data.
/// </summary>
/// <param name="reply">DNS server reply data.</param>
/// <param name="offset">Current offset in reply data.</param>
/// <param name="rdLength">Resource record data length.</param>
/// <param name="ttl">Time to live in seconds.</param>
public static DNS_rr_A Parse(byte[] reply,ref int offset,int rdLength,int ttl)
{
// IPv4 = byte byte byte byte
byte[] ip = new byte[rdLength];
Array.Copy(reply,offset,ip,0,rdLength);
offset += rdLength;
return new DNS_rr_A(new IPAddress(ip),ttl);
}
#endregion
#region Properties Implementation
/// <summary>
/// Gets host IP address.
/// </summary>
public IPAddress IP
{
get{ return m_IP; }
}
#endregion
}
}
| bsd-3-clause |
lsanzdiaz/MITK-BiiG | Core/Code/Interactions/mitkDisplayVectorInteractorLevelWindow.h | 3003 | /*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#ifndef MITKDisplayVectorInteractorLevelWindow_H_HEADER_INCLUDED_C10DC4EB
#define MITKDisplayVectorInteractorLevelWindow_H_HEADER_INCLUDED_C10DC4EB
#include <MitkCoreExports.h>
#include "mitkBaseRenderer.h"
#include "mitkStateMachine.h"
namespace mitk {
class Operation;
class OperationActor;
/**
* @brief Interactor for adjusting both level- and window-values for an image
*
* This class implements an Interactor for adjusting the LevelWindow. It is defined by the 'LevelWindow'-statemachine which maps 'initmove' to right mousebutton pressed,
* 'levelwindow' to right mousebutton and move and 'finishmove' to right mousebutton released.
*
* Using this tool, it is possible to increase the 'level'-value of the selected image
* ( if no image has the 'selected'-property == true, the first image in the DataStorage is used )
* by moving the mouse right and decreasing the level by moving the mouse to the left.
*
* The 'window'-value and also be adjusted by moving the mouse-curser up (increase) and down (decrease).
*
* @ingroup MITK_CORE_EXPORT
**/
class MITK_CORE_EXPORT DisplayVectorInteractorLevelWindow : public StateMachine
{
public:
mitkClassMacro(DisplayVectorInteractorLevelWindow, StateMachine);
mitkNewMacro1Param(Self, const char*);
itkEventMacro( InteractionEvent, itk::AnyEvent );
itkEventMacro( StartInteractionEvent, InteractionEvent );
itkEventMacro( EndInteractionEvent, InteractionEvent );
//static Pointer New(const char* type)
//{
// Pointer smartPtr = new DisplayVectorInteractorLevelWindow ( type );
// smartPtr->UnRegister();
// return smartPtr;
//}
/**
* @brief Method derived from OperationActor to recieve and execute operations
**/
virtual void ExecuteOperation(Operation* operation);
protected:
/**
* @brief Default Constructor
**/
DisplayVectorInteractorLevelWindow(const char * type);
/**
* @brief Default Destructor
**/
virtual ~DisplayVectorInteractorLevelWindow();
/**
* @brief Method derived from StateMachine to implement the own actions
**/
virtual bool ExecuteAction(Action* action, mitk::StateEvent const* stateEvent);
private:
BaseRenderer::Pointer m_Sender;
mitk::Point2D m_StartDisplayCoordinate;
mitk::Point2D m_LastDisplayCoordinate;
mitk::Point2D m_CurrentDisplayCoordinate;
};
} // namespace mitk
#endif /* MITKDISPLAYVECTORINTERACTOR_H_HEADER_INCLUDED_C10DC4EB */
| bsd-3-clause |
maxwell-demon/grpc | src/ruby/ext/grpc/rb_call_credentials.c | 11264 | /*
*
* Copyright 2015, Google 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 Google Inc. 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.
*
*/
#include "rb_call_credentials.h"
#include <ruby/ruby.h>
#include <ruby/thread.h>
#include <grpc/grpc.h>
#include <grpc/grpc_security.h>
#include "rb_call.h"
#include "rb_grpc.h"
/* grpc_rb_cCallCredentials is the ruby class that proxies
* grpc_call_credentials */
static VALUE grpc_rb_cCallCredentials = Qnil;
/* grpc_rb_call_credentials wraps a grpc_call_credentials. It provides a peer
* ruby object, 'mark' to minimize copying when a credential is created from
* ruby. */
typedef struct grpc_rb_call_credentials {
/* Holder of ruby objects involved in contructing the credentials */
VALUE mark;
/* The actual credentials */
grpc_call_credentials *wrapped;
} grpc_rb_call_credentials;
typedef struct callback_params {
VALUE get_metadata;
grpc_auth_metadata_context context;
void *user_data;
grpc_credentials_plugin_metadata_cb callback;
} callback_params;
static VALUE grpc_rb_call_credentials_callback(VALUE callback_args) {
VALUE result = rb_hash_new();
VALUE metadata = rb_funcall(rb_ary_entry(callback_args, 0), rb_intern("call"),
1, rb_ary_entry(callback_args, 1));
rb_hash_aset(result, rb_str_new2("metadata"), metadata);
rb_hash_aset(result, rb_str_new2("status"), INT2NUM(GRPC_STATUS_OK));
rb_hash_aset(result, rb_str_new2("details"), rb_str_new2(""));
return result;
}
static VALUE grpc_rb_call_credentials_callback_rescue(VALUE args,
VALUE exception_object) {
VALUE result = rb_hash_new();
rb_hash_aset(result, rb_str_new2("metadata"), Qnil);
/* Currently only gives the exception class name. It should be possible get
more details */
rb_hash_aset(result, rb_str_new2("status"),
INT2NUM(GRPC_STATUS_PERMISSION_DENIED));
rb_hash_aset(result, rb_str_new2("details"),
rb_str_new2(rb_obj_classname(exception_object)));
return result;
}
static void *grpc_rb_call_credentials_callback_with_gil(void *param) {
callback_params *const params = (callback_params *)param;
VALUE auth_uri = rb_str_new_cstr(params->context.service_url);
/* Pass the arguments to the proc in a hash, which currently only has they key
'auth_uri' */
VALUE callback_args = rb_ary_new();
VALUE args = rb_hash_new();
VALUE result;
grpc_metadata_array md_ary;
grpc_status_code status;
VALUE details;
char *error_details;
grpc_metadata_array_init(&md_ary);
rb_hash_aset(args, ID2SYM(rb_intern("jwt_aud_uri")), auth_uri);
rb_ary_push(callback_args, params->get_metadata);
rb_ary_push(callback_args, args);
result = rb_rescue(grpc_rb_call_credentials_callback, callback_args,
grpc_rb_call_credentials_callback_rescue, Qnil);
// Both callbacks return a hash, so result should be a hash
grpc_rb_md_ary_convert(rb_hash_aref(result, rb_str_new2("metadata")), &md_ary);
status = NUM2INT(rb_hash_aref(result, rb_str_new2("status")));
details = rb_hash_aref(result, rb_str_new2("details"));
error_details = StringValueCStr(details);
params->callback(params->user_data, md_ary.metadata, md_ary.count, status,
error_details);
grpc_metadata_array_destroy(&md_ary);
return NULL;
}
static void grpc_rb_call_credentials_plugin_get_metadata(
void *state, grpc_auth_metadata_context context,
grpc_credentials_plugin_metadata_cb cb, void *user_data) {
callback_params params;
params.get_metadata = (VALUE)state;
params.context = context;
params.user_data = user_data;
params.callback = cb;
rb_thread_call_with_gvl(grpc_rb_call_credentials_callback_with_gil,
(void*)(¶ms));
}
static void grpc_rb_call_credentials_plugin_destroy(void *state) {
// Not sure what needs to be done here
}
/* Destroys the credentials instances. */
static void grpc_rb_call_credentials_free(void *p) {
grpc_rb_call_credentials *wrapper;
if (p == NULL) {
return;
}
wrapper = (grpc_rb_call_credentials *)p;
/* Delete the wrapped object if the mark object is Qnil, which indicates that
* no other object is the actual owner. */
if (wrapper->wrapped != NULL && wrapper->mark == Qnil) {
grpc_call_credentials_release(wrapper->wrapped);
wrapper->wrapped = NULL;
}
xfree(p);
}
/* Protects the mark object from GC */
static void grpc_rb_call_credentials_mark(void *p) {
grpc_rb_call_credentials *wrapper = NULL;
if (p == NULL) {
return;
}
wrapper = (grpc_rb_call_credentials *)p;
/* If it's not already cleaned up, mark the mark object */
if (wrapper->mark != Qnil) {
rb_gc_mark(wrapper->mark);
}
}
static rb_data_type_t grpc_rb_call_credentials_data_type = {
"grpc_call_credentials",
{grpc_rb_call_credentials_mark, grpc_rb_call_credentials_free,
GRPC_RB_MEMSIZE_UNAVAILABLE, {NULL, NULL}},
NULL,
NULL,
#ifdef RUBY_TYPED_FREE_IMMEDIATELY
RUBY_TYPED_FREE_IMMEDIATELY
#endif
};
/* Allocates CallCredentials instances.
Provides safe initial defaults for the instance fields. */
static VALUE grpc_rb_call_credentials_alloc(VALUE cls) {
grpc_rb_call_credentials *wrapper = ALLOC(grpc_rb_call_credentials);
wrapper->wrapped = NULL;
wrapper->mark = Qnil;
return TypedData_Wrap_Struct(cls, &grpc_rb_call_credentials_data_type, wrapper);
}
/* Creates a wrapping object for a given call credentials. This should only be
* called with grpc_call_credentials objects that are not already associated
* with any Ruby object */
VALUE grpc_rb_wrap_call_credentials(grpc_call_credentials *c) {
VALUE rb_wrapper;
grpc_rb_call_credentials *wrapper;
if (c == NULL) {
return Qnil;
}
rb_wrapper = grpc_rb_call_credentials_alloc(grpc_rb_cCallCredentials);
TypedData_Get_Struct(rb_wrapper, grpc_rb_call_credentials,
&grpc_rb_call_credentials_data_type, wrapper);
wrapper->wrapped = c;
return rb_wrapper;
}
/* Clones CallCredentials instances.
Gives CallCredentials a consistent implementation of Ruby's object copy/dup
protocol. */
static VALUE grpc_rb_call_credentials_init_copy(VALUE copy, VALUE orig) {
grpc_rb_call_credentials *orig_cred = NULL;
grpc_rb_call_credentials *copy_cred = NULL;
if (copy == orig) {
return copy;
}
/* Raise an error if orig is not a credentials object or a subclass. */
if (TYPE(orig) != T_DATA ||
RDATA(orig)->dfree != (RUBY_DATA_FUNC)grpc_rb_call_credentials_free) {
rb_raise(rb_eTypeError, "not a %s",
rb_obj_classname(grpc_rb_cCallCredentials));
}
TypedData_Get_Struct(orig, grpc_rb_call_credentials,
&grpc_rb_call_credentials_data_type, orig_cred);
TypedData_Get_Struct(copy, grpc_rb_call_credentials,
&grpc_rb_call_credentials_data_type, copy_cred);
/* use ruby's MEMCPY to make a byte-for-byte copy of the credentials
* wrapper object. */
MEMCPY(copy_cred, orig_cred, grpc_rb_call_credentials, 1);
return copy;
}
/* The attribute used on the mark object to hold the callback */
static ID id_callback;
/*
call-seq:
creds = Credentials.new auth_proc
proc: (required) Proc that generates auth metadata
Initializes CallCredential instances. */
static VALUE grpc_rb_call_credentials_init(VALUE self, VALUE proc) {
grpc_rb_call_credentials *wrapper = NULL;
grpc_call_credentials *creds = NULL;
grpc_metadata_credentials_plugin plugin;
TypedData_Get_Struct(self, grpc_rb_call_credentials,
&grpc_rb_call_credentials_data_type, wrapper);
plugin.get_metadata = grpc_rb_call_credentials_plugin_get_metadata;
plugin.destroy = grpc_rb_call_credentials_plugin_destroy;
if (!rb_obj_is_proc(proc)) {
rb_raise(rb_eTypeError, "Argument to CallCredentials#new must be a proc");
return Qnil;
}
plugin.state = (void*)proc;
plugin.type = "";
creds = grpc_metadata_credentials_create_from_plugin(plugin, NULL);
if (creds == NULL) {
rb_raise(rb_eRuntimeError, "could not create a credentials, not sure why");
return Qnil;
}
wrapper->wrapped = creds;
rb_ivar_set(self, id_callback, proc);
return self;
}
static VALUE grpc_rb_call_credentials_compose(int argc, VALUE *argv,
VALUE self) {
grpc_call_credentials *creds;
grpc_call_credentials *other;
if (argc == 0) {
return self;
}
creds = grpc_rb_get_wrapped_call_credentials(self);
for (int i = 0; i < argc; i++) {
other = grpc_rb_get_wrapped_call_credentials(argv[i]);
creds = grpc_composite_call_credentials_create(creds, other, NULL);
}
return grpc_rb_wrap_call_credentials(creds);
}
void Init_grpc_call_credentials() {
grpc_rb_cCallCredentials =
rb_define_class_under(grpc_rb_mGrpcCore, "CallCredentials", rb_cObject);
/* Allocates an object managed by the ruby runtime */
rb_define_alloc_func(grpc_rb_cCallCredentials,
grpc_rb_call_credentials_alloc);
/* Provides a ruby constructor and support for dup/clone. */
rb_define_method(grpc_rb_cCallCredentials, "initialize",
grpc_rb_call_credentials_init, 1);
rb_define_method(grpc_rb_cCallCredentials, "initialize_copy",
grpc_rb_call_credentials_init_copy, 1);
rb_define_method(grpc_rb_cCallCredentials, "compose",
grpc_rb_call_credentials_compose, -1);
id_callback = rb_intern("__callback");
}
/* Gets the wrapped grpc_call_credentials from the ruby wrapper */
grpc_call_credentials *grpc_rb_get_wrapped_call_credentials(VALUE v) {
grpc_rb_call_credentials *wrapper = NULL;
TypedData_Get_Struct(v, grpc_rb_call_credentials,
&grpc_rb_call_credentials_data_type,
wrapper);
return wrapper->wrapped;
}
| bsd-3-clause |
aislab-hevs/magpie | MAGPIE/library/src/main/java/ch/hevs/aislab/magpie/event/LogicTupleEvent.java | 3019 | package ch.hevs.aislab.magpie.event;
import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList;
import java.util.List;
import alice.tuprolog.Term;
import ch.hevs.aislab.magpie.environment.Services;
public class LogicTupleEvent extends MagpieEvent {
private String logicRepresentation;
public LogicTupleEvent(Term term) {
this.type = Services.LOGIC_TUPLE;
this.logicRepresentation = term.toString();
}
public LogicTupleEvent(long timestamp, String logicEvent) {
this(logicEvent);
this.setTimestamp(timestamp);
}
public LogicTupleEvent(String logicEvent) {
this.type = Services.LOGIC_TUPLE;
// This checks if the Term is correct
Term term = Term.createTerm(logicEvent);
this.logicRepresentation = term.toString();
}
/**
* Creates a logic tuple with format: name(arg1,arg2,...,argN), and assigns the timestamp to the
* event
* @param timestamp
* @param name
* @param args
*/
public LogicTupleEvent(long timestamp, String name, String ... args) {
this(name, args);
this.setTimestamp(timestamp);
}
/**
* Creates a logic tuple with format: name(arg1,arg2,...,argN), and assigns the current timestamp
* to the event
* @param name
* @param args
*/
public LogicTupleEvent(String name, String ... args) {
this.type = Services.LOGIC_TUPLE;
String tuple = name + "(";
for (String arg : args) {
tuple = tuple + arg + ",";
}
// Remove the last comma and close the parenthesis
tuple = tuple.substring(0, tuple.length() - 1);
tuple = tuple + ")";
this.logicRepresentation = tuple;
}
/**
* It returns the tuple representation of the event
*
* @return
*/
public String toTuple(){
return logicRepresentation;
}
public String getName() {
int end = logicRepresentation.indexOf("(");
return logicRepresentation.substring(0,end);
}
public List<String> getArguments() {
List<String> arguments = new ArrayList<>();
int elements = StringUtils.countMatches(logicRepresentation, ",");
if (elements == 0) {
arguments.add(getSubstring("(", ")"));
} else if (elements == 1) {
arguments.add(getSubstring("(", ","));
arguments.add(getSubstring(",", ")"));
} else if (elements > 1) {
arguments.add(getSubstring("(", ","));
String restString = getSubstring(",", ")");
String[] restArray = StringUtils.split(restString, ",");
for (String aRestArray : restArray) {
arguments.add(aRestArray);
}
}
return arguments;
}
private String getSubstring(String start, String end) {
int first = StringUtils.indexOf(logicRepresentation, start);
int second = StringUtils.indexOf(logicRepresentation, end);
return StringUtils.substring(logicRepresentation, first + 1, second);
}
}
| bsd-3-clause |
FarGroup/FarManager | enc/enc_rus/meta/structures/openinfo.html | 9307 | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>OpenInfo</title>
<meta http-equiv="Content-Type" Content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="../../styles/styles.css">
<script language="javascript" src='../links.js' type="text/javascript"></script>
</head>
<body>
<h1>OpenInfo</h1>
<div class=navbar>
<a href="../index.html">главная</a> |
<a href="index.html">структуры</a> |
<a href="../basicapi/index.html">Basic API</a>
</div>
<div class=shortdescr>
Структура <code>OpenInfo</code> используется для возвращения Far Manager'ом информации о плагине в функцию <a href="../exported_functions/openw.html">OpenW</a>.
</div>
<pre class=syntax>
struct OpenInfo
{
size_t StructSize;
enum OPENFROM OpenFrom;
const GUID *Guid;
intptr_t Data;
};
</pre>
<h3>Элементы</h3>
<div class=descr>
<div class=dfn>StructSize</div>
<div class=dfndescr>Это поле содержит размер структуры <code>OpenInfo</code>.</div>
<div class=dfn>OpenFrom</div>
<div class=dfndescr>Идентификатор, определяющий, откуда был вызван плагин. Может принимать одно из следующих значений (перечисление <a name="OPENFROM">OPENFROM</a>):
<table class="cont">
<tr class="cont"><th class="cont" width="40%">Константа</th><th class="cont" width="60%">Описание</th></tr>
<tr class="cont"><td class="cont" width="40%"><a name="OPEN_LEFTDISKMENU">OPEN_LEFTDISKMENU</a></td>
<td class="cont" width="60%">Открыт из левого меню "Сменить диск" (<kbd>Alt</kbd>+<kbd>F1</kbd>).</td></tr>
<tr class="cont"><td class="cont" width="40%"><a name="OPEN_PLUGINSMENU">OPEN_PLUGINSMENU</a></td>
<td class="cont" width="60%">Открыт из меню "Команды внешних модулей" (<kbd>F11</kbd>).</td></tr>
<tr class="cont"><td class="cont" width="40%"><a name="OPEN_FINDLIST">OPEN_FINDLIST</a></td>
<td class="cont" width="60%">Открыт из диалога "Поиск файла". Этот идентификатор плагин получит только в том случае, если он экспортирует функцию <a href="../exported_functions/setfindlistw.html">SetFindListW</a>.
Последующий вызов функции <a href="../exported_functions/setfindlistw.html">SetFindListW</a> произойдёт только в том случае, если функция <code>OpenW</code> вернёт значение отличное от <code>NULL</code>.</td></tr>
<tr class="cont"><td class="cont" width="40%"><a name="OPEN_SHORTCUT">OPEN_SHORTCUT</a></td>
<td class="cont" width="60%">Открыт через ссылку на папку в меню "Команды" - "Ссылки на папки".</td></tr>
<tr class="cont"><td class="cont" width="40%"><a name="OPEN_COMMANDLINE">OPEN_COMMANDLINE</a></td>
<td class="cont" width="60%">Был открыт из командной строки. Этот параметр может использоваться, только если плагин определил вызывающий префикс в функции
<a href="../exported_functions/getplugininfow.html">GetPluginInfoW</a> и этот префикс, с двоеточием после него, был указан в командной строке.</td></tr>
<tr class="cont"><td class="cont" width="40%"><a name="OPEN_EDITOR">OPEN_EDITOR</a></td>
<td class="cont" width="60%">Открыт из редактора.</td></tr>
<tr class="cont"><td class="cont" width="40%"><a name="OPEN_VIEWER">OPEN_VIEWER</a></td>
<td class="cont" width="60%">Открыт из встроенной программы просмотра.</td></tr>
<tr class="cont"><td class="cont" width="40%"><a name="OPEN_FILEPANEL">OPEN_FILEPANEL</a></td>
<td class="cont" width="60%">Открыт из панелей.</td></tr>
<tr class="cont"><td class="cont" width="40%"><a name="OPEN_DIALOG">OPEN_DIALOG</a></td>
<td class="cont" width="60%">Открыт из диалога.</td></tr>
<tr class="cont"><td class="cont" width="40%"><a name="OPEN_ANALYSE">OPEN_ANALYSE</a></td>
<td class="cont" width="60%">Открыт после анализа содержимого файла (например, архива)</td></tr>
<tr class="cont"><td class="cont" width="40%"><a name="OPEN_RIGHTDISKMENU">OPEN_RIGHTDISKMENU</a></td>
<td class="cont" width="60%">Открыт из правого меню "Сменить диск" (<kbd>Alt</kbd>+<kbd>F2</kbd>).</td></tr>
<tr class="cont"><td class="cont" width="40%"><a name="OPEN_FROMMACRO">OPEN_FROMMACRO</a></td>
<td class="cont" width="60%">Открыт из макрокоманды макрофункцией <a href="../macro/macrocmd/prop_func/general.html#Plugin.Call">Plugin.Call</a>.</td></tr>
<tr class="cont"><td class="cont" width="40%"><a name="OPEN_LUAMACRO">OPEN_LUAMACRO</a></td>
<td class="cont" width="60%">Открыт для проверки или исполнения Lua-макроскрипта.</td></tr>
</table></div>
<div class=dfn>Guid</div>
<div class=dfndescr>GUID выбранного элемента в списке пунктов, экспортированном данным плагином в меню "Диск", "Команды внешних модулей".</div>
<div class=dfn>Data</div>
<div class=dfndescr>Интерпретация параметра зависит от <code>OpenFrom</code>:
<table class="cont">
<tr class="cont"><th class="cont" width="40%">Константа</th><th class="cont" width="60%">Описание</th></tr>
<tr class="cont"><td class="cont" width="40%"><a name="OPEN_LEFTDISKMENU">OPEN_LEFTDISKMENU</a></td>
<td class="cont" width="60%">Этот параметр всегда равен <code>0</code>.</td></tr>
<tr class="cont"><td class="cont" width="40%"><a name="OPEN_PLUGINSMENU">OPEN_PLUGINSMENU</a></td>
<td class="cont" width="60%">Этот параметр всегда равен <code>0</code>.</td></tr>
<tr class="cont"><td class="cont" width="40%"><a name="OPEN_FINDLIST">OPEN_FINDLIST</a></td>
<td class="cont" width="60%">Этот параметр всегда равен <code>0</code>.</td></tr>
<tr class="cont"><td class="cont" width="40%"><a name="OPEN_SHORTCUT">OPEN_SHORTCUT</a></td>
<td class="cont" width="60%">Этот параметр равен адресу структуры <a href="../structures/openshortcutinfo.html">OpenShortcutInfo</a>, данные в момент сохранения горячей клавиши.</td></tr>
<tr class="cont"><td class="cont" width="40%"><a name="OPEN_COMMANDLINE">OPEN_COMMANDLINE</a></td>
<td class="cont" width="60%">Этот параметр равен адресу структуры <a href="../structures/opencommandlineinfo.html">OpenCommandLineInfo</a>, данные о командной строке.</td></tr>
<tr class="cont"><td class="cont" width="40%"><a name="OPEN_EDITOR">OPEN_EDITOR</a></td>
<td class="cont" width="60%">Этот параметр всегда равен <code>0</code>.</td></tr>
<tr class="cont"><td class="cont" width="40%"><a name="OPEN_VIEWER">OPEN_VIEWER</a></td>
<td class="cont" width="60%">Этот параметр всегда равен <code>0</code>.</td></tr>
<tr class="cont"><td class="cont" width="40%"><a name="OPEN_FILEPANEL">OPEN_FILEPANEL</a></td>
<td class="cont" width="60%">Этот параметр всегда равен <code>0</code>.</td></tr>
<tr class="cont"><td class="cont" width="40%"><a name="OPEN_DIALOG">OPEN_DIALOG</a></td>
<td class="cont" width="60%">Этот параметр равен адресу структуры <a href="../structures/opendlgplugindata.html">OpenDlgPluginData</a>, данные о диалоге.</td></tr>
<tr class="cont"><td class="cont" width="40%"><a name="OPEN_ANALYSE">OPEN_ANALYSE</a></td>
<td class="cont" width="60%">Этот параметр равен адресу структуры <a href="../structures/openanalyseinfo.html">OpenAnalyseInfo</a>, данные о файле-контейнере. Вы должны освободить их так, как будто бы получили их в <a href="../exported_functions/closeanalysew.html">CloseAnalyseW</a></td></tr>
<tr class="cont"><td class="cont" width="40%"><a name="OPEN_RIGHTDISKMENU">OPEN_RIGHTDISKMENU</a></td>
<td class="cont" width="60%">Этот параметр всегда равен <code>0</code>.</td></tr>
<tr class="cont"><td class="cont" width="40%"><a name="OPEN_FROMMACRO">OPEN_FROMMACRO</a></td>
<td class="cont" width="60%">Этот параметр равен адресу структуры <a href="openmacroinfo.html">OpenMacroInfo</a>.</td></tr>
</table></div>
</div>
<div class=see>Смотрите также:</div>
<div class=seecont>
<a href="index.html">структуры</a>
</div>
</body>
</html> | bsd-3-clause |
patrick-luethi/Envision | ModelBase/src/test_nodes/PositionExtension.cpp | 2073 | /***********************************************************************************************************************
**
** Copyright (c) 2011, 2014 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.
**
***********************************************************************************************************************/
#include "test_nodes/PositionExtension.h"
namespace TestNodes {
DEFINE_EXTENSION(PositionExtension)
REGISTER_EXTENSION_ATTRIBUTE(PositionExtension, x, Integer, false, false, true)
REGISTER_EXTENSION_ATTRIBUTE(PositionExtension, y, Integer, false, false, true)
}
| bsd-3-clause |
JianpingZeng/xcc | xcc/test/juliet/testcases/CWE789_Uncontrolled_Mem_Alloc/s01/CWE789_Uncontrolled_Mem_Alloc__malloc_wchar_t_connect_socket_81.h | 1805 | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE789_Uncontrolled_Mem_Alloc__malloc_wchar_t_connect_socket_81.h
Label Definition File: CWE789_Uncontrolled_Mem_Alloc__malloc.label.xml
Template File: sources-sinks-81.tmpl.h
*/
/*
* @description
* CWE: 789 Uncontrolled Memory Allocation
* BadSource: connect_socket Read data using a connect socket (client side)
* GoodSource: Small number greater than zero
* Sinks:
* GoodSink: Allocate memory with malloc() and check the size of the memory to be allocated
* BadSink : Allocate memory with malloc(), but incorrectly check the size of the memory to be allocated
* Flow Variant: 81 Data flow: data passed in a parameter to an virtual method called via a reference
*
* */
#include "std_testcase.h"
#ifndef _WIN32
#include <wchar.h>
#endif
namespace CWE789_Uncontrolled_Mem_Alloc__malloc_wchar_t_connect_socket_81
{
class CWE789_Uncontrolled_Mem_Alloc__malloc_wchar_t_connect_socket_81_base
{
public:
/* pure virtual function */
virtual void action(size_t data) const = 0;
};
#ifndef OMITBAD
class CWE789_Uncontrolled_Mem_Alloc__malloc_wchar_t_connect_socket_81_bad : public CWE789_Uncontrolled_Mem_Alloc__malloc_wchar_t_connect_socket_81_base
{
public:
void action(size_t data) const;
};
#endif /* OMITBAD */
#ifndef OMITGOOD
class CWE789_Uncontrolled_Mem_Alloc__malloc_wchar_t_connect_socket_81_goodG2B : public CWE789_Uncontrolled_Mem_Alloc__malloc_wchar_t_connect_socket_81_base
{
public:
void action(size_t data) const;
};
class CWE789_Uncontrolled_Mem_Alloc__malloc_wchar_t_connect_socket_81_goodB2G : public CWE789_Uncontrolled_Mem_Alloc__malloc_wchar_t_connect_socket_81_base
{
public:
void action(size_t data) const;
};
#endif /* OMITGOOD */
}
| bsd-3-clause |
scheib/chromium | chrome/common/safe_browsing/binary_feature_extractor_win_unittest.cc | 8848 | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/common/safe_browsing/binary_feature_extractor.h"
#include <string>
#include <vector>
#include "base/base_paths.h"
#include "base/files/file_path.h"
#include "base/memory/ref_counted.h"
#include "base/path_service.h"
#include "chrome/common/chrome_paths.h"
#include "components/safe_browsing/core/common/proto/csd.pb.h"
#include "net/cert/x509_cert_types.h"
#include "net/cert/x509_certificate.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace safe_browsing {
class BinaryFeatureExtractorWinTest : public testing::Test {
protected:
void SetUp() override {
base::FilePath source_path;
ASSERT_TRUE(base::PathService::Get(chrome::DIR_TEST_DATA, &source_path));
testdata_path_ = source_path
.AppendASCII("safe_browsing")
.AppendASCII("download_protection");
binary_feature_extractor_ = new BinaryFeatureExtractor();
}
// Given a certificate chain protobuf, parse it into X509Certificates.
void ParseCertificateChain(
const ClientDownloadRequest_CertificateChain& chain,
std::vector<scoped_refptr<net::X509Certificate> >* certs) {
for (int i = 0; i < chain.element_size(); ++i) {
scoped_refptr<net::X509Certificate> cert =
net::X509Certificate::CreateFromBytes(
base::as_bytes(base::make_span(chain.element(i).certificate())));
if (cert)
certs->push_back(cert);
}
}
base::FilePath testdata_path_;
scoped_refptr<BinaryFeatureExtractor> binary_feature_extractor_;
};
TEST_F(BinaryFeatureExtractorWinTest, UntrustedSignedBinary) {
// signed.exe is signed by an untrusted root CA.
ClientDownloadRequest_SignatureInfo signature_info;
binary_feature_extractor_->CheckSignature(
testdata_path_.Append(L"signed.exe"),
&signature_info);
ASSERT_EQ(1, signature_info.certificate_chain_size());
std::vector<scoped_refptr<net::X509Certificate> > certs;
ParseCertificateChain(signature_info.certificate_chain(0), &certs);
ASSERT_EQ(2u, certs.size());
EXPECT_EQ("Joe's-Software-Emporium", certs[0]->subject().common_name);
EXPECT_EQ("Root Agency", certs[1]->subject().common_name);
EXPECT_TRUE(signature_info.has_trusted());
EXPECT_FALSE(signature_info.trusted());
}
TEST_F(BinaryFeatureExtractorWinTest, TrustedBinary) {
// disable_outdated_build_detector.exe is dual signed using Google's signing
// certifiacte.
ClientDownloadRequest_SignatureInfo signature_info;
binary_feature_extractor_->CheckSignature(
testdata_path_.Append(L"disable_outdated_build_detector.exe"),
&signature_info);
ASSERT_EQ(1, signature_info.certificate_chain_size());
std::vector<scoped_refptr<net::X509Certificate> > certs;
ParseCertificateChain(signature_info.certificate_chain(0), &certs);
ASSERT_EQ(3u, certs.size());
EXPECT_EQ("Google Inc", certs[0]->subject().common_name);
EXPECT_EQ("VeriSign Class 3 Code Signing 2010 CA",
certs[1]->subject().common_name);
EXPECT_EQ("VeriSign Trust Network",
certs[2]->subject().organization_unit_names[0]);
EXPECT_TRUE(signature_info.trusted());
}
TEST_F(BinaryFeatureExtractorWinTest, UnsignedBinary) {
// unsigned.exe has no signature information.
ClientDownloadRequest_SignatureInfo signature_info;
binary_feature_extractor_->CheckSignature(
testdata_path_.Append(L"unsigned.exe"),
&signature_info);
EXPECT_EQ(0, signature_info.certificate_chain_size());
EXPECT_FALSE(signature_info.has_trusted());
}
TEST_F(BinaryFeatureExtractorWinTest, NonExistentBinary) {
// Test a file that doesn't exist.
ClientDownloadRequest_SignatureInfo signature_info;
binary_feature_extractor_->CheckSignature(
testdata_path_.Append(L"doesnotexist.exe"),
&signature_info);
EXPECT_EQ(0, signature_info.certificate_chain_size());
EXPECT_FALSE(signature_info.has_trusted());
}
TEST_F(BinaryFeatureExtractorWinTest, ExtractImageFeaturesNoFile) {
// Test extracting headers from a file that doesn't exist.
ClientDownloadRequest_ImageHeaders image_headers;
ASSERT_FALSE(binary_feature_extractor_->ExtractImageFeatures(
testdata_path_.AppendASCII("this_file_does_not_exist"),
BinaryFeatureExtractor::kDefaultOptions, &image_headers,
nullptr /* signed_data */));
EXPECT_FALSE(image_headers.has_pe_headers());
}
TEST_F(BinaryFeatureExtractorWinTest, ExtractImageFeaturesNonImage) {
// Test extracting headers from something that is not a PE image.
ClientDownloadRequest_ImageHeaders image_headers;
ASSERT_FALSE(binary_feature_extractor_->ExtractImageFeatures(
testdata_path_.AppendASCII("simple_exe.cc"),
BinaryFeatureExtractor::kDefaultOptions, &image_headers,
nullptr /* signed_data */));
EXPECT_FALSE(image_headers.has_pe_headers());
}
TEST_F(BinaryFeatureExtractorWinTest, ExtractImageFeatures) {
// Test extracting features from something that is a PE image.
ClientDownloadRequest_ImageHeaders image_headers;
google::protobuf::RepeatedPtrField<std::string> signed_data;
ASSERT_TRUE(binary_feature_extractor_->ExtractImageFeatures(
testdata_path_.AppendASCII("unsigned.exe"),
BinaryFeatureExtractor::kDefaultOptions, &image_headers, &signed_data));
EXPECT_TRUE(image_headers.has_pe_headers());
const ClientDownloadRequest_PEImageHeaders& pe_headers =
image_headers.pe_headers();
EXPECT_TRUE(pe_headers.has_dos_header());
EXPECT_TRUE(pe_headers.has_file_header());
EXPECT_TRUE(pe_headers.has_optional_headers32());
EXPECT_FALSE(pe_headers.has_optional_headers64());
EXPECT_NE(0, pe_headers.section_header_size());
EXPECT_FALSE(pe_headers.has_export_section_data());
EXPECT_EQ(0, pe_headers.debug_data_size());
EXPECT_EQ(0, signed_data.size());
}
TEST_F(BinaryFeatureExtractorWinTest, ExtractImageFeaturesWithDebugData) {
// Test extracting headers from something that is a PE image with debug data.
ClientDownloadRequest_ImageHeaders image_headers;
ASSERT_TRUE(binary_feature_extractor_->ExtractImageFeatures(
testdata_path_.DirName().AppendASCII("module_with_exports_x86.dll"),
BinaryFeatureExtractor::kDefaultOptions, &image_headers,
nullptr /* signed_data */));
EXPECT_TRUE(image_headers.has_pe_headers());
const ClientDownloadRequest_PEImageHeaders& pe_headers =
image_headers.pe_headers();
EXPECT_TRUE(pe_headers.has_dos_header());
EXPECT_TRUE(pe_headers.has_file_header());
EXPECT_TRUE(pe_headers.has_optional_headers32());
EXPECT_FALSE(pe_headers.has_optional_headers64());
EXPECT_NE(0, pe_headers.section_header_size());
EXPECT_TRUE(pe_headers.has_export_section_data());
EXPECT_EQ(1, pe_headers.debug_data_size());
}
TEST_F(BinaryFeatureExtractorWinTest, ExtractImageFeaturesWithoutExports) {
// Test extracting headers from something that is a PE image with debug data.
ClientDownloadRequest_ImageHeaders image_headers;
ASSERT_TRUE(binary_feature_extractor_->ExtractImageFeatures(
testdata_path_.DirName().AppendASCII("module_with_exports_x86.dll"),
BinaryFeatureExtractor::kOmitExports, &image_headers,
nullptr /* signed_data */));
EXPECT_TRUE(image_headers.has_pe_headers());
const ClientDownloadRequest_PEImageHeaders& pe_headers =
image_headers.pe_headers();
EXPECT_TRUE(pe_headers.has_dos_header());
EXPECT_TRUE(pe_headers.has_file_header());
EXPECT_TRUE(pe_headers.has_optional_headers32());
EXPECT_FALSE(pe_headers.has_optional_headers64());
EXPECT_NE(0, pe_headers.section_header_size());
EXPECT_FALSE(pe_headers.has_export_section_data());
EXPECT_EQ(1, pe_headers.debug_data_size());
}
TEST_F(BinaryFeatureExtractorWinTest, ExtractImageFeaturesUntrustedSigned) {
// Test extracting features from a signed PE image.
ClientDownloadRequest_ImageHeaders image_headers;
google::protobuf::RepeatedPtrField<std::string> signed_data;
ASSERT_TRUE(binary_feature_extractor_->ExtractImageFeatures(
testdata_path_.AppendASCII("signed.exe"),
BinaryFeatureExtractor::kDefaultOptions, &image_headers, &signed_data));
ASSERT_EQ(1, signed_data.size());
ASSERT_LT(0U, signed_data.Get(0).size());
}
TEST_F(BinaryFeatureExtractorWinTest, ExtractImageFeaturesTrustedSigned) {
// Test extracting features from a signed PE image from a trusted root.
ClientDownloadRequest_ImageHeaders image_headers;
google::protobuf::RepeatedPtrField<std::string> signed_data;
ASSERT_TRUE(binary_feature_extractor_->ExtractImageFeatures(
testdata_path_.AppendASCII("disable_outdated_build_detector.exe"),
BinaryFeatureExtractor::kDefaultOptions, &image_headers, &signed_data));
ASSERT_EQ(1, signed_data.size());
ASSERT_LT(0U, signed_data.Get(0).size());
}
} // namespace safe_browsing
| bsd-3-clause |
beiyuxinke/CONNECT | Product/Production/Adapters/General/CONNECTDirectConfig/src/main/java/gov/hhs/fha/nhinc/directconfig/service/jaxws/DisassociatePolicyGroupFromDomains.java | 4210 | /*
* Copyright (c) 2009-2015, United States Government, as represented by the Secretary of Health and Human Services.
* 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 United States Government 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 UNITED STATES GOVERNMENT 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.
*/
/*
Copyright (c) 2010, NHIN Direct Project
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. 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.
3. Neither the name of the The NHIN Direct Project (nhindirect.org) 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.
*/
package gov.hhs.fha.nhinc.directconfig.service.jaxws;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
@XmlRootElement(name = "disassociatePolicyGroupFromDomains", namespace = "http://nhind.org/config")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "disassociatePolicyGroupFromDomains", namespace = "http://nhind.org/config")
public class DisassociatePolicyGroupFromDomains {
@XmlElement(name = "policyGroupId", namespace = "")
private long policyGroupId;
/**
*
* @return
* returns long
*/
public long getPolicyGroupId() {
return this.policyGroupId;
}
/**
*
* @param policyGroupId
* the value for the policyGroupId property
*/
public void setPolicyGroupId(long policyGroupId) {
this.policyGroupId = policyGroupId;
}
}
| bsd-3-clause |
tommy-u/enable | kiva/agg/agg-24/src/agg_vcgen_stroke.cpp | 7176 | //----------------------------------------------------------------------------
// Anti-Grain Geometry - Version 2.4
// Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com)
//
// Permission to copy, use, modify, sell and distribute this software
// is granted provided this copyright notice appears in all copies.
// This software is provided "as is" without express or implied
// warranty, and with no claim as to its suitability for any purpose.
//
//----------------------------------------------------------------------------
// Contact: [email protected]
// [email protected]
// http://www.antigrain.com
//----------------------------------------------------------------------------
//
// Stroke generator
//
//----------------------------------------------------------------------------
#include <math.h>
#include "agg_vcgen_stroke.h"
#include "agg_shorten_path.h"
namespace agg24
{
//------------------------------------------------------------------------
vcgen_stroke::vcgen_stroke() :
m_stroker(),
m_src_vertices(),
m_out_vertices(),
m_shorten(0.0),
m_closed(0),
m_status(initial),
m_src_vertex(0),
m_out_vertex(0)
{
}
//------------------------------------------------------------------------
void vcgen_stroke::remove_all()
{
m_src_vertices.remove_all();
m_closed = 0;
m_status = initial;
}
//------------------------------------------------------------------------
void vcgen_stroke::add_vertex(double x, double y, unsigned cmd)
{
m_status = initial;
if(is_move_to(cmd))
{
m_src_vertices.modify_last(vertex_dist(x, y));
}
else
{
if(is_vertex(cmd))
{
m_src_vertices.add(vertex_dist(x, y));
}
else
{
m_closed = get_close_flag(cmd);
}
}
}
//------------------------------------------------------------------------
void vcgen_stroke::rewind(unsigned)
{
if(m_status == initial)
{
m_src_vertices.close(m_closed != 0);
shorten_path(m_src_vertices, m_shorten, m_closed);
if(m_src_vertices.size() < 3) m_closed = 0;
}
m_status = ready;
m_src_vertex = 0;
m_out_vertex = 0;
}
//------------------------------------------------------------------------
unsigned vcgen_stroke::vertex(double* x, double* y)
{
unsigned cmd = path_cmd_line_to;
while(!is_stop(cmd))
{
switch(m_status)
{
case initial:
rewind(0);
case ready:
if(m_src_vertices.size() < 2 + unsigned(m_closed != 0))
{
cmd = path_cmd_stop;
break;
}
m_status = m_closed ? outline1 : cap1;
cmd = path_cmd_move_to;
m_src_vertex = 0;
m_out_vertex = 0;
break;
case cap1:
m_stroker.calc_cap(m_out_vertices,
m_src_vertices[0],
m_src_vertices[1],
m_src_vertices[0].dist);
m_src_vertex = 1;
m_prev_status = outline1;
m_status = out_vertices;
m_out_vertex = 0;
break;
case cap2:
m_stroker.calc_cap(m_out_vertices,
m_src_vertices[m_src_vertices.size() - 1],
m_src_vertices[m_src_vertices.size() - 2],
m_src_vertices[m_src_vertices.size() - 2].dist);
m_prev_status = outline2;
m_status = out_vertices;
m_out_vertex = 0;
break;
case outline1:
if(m_closed)
{
if(m_src_vertex >= m_src_vertices.size())
{
m_prev_status = close_first;
m_status = end_poly1;
break;
}
}
else
{
if(m_src_vertex >= m_src_vertices.size() - 1)
{
m_status = cap2;
break;
}
}
m_stroker.calc_join(m_out_vertices,
m_src_vertices.prev(m_src_vertex),
m_src_vertices.curr(m_src_vertex),
m_src_vertices.next(m_src_vertex),
m_src_vertices.prev(m_src_vertex).dist,
m_src_vertices.curr(m_src_vertex).dist);
++m_src_vertex;
m_prev_status = m_status;
m_status = out_vertices;
m_out_vertex = 0;
break;
case close_first:
m_status = outline2;
cmd = path_cmd_move_to;
case outline2:
if(m_src_vertex <= unsigned(m_closed == 0))
{
m_status = end_poly2;
m_prev_status = stop;
break;
}
--m_src_vertex;
m_stroker.calc_join(m_out_vertices,
m_src_vertices.next(m_src_vertex),
m_src_vertices.curr(m_src_vertex),
m_src_vertices.prev(m_src_vertex),
m_src_vertices.curr(m_src_vertex).dist,
m_src_vertices.prev(m_src_vertex).dist);
m_prev_status = m_status;
m_status = out_vertices;
m_out_vertex = 0;
break;
case out_vertices:
if(m_out_vertex >= m_out_vertices.size())
{
m_status = m_prev_status;
}
else
{
const point_d& c = m_out_vertices[m_out_vertex++];
*x = c.x;
*y = c.y;
return cmd;
}
break;
case end_poly1:
m_status = m_prev_status;
return path_cmd_end_poly | path_flags_close | path_flags_ccw;
case end_poly2:
m_status = m_prev_status;
return path_cmd_end_poly | path_flags_close | path_flags_cw;
case stop:
cmd = path_cmd_stop;
break;
}
}
return cmd;
}
}
| bsd-3-clause |
prakasha/Orchard1.4 | Modules/ESchool/Controllers/Frontend/CourseController.cs | 1352 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Orchard.Themes;
using Orchard.UI.Admin;
using Orchard.Data;
using ESchool.Models;
using Orchard.ContentManagement;
using Orchard;
using Orchard.Localization;
using Orchard.DisplayManagement;
using Orchard.UI.Notify;
using Orchard.Core.Feeds;
namespace ESchool.Controllers
{
[Themed]
public class CourseController : Controller
{
private readonly IContentManager contentManager;
dynamic Shape { get; set; }
public CourseController(IContentManager contentManager, IShapeFactory shapeFactory)
{
this.contentManager = contentManager;
Shape = shapeFactory;
}
public ActionResult List(int idYear)
{
var list = Shape.List();
list.AddRange(contentManager.Query<CoursePart, CourseRecord>(VersionOptions.Published).Where(x => x.Year.Id == idYear).OrderBy(x => x.Name).List().Select(b =>
{
var courseDisplay = contentManager.BuildDisplay(b);
return courseDisplay;
}));
var year = contentManager.Get<YearPart>(idYear);
dynamic viewModel = Shape.ViewModel().ContentItems(list).Year(year);
return View((object)viewModel);
}
}
} | bsd-3-clause |
modulexcite/MOSA-Project | Source/Mosa.Platform.x86/Instructions/Sar.cs | 1628 | // Copyright (c) MOSA Project. Licensed under the New BSD License.
using Mosa.Compiler.Framework;
namespace Mosa.Platform.x86.Instructions
{
/// <summary>
/// Intermediate representation of the arithmetic shift right instruction.
/// </summary>
public sealed class Sar : X86Instruction
{
#region Data Members
private static readonly OpCode C = new OpCode(new byte[] { 0xC1 }, 7);
private static readonly OpCode C1 = new OpCode(new byte[] { 0xD1 }, 7);
private static readonly OpCode RM = new OpCode(new byte[] { 0xD3 }, 7);
#endregion Data Members
#region Construction
/// <summary>
/// Initializes a new instance of <see cref="Shr"/>.
/// </summary>
public Sar() :
base(1, 2)
{
}
#endregion Construction
#region Methods
/// <summary>
/// Emits the specified platform instruction.
/// </summary>
/// <param name="node">The node.</param>
/// <param name="emitter">The emitter.</param>
protected override void Emit(InstructionNode node, MachineCodeEmitter emitter)
{
if (node.Operand2.IsConstant)
{
if (node.Operand2.IsConstantOne)
{
emitter.Emit(C1, node.Result, null);
}
else
{
emitter.Emit(C, node.Result, node.Operand2);
}
}
else
{
emitter.Emit(RM, node.Operand1, null);
}
}
/// <summary>
/// Allows visitor based dispatch for this instruction object.
/// </summary>
/// <param name="visitor">The visitor object.</param>
/// <param name="context">The context.</param>
public override void Visit(IX86Visitor visitor, Context context)
{
visitor.Sar(context);
}
#endregion Methods
}
}
| bsd-3-clause |
theosyspe/levent_01 | vendor/ZF2/bin/test/g/e.php | 35 | <?php
namespace test\g;
class e { } | bsd-3-clause |
openthread/openthread | src/core/net/ip6.cpp | 45337 | /*
* Copyright (c) 2016, The OpenThread Authors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
* 3. Neither the name of the copyright holder 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.
*/
/**
* @file
* This file implements IPv6 networking.
*/
#include "ip6.hpp"
#include "backbone_router/bbr_leader.hpp"
#include "backbone_router/bbr_local.hpp"
#include "backbone_router/ndproxy_table.hpp"
#include "common/code_utils.hpp"
#include "common/debug.hpp"
#include "common/instance.hpp"
#include "common/locator_getters.hpp"
#include "common/log.hpp"
#include "common/message.hpp"
#include "common/random.hpp"
#include "net/checksum.hpp"
#include "net/icmp6.hpp"
#include "net/ip6_address.hpp"
#include "net/ip6_filter.hpp"
#include "net/netif.hpp"
#include "net/udp6.hpp"
#include "openthread/ip6.h"
#include "thread/mle.hpp"
using IcmpType = ot::Ip6::Icmp::Header::Type;
static const IcmpType sForwardICMPTypes[] = {
IcmpType::kTypeDstUnreach, IcmpType::kTypePacketToBig, IcmpType::kTypeTimeExceeded,
IcmpType::kTypeParameterProblem, IcmpType::kTypeEchoRequest, IcmpType::kTypeEchoReply,
};
namespace ot {
namespace Ip6 {
RegisterLogModule("Ip6");
Ip6::Ip6(Instance &aInstance)
: InstanceLocator(aInstance)
, mForwardingEnabled(false)
, mIsReceiveIp6FilterEnabled(false)
, mReceiveIp6DatagramCallback(nullptr)
, mReceiveIp6DatagramCallbackContext(nullptr)
, mSendQueueTask(aInstance, Ip6::HandleSendQueue)
, mIcmp(aInstance)
, mUdp(aInstance)
, mMpl(aInstance)
#if OPENTHREAD_CONFIG_TCP_ENABLE
, mTcp(aInstance)
#endif
{
}
Message *Ip6::NewMessage(uint16_t aReserved, const Message::Settings &aSettings)
{
return Get<MessagePool>().Allocate(
Message::kTypeIp6, sizeof(Header) + sizeof(HopByHopHeader) + sizeof(OptionMpl) + aReserved, aSettings);
}
Message *Ip6::NewMessage(const uint8_t *aData, uint16_t aDataLength, const Message::Settings &aSettings)
{
Message *message = Get<MessagePool>().Allocate(Message::kTypeIp6, /* aReserveHeader */ 0, aSettings);
VerifyOrExit(message != nullptr);
if (message->AppendBytes(aData, aDataLength) != kErrorNone)
{
message->Free();
message = nullptr;
}
exit:
return message;
}
Message *Ip6::NewMessage(const uint8_t *aData, uint16_t aDataLength)
{
Message * message = nullptr;
Message::Priority priority;
SuccessOrExit(GetDatagramPriority(aData, aDataLength, priority));
message = NewMessage(aData, aDataLength, Message::Settings(Message::kWithLinkSecurity, priority));
exit:
return message;
}
Message::Priority Ip6::DscpToPriority(uint8_t aDscp)
{
Message::Priority priority;
uint8_t cs = aDscp & kDscpCsMask;
switch (cs)
{
case kDscpCs1:
case kDscpCs2:
priority = Message::kPriorityLow;
break;
case kDscpCs0:
case kDscpCs3:
priority = Message::kPriorityNormal;
break;
case kDscpCs4:
case kDscpCs5:
case kDscpCs6:
case kDscpCs7:
priority = Message::kPriorityHigh;
break;
default:
priority = Message::kPriorityNormal;
break;
}
return priority;
}
uint8_t Ip6::PriorityToDscp(Message::Priority aPriority)
{
uint8_t dscp = kDscpCs0;
switch (aPriority)
{
case Message::kPriorityLow:
dscp = kDscpCs1;
break;
case Message::kPriorityNormal:
case Message::kPriorityNet:
dscp = kDscpCs0;
break;
case Message::kPriorityHigh:
dscp = kDscpCs4;
break;
}
return dscp;
}
Error Ip6::GetDatagramPriority(const uint8_t *aData, uint16_t aDataLen, Message::Priority &aPriority)
{
Error error = kErrorNone;
const Header *header;
VerifyOrExit((aData != nullptr) && (aDataLen >= sizeof(Header)), error = kErrorInvalidArgs);
header = reinterpret_cast<const Header *>(aData);
VerifyOrExit(header->IsValid(), error = kErrorParse);
VerifyOrExit(sizeof(Header) + header->GetPayloadLength() == aDataLen, error = kErrorParse);
aPriority = DscpToPriority(header->GetDscp());
exit:
return error;
}
void Ip6::SetReceiveDatagramCallback(otIp6ReceiveCallback aCallback, void *aCallbackContext)
{
mReceiveIp6DatagramCallback = aCallback;
mReceiveIp6DatagramCallbackContext = aCallbackContext;
}
Error Ip6::AddMplOption(Message &aMessage, Header &aHeader)
{
Error error = kErrorNone;
HopByHopHeader hbhHeader;
OptionMpl mplOption;
OptionPadN padOption;
hbhHeader.SetNextHeader(aHeader.GetNextHeader());
hbhHeader.SetLength(0);
mMpl.InitOption(mplOption, aHeader.GetSource());
// Mpl option may require two bytes padding.
if ((mplOption.GetTotalLength() + sizeof(hbhHeader)) % 8)
{
padOption.Init(2);
SuccessOrExit(error = aMessage.PrependBytes(&padOption, padOption.GetTotalLength()));
}
SuccessOrExit(error = aMessage.PrependBytes(&mplOption, mplOption.GetTotalLength()));
SuccessOrExit(error = aMessage.Prepend(hbhHeader));
aHeader.SetPayloadLength(aHeader.GetPayloadLength() + sizeof(hbhHeader) + sizeof(mplOption));
aHeader.SetNextHeader(kProtoHopOpts);
exit:
return error;
}
Error Ip6::AddTunneledMplOption(Message &aMessage, Header &aHeader, MessageInfo &aMessageInfo)
{
Error error = kErrorNone;
Header tunnelHeader;
const Netif::UnicastAddress *source;
MessageInfo messageInfo(aMessageInfo);
// Use IP-in-IP encapsulation (RFC2473) and ALL_MPL_FORWARDERS address.
messageInfo.GetPeerAddr().SetToRealmLocalAllMplForwarders();
tunnelHeader.Init();
tunnelHeader.SetHopLimit(static_cast<uint8_t>(kDefaultHopLimit));
tunnelHeader.SetPayloadLength(aHeader.GetPayloadLength() + sizeof(tunnelHeader));
tunnelHeader.SetDestination(messageInfo.GetPeerAddr());
tunnelHeader.SetNextHeader(kProtoIp6);
VerifyOrExit((source = SelectSourceAddress(messageInfo)) != nullptr, error = kErrorInvalidSourceAddress);
tunnelHeader.SetSource(source->GetAddress());
SuccessOrExit(error = AddMplOption(aMessage, tunnelHeader));
SuccessOrExit(error = aMessage.Prepend(tunnelHeader));
exit:
return error;
}
Error Ip6::InsertMplOption(Message &aMessage, Header &aHeader, MessageInfo &aMessageInfo)
{
Error error = kErrorNone;
VerifyOrExit(aHeader.GetDestination().IsMulticast() &&
aHeader.GetDestination().GetScope() >= Address::kRealmLocalScope);
if (aHeader.GetDestination().IsRealmLocalMulticast())
{
aMessage.RemoveHeader(sizeof(aHeader));
if (aHeader.GetNextHeader() == kProtoHopOpts)
{
HopByHopHeader hbh;
uint16_t hbhLength = 0;
OptionMpl mplOption;
// read existing hop-by-hop option header
SuccessOrExit(error = aMessage.Read(0, hbh));
hbhLength = (hbh.GetLength() + 1) * 8;
VerifyOrExit(hbhLength <= aHeader.GetPayloadLength(), error = kErrorParse);
// increase existing hop-by-hop option header length by 8 bytes
hbh.SetLength(hbh.GetLength() + 1);
aMessage.Write(0, hbh);
// make space for MPL Option + padding by shifting hop-by-hop option header
SuccessOrExit(error = aMessage.PrependBytes(nullptr, 8));
aMessage.CopyTo(8, 0, hbhLength, aMessage);
// insert MPL Option
mMpl.InitOption(mplOption, aHeader.GetSource());
aMessage.WriteBytes(hbhLength, &mplOption, mplOption.GetTotalLength());
// insert Pad Option (if needed)
if (mplOption.GetTotalLength() % 8)
{
OptionPadN padOption;
padOption.Init(8 - (mplOption.GetTotalLength() % 8));
aMessage.WriteBytes(hbhLength + mplOption.GetTotalLength(), &padOption, padOption.GetTotalLength());
}
// increase IPv6 Payload Length
aHeader.SetPayloadLength(aHeader.GetPayloadLength() + 8);
}
else
{
SuccessOrExit(error = AddMplOption(aMessage, aHeader));
}
SuccessOrExit(error = aMessage.Prepend(aHeader));
}
else
{
#if OPENTHREAD_FTD
if (aHeader.GetDestination().IsMulticastLargerThanRealmLocal() &&
Get<ChildTable>().HasSleepyChildWithAddress(aHeader.GetDestination()))
{
Message *messageCopy = nullptr;
if ((messageCopy = aMessage.Clone()) != nullptr)
{
IgnoreError(HandleDatagram(*messageCopy, nullptr, nullptr, /* aFromHost */ true));
LogInfo("Message copy for indirect transmission to sleepy children");
}
else
{
LogWarn("No enough buffer for message copy for indirect transmission to sleepy children");
}
}
#endif
SuccessOrExit(error = AddTunneledMplOption(aMessage, aHeader, aMessageInfo));
}
exit:
return error;
}
Error Ip6::RemoveMplOption(Message &aMessage)
{
Error error = kErrorNone;
Header ip6Header;
HopByHopHeader hbh;
uint16_t offset;
uint16_t endOffset;
uint16_t mplOffset = 0;
uint8_t mplLength = 0;
bool remove = false;
offset = 0;
IgnoreError(aMessage.Read(offset, ip6Header));
offset += sizeof(ip6Header);
VerifyOrExit(ip6Header.GetNextHeader() == kProtoHopOpts);
IgnoreError(aMessage.Read(offset, hbh));
endOffset = offset + (hbh.GetLength() + 1) * 8;
VerifyOrExit(aMessage.GetLength() >= endOffset, error = kErrorParse);
offset += sizeof(hbh);
while (offset < endOffset)
{
OptionHeader option;
IgnoreError(aMessage.Read(offset, option));
switch (option.GetType())
{
case OptionMpl::kType:
// if multiple MPL options exist, discard packet
VerifyOrExit(mplOffset == 0, error = kErrorParse);
mplOffset = offset;
mplLength = option.GetLength();
VerifyOrExit(mplLength <= sizeof(OptionMpl) - sizeof(OptionHeader), error = kErrorParse);
if (mplOffset == sizeof(ip6Header) + sizeof(hbh) && hbh.GetLength() == 0)
{
// first and only IPv6 Option, remove IPv6 HBH Option header
remove = true;
}
else if (mplOffset + 8 == endOffset)
{
// last IPv6 Option, remove last 8 bytes
remove = true;
}
offset += sizeof(option) + option.GetLength();
break;
case OptionPad1::kType:
offset += sizeof(OptionPad1);
break;
case OptionPadN::kType:
offset += sizeof(option) + option.GetLength();
break;
default:
// encountered another option, now just replace MPL Option with PadN
remove = false;
offset += sizeof(option) + option.GetLength();
break;
}
}
// verify that IPv6 Options header is properly formed
VerifyOrExit(offset == endOffset, error = kErrorParse);
if (remove)
{
// last IPv6 Option, shrink HBH Option header
uint8_t buf[8];
offset = endOffset - sizeof(buf);
while (offset >= sizeof(buf))
{
IgnoreError(aMessage.Read(offset - sizeof(buf), buf));
aMessage.Write(offset, buf);
offset -= sizeof(buf);
}
aMessage.RemoveHeader(sizeof(buf));
if (mplOffset == sizeof(ip6Header) + sizeof(hbh))
{
// remove entire HBH header
ip6Header.SetNextHeader(hbh.GetNextHeader());
}
else
{
// update HBH header length
hbh.SetLength(hbh.GetLength() - 1);
aMessage.Write(sizeof(ip6Header), hbh);
}
ip6Header.SetPayloadLength(ip6Header.GetPayloadLength() - sizeof(buf));
aMessage.Write(0, ip6Header);
}
else if (mplOffset != 0)
{
// replace MPL Option with PadN Option
OptionPadN padOption;
padOption.Init(sizeof(OptionHeader) + mplLength);
aMessage.WriteBytes(mplOffset, &padOption, padOption.GetTotalLength());
}
exit:
return error;
}
void Ip6::EnqueueDatagram(Message &aMessage)
{
mSendQueue.Enqueue(aMessage);
mSendQueueTask.Post();
}
Error Ip6::SendDatagram(Message &aMessage, MessageInfo &aMessageInfo, uint8_t aIpProto)
{
Error error = kErrorNone;
Header header;
uint16_t payloadLength = aMessage.GetLength();
header.Init();
header.SetDscp(PriorityToDscp(aMessage.GetPriority()));
header.SetEcn(aMessageInfo.mEcn);
header.SetPayloadLength(payloadLength);
header.SetNextHeader(aIpProto);
if (aMessageInfo.GetHopLimit() != 0 || aMessageInfo.ShouldAllowZeroHopLimit())
{
header.SetHopLimit(aMessageInfo.GetHopLimit());
}
else
{
header.SetHopLimit(static_cast<uint8_t>(kDefaultHopLimit));
}
if (aMessageInfo.GetSockAddr().IsUnspecified() || aMessageInfo.GetSockAddr().IsMulticast())
{
const Netif::UnicastAddress *source = SelectSourceAddress(aMessageInfo);
VerifyOrExit(source != nullptr, error = kErrorInvalidSourceAddress);
header.SetSource(source->GetAddress());
}
else
{
header.SetSource(aMessageInfo.GetSockAddr());
}
header.SetDestination(aMessageInfo.GetPeerAddr());
if (aMessageInfo.GetPeerAddr().IsRealmLocalMulticast())
{
SuccessOrExit(error = AddMplOption(aMessage, header));
}
SuccessOrExit(error = aMessage.Prepend(header));
Checksum::UpdateMessageChecksum(aMessage, header.GetSource(), header.GetDestination(), aIpProto);
if (aMessageInfo.GetPeerAddr().IsMulticastLargerThanRealmLocal())
{
#if OPENTHREAD_FTD
if (Get<ChildTable>().HasSleepyChildWithAddress(header.GetDestination()))
{
Message *messageCopy = aMessage.Clone();
if (messageCopy != nullptr)
{
LogInfo("Message copy for indirect transmission to sleepy children");
EnqueueDatagram(*messageCopy);
}
else
{
LogWarn("No enough buffer for message copy for indirect transmission to sleepy children");
}
}
#endif
SuccessOrExit(error = AddTunneledMplOption(aMessage, header, aMessageInfo));
}
aMessage.SetMulticastLoop(aMessageInfo.GetMulticastLoop());
if (aMessage.GetLength() > kMaxDatagramLength)
{
error = FragmentDatagram(aMessage, aIpProto);
}
else
{
EnqueueDatagram(aMessage);
}
exit:
return error;
}
void Ip6::HandleSendQueue(Tasklet &aTasklet)
{
aTasklet.Get<Ip6>().HandleSendQueue();
}
void Ip6::HandleSendQueue(void)
{
Message *message;
while ((message = mSendQueue.GetHead()) != nullptr)
{
mSendQueue.Dequeue(*message);
IgnoreError(HandleDatagram(*message, nullptr, nullptr, /* aFromHost */ false));
}
}
Error Ip6::HandleOptions(Message &aMessage, Header &aHeader, bool aIsOutbound, bool &aReceive)
{
Error error = kErrorNone;
HopByHopHeader hbhHeader;
OptionHeader optionHeader;
uint16_t endOffset;
SuccessOrExit(error = aMessage.Read(aMessage.GetOffset(), hbhHeader));
endOffset = aMessage.GetOffset() + (hbhHeader.GetLength() + 1) * 8;
VerifyOrExit(endOffset <= aMessage.GetLength(), error = kErrorParse);
aMessage.MoveOffset(sizeof(optionHeader));
while (aMessage.GetOffset() < endOffset)
{
SuccessOrExit(error = aMessage.Read(aMessage.GetOffset(), optionHeader));
if (optionHeader.GetType() == OptionPad1::kType)
{
aMessage.MoveOffset(sizeof(OptionPad1));
continue;
}
VerifyOrExit(aMessage.GetOffset() + sizeof(optionHeader) + optionHeader.GetLength() <= endOffset,
error = kErrorParse);
switch (optionHeader.GetType())
{
case OptionMpl::kType:
SuccessOrExit(error = mMpl.ProcessOption(aMessage, aHeader.GetSource(), aIsOutbound, aReceive));
break;
default:
switch (optionHeader.GetAction())
{
case OptionHeader::kActionSkip:
break;
case OptionHeader::kActionDiscard:
ExitNow(error = kErrorDrop);
case OptionHeader::kActionForceIcmp:
// TODO: send icmp error
ExitNow(error = kErrorDrop);
case OptionHeader::kActionIcmp:
// TODO: send icmp error
ExitNow(error = kErrorDrop);
}
break;
}
aMessage.MoveOffset(sizeof(optionHeader) + optionHeader.GetLength());
}
exit:
return error;
}
#if OPENTHREAD_CONFIG_IP6_FRAGMENTATION_ENABLE
Error Ip6::FragmentDatagram(Message &aMessage, uint8_t aIpProto)
{
Error error = kErrorNone;
Header header;
FragmentHeader fragmentHeader;
Message * fragment = nullptr;
uint16_t fragmentCnt = 0;
uint16_t payloadFragment = 0;
uint16_t offset = 0;
uint16_t maxPayloadFragment =
FragmentHeader::MakeDivisibleByEight(kMinimalMtu - aMessage.GetOffset() - sizeof(fragmentHeader));
uint16_t payloadLeft = aMessage.GetLength() - aMessage.GetOffset();
SuccessOrExit(error = aMessage.Read(0, header));
header.SetNextHeader(kProtoFragment);
fragmentHeader.Init();
fragmentHeader.SetIdentification(Random::NonCrypto::GetUint32());
fragmentHeader.SetNextHeader(aIpProto);
fragmentHeader.SetMoreFlag();
while (payloadLeft != 0)
{
if (payloadLeft < maxPayloadFragment)
{
fragmentHeader.ClearMoreFlag();
payloadFragment = payloadLeft;
payloadLeft = 0;
LogDebg("Last Fragment");
}
else
{
payloadLeft -= maxPayloadFragment;
payloadFragment = maxPayloadFragment;
}
offset = fragmentCnt * FragmentHeader::BytesToFragmentOffset(maxPayloadFragment);
fragmentHeader.SetOffset(offset);
VerifyOrExit((fragment = NewMessage(0)) != nullptr, error = kErrorNoBufs);
SuccessOrExit(error = fragment->SetLength(aMessage.GetOffset() + sizeof(fragmentHeader) + payloadFragment));
header.SetPayloadLength(payloadFragment + sizeof(fragmentHeader));
fragment->Write(0, header);
fragment->SetOffset(aMessage.GetOffset());
fragment->Write(aMessage.GetOffset(), fragmentHeader);
VerifyOrExit(aMessage.CopyTo(aMessage.GetOffset() + FragmentHeader::FragmentOffsetToBytes(offset),
aMessage.GetOffset() + sizeof(fragmentHeader), payloadFragment,
*fragment) == static_cast<int>(payloadFragment),
error = kErrorNoBufs);
EnqueueDatagram(*fragment);
fragmentCnt++;
fragment = nullptr;
LogInfo("Fragment %d with %d bytes sent", fragmentCnt, payloadFragment);
}
aMessage.Free();
exit:
if (error == kErrorNoBufs)
{
LogWarn("No buffer for Ip6 fragmentation");
}
FreeMessageOnError(fragment, error);
return error;
}
Error Ip6::HandleFragment(Message &aMessage, Netif *aNetif, MessageInfo &aMessageInfo, bool aFromHost)
{
Error error = kErrorNone;
Header header, headerBuffer;
FragmentHeader fragmentHeader;
Message * message = nullptr;
uint16_t offset = 0;
uint16_t payloadFragment = 0;
int assertValue = 0;
bool isFragmented = true;
OT_UNUSED_VARIABLE(assertValue);
SuccessOrExit(error = aMessage.Read(0, header));
SuccessOrExit(error = aMessage.Read(aMessage.GetOffset(), fragmentHeader));
if (fragmentHeader.GetOffset() == 0 && !fragmentHeader.IsMoreFlagSet())
{
isFragmented = false;
aMessage.MoveOffset(sizeof(fragmentHeader));
ExitNow();
}
for (message = mReassemblyList.GetHead(); message; message = message->GetNext())
{
SuccessOrExit(error = message->Read(0, headerBuffer));
if (message->GetDatagramTag() == fragmentHeader.GetIdentification() &&
headerBuffer.GetSource() == header.GetSource() && headerBuffer.GetDestination() == header.GetDestination())
{
break;
}
}
offset = FragmentHeader::FragmentOffsetToBytes(fragmentHeader.GetOffset());
payloadFragment = aMessage.GetLength() - aMessage.GetOffset() - sizeof(fragmentHeader);
LogInfo("Fragment with id %d received > %d bytes, offset %d", fragmentHeader.GetIdentification(), payloadFragment,
offset);
if (offset + payloadFragment + aMessage.GetOffset() > kMaxAssembledDatagramLength)
{
LogWarn("Packet too large for fragment buffer");
ExitNow(error = kErrorNoBufs);
}
if (message == nullptr)
{
LogDebg("start reassembly");
VerifyOrExit((message = NewMessage(0)) != nullptr, error = kErrorNoBufs);
mReassemblyList.Enqueue(*message);
SuccessOrExit(error = message->SetLength(aMessage.GetOffset()));
message->SetTimeout(kIp6ReassemblyTimeout);
message->SetOffset(0);
message->SetDatagramTag(fragmentHeader.GetIdentification());
// copying the non-fragmentable header to the fragmentation buffer
assertValue = aMessage.CopyTo(0, 0, aMessage.GetOffset(), *message);
OT_ASSERT(assertValue == aMessage.GetOffset());
Get<TimeTicker>().RegisterReceiver(TimeTicker::kIp6FragmentReassembler);
}
// increase message buffer if necessary
if (message->GetLength() < offset + payloadFragment + aMessage.GetOffset())
{
SuccessOrExit(error = message->SetLength(offset + payloadFragment + aMessage.GetOffset()));
}
// copy the fragment payload into the message buffer
assertValue = aMessage.CopyTo(aMessage.GetOffset() + sizeof(fragmentHeader), aMessage.GetOffset() + offset,
payloadFragment, *message);
OT_ASSERT(assertValue == static_cast<int>(payloadFragment));
// check if it is the last frame
if (!fragmentHeader.IsMoreFlagSet())
{
// use the offset value for the whole ip message length
message->SetOffset(aMessage.GetOffset() + offset + payloadFragment);
// creates the header for the reassembled ipv6 package
SuccessOrExit(error = aMessage.Read(0, header));
header.SetPayloadLength(message->GetLength() - sizeof(header));
header.SetNextHeader(fragmentHeader.GetNextHeader());
message->Write(0, header);
LogDebg("Reassembly complete.");
mReassemblyList.Dequeue(*message);
IgnoreError(HandleDatagram(*message, aNetif, aMessageInfo.mLinkInfo, aFromHost));
}
exit:
if (error != kErrorDrop && error != kErrorNone && isFragmented)
{
if (message != nullptr)
{
mReassemblyList.DequeueAndFree(*message);
}
LogWarn("Reassembly failed: %s", ErrorToString(error));
}
if (isFragmented)
{
// drop all fragments, the payload is stored in the fragment buffer
error = kErrorDrop;
}
return error;
}
void Ip6::CleanupFragmentationBuffer(void)
{
mReassemblyList.DequeueAndFreeAll();
}
void Ip6::HandleTimeTick(void)
{
UpdateReassemblyList();
if (mReassemblyList.GetHead() == nullptr)
{
Get<TimeTicker>().UnregisterReceiver(TimeTicker::kIp6FragmentReassembler);
}
}
void Ip6::UpdateReassemblyList(void)
{
Message *next;
for (Message *message = mReassemblyList.GetHead(); message; message = next)
{
next = message->GetNext();
if (message->GetTimeout() > 0)
{
message->DecrementTimeout();
}
else
{
LogNote("Reassembly timeout.");
SendIcmpError(*message, Icmp::Header::kTypeTimeExceeded, Icmp::Header::kCodeFragmReasTimeEx);
mReassemblyList.DequeueAndFree(*message);
}
}
}
void Ip6::SendIcmpError(Message &aMessage, Icmp::Header::Type aIcmpType, Icmp::Header::Code aIcmpCode)
{
Error error = kErrorNone;
Header header;
MessageInfo messageInfo;
SuccessOrExit(error = aMessage.Read(0, header));
messageInfo.SetPeerAddr(header.GetSource());
messageInfo.SetSockAddr(header.GetDestination());
messageInfo.SetHopLimit(header.GetHopLimit());
messageInfo.SetLinkInfo(nullptr);
error = mIcmp.SendError(aIcmpType, aIcmpCode, messageInfo, aMessage);
exit:
if (error != kErrorNone)
{
LogWarn("Failed to send ICMP error: %s", ErrorToString(error));
}
}
#else
Error Ip6::FragmentDatagram(Message &aMessage, uint8_t aIpProto)
{
OT_UNUSED_VARIABLE(aIpProto);
EnqueueDatagram(aMessage);
return kErrorNone;
}
Error Ip6::HandleFragment(Message &aMessage, Netif *aNetif, MessageInfo &aMessageInfo, bool aFromHost)
{
OT_UNUSED_VARIABLE(aNetif);
OT_UNUSED_VARIABLE(aMessageInfo);
OT_UNUSED_VARIABLE(aFromHost);
Error error = kErrorNone;
FragmentHeader fragmentHeader;
SuccessOrExit(error = aMessage.Read(aMessage.GetOffset(), fragmentHeader));
VerifyOrExit(fragmentHeader.GetOffset() == 0 && !fragmentHeader.IsMoreFlagSet(), error = kErrorDrop);
aMessage.MoveOffset(sizeof(fragmentHeader));
exit:
return error;
}
#endif // OPENTHREAD_CONFIG_IP6_FRAGMENTATION_ENABLE
Error Ip6::HandleExtensionHeaders(Message & aMessage,
Netif * aNetif,
MessageInfo &aMessageInfo,
Header & aHeader,
uint8_t & aNextHeader,
bool aIsOutbound,
bool aFromHost,
bool & aReceive)
{
Error error = kErrorNone;
ExtensionHeader extHeader;
while (aReceive || aNextHeader == kProtoHopOpts)
{
SuccessOrExit(error = aMessage.Read(aMessage.GetOffset(), extHeader));
switch (aNextHeader)
{
case kProtoHopOpts:
SuccessOrExit(error = HandleOptions(aMessage, aHeader, aIsOutbound, aReceive));
break;
case kProtoFragment:
#if !OPENTHREAD_CONFIG_IP6_FRAGMENTATION_ENABLE
IgnoreError(ProcessReceiveCallback(aMessage, aMessageInfo, aNextHeader, aFromHost,
/* aAllowReceiveFilter */ false, Message::kCopyToUse));
#endif
SuccessOrExit(error = HandleFragment(aMessage, aNetif, aMessageInfo, aFromHost));
break;
case kProtoDstOpts:
SuccessOrExit(error = HandleOptions(aMessage, aHeader, aIsOutbound, aReceive));
break;
case kProtoIp6:
ExitNow();
case kProtoRouting:
case kProtoNone:
ExitNow(error = kErrorDrop);
default:
ExitNow();
}
aNextHeader = static_cast<uint8_t>(extHeader.GetNextHeader());
}
exit:
return error;
}
Error Ip6::HandlePayload(Header & aIp6Header,
Message & aMessage,
MessageInfo & aMessageInfo,
uint8_t aIpProto,
Message::Ownership aMessageOwnership)
{
#if !OPENTHREAD_CONFIG_TCP_ENABLE
OT_UNUSED_VARIABLE(aIp6Header);
#endif
Error error = kErrorNone;
Message *message = (aMessageOwnership == Message::kTakeCustody) ? &aMessage : nullptr;
VerifyOrExit(aIpProto == kProtoTcp || aIpProto == kProtoUdp || aIpProto == kProtoIcmp6);
if (aMessageOwnership == Message::kCopyToUse)
{
VerifyOrExit((message = aMessage.Clone()) != nullptr, error = kErrorNoBufs);
}
switch (aIpProto)
{
#if OPENTHREAD_CONFIG_TCP_ENABLE
case kProtoTcp:
error = mTcp.HandleMessage(aIp6Header, *message, aMessageInfo);
if (error == kErrorDrop)
{
LogNote("Error TCP Checksum");
}
break;
#endif
case kProtoUdp:
error = mUdp.HandleMessage(*message, aMessageInfo);
if (error == kErrorDrop)
{
LogNote("Error UDP Checksum");
}
break;
case kProtoIcmp6:
error = mIcmp.HandleMessage(*message, aMessageInfo);
break;
default:
break;
}
exit:
if (error != kErrorNone)
{
LogNote("Failed to handle payload: %s", ErrorToString(error));
}
FreeMessage(message);
return error;
}
Error Ip6::ProcessReceiveCallback(Message & aMessage,
const MessageInfo &aMessageInfo,
uint8_t aIpProto,
bool aFromHost,
bool aAllowReceiveFilter,
Message::Ownership aMessageOwnership)
{
Error error = kErrorNone;
Message *message = &aMessage;
VerifyOrExit(!aFromHost, error = kErrorNoRoute);
VerifyOrExit(mReceiveIp6DatagramCallback != nullptr, error = kErrorNoRoute);
// Do not forward reassembled IPv6 packets.
VerifyOrExit(aMessage.GetLength() <= kMinimalMtu, error = kErrorDrop);
if (mIsReceiveIp6FilterEnabled && aAllowReceiveFilter)
{
#if !OPENTHREAD_CONFIG_PLATFORM_NETIF_ENABLE
// do not pass messages sent to an RLOC/ALOC, except Service Locator
bool isLocator = Get<Mle::Mle>().IsMeshLocalAddress(aMessageInfo.GetSockAddr()) &&
aMessageInfo.GetSockAddr().GetIid().IsLocator();
VerifyOrExit(!isLocator || aMessageInfo.GetSockAddr().GetIid().IsAnycastServiceLocator(),
error = kErrorNoRoute);
#endif
switch (aIpProto)
{
case kProtoIcmp6:
if (mIcmp.ShouldHandleEchoRequest(aMessageInfo))
{
Icmp::Header icmp;
IgnoreError(aMessage.Read(aMessage.GetOffset(), icmp));
// do not pass ICMP Echo Request messages
VerifyOrExit(icmp.GetType() != Icmp::Header::kTypeEchoRequest, error = kErrorDrop);
}
break;
case kProtoUdp:
{
Udp::Header udp;
IgnoreError(aMessage.Read(aMessage.GetOffset(), udp));
VerifyOrExit(Get<Udp>().ShouldUsePlatformUdp(udp.GetDestinationPort()) &&
!Get<Udp>().IsPortInUse(udp.GetDestinationPort()),
error = kErrorNoRoute);
break;
}
default:
break;
}
}
switch (aMessageOwnership)
{
case Message::kTakeCustody:
break;
case Message::kCopyToUse:
message = aMessage.Clone();
if (message == nullptr)
{
LogWarn("No buff to clone msg (len: %d) to pass to host", aMessage.GetLength());
ExitNow(error = kErrorNoBufs);
}
break;
}
IgnoreError(RemoveMplOption(*message));
mReceiveIp6DatagramCallback(message, mReceiveIp6DatagramCallbackContext);
exit:
if ((error != kErrorNone) && (aMessageOwnership == Message::kTakeCustody))
{
aMessage.Free();
}
return error;
}
Error Ip6::SendRaw(Message &aMessage, bool aFromHost)
{
Error error = kErrorNone;
Header header;
MessageInfo messageInfo;
bool freed = false;
SuccessOrExit(error = header.Init(aMessage));
VerifyOrExit(!header.GetSource().IsMulticast(), error = kErrorInvalidSourceAddress);
messageInfo.SetPeerAddr(header.GetSource());
messageInfo.SetSockAddr(header.GetDestination());
messageInfo.SetHopLimit(header.GetHopLimit());
if (header.GetDestination().IsMulticast())
{
SuccessOrExit(error = InsertMplOption(aMessage, header, messageInfo));
}
error = HandleDatagram(aMessage, nullptr, nullptr, aFromHost);
freed = true;
exit:
if (!freed)
{
aMessage.Free();
}
return error;
}
Error Ip6::HandleDatagram(Message &aMessage, Netif *aNetif, const void *aLinkMessageInfo, bool aFromHost)
{
Error error;
MessageInfo messageInfo;
Header header;
bool receive;
bool forwardThread;
bool forwardHost;
bool shouldFreeMessage;
uint8_t nextHeader;
start:
receive = false;
forwardThread = false;
forwardHost = false;
shouldFreeMessage = true;
SuccessOrExit(error = header.Init(aMessage));
messageInfo.Clear();
messageInfo.SetPeerAddr(header.GetSource());
messageInfo.SetSockAddr(header.GetDestination());
messageInfo.SetHopLimit(header.GetHopLimit());
messageInfo.SetLinkInfo(aLinkMessageInfo);
// determine destination of packet
if (header.GetDestination().IsMulticast())
{
Netif *netif;
if (aNetif != nullptr)
{
#if OPENTHREAD_FTD
if (header.GetDestination().IsMulticastLargerThanRealmLocal() &&
Get<ChildTable>().HasSleepyChildWithAddress(header.GetDestination()))
{
forwardThread = true;
}
#endif
netif = aNetif;
}
else
{
forwardThread = true;
netif = &Get<ThreadNetif>();
}
forwardHost = header.GetDestination().IsMulticastLargerThanRealmLocal();
if ((aNetif != nullptr || aMessage.GetMulticastLoop()) && netif->IsMulticastSubscribed(header.GetDestination()))
{
receive = true;
}
else if (netif->IsMulticastPromiscuousEnabled())
{
forwardHost = true;
}
}
else
{
// unicast
if (Get<ThreadNetif>().HasUnicastAddress(header.GetDestination()))
{
receive = true;
}
else if (!header.GetDestination().IsLinkLocal())
{
forwardThread = true;
}
else if (aNetif == nullptr)
{
forwardThread = true;
}
if (forwardThread && !ShouldForwardToThread(messageInfo, aFromHost))
{
forwardThread = false;
forwardHost = true;
}
}
aMessage.SetOffset(sizeof(header));
// process IPv6 Extension Headers
nextHeader = static_cast<uint8_t>(header.GetNextHeader());
SuccessOrExit(error = HandleExtensionHeaders(aMessage, aNetif, messageInfo, header, nextHeader, aNetif == nullptr,
aFromHost, receive));
// process IPv6 Payload
if (receive)
{
if (nextHeader == kProtoIp6)
{
// Remove encapsulating header and start over.
aMessage.RemoveHeader(aMessage.GetOffset());
Get<MeshForwarder>().LogMessage(MeshForwarder::kMessageReceive, aMessage, nullptr, kErrorNone);
goto start;
}
error = ProcessReceiveCallback(aMessage, messageInfo, nextHeader, aFromHost,
/* aAllowReceiveFilter */ !forwardHost, Message::kCopyToUse);
if ((error == kErrorNone || error == kErrorNoRoute) && forwardHost)
{
forwardHost = false;
}
error = HandlePayload(header, aMessage, messageInfo, nextHeader,
(forwardThread || forwardHost ? Message::kCopyToUse : Message::kTakeCustody));
shouldFreeMessage = forwardThread || forwardHost;
}
if (forwardHost)
{
// try passing to host
error = ProcessReceiveCallback(aMessage, messageInfo, nextHeader, aFromHost, /* aAllowReceiveFilter */ false,
forwardThread ? Message::kCopyToUse : Message::kTakeCustody);
shouldFreeMessage = forwardThread;
}
if (forwardThread)
{
uint8_t hopLimit;
if (aNetif != nullptr)
{
VerifyOrExit(mForwardingEnabled);
header.SetHopLimit(header.GetHopLimit() - 1);
}
VerifyOrExit(header.GetHopLimit() > 0, error = kErrorDrop);
hopLimit = header.GetHopLimit();
aMessage.Write(Header::kHopLimitFieldOffset, hopLimit);
if (nextHeader == kProtoIcmp6)
{
uint8_t icmpType;
bool isAllowedType = false;
SuccessOrExit(error = aMessage.Read(aMessage.GetOffset(), icmpType));
for (IcmpType type : sForwardICMPTypes)
{
if (icmpType == type)
{
isAllowedType = true;
break;
}
}
VerifyOrExit(isAllowedType, error = kErrorDrop);
}
#if !OPENTHREAD_CONFIG_REFERENCE_DEVICE_ENABLE
if (aFromHost && (nextHeader == kProtoUdp))
{
uint16_t destPort;
SuccessOrExit(error = aMessage.Read(aMessage.GetOffset() + Udp::Header::kDestPortFieldOffset, destPort));
destPort = HostSwap16(destPort);
if (nextHeader == kProtoUdp)
{
VerifyOrExit(Get<Udp>().ShouldUsePlatformUdp(destPort), error = kErrorDrop);
}
}
#endif
#if OPENTHREAD_CONFIG_MULTI_RADIO
// Since the message will be forwarded, we clear the radio
// type on the message to allow the radio type for tx to be
// selected later (based on the radios supported by the next
// hop).
aMessage.ClearRadioType();
#endif
// `SendMessage()` takes custody of message in the success case
SuccessOrExit(error = Get<ThreadNetif>().SendMessage(aMessage));
shouldFreeMessage = false;
}
exit:
if (shouldFreeMessage)
{
aMessage.Free();
}
return error;
}
bool Ip6::ShouldForwardToThread(const MessageInfo &aMessageInfo, bool aFromHost) const
{
OT_UNUSED_VARIABLE(aFromHost);
bool rval = false;
if (aMessageInfo.GetSockAddr().IsMulticast())
{
// multicast
ExitNow(rval = true);
}
else if (aMessageInfo.GetSockAddr().IsLinkLocal())
{
// on-link link-local address
ExitNow(rval = true);
}
else if (IsOnLink(aMessageInfo.GetSockAddr()))
{
// on-link global address
#if OPENTHREAD_FTD && OPENTHREAD_CONFIG_BACKBONE_ROUTER_DUA_NDPROXYING_ENABLE
ExitNow(rval = (aFromHost ||
!Get<BackboneRouter::Manager>().ShouldForwardDuaToBackbone(aMessageInfo.GetSockAddr())));
#else
ExitNow(rval = true);
#endif
}
else if (Get<ThreadNetif>().RouteLookup(aMessageInfo.GetPeerAddr(), aMessageInfo.GetSockAddr(), nullptr) ==
kErrorNone)
{
// route
ExitNow(rval = true);
}
else
{
ExitNow(rval = false);
}
exit:
return rval;
}
const Netif::UnicastAddress *Ip6::SelectSourceAddress(MessageInfo &aMessageInfo)
{
Address * destination = &aMessageInfo.GetPeerAddr();
uint8_t destinationScope = destination->GetScope();
const bool destinationIsRoutingLocator = Get<Mle::Mle>().IsRoutingLocator(*destination);
const Netif::UnicastAddress *rvalAddr = nullptr;
uint8_t rvalPrefixMatched = 0;
for (const Netif::UnicastAddress &addr : Get<ThreadNetif>().GetUnicastAddresses())
{
const Address *candidateAddr = &addr.GetAddress();
uint8_t candidatePrefixMatched;
uint8_t overrideScope;
if (Get<Mle::Mle>().IsAnycastLocator(*candidateAddr))
{
// Don't use anycast address as source address.
continue;
}
candidatePrefixMatched = destination->PrefixMatch(*candidateAddr);
if (candidatePrefixMatched >= addr.mPrefixLength)
{
candidatePrefixMatched = addr.mPrefixLength;
overrideScope = addr.GetScope();
}
else
{
overrideScope = destinationScope;
}
if (rvalAddr == nullptr)
{
// Rule 0: Prefer any address
rvalAddr = &addr;
rvalPrefixMatched = candidatePrefixMatched;
}
else if (*candidateAddr == *destination)
{
// Rule 1: Prefer same address
rvalAddr = &addr;
ExitNow();
}
else if (addr.GetScope() < rvalAddr->GetScope())
{
// Rule 2: Prefer appropriate scope
if (addr.GetScope() >= overrideScope)
{
rvalAddr = &addr;
rvalPrefixMatched = candidatePrefixMatched;
}
else
{
continue;
}
}
else if (addr.GetScope() > rvalAddr->GetScope())
{
if (rvalAddr->GetScope() < overrideScope)
{
rvalAddr = &addr;
rvalPrefixMatched = candidatePrefixMatched;
}
else
{
continue;
}
}
else if (addr.mPreferred && !rvalAddr->mPreferred)
{
// Rule 3: Avoid deprecated addresses
rvalAddr = &addr;
rvalPrefixMatched = candidatePrefixMatched;
}
else if (candidatePrefixMatched > rvalPrefixMatched)
{
// Rule 6: Prefer matching label
// Rule 7: Prefer public address
// Rule 8: Use longest prefix matching
rvalAddr = &addr;
rvalPrefixMatched = candidatePrefixMatched;
}
else if ((candidatePrefixMatched == rvalPrefixMatched) &&
(destinationIsRoutingLocator == Get<Mle::Mle>().IsRoutingLocator(*candidateAddr)))
{
// Additional rule: Prefer RLOC source for RLOC destination, EID source for anything else
rvalAddr = &addr;
rvalPrefixMatched = candidatePrefixMatched;
}
else
{
continue;
}
// infer destination scope based on prefix match
if (rvalPrefixMatched >= rvalAddr->mPrefixLength)
{
destinationScope = rvalAddr->GetScope();
}
}
exit:
return rvalAddr;
}
bool Ip6::IsOnLink(const Address &aAddress) const
{
bool rval = false;
if (Get<ThreadNetif>().IsOnMesh(aAddress))
{
ExitNow(rval = true);
}
for (const Netif::UnicastAddress &cur : Get<ThreadNetif>().GetUnicastAddresses())
{
if (cur.GetAddress().PrefixMatch(aAddress) >= cur.mPrefixLength)
{
ExitNow(rval = true);
}
}
exit:
return rval;
}
// LCOV_EXCL_START
const char *Ip6::IpProtoToString(uint8_t aIpProto)
{
static constexpr Stringify::Entry kIpProtoTable[] = {
{kProtoHopOpts, "HopOpts"}, {kProtoTcp, "TCP"}, {kProtoUdp, "UDP"},
{kProtoIp6, "IP6"}, {kProtoRouting, "Routing"}, {kProtoFragment, "Frag"},
{kProtoIcmp6, "ICMP6"}, {kProtoNone, "None"}, {kProtoDstOpts, "DstOpts"},
};
static_assert(Stringify::IsSorted(kIpProtoTable), "kIpProtoTable is not sorted");
return Stringify::Lookup(aIpProto, kIpProtoTable, "Unknown");
}
// LCOV_EXCL_STOP
} // namespace Ip6
} // namespace ot
| bsd-3-clause |
nwjs/chromium.src | components/omnibox/browser/autocomplete_match.cc | 58314 | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/omnibox/browser/autocomplete_match.h"
#include <algorithm>
#include "base/check_op.h"
#include "base/cxx17_backports.h"
#include "base/debug/crash_logging.h"
#include "base/feature_list.h"
#include "base/i18n/case_conversion.h"
#include "base/logging.h"
#include "base/metrics/histogram_macros.h"
#include "base/notreached.h"
#include "base/ranges/algorithm.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_piece.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/time/time.h"
#include "base/trace_event/memory_usage_estimator.h"
#include "base/trace_event/trace_event.h"
#include "components/omnibox/browser/actions/omnibox_action.h"
#include "components/omnibox/browser/autocomplete_provider.h"
#include "components/omnibox/browser/document_provider.h"
#include "components/omnibox/browser/omnibox_field_trial.h"
#include "components/omnibox/common/omnibox_features.h"
#include "components/search_engines/search_engine_utils.h"
#include "components/search_engines/template_url_service.h"
#include "inline_autocompletion_util.h"
#include "net/base/registry_controlled_domains/registry_controlled_domain.h"
#include "ui/gfx/vector_icon_types.h"
#include "url/third_party/mozilla/url_parse.h"
#if (!defined(OS_ANDROID) || BUILDFLAG(ENABLE_VR)) && !defined(OS_IOS)
#include "components/omnibox/browser/suggestion_answer.h"
#include "components/omnibox/browser/vector_icons.h" // nogncheck
#include "components/vector_icons/vector_icons.h" // nogncheck
#endif
namespace {
bool IsTrivialClassification(const ACMatchClassifications& classifications) {
return classifications.empty() ||
((classifications.size() == 1) &&
(classifications.back().style == ACMatchClassification::NONE));
}
// Returns true if one of the |terms_prefixed_by_http_or_https| matches the
// beginning of the URL (sans scheme). (Recall that
// |terms_prefixed_by_http_or_https|, for the input "http://a b" will be
// ["a"].) This suggests that the user wants a particular URL with a scheme
// in mind, hence the caller should not consider another URL like this one
// but with a different scheme to be a duplicate.
bool WordMatchesURLContent(
const std::vector<std::u16string>& terms_prefixed_by_http_or_https,
const GURL& url) {
size_t prefix_length =
url.scheme().length() + strlen(url::kStandardSchemeSeparator);
DCHECK_GE(url.spec().length(), prefix_length);
const std::u16string& formatted_url = url_formatter::FormatUrl(
url, url_formatter::kFormatUrlOmitNothing, net::UnescapeRule::NORMAL,
nullptr, nullptr, &prefix_length);
if (prefix_length == std::u16string::npos)
return false;
const std::u16string& formatted_url_without_scheme =
formatted_url.substr(prefix_length);
for (const auto& term : terms_prefixed_by_http_or_https) {
if (base::StartsWith(formatted_url_without_scheme, term,
base::CompareCase::SENSITIVE))
return true;
}
return false;
}
// Check if title or non-prefix rich autocompletion is possible. I.e.:
// 1) Enabled for all providers OR for the shortcut provider if the suggestion
// is from the shortcut provider.
// 2) The input is longer than the threshold.
// 3) Enabled for inputs containing spaces OR the input contains no spaces.
bool RichAutocompletionApplicable(bool enabled_all_providers,
bool enabled_shortcut_provider,
size_t min_char,
bool no_inputs_with_spaces,
bool shortcut_provider,
const std::u16string& input_text) {
return (enabled_all_providers ||
(shortcut_provider && enabled_shortcut_provider)) &&
input_text.size() >= min_char &&
(!no_inputs_with_spaces ||
base::ranges::none_of(input_text, &base::IsAsciiWhitespace<char>));
}
} // namespace
SplitAutocompletion::SplitAutocompletion(std::u16string display_text,
std::vector<gfx::Range> selections)
: display_text(display_text), selections(selections) {}
SplitAutocompletion::SplitAutocompletion() = default;
SplitAutocompletion::SplitAutocompletion(const SplitAutocompletion& copy) =
default;
SplitAutocompletion::SplitAutocompletion(SplitAutocompletion&& other) noexcept =
default;
SplitAutocompletion& SplitAutocompletion::operator=(
const SplitAutocompletion&) = default;
SplitAutocompletion& SplitAutocompletion::operator=(
SplitAutocompletion&&) noexcept = default;
SplitAutocompletion::~SplitAutocompletion() = default;
bool SplitAutocompletion::Empty() const {
return selections.empty();
}
void SplitAutocompletion::Clear() {
selections.clear();
}
// AutocompleteMatch ----------------------------------------------------------
// static
const char* const AutocompleteMatch::kDocumentTypeStrings[]{
"none", "drive_docs", "drive_forms", "drive_sheets", "drive_slides",
"drive_image", "drive_pdf", "drive_video", "drive_folder", "drive_other"};
static_assert(
base::size(AutocompleteMatch::kDocumentTypeStrings) ==
static_cast<int>(AutocompleteMatch::DocumentType::DOCUMENT_TYPE_SIZE),
"Sizes of AutocompleteMatch::kDocumentTypeStrings and "
"AutocompleteMatch::DocumentType don't match.");
// static
const char* AutocompleteMatch::DocumentTypeString(DocumentType type) {
return kDocumentTypeStrings[static_cast<int>(type)];
}
// static
bool AutocompleteMatch::DocumentTypeFromInteger(int value,
DocumentType* result) {
DCHECK(result);
// The resulting value may still be invalid after the static_cast.
DocumentType document_type = static_cast<DocumentType>(value);
if (document_type >= DocumentType::NONE &&
document_type < DocumentType::DOCUMENT_TYPE_SIZE) {
*result = document_type;
return true;
}
return false;
}
// static
const char16_t AutocompleteMatch::kInvalidChars[] = {
'\n', '\r', '\t',
0x2028, // Line separator
0x2029, // Paragraph separator
0};
// static
const char16_t AutocompleteMatch::kEllipsis[] = u"... ";
AutocompleteMatch::AutocompleteMatch()
: transition(ui::PAGE_TRANSITION_GENERATED) {}
AutocompleteMatch::AutocompleteMatch(AutocompleteProvider* provider,
int relevance,
bool deletable,
Type type)
: provider(provider),
relevance(relevance),
deletable(deletable),
transition(ui::PAGE_TRANSITION_TYPED),
type(type) {}
AutocompleteMatch::AutocompleteMatch(const AutocompleteMatch& match)
: provider(match.provider),
relevance(match.relevance),
typed_count(match.typed_count),
deletable(match.deletable),
fill_into_edit(match.fill_into_edit),
additional_text(match.additional_text),
inline_autocompletion(match.inline_autocompletion),
rich_autocompletion_triggered(match.rich_autocompletion_triggered),
prefix_autocompletion(match.prefix_autocompletion),
split_autocompletion(match.split_autocompletion),
allowed_to_be_default_match(match.allowed_to_be_default_match),
destination_url(match.destination_url),
stripped_destination_url(match.stripped_destination_url),
image_dominant_color(match.image_dominant_color),
image_url(match.image_url),
document_type(match.document_type),
tail_suggest_common_prefix(match.tail_suggest_common_prefix),
contents(match.contents),
contents_class(match.contents_class),
description(match.description),
description_class(match.description_class),
description_for_shortcuts(match.description_for_shortcuts),
description_class_for_shortcuts(match.description_class_for_shortcuts),
suggestion_group_id(match.suggestion_group_id),
swap_contents_and_description(match.swap_contents_and_description),
answer(match.answer),
transition(match.transition),
type(match.type),
has_tab_match(match.has_tab_match),
subtypes(match.subtypes),
associated_keyword(match.associated_keyword
? new AutocompleteMatch(*match.associated_keyword)
: nullptr),
keyword(match.keyword),
from_keyword(match.from_keyword),
action(match.action),
from_previous(match.from_previous),
search_terms_args(
match.search_terms_args
? new TemplateURLRef::SearchTermsArgs(*match.search_terms_args)
: nullptr),
post_content(match.post_content
? new TemplateURLRef::PostContent(*match.post_content)
: nullptr),
additional_info(match.additional_info),
duplicate_matches(match.duplicate_matches),
query_tiles(match.query_tiles),
navsuggest_tiles(match.navsuggest_tiles) {}
AutocompleteMatch::AutocompleteMatch(AutocompleteMatch&& match) noexcept {
*this = std::move(match);
}
AutocompleteMatch& AutocompleteMatch::operator=(
AutocompleteMatch&& match) noexcept {
provider = std::move(match.provider);
relevance = std::move(match.relevance);
typed_count = std::move(match.typed_count);
deletable = std::move(match.deletable);
fill_into_edit = std::move(match.fill_into_edit);
additional_text = std::move(match.additional_text);
inline_autocompletion = std::move(match.inline_autocompletion);
rich_autocompletion_triggered =
std::move(match.rich_autocompletion_triggered);
prefix_autocompletion = std::move(match.prefix_autocompletion);
split_autocompletion = std::move(match.split_autocompletion);
allowed_to_be_default_match = std::move(match.allowed_to_be_default_match);
destination_url = std::move(match.destination_url);
stripped_destination_url = std::move(match.stripped_destination_url);
image_dominant_color = std::move(match.image_dominant_color);
image_url = std::move(match.image_url);
document_type = std::move(match.document_type);
tail_suggest_common_prefix = std::move(match.tail_suggest_common_prefix);
contents = std::move(match.contents);
contents_class = std::move(match.contents_class);
description = std::move(match.description);
description_class = std::move(match.description_class);
description_for_shortcuts = std::move(match.description_for_shortcuts);
description_class_for_shortcuts =
std::move(match.description_class_for_shortcuts);
suggestion_group_id = std::move(match.suggestion_group_id);
swap_contents_and_description =
std::move(match.swap_contents_and_description);
answer = std::move(match.answer);
transition = std::move(match.transition);
type = std::move(match.type);
has_tab_match = std::move(match.has_tab_match);
subtypes = std::move(match.subtypes);
associated_keyword = std::move(match.associated_keyword);
keyword = std::move(match.keyword);
from_keyword = std::move(match.from_keyword);
action = std::move(match.action);
from_previous = std::move(match.from_previous);
search_terms_args = std::move(match.search_terms_args);
post_content = std::move(match.post_content);
additional_info = std::move(match.additional_info);
duplicate_matches = std::move(match.duplicate_matches);
query_tiles = std::move(match.query_tiles);
navsuggest_tiles = std::move(match.navsuggest_tiles);
#if defined(OS_ANDROID)
DestroyJavaObject();
std::swap(java_match_, match.java_match_);
std::swap(matching_java_tab_, match.matching_java_tab_);
UpdateJavaObjectNativeRef();
#endif
return *this;
}
AutocompleteMatch::~AutocompleteMatch() {
#if defined(OS_ANDROID)
DestroyJavaObject();
#endif
}
AutocompleteMatch& AutocompleteMatch::operator=(
const AutocompleteMatch& match) {
if (this == &match)
return *this;
provider = match.provider;
relevance = match.relevance;
typed_count = match.typed_count;
deletable = match.deletable;
fill_into_edit = match.fill_into_edit;
additional_text = match.additional_text;
inline_autocompletion = match.inline_autocompletion;
rich_autocompletion_triggered = match.rich_autocompletion_triggered;
prefix_autocompletion = match.prefix_autocompletion;
split_autocompletion = match.split_autocompletion;
allowed_to_be_default_match = match.allowed_to_be_default_match;
destination_url = match.destination_url;
stripped_destination_url = match.stripped_destination_url;
image_dominant_color = match.image_dominant_color;
image_url = match.image_url;
document_type = match.document_type;
tail_suggest_common_prefix = match.tail_suggest_common_prefix;
contents = match.contents;
contents_class = match.contents_class;
description = match.description;
description_class = match.description_class;
description_for_shortcuts = match.description_for_shortcuts;
description_class_for_shortcuts = match.description_class_for_shortcuts;
suggestion_group_id = match.suggestion_group_id;
swap_contents_and_description = match.swap_contents_and_description;
answer = match.answer;
transition = match.transition;
type = match.type;
has_tab_match = match.has_tab_match;
subtypes = match.subtypes;
associated_keyword.reset(
match.associated_keyword
? new AutocompleteMatch(*match.associated_keyword)
: nullptr);
keyword = match.keyword;
from_keyword = match.from_keyword;
action = match.action;
from_previous = match.from_previous;
search_terms_args.reset(
match.search_terms_args
? new TemplateURLRef::SearchTermsArgs(*match.search_terms_args)
: nullptr);
post_content.reset(match.post_content
? new TemplateURLRef::PostContent(*match.post_content)
: nullptr);
additional_info = match.additional_info;
duplicate_matches = match.duplicate_matches;
query_tiles = match.query_tiles;
navsuggest_tiles = match.navsuggest_tiles;
#if defined(OS_ANDROID)
// In case the target element previously held a java object, release it.
// This happens, when in an expression "match1 = match2;" match1 already
// is initialized and linked to a Java object: we rewrite the contents of the
// match1 object and it would be desired to either update its corresponding
// Java element, or drop it and construct it lazily the next time it is
// needed.
// Note that because Java<>C++ AutocompleteMatch relation is 1:1, we do not
// want to copy the object here.
DestroyJavaObject();
#endif
return *this;
}
#if (!defined(OS_ANDROID) || BUILDFLAG(ENABLE_VR)) && !defined(OS_IOS)
// static
const gfx::VectorIcon& AutocompleteMatch::AnswerTypeToAnswerIcon(int type) {
switch (static_cast<SuggestionAnswer::AnswerType>(type)) {
case SuggestionAnswer::ANSWER_TYPE_CURRENCY:
return omnibox::kAnswerCurrencyIcon;
case SuggestionAnswer::ANSWER_TYPE_DICTIONARY:
return omnibox::kAnswerDictionaryIcon;
case SuggestionAnswer::ANSWER_TYPE_FINANCE:
return omnibox::kAnswerFinanceIcon;
case SuggestionAnswer::ANSWER_TYPE_SUNRISE:
return omnibox::kAnswerSunriseIcon;
case SuggestionAnswer::ANSWER_TYPE_TRANSLATION:
return omnibox::kAnswerTranslationIcon;
case SuggestionAnswer::ANSWER_TYPE_WHEN_IS:
return omnibox::kAnswerWhenIsIcon;
default:
return omnibox::kAnswerDefaultIcon;
}
}
const gfx::VectorIcon& AutocompleteMatch::GetVectorIcon(
bool is_bookmark) const {
// TODO(https://crbug.com/1024114): Remove crash logging once fixed.
SCOPED_CRASH_KEY_NUMBER("AutocompleteMatch", "type", type);
SCOPED_CRASH_KEY_NUMBER("AutocompleteMatch", "provider_type",
provider ? provider->type() : -1);
if (is_bookmark)
return omnibox::kBookmarkIcon;
if (answer.has_value())
return AnswerTypeToAnswerIcon(answer->type());
switch (type) {
case Type::URL_WHAT_YOU_TYPED:
case Type::HISTORY_URL:
case Type::HISTORY_TITLE:
case Type::HISTORY_BODY:
case Type::HISTORY_KEYWORD:
case Type::NAVSUGGEST:
case Type::BOOKMARK_TITLE:
case Type::NAVSUGGEST_PERSONALIZED:
case Type::CLIPBOARD_URL:
case Type::PHYSICAL_WEB_DEPRECATED:
case Type::PHYSICAL_WEB_OVERFLOW_DEPRECATED:
case Type::TAB_SEARCH_DEPRECATED:
case Type::TILE_NAVSUGGEST:
return omnibox::kPageIcon;
case Type::SEARCH_SUGGEST: {
if (subtypes.contains(/*SUBTYPE_TRENDS=*/143))
return omnibox::kTrendingUpIcon;
return vector_icons::kSearchIcon;
}
case Type::SEARCH_WHAT_YOU_TYPED:
case Type::SEARCH_SUGGEST_ENTITY:
case Type::SEARCH_SUGGEST_PROFILE:
case Type::SEARCH_OTHER_ENGINE:
case Type::CONTACT_DEPRECATED:
case Type::VOICE_SUGGEST:
case Type::PEDAL_DEPRECATED:
case Type::CLIPBOARD_TEXT:
case Type::CLIPBOARD_IMAGE:
case Type::TILE_SUGGESTION:
return vector_icons::kSearchIcon;
case Type::SEARCH_HISTORY:
case Type::SEARCH_SUGGEST_PERSONALIZED: {
DCHECK(IsSearchHistoryType(type));
return omnibox::kClockIcon;
}
case Type::EXTENSION_APP_DEPRECATED:
return omnibox::kExtensionAppIcon;
case Type::CALCULATOR:
return omnibox::kCalculatorIcon;
case Type::SEARCH_SUGGEST_TAIL:
return omnibox::kBlankIcon;
case Type::DOCUMENT_SUGGESTION:
switch (document_type) {
case DocumentType::DRIVE_DOCS:
return omnibox::kDriveDocsIcon;
case DocumentType::DRIVE_FORMS:
return omnibox::kDriveFormsIcon;
case DocumentType::DRIVE_SHEETS:
return omnibox::kDriveSheetsIcon;
case DocumentType::DRIVE_SLIDES:
return omnibox::kDriveSlidesIcon;
case DocumentType::DRIVE_IMAGE:
return omnibox::kDriveImageIcon;
case DocumentType::DRIVE_PDF:
return omnibox::kDrivePdfIcon;
case DocumentType::DRIVE_VIDEO:
return omnibox::kDriveVideoIcon;
case DocumentType::DRIVE_FOLDER:
return omnibox::kDriveFolderIcon;
case DocumentType::DRIVE_OTHER:
return omnibox::kDriveLogoIcon;
default:
return omnibox::kPageIcon;
}
case Type::NUM_TYPES:
// TODO(https://crbug.com/1024114): Replace with NOTREACHED() once fixed.
CHECK(false);
return vector_icons::kErrorIcon;
}
// TODO(https://crbug.com/1024114): Replace with NOTREACHED() once fixed.
CHECK(false);
return vector_icons::kErrorIcon;
}
#endif
// static
bool AutocompleteMatch::MoreRelevant(const AutocompleteMatch& match1,
const AutocompleteMatch& match2) {
// For equal-relevance matches, we sort alphabetically, so that providers
// who return multiple elements at the same priority get a "stable" sort
// across multiple updates.
return (match1.relevance == match2.relevance)
? (match1.contents < match2.contents)
: (match1.relevance > match2.relevance);
}
// static
bool AutocompleteMatch::BetterDuplicate(const AutocompleteMatch& match1,
const AutocompleteMatch& match2) {
// Prefer the Entity Match over the non-entity match, if they have the same
// |fill_into_edit| value.
if (match1.type == AutocompleteMatchType::SEARCH_SUGGEST_ENTITY &&
match2.type != AutocompleteMatchType::SEARCH_SUGGEST_ENTITY &&
match1.fill_into_edit == match2.fill_into_edit) {
return true;
}
if (match1.type != AutocompleteMatchType::SEARCH_SUGGEST_ENTITY &&
match2.type == AutocompleteMatchType::SEARCH_SUGGEST_ENTITY &&
match1.fill_into_edit == match2.fill_into_edit) {
return false;
}
// Prefer matches allowed to be the default match.
if (match1.allowed_to_be_default_match && !match2.allowed_to_be_default_match)
return true;
if (!match1.allowed_to_be_default_match && match2.allowed_to_be_default_match)
return false;
// Prefer URL autocompleted default matches if the appropriate param is true.
if (OmniboxFieldTrial::kRichAutocompletionAutocompletePreferUrlsOverPrefixes
.Get()) {
if (match1.additional_text.empty() && !match2.additional_text.empty())
return true;
if (!match1.additional_text.empty() && match2.additional_text.empty())
return false;
}
// Prefer live document suggestions. We check provider type instead of match
// type in order to distinguish live suggestions from the document provider
// from stale suggestions from the shortcuts providers, because the latter
// omits changing metadata such as last access date.
if (match1.provider->type() == AutocompleteProvider::TYPE_DOCUMENT &&
match2.provider->type() != AutocompleteProvider::TYPE_DOCUMENT) {
return true;
}
if (match1.provider->type() != AutocompleteProvider::TYPE_DOCUMENT &&
match2.provider->type() == AutocompleteProvider::TYPE_DOCUMENT) {
return false;
}
// By default, simply prefer the more relevant match.
return MoreRelevant(match1, match2);
}
// static
bool AutocompleteMatch::BetterDuplicateByIterator(
const std::vector<AutocompleteMatch>::const_iterator it1,
const std::vector<AutocompleteMatch>::const_iterator it2) {
return BetterDuplicate(*it1, *it2);
}
// static
void AutocompleteMatch::ClassifyMatchInString(
const std::u16string& find_text,
const std::u16string& text,
int style,
ACMatchClassifications* classification) {
ClassifyLocationInString(text.find(find_text), find_text.length(),
text.length(), style, classification);
}
// static
void AutocompleteMatch::ClassifyLocationInString(
size_t match_location,
size_t match_length,
size_t overall_length,
int style,
ACMatchClassifications* classification) {
classification->clear();
// Don't classify anything about an empty string
// (AutocompleteMatch::Validate() checks this).
if (overall_length == 0)
return;
// Mark pre-match portion of string (if any).
if (match_location != 0) {
classification->push_back(ACMatchClassification(0, style));
}
// Mark matching portion of string.
if (match_location == std::u16string::npos) {
// No match, above classification will suffice for whole string.
return;
}
// Classifying an empty match makes no sense and will lead to validation
// errors later.
DCHECK_GT(match_length, 0U);
classification->push_back(ACMatchClassification(match_location,
(style | ACMatchClassification::MATCH) & ~ACMatchClassification::DIM));
// Mark post-match portion of string (if any).
const size_t after_match(match_location + match_length);
if (after_match < overall_length) {
classification->push_back(ACMatchClassification(after_match, style));
}
}
// static
AutocompleteMatch::ACMatchClassifications
AutocompleteMatch::MergeClassifications(
const ACMatchClassifications& classifications1,
const ACMatchClassifications& classifications2) {
// We must return the empty vector only if both inputs are truly empty.
// The result of merging an empty vector with a single (0, NONE)
// classification is the latter one-entry vector.
if (IsTrivialClassification(classifications1))
return classifications2.empty() ? classifications1 : classifications2;
if (IsTrivialClassification(classifications2))
return classifications1;
ACMatchClassifications output;
for (auto i = classifications1.begin(), j = classifications2.begin();
i != classifications1.end();) {
AutocompleteMatch::AddLastClassificationIfNecessary(&output,
std::max(i->offset, j->offset), i->style | j->style);
const size_t next_i_offset = (i + 1) == classifications1.end() ?
static_cast<size_t>(-1) : (i + 1)->offset;
const size_t next_j_offset = (j + 1) == classifications2.end() ?
static_cast<size_t>(-1) : (j + 1)->offset;
if (next_i_offset >= next_j_offset)
++j;
if (next_j_offset >= next_i_offset)
++i;
}
return output;
}
// static
std::string AutocompleteMatch::ClassificationsToString(
const ACMatchClassifications& classifications) {
std::string serialized_classifications;
for (size_t i = 0; i < classifications.size(); ++i) {
if (i)
serialized_classifications += ',';
serialized_classifications +=
base::NumberToString(classifications[i].offset) + ',' +
base::NumberToString(classifications[i].style);
}
return serialized_classifications;
}
// static
ACMatchClassifications AutocompleteMatch::ClassificationsFromString(
const std::string& serialized_classifications) {
ACMatchClassifications classifications;
std::vector<base::StringPiece> tokens = base::SplitStringPiece(
serialized_classifications, ",", base::KEEP_WHITESPACE,
base::SPLIT_WANT_NONEMPTY);
DCHECK(!(tokens.size() & 1)); // The number of tokens should be even.
for (size_t i = 0; i < tokens.size(); i += 2) {
int classification_offset = 0;
int classification_style = ACMatchClassification::NONE;
if (!base::StringToInt(tokens[i], &classification_offset) ||
!base::StringToInt(tokens[i + 1], &classification_style)) {
NOTREACHED();
return classifications;
}
classifications.push_back(ACMatchClassification(classification_offset,
classification_style));
}
return classifications;
}
// static
void AutocompleteMatch::AddLastClassificationIfNecessary(
ACMatchClassifications* classifications,
size_t offset,
int style) {
DCHECK(classifications);
if (classifications->empty() || classifications->back().style != style) {
DCHECK(classifications->empty() ||
(offset > classifications->back().offset));
classifications->push_back(ACMatchClassification(offset, style));
}
}
// static
bool AutocompleteMatch::HasMatchStyle(
const ACMatchClassifications& classifications) {
for (const auto& it : classifications) {
if (it.style & AutocompleteMatch::ACMatchClassification::MATCH)
return true;
}
return false;
}
// static
std::u16string AutocompleteMatch::SanitizeString(const std::u16string& text) {
// NOTE: This logic is mirrored by |sanitizeString()| in
// omnibox_custom_bindings.js.
std::u16string result;
base::TrimWhitespace(text, base::TRIM_LEADING, &result);
base::RemoveChars(result, kInvalidChars, &result);
return result;
}
// static
bool AutocompleteMatch::IsSearchType(Type type) {
return type == AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED ||
type == AutocompleteMatchType::SEARCH_HISTORY ||
type == AutocompleteMatchType::SEARCH_SUGGEST ||
type == AutocompleteMatchType::SEARCH_OTHER_ENGINE ||
type == AutocompleteMatchType::CALCULATOR ||
type == AutocompleteMatchType::VOICE_SUGGEST ||
IsSpecializedSearchType(type);
}
// static
bool AutocompleteMatch::IsSpecializedSearchType(Type type) {
return type == AutocompleteMatchType::SEARCH_SUGGEST_ENTITY ||
type == AutocompleteMatchType::SEARCH_SUGGEST_TAIL ||
type == AutocompleteMatchType::SEARCH_SUGGEST_PERSONALIZED ||
type == AutocompleteMatchType::TILE_SUGGESTION ||
type == AutocompleteMatchType::SEARCH_SUGGEST_PROFILE;
}
// static
bool AutocompleteMatch::IsSearchHistoryType(Type type) {
return type == AutocompleteMatchType::SEARCH_HISTORY ||
type == AutocompleteMatchType::SEARCH_SUGGEST_PERSONALIZED;
}
// static
bool AutocompleteMatch::IsActionCompatibleType(Type type) {
// Note: There is a PEDAL type, but it is deprecated because Pedals always
// attach to matches of other types instead of creating dedicated matches.
return type != AutocompleteMatchType::SEARCH_SUGGEST_ENTITY;
}
// static
bool AutocompleteMatch::ShouldBeSkippedForGroupBySearchVsUrl(Type type) {
return type == AutocompleteMatchType::CLIPBOARD_URL ||
type == AutocompleteMatchType::CLIPBOARD_TEXT ||
type == AutocompleteMatchType::CLIPBOARD_IMAGE ||
type == AutocompleteMatchType::TILE_NAVSUGGEST ||
type == AutocompleteMatchType::TILE_SUGGESTION;
}
// static
TemplateURL* AutocompleteMatch::GetTemplateURLWithKeyword(
TemplateURLService* template_url_service,
const std::u16string& keyword,
const std::string& host) {
return const_cast<TemplateURL*>(GetTemplateURLWithKeyword(
static_cast<const TemplateURLService*>(template_url_service), keyword,
host));
}
// static
const TemplateURL* AutocompleteMatch::GetTemplateURLWithKeyword(
const TemplateURLService* template_url_service,
const std::u16string& keyword,
const std::string& host) {
if (template_url_service == nullptr)
return nullptr;
const TemplateURL* template_url =
keyword.empty() ? nullptr
: template_url_service->GetTemplateURLForKeyword(keyword);
return (template_url || host.empty()) ?
template_url : template_url_service->GetTemplateURLForHost(host);
}
// static
GURL AutocompleteMatch::GURLToStrippedGURL(
const GURL& url,
const AutocompleteInput& input,
const TemplateURLService* template_url_service,
const std::u16string& keyword) {
if (!url.is_valid())
return url;
// Special-case canonicalizing Docs URLs. This logic is self-contained and
// will not participate in the TemplateURL canonicalization.
GURL docs_url = DocumentProvider::GetURLForDeduping(url);
if (docs_url.is_valid())
return docs_url;
GURL stripped_destination_url = url;
// If the destination URL looks like it was generated from a TemplateURL,
// remove all substitutions other than the search terms. This allows us
// to eliminate cases like past search URLs from history that differ only
// by some obscure query param from each other or from the search/keyword
// provider matches.
const TemplateURL* template_url = GetTemplateURLWithKeyword(
template_url_service, keyword, stripped_destination_url.host());
if (template_url != nullptr &&
template_url->SupportsReplacement(
template_url_service->search_terms_data())) {
std::u16string search_terms;
if (template_url->ExtractSearchTermsFromURL(
stripped_destination_url,
template_url_service->search_terms_data(),
&search_terms)) {
stripped_destination_url =
GURL(template_url->url_ref().ReplaceSearchTerms(
TemplateURLRef::SearchTermsArgs(search_terms),
template_url_service->search_terms_data()));
}
}
// |replacements| keeps all the substitutions we're going to make to
// from {destination_url} to {stripped_destination_url}. |need_replacement|
// is a helper variable that helps us keep track of whether we need
// to apply the replacement.
bool needs_replacement = false;
GURL::Replacements replacements;
// Remove the www. prefix from the host.
static const char prefix[] = "www.";
static const size_t prefix_len = base::size(prefix) - 1;
std::string host = stripped_destination_url.host();
if (host.compare(0, prefix_len, prefix) == 0 && host.length() > prefix_len) {
replacements.SetHostStr(base::StringPiece(host).substr(prefix_len));
needs_replacement = true;
}
// Replace https protocol with http, as long as the user didn't explicitly
// specify one of the two.
if (stripped_destination_url.SchemeIs(url::kHttpsScheme) &&
(input.terms_prefixed_by_http_or_https().empty() ||
!WordMatchesURLContent(
input.terms_prefixed_by_http_or_https(), url))) {
replacements.SetScheme(url::kHttpScheme,
url::Component(0, strlen(url::kHttpScheme)));
needs_replacement = true;
}
if (!input.parts().ref.is_nonempty() && url.has_ref()) {
replacements.ClearRef();
needs_replacement = true;
}
if (needs_replacement)
stripped_destination_url = stripped_destination_url.ReplaceComponents(
replacements);
return stripped_destination_url;
}
// static
void AutocompleteMatch::GetMatchComponents(
const GURL& url,
const std::vector<MatchPosition>& match_positions,
bool* match_in_scheme,
bool* match_in_subdomain) {
DCHECK(match_in_scheme);
DCHECK(match_in_subdomain);
size_t domain_length =
net::registry_controlled_domains::GetDomainAndRegistry(
url, net::registry_controlled_domains::EXCLUDE_PRIVATE_REGISTRIES)
.size();
const url::Parsed& parsed = url.parsed_for_possibly_invalid_spec();
size_t host_pos = parsed.CountCharactersBefore(url::Parsed::HOST, false);
bool has_subdomain =
domain_length > 0 && domain_length < url.host_piece().length();
// Subtract an extra character from the domain start to exclude the '.'
// delimiter between subdomain and domain.
size_t subdomain_end =
has_subdomain ? host_pos + url.host_piece().length() - domain_length - 1
: std::string::npos;
for (auto& position : match_positions) {
// Only flag |match_in_scheme| if the match starts at the very beginning.
if (position.first == 0 && parsed.scheme.is_nonempty())
*match_in_scheme = true;
// Subdomain matches must begin before the domain, and end somewhere within
// the host or later.
if (has_subdomain && position.first < subdomain_end &&
position.second > host_pos && parsed.host.is_nonempty()) {
*match_in_subdomain = true;
}
}
}
// static
url_formatter::FormatUrlTypes AutocompleteMatch::GetFormatTypes(
bool preserve_scheme,
bool preserve_subdomain) {
auto format_types = url_formatter::kFormatUrlOmitDefaults;
if (preserve_scheme) {
format_types &= ~url_formatter::kFormatUrlOmitHTTP;
} else {
format_types |= url_formatter::kFormatUrlOmitHTTPS;
}
if (!preserve_subdomain) {
format_types |= url_formatter::kFormatUrlOmitTrivialSubdomains;
}
return format_types;
}
// static
void AutocompleteMatch::LogSearchEngineUsed(
const AutocompleteMatch& match,
TemplateURLService* template_url_service) {
DCHECK(template_url_service);
TemplateURL* template_url = match.GetTemplateURL(template_url_service, false);
if (template_url) {
SearchEngineType search_engine_type =
match.destination_url.is_valid()
? SearchEngineUtils::GetEngineType(match.destination_url)
: SEARCH_ENGINE_OTHER;
UMA_HISTOGRAM_ENUMERATION("Omnibox.SearchEngineType", search_engine_type,
SEARCH_ENGINE_MAX);
}
}
void AutocompleteMatch::ComputeStrippedDestinationURL(
const AutocompleteInput& input,
TemplateURLService* template_url_service) {
// Other than document suggestions, computing |stripped_destination_url| will
// have the same result during a match's lifecycle, so it's safe to skip
// re-computing it if it's already computed. Document suggestions'
// |stripped_url|s are pre-computed by the document provider, and overwriting
// them here would prevent potential deduping.
if (stripped_destination_url.is_empty()) {
stripped_destination_url = GURLToStrippedGURL(
destination_url, input, template_url_service, keyword);
}
}
void AutocompleteMatch::GetKeywordUIState(
TemplateURLService* template_url_service,
std::u16string* keyword_out,
bool* is_keyword_hint) const {
*is_keyword_hint = associated_keyword != nullptr;
keyword_out->assign(
*is_keyword_hint
? associated_keyword->keyword
: GetSubstitutingExplicitlyInvokedKeyword(template_url_service));
}
std::u16string AutocompleteMatch::GetSubstitutingExplicitlyInvokedKeyword(
TemplateURLService* template_url_service) const {
if (!ui::PageTransitionCoreTypeIs(transition, ui::PAGE_TRANSITION_KEYWORD) ||
template_url_service == nullptr) {
return std::u16string();
}
const TemplateURL* t_url = GetTemplateURL(template_url_service, false);
return (t_url &&
t_url->SupportsReplacement(template_url_service->search_terms_data()))
? keyword
: std::u16string();
}
TemplateURL* AutocompleteMatch::GetTemplateURL(
TemplateURLService* template_url_service,
bool allow_fallback_to_destination_host) const {
return GetTemplateURLWithKeyword(
template_url_service, keyword,
allow_fallback_to_destination_host ?
destination_url.host() : std::string());
}
GURL AutocompleteMatch::ImageUrl() const {
return answer ? answer->image_url() : image_url;
}
void AutocompleteMatch::RecordAdditionalInfo(const std::string& property,
const std::string& value) {
DCHECK(!property.empty());
additional_info[property] = value;
}
void AutocompleteMatch::RecordAdditionalInfo(const std::string& property,
const std::u16string& value) {
RecordAdditionalInfo(property, base::UTF16ToUTF8(value));
}
void AutocompleteMatch::RecordAdditionalInfo(const std::string& property,
int value) {
RecordAdditionalInfo(property, base::NumberToString(value));
}
void AutocompleteMatch::RecordAdditionalInfo(const std::string& property,
base::Time value) {
RecordAdditionalInfo(
property, base::StringPrintf("%d hours ago",
(base::Time::Now() - value).InHours()));
}
std::string AutocompleteMatch::GetAdditionalInfo(
const std::string& property) const {
auto i(additional_info.find(property));
return (i == additional_info.end()) ? std::string() : i->second;
}
metrics::OmniboxEventProto::Suggestion::ResultType
AutocompleteMatch::AsOmniboxEventResultType() const {
using metrics::OmniboxEventProto;
switch (type) {
case AutocompleteMatchType::URL_WHAT_YOU_TYPED:
return OmniboxEventProto::Suggestion::URL_WHAT_YOU_TYPED;
case AutocompleteMatchType::HISTORY_URL:
return OmniboxEventProto::Suggestion::HISTORY_URL;
case AutocompleteMatchType::HISTORY_TITLE:
return OmniboxEventProto::Suggestion::HISTORY_TITLE;
case AutocompleteMatchType::HISTORY_BODY:
return OmniboxEventProto::Suggestion::HISTORY_BODY;
case AutocompleteMatchType::HISTORY_KEYWORD:
return OmniboxEventProto::Suggestion::HISTORY_KEYWORD;
case AutocompleteMatchType::NAVSUGGEST:
return OmniboxEventProto::Suggestion::NAVSUGGEST;
case AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED:
return OmniboxEventProto::Suggestion::SEARCH_WHAT_YOU_TYPED;
case AutocompleteMatchType::SEARCH_HISTORY:
return OmniboxEventProto::Suggestion::SEARCH_HISTORY;
case AutocompleteMatchType::SEARCH_SUGGEST:
return OmniboxEventProto::Suggestion::SEARCH_SUGGEST;
case AutocompleteMatchType::SEARCH_SUGGEST_ENTITY:
return OmniboxEventProto::Suggestion::SEARCH_SUGGEST_ENTITY;
case AutocompleteMatchType::SEARCH_SUGGEST_TAIL:
return OmniboxEventProto::Suggestion::SEARCH_SUGGEST_TAIL;
case AutocompleteMatchType::SEARCH_SUGGEST_PERSONALIZED:
return OmniboxEventProto::Suggestion::SEARCH_SUGGEST_PERSONALIZED;
case AutocompleteMatchType::SEARCH_SUGGEST_PROFILE:
return OmniboxEventProto::Suggestion::SEARCH_SUGGEST_PROFILE;
case AutocompleteMatchType::CALCULATOR:
return OmniboxEventProto::Suggestion::CALCULATOR;
case AutocompleteMatchType::SEARCH_OTHER_ENGINE:
return OmniboxEventProto::Suggestion::SEARCH_OTHER_ENGINE;
case AutocompleteMatchType::EXTENSION_APP_DEPRECATED:
return OmniboxEventProto::Suggestion::EXTENSION_APP;
case AutocompleteMatchType::BOOKMARK_TITLE:
return OmniboxEventProto::Suggestion::BOOKMARK_TITLE;
case AutocompleteMatchType::NAVSUGGEST_PERSONALIZED:
return OmniboxEventProto::Suggestion::NAVSUGGEST_PERSONALIZED;
case AutocompleteMatchType::CLIPBOARD_URL:
return OmniboxEventProto::Suggestion::CLIPBOARD_URL;
case AutocompleteMatchType::DOCUMENT_SUGGESTION:
return OmniboxEventProto::Suggestion::DOCUMENT;
case AutocompleteMatchType::CLIPBOARD_TEXT:
return OmniboxEventProto::Suggestion::CLIPBOARD_TEXT;
case AutocompleteMatchType::CLIPBOARD_IMAGE:
return OmniboxEventProto::Suggestion::CLIPBOARD_IMAGE;
case AutocompleteMatchType::TILE_SUGGESTION:
return OmniboxEventProto::Suggestion::TILE_SUGGESTION;
case AutocompleteMatchType::TILE_NAVSUGGEST:
return OmniboxEventProto::Suggestion::NAVSUGGEST;
case AutocompleteMatchType::VOICE_SUGGEST:
// VOICE_SUGGEST matches are only used in Java and are not logged,
// so we should never reach this case.
case AutocompleteMatchType::CONTACT_DEPRECATED:
case AutocompleteMatchType::PHYSICAL_WEB_DEPRECATED:
case AutocompleteMatchType::PHYSICAL_WEB_OVERFLOW_DEPRECATED:
case AutocompleteMatchType::TAB_SEARCH_DEPRECATED:
case AutocompleteMatchType::PEDAL_DEPRECATED:
case AutocompleteMatchType::NUM_TYPES:
break;
}
NOTREACHED();
return OmniboxEventProto::Suggestion::UNKNOWN_RESULT_TYPE;
}
bool AutocompleteMatch::IsVerbatimType() const {
const bool is_keyword_verbatim_match =
(type == AutocompleteMatchType::SEARCH_OTHER_ENGINE &&
provider != nullptr &&
provider->type() == AutocompleteProvider::TYPE_SEARCH);
return type == AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED ||
type == AutocompleteMatchType::URL_WHAT_YOU_TYPED ||
is_keyword_verbatim_match;
}
bool AutocompleteMatch::IsSearchProviderSearchSuggestion() const {
const bool from_search_provider =
(provider && provider->type() == AutocompleteProvider::TYPE_SEARCH);
return from_search_provider &&
type != AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED;
}
bool AutocompleteMatch::IsOnDeviceSearchSuggestion() const {
const bool from_on_device_provider =
(provider &&
provider->type() == AutocompleteProvider::TYPE_ON_DEVICE_HEAD);
return from_on_device_provider && subtypes.contains(271);
}
bool AutocompleteMatch::IsTrivialAutocompletion() const {
return type == AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED ||
type == AutocompleteMatchType::URL_WHAT_YOU_TYPED ||
type == AutocompleteMatchType::SEARCH_OTHER_ENGINE;
}
bool AutocompleteMatch::SupportsDeletion() const {
return deletable ||
std::any_of(duplicate_matches.begin(), duplicate_matches.end(),
[](const auto& m) { return m.deletable; });
}
AutocompleteMatch
AutocompleteMatch::GetMatchWithContentsAndDescriptionPossiblySwapped() const {
AutocompleteMatch copy(*this);
if (copy.swap_contents_and_description) {
std::swap(copy.contents, copy.description);
std::swap(copy.contents_class, copy.description_class);
copy.description_for_shortcuts.clear();
copy.description_class_for_shortcuts.clear();
// Clear bit to prevent accidentally performing the swap again.
copy.swap_contents_and_description = false;
}
return copy;
}
void AutocompleteMatch::SetAllowedToBeDefault(const AutocompleteInput& input) {
if (IsEmptyAutocompletion())
allowed_to_be_default_match = true;
else if (input.prevent_inline_autocomplete())
allowed_to_be_default_match = false;
else if (input.text().empty() ||
!base::IsUnicodeWhitespace(input.text().back()))
allowed_to_be_default_match = true;
else {
// If we've reached here, the input ends in trailing whitespace. If the
// trailing whitespace prefixes |inline_autocompletion|, then allow the
// match to be default and remove the whitespace from
// |inline_autocompletion|.
size_t last_non_whitespace_pos =
input.text().find_last_not_of(base::kWhitespaceUTF16);
DCHECK_NE(last_non_whitespace_pos, std::string::npos);
auto whitespace_suffix = input.text().substr(last_non_whitespace_pos + 1);
if (base::StartsWith(inline_autocompletion, whitespace_suffix,
base::CompareCase::SENSITIVE)) {
inline_autocompletion =
inline_autocompletion.substr(whitespace_suffix.size());
allowed_to_be_default_match = true;
} else
allowed_to_be_default_match = false;
}
}
void AutocompleteMatch::InlineTailPrefix(const std::u16string& common_prefix) {
// Prevent re-addition of prefix.
if (type == AutocompleteMatchType::SEARCH_SUGGEST_TAIL &&
tail_suggest_common_prefix.empty()) {
tail_suggest_common_prefix = common_prefix;
// Insert an ellipsis before uncommon part.
const std::u16string ellipsis = kEllipsis;
contents = ellipsis + contents;
// If the first class is not already NONE, prepend a NONE class for the new
// ellipsis.
if (contents_class.empty() ||
(contents_class[0].offset == 0 &&
contents_class[0].style != ACMatchClassification::NONE)) {
contents_class.insert(contents_class.begin(),
{0, ACMatchClassification::NONE});
}
// Shift existing styles.
for (size_t i = 1; i < contents_class.size(); ++i)
contents_class[i].offset += ellipsis.size();
}
}
size_t AutocompleteMatch::EstimateMemoryUsage() const {
size_t res = 0;
res += base::trace_event::EstimateMemoryUsage(fill_into_edit);
res += base::trace_event::EstimateMemoryUsage(additional_text);
res += base::trace_event::EstimateMemoryUsage(inline_autocompletion);
res += base::trace_event::EstimateMemoryUsage(prefix_autocompletion);
res += base::trace_event::EstimateMemoryUsage(destination_url);
res += base::trace_event::EstimateMemoryUsage(stripped_destination_url);
res += base::trace_event::EstimateMemoryUsage(image_dominant_color);
res += base::trace_event::EstimateMemoryUsage(image_url);
res += base::trace_event::EstimateMemoryUsage(tail_suggest_common_prefix);
res += base::trace_event::EstimateMemoryUsage(contents);
res += base::trace_event::EstimateMemoryUsage(contents_class);
res += base::trace_event::EstimateMemoryUsage(description);
res += base::trace_event::EstimateMemoryUsage(description_class);
res += base::trace_event::EstimateMemoryUsage(description_for_shortcuts);
res +=
base::trace_event::EstimateMemoryUsage(description_class_for_shortcuts);
if (answer)
res += base::trace_event::EstimateMemoryUsage(answer.value());
else
res += sizeof(SuggestionAnswer);
res += base::trace_event::EstimateMemoryUsage(associated_keyword);
res += base::trace_event::EstimateMemoryUsage(keyword);
res += base::trace_event::EstimateMemoryUsage(search_terms_args);
res += base::trace_event::EstimateMemoryUsage(post_content);
res += base::trace_event::EstimateMemoryUsage(additional_info);
res += base::trace_event::EstimateMemoryUsage(duplicate_matches);
return res;
}
void AutocompleteMatch::UpgradeMatchWithPropertiesFrom(
AutocompleteMatch& duplicate_match) {
// For Entity Matches, absorb the duplicate match's |allowed_to_be_default|
// and |inline_autocompletion| properties.
if (type == AutocompleteMatchType::SEARCH_SUGGEST_ENTITY &&
fill_into_edit == duplicate_match.fill_into_edit &&
duplicate_match.allowed_to_be_default_match) {
allowed_to_be_default_match = true;
if (IsEmptyAutocompletion()) {
inline_autocompletion = duplicate_match.inline_autocompletion;
prefix_autocompletion = duplicate_match.prefix_autocompletion;
split_autocompletion = duplicate_match.split_autocompletion;
}
}
// For Search Suggest and Search What-You-Typed matches, absorb any
// Search History type.
if ((type == AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED ||
type == AutocompleteMatchType::SEARCH_SUGGEST) &&
fill_into_edit == duplicate_match.fill_into_edit &&
IsSearchHistoryType(duplicate_match.type)) {
type = duplicate_match.type;
}
// And always absorb the higher relevance score of duplicates.
if (duplicate_match.relevance > relevance) {
RecordAdditionalInfo(kACMatchPropertyScoreBoostedFrom, relevance);
relevance = duplicate_match.relevance;
}
// Take the |action|, if any, so that it will be presented instead of buried.
if (!action && duplicate_match.action &&
AutocompleteMatch::IsActionCompatibleType(type)) {
action = duplicate_match.action;
duplicate_match.action = nullptr;
}
// Copy |rich_autocompletion_triggered| for counterfactual logging. Only copy
// true values since a rich autocompleted would have
// |allowed_to_be_default_match| true and would be preferred to a non rich
// autocompleted duplicate in non-counterfactual variations.
if (duplicate_match.rich_autocompletion_triggered)
rich_autocompletion_triggered = true;
}
bool AutocompleteMatch::TryRichAutocompletion(
const std::u16string& primary_text,
const std::u16string& secondary_text,
const AutocompleteInput& input,
bool shortcut_provider) {
if (!OmniboxFieldTrial::IsRichAutocompletionEnabled())
return false;
bool counterfactual =
OmniboxFieldTrial::kRichAutocompletionCounterfactual.Get();
if (input.prevent_inline_autocomplete())
return false;
const std::u16string primary_text_lower{base::i18n::ToLower(primary_text)};
const std::u16string secondary_text_lower{
base::i18n::ToLower(secondary_text)};
const std::u16string input_text_lower{base::i18n::ToLower(input.text())};
// Try matching the prefix of |primary_text|.
if (base::StartsWith(primary_text_lower, input_text_lower,
base::CompareCase::SENSITIVE)) {
if (counterfactual)
return false;
// This case intentionally doesn't set |rich_autocompletion_triggered| to
// true since presumably non-rich autocompletion should also be able to
// handle this case.
inline_autocompletion = primary_text.substr(input_text_lower.length());
allowed_to_be_default_match = true;
RecordAdditionalInfo("autocompletion", "primary & prefix");
return true;
}
const bool can_autocomplete_titles = RichAutocompletionApplicable(
OmniboxFieldTrial::kRichAutocompletionAutocompleteTitles.Get(),
OmniboxFieldTrial::kRichAutocompletionAutocompleteTitlesShortcutProvider
.Get(),
OmniboxFieldTrial::kRichAutocompletionAutocompleteTitlesMinChar.Get(),
OmniboxFieldTrial::kRichAutocompletionAutocompleteTitlesNoInputsWithSpaces
.Get(),
shortcut_provider, input.text());
const bool can_autocomplete_non_prefix = RichAutocompletionApplicable(
OmniboxFieldTrial::kRichAutocompletionAutocompleteNonPrefixAll.Get(),
OmniboxFieldTrial::
kRichAutocompletionAutocompleteNonPrefixShortcutProvider.Get(),
OmniboxFieldTrial::kRichAutocompletionAutocompleteNonPrefixMinChar.Get(),
OmniboxFieldTrial::
kRichAutocompletionAutocompleteNonPrefixNoInputsWithSpaces.Get(),
shortcut_provider, input.text());
// All else equal, prefer matching primary over secondary texts and prefixes
// over non-prefixes. |prefer_primary_non_prefix_over_secondary_prefix|
// determines whether to prefer matching primary text non-prefixes or
// secondary text prefixes.
bool prefer_primary_non_prefix_over_secondary_prefix =
OmniboxFieldTrial::kRichAutocompletionAutocompletePreferUrlsOverPrefixes
.Get();
size_t find_index;
// A helper to avoid duplicate code. Depending on the
// |prefer_primary_non_prefix_over_secondary_prefix|, this may be invoked
// either before or after trying prefix secondary autocompletion.
auto NonPrefixPrimaryHelper = [&]() {
rich_autocompletion_triggered = true;
if (counterfactual)
return false;
inline_autocompletion =
primary_text.substr(find_index + input_text_lower.length());
prefix_autocompletion = primary_text.substr(0, find_index);
allowed_to_be_default_match = true;
RecordAdditionalInfo("autocompletion", "primary & non-prefix");
return true;
};
// Try matching a non-prefix of |primary_text| if
// |prefer_primary_non_prefix_over_secondary_prefix| is true; otherwise, we'll
// try this only after tying to match the prefix of |secondary_text|.
if (prefer_primary_non_prefix_over_secondary_prefix &&
can_autocomplete_non_prefix &&
(find_index = FindAtWordbreak(primary_text_lower, input_text_lower)) !=
std::u16string::npos) {
return NonPrefixPrimaryHelper();
}
// Try matching the prefix of |secondary_text|.
if (can_autocomplete_titles &&
base::StartsWith(secondary_text_lower, input_text_lower,
base::CompareCase::SENSITIVE)) {
rich_autocompletion_triggered = true;
if (counterfactual)
return false;
additional_text = primary_text;
inline_autocompletion = secondary_text.substr(input_text_lower.length());
allowed_to_be_default_match = true;
RecordAdditionalInfo("autocompletion", "secondary & prefix");
return true;
}
// Try matching a non-prefix of |primary_text|. If
// |prefer_primary_non_prefix_over_secondary_prefix| is false; otherwise, this
// was already tried above.
if (!prefer_primary_non_prefix_over_secondary_prefix &&
can_autocomplete_non_prefix &&
(find_index = FindAtWordbreak(primary_text_lower, input_text_lower)) !=
std::u16string::npos) {
return NonPrefixPrimaryHelper();
}
// Try matching a non-prefix of |secondary_text|.
if (can_autocomplete_non_prefix && can_autocomplete_titles &&
(find_index = FindAtWordbreak(secondary_text_lower, input_text_lower)) !=
std::u16string::npos) {
rich_autocompletion_triggered = true;
if (counterfactual)
return false;
additional_text = primary_text;
inline_autocompletion =
secondary_text.substr(find_index + input_text_lower.length());
prefix_autocompletion = secondary_text.substr(0, find_index);
allowed_to_be_default_match = true;
RecordAdditionalInfo("autocompletion", "secondary & non-prefix");
return true;
}
const bool can_autocomplete_split_url =
OmniboxFieldTrial::kRichAutocompletionSplitUrlCompletion.Get() &&
input.text().size() >=
static_cast<size_t>(
OmniboxFieldTrial::kRichAutocompletionSplitCompletionMinChar
.Get());
// Try split matching (see comments for |split_autocompletion|) with
// |primary_text|.
std::vector<std::pair<size_t, size_t>> input_words;
if (can_autocomplete_split_url &&
!(input_words = FindWordsSequentiallyAtWordbreak(primary_text_lower,
input_text_lower))
.empty()) {
rich_autocompletion_triggered = true;
if (counterfactual)
return false;
split_autocompletion = SplitAutocompletion(
primary_text_lower,
TermMatchesToSelections(primary_text_lower.length(), input_words));
allowed_to_be_default_match = true;
RecordAdditionalInfo("autocompletion", "primary & split");
return true;
}
// Try split matching (see comments for |split_autocompletion|) with
// |secondary_text|.
const bool can_autocomplete_split_title =
OmniboxFieldTrial::kRichAutocompletionSplitTitleCompletion.Get() &&
input.text().size() >=
static_cast<size_t>(
OmniboxFieldTrial::kRichAutocompletionSplitCompletionMinChar
.Get());
if (can_autocomplete_split_title &&
!(input_words = FindWordsSequentiallyAtWordbreak(secondary_text_lower,
input_text_lower))
.empty()) {
rich_autocompletion_triggered = true;
if (counterfactual)
return false;
additional_text = primary_text;
split_autocompletion = SplitAutocompletion(
secondary_text_lower,
TermMatchesToSelections(secondary_text_lower.length(), input_words));
allowed_to_be_default_match = true;
RecordAdditionalInfo("autocompletion", "secondary & split");
return true;
}
return false;
}
bool AutocompleteMatch::IsEmptyAutocompletion() const {
return inline_autocompletion.empty() && prefix_autocompletion.empty() &&
split_autocompletion.Empty();
}
void AutocompleteMatch::WriteIntoTrace(perfetto::TracedValue context) const {
perfetto::TracedDictionary dict = std::move(context).WriteDictionary();
dict.Add("fill_into_edit", fill_into_edit);
dict.Add("additional_text", additional_text);
dict.Add("destination_url", destination_url);
dict.Add("keyword", keyword);
}
#if DCHECK_IS_ON()
void AutocompleteMatch::Validate() const {
std::string provider_name = provider ? provider->GetName() : "None";
ValidateClassifications(contents, contents_class, provider_name);
ValidateClassifications(description, description_class, provider_name);
ValidateClassifications(description_for_shortcuts,
description_class_for_shortcuts, provider_name);
}
#endif // DCHECK_IS_ON()
// static
void AutocompleteMatch::ValidateClassifications(
const std::u16string& text,
const ACMatchClassifications& classifications,
const std::string& provider_name) {
if (text.empty()) {
DCHECK(classifications.empty());
return;
}
// The classifications should always cover the whole string.
DCHECK(!classifications.empty()) << "No classification for \"" << text << '"';
DCHECK_EQ(0U, classifications[0].offset)
<< "Classification misses beginning for \"" << text << '"';
if (classifications.size() == 1)
return;
// The classifications should always be sorted.
size_t last_offset = classifications[0].offset;
for (auto i(classifications.begin() + 1); i != classifications.end(); ++i) {
DCHECK_GT(i->offset, last_offset)
<< " Classification for \"" << text << "\" with offset of " << i->offset
<< " is unsorted in relation to last offset of " << last_offset
<< ". Provider: " << provider_name << ".";
DCHECK_LT(i->offset, text.length())
<< " Classification of [" << i->offset << "," << text.length()
<< "] is out of bounds for \"" << text << "\". Provider: "
<< provider_name << ".";
last_offset = i->offset;
}
}
| bsd-3-clause |
anuragsoni/learn-polymer | dist/elements/my-jumbotron/my-jumbotron.html | 1259 | <!--
@license
Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
-->
<link rel="import" href="../../bower_components/polymer/polymer.html">
<dom-module id="my-jumbotron">
<template>
<style>
:host {
display: block;
}
</style>
<div class="jumbotron">
<div class="container">
<h1>This is a jumbotron</h1>
<p>Testing out front end options for an experimental Go Service</p>
<p><a class="btn btn-primary btn-lg" href="#" role="button">Learn more</a></p>
</div>
</div>
</template>
<script>
(function() {
'use strict';
Polymer({
is: 'my-jumbotron',
properties: {
foo: {
type: String,
value: 'my-jumbotron',
notify: true
}
}
});
})();
</script>
</dom-module>
| bsd-3-clause |
stonebig/bokeh | bokeh/command/subcommands/tests/test_secret.py | 2391 | #-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2019, Anaconda, Inc., and Bokeh Contributors.
# All rights reserved.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Boilerplate
#-----------------------------------------------------------------------------
from __future__ import absolute_import, division, print_function, unicode_literals
import pytest ; pytest
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
# Standard library imports
# External imports
# Bokeh imports
from bokeh.command.bootstrap import main
# Module under test
import bokeh.command.subcommands.secret as scsecret
#-----------------------------------------------------------------------------
# Setup
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# General API
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Dev API
#-----------------------------------------------------------------------------
def test_create():
import argparse
from bokeh.command.subcommand import Subcommand
obj = scsecret.Secret(parser=argparse.ArgumentParser())
assert isinstance(obj, Subcommand)
def test_name():
assert scsecret.Secret.name == "secret"
def test_help():
assert scsecret.Secret.help == "Create a Bokeh secret key for use with Bokeh server"
def test_args():
assert scsecret.Secret.args == (
)
def test_run(capsys):
main(["bokeh", "secret"])
out, err = capsys.readouterr()
assert err == ""
assert len(out) == 45
assert out[-1] == '\n'
#-----------------------------------------------------------------------------
# Private API
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------
| bsd-3-clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.