blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
c6f27342c148345735ff759e6b433373e9c9210b
4bac3093205faa29e99bc0a433614dfa779462c2
/Taggers/interface/EEDumpers.h
210d57147e8e398ce57d2a9521a7ba146fe9615f
[]
no_license
fravera/flashgg
407fb41553933397a623e1aefc166ff1f5636021
20e9241d44f189c2475ecf9756db11c3e122aedc
refs/heads/master
2021-01-19T05:08:11.973657
2016-09-21T08:19:34
2016-09-21T08:19:34
60,917,282
0
0
null
2016-06-11T16:45:27
2016-06-11T16:45:26
null
UTF-8
C++
false
false
924
h
#ifndef flashgg_EEDumpers_h #define flashgg_EEDumpers_h #include "flashgg/DataFormats/interface/DiElectronCandidate.h" #include "flashgg/DataFormats/interface/EEGammaCandidate.h" #include "flashgg/Taggers/interface/CollectionDumper.h" namespace flashgg { typedef CollectionDumper<std::vector<DiElectronCandidate> > DiElectronDumper; typedef CollectionDumper<std::vector<DiElectronCandidate>, DiElectronCandidate, CutBasedClassifier<DiElectronCandidate> > CutBasedDiElectronDumper; typedef CollectionDumper<std::vector<EEGammaCandidate> > EEGammaDumper; typedef CollectionDumper<std::vector<EEGammaCandidate>, EEGammaCandidate, CutBasedClassifier<EEGammaCandidate> > CutBasedEEGammaDumper; } #endif // Local Variables: // mode:c++ // indent-tabs-mode:nil // tab-width:4 // c-basic-offset:4 // End: // vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
7461a9b9138abe9069c10b265da9ef39b70f9b40
62917ce95d514e6404193acfc341bfc0e3e6b5af
/src/observables.h
3dc8eabcfba011ae81d446b51d3fa6f9e0926da0
[]
no_license
ssailer/ExpandingBEC2D
7db2756abc6643e9211a238eb56cdbef630fa21d
3eb1e5fdda01237fb6c102d46cfad467fb6320b1
refs/heads/master
2023-07-02T13:55:19.821817
2021-08-12T09:46:12
2021-08-12T09:46:12
51,006,853
0
0
null
null
null
null
UTF-8
C++
false
false
7,332
h
#ifndef EXP2D_OBSERVABLE_H__ #define EXP2D_OBSERVABLE_H__ #include <iostream> #include <complex> #include <math.h> #include <vector> #include <omp.h> #include <string> #include "tools.h" #include <eigen3/Eigen/Dense> using namespace std; using namespace Eigen; class Observables { public: double Ekin, particle_count, healing_length, volume, density, aspectRatio, alpha, r_max, r_min, r_max_phi, r_min_phi, Rx, Ry, n0; ArrayXd number; ArrayXd k,r; ArrayXd angularDensity,radialDensity; ArrayXd fixedAspectRatio; Observables(); Observables(int avgrid); Observables operator+ (const Observables &a) const; Observables operator- (const Observables &a) const; Observables operator* (const Observables &a) const; Observables operator* (double d) const; Observables operator/ (double d) const; Observables &operator+= (const Observables &a); Observables &operator-= (const Observables &a); Observables &operator*= (const Observables &a); Observables &operator/= (double d); Observables &operator*= (double d); }; typedef struct { int32_t n; Coordinate<double> c; double surroundDens; double zeroDensity; } VortexData; struct Ellipse { Matrix<double, 6,1> coef; vector<double> center; double major; double minor; double angle; }; inline Observables::Observables() : number(), k(), r(), radialDensity(), angularDensity(360), fixedAspectRatio(360) { Ekin = particle_count = healing_length = volume = density = aspectRatio = alpha = r_max = r_min = r_max_phi = r_min_phi = Rx = Ry = 0.0; number.setZero(); k.setZero(); r.setZero(); radialDensity.setZero(); angularDensity.setZero(); fixedAspectRatio.setZero(); } inline Observables::Observables(int avgrid) : number(avgrid), k(avgrid), r(avgrid), radialDensity(avgrid), angularDensity(360), fixedAspectRatio(360) { Ekin = particle_count = healing_length = volume = density = aspectRatio = alpha = r_max = r_min = r_max_phi = r_min_phi = Rx = Ry = n0 = 0.0; number.setZero(); k.setZero(); r.setZero(); radialDensity.setZero(); angularDensity.setZero(); fixedAspectRatio.setZero(); } inline Observables Observables::operator+ (const Observables &a) const { Observables ret(number.size()); ret.particle_count = particle_count + a.particle_count; ret.healing_length = healing_length + a.healing_length; ret.Ekin = Ekin + a.Ekin; ret.aspectRatio = aspectRatio + a.aspectRatio; ret.fixedAspectRatio = fixedAspectRatio + a.fixedAspectRatio; ret.alpha = alpha + a.alpha; ret.r_max = r_max + a.r_max; ret.r_min = r_min + a.r_min; ret.r_max_phi = r_max_phi + a.r_max_phi; ret.r_min_phi = r_min_phi + a.r_min_phi; ret.Rx = Rx + a.Rx; ret.Ry = Ry + a.Ry; ret.density = density + a.density; ret.volume = volume + a.volume; ret.angularDensity = angularDensity + a.angularDensity; ret.radialDensity = radialDensity + a.radialDensity; ret.n0 = n0 + a.n0; ret.number = number + a.number; ret.k = k + a.k; ret.r = r + a.r; return ret; } inline Observables Observables::operator- (const Observables &a) const { Observables ret(number.size()); ret.particle_count = particle_count - a.particle_count; ret.healing_length = healing_length - a.healing_length; ret.Ekin = Ekin - a.Ekin; ret.aspectRatio = aspectRatio - a.aspectRatio; ret.fixedAspectRatio = fixedAspectRatio - a.fixedAspectRatio; ret.alpha = alpha - a.alpha; ret.r_max = r_max - a.r_max; ret.r_min = r_min - a.r_min; ret.r_max_phi = r_max_phi - a.r_max_phi; ret.r_min_phi = r_min_phi - a.r_min_phi; ret.Rx = Rx - a.Rx; ret.Ry = Ry - a.Ry; ret.density = density - a.density; ret.volume = volume - a.volume; ret.angularDensity = angularDensity - a.angularDensity; ret.radialDensity = radialDensity - a.radialDensity; ret.n0 = n0 - a.n0; ret.number = number - a.number; ret.k = k - a.k; ret.r = r - a.r; return ret; } inline Observables Observables::operator* (const Observables &a) const { Observables ret(number.size()); ret.particle_count = particle_count * a.particle_count; ret.healing_length = healing_length * a.healing_length; ret.Ekin = Ekin * a.Ekin; ret.aspectRatio = aspectRatio * a.aspectRatio; ret.fixedAspectRatio = fixedAspectRatio * a.fixedAspectRatio; ret.alpha = alpha * a.alpha; ret.r_max = r_max * a.r_max; ret.r_min = r_min * a.r_min; ret.r_max_phi = r_max_phi * a.r_max_phi; ret.r_min_phi = r_min_phi * a.r_min_phi; ret.Rx = Rx * a.Rx; ret.Ry = Ry * a.Ry; ret.density = density * a.density; ret.volume = volume * a.volume; ret.angularDensity = angularDensity * a.angularDensity; ret.radialDensity = radialDensity * a.radialDensity; ret.n0 = n0 * a.n0; ret.number = number * a.number; ret.k = k * a.k; ret.r = r * a.r; return ret; } inline Observables Observables::operator* (double d) const { Observables ret(number.size()); ret.particle_count = particle_count * d; ret.healing_length = healing_length * d; ret.Ekin = Ekin * d; ret.aspectRatio = aspectRatio * d; ret.fixedAspectRatio = fixedAspectRatio * d; ret.alpha = alpha * d; ret.r_max = r_max * d; ret.r_min = r_min * d; ret.r_max_phi = r_max_phi * d; ret.r_min_phi = r_min_phi * d; ret.Rx = Rx * d; ret.Ry = Ry * d; ret.density = density * d; ret.volume = volume * d; ret.angularDensity = angularDensity * d; ret.radialDensity = radialDensity * d; ret.n0 = n0 * d; ret.number = number * d; ret.k = k * d; ret.r = r * d; return ret; } inline Observables Observables::operator/ (double d) const { Observables ret(number.size()); ret.particle_count = particle_count / d; ret.healing_length = healing_length / d; ret.Ekin = Ekin / d; ret.aspectRatio = aspectRatio / d; ret.fixedAspectRatio = fixedAspectRatio / d; ret.alpha = alpha / d; ret.r_max = r_max / d; ret.r_min = r_min / d; ret.r_max_phi = r_max_phi / d; ret.r_min_phi = r_min_phi / d; ret.Rx = Rx / d; ret.Ry = Ry / d; ret.density = density / d; ret.volume = volume / d; ret.angularDensity = angularDensity / d; ret.radialDensity = radialDensity / d; ret.n0 = n0 / d; ret.number = number / d; ret.k = k / d; ret.r = r / d; return ret; } inline Observables & Observables::operator+= (const Observables &a) { *this = *this + a; return *this; } inline Observables & Observables::operator-= (const Observables &a) { *this = *this - a; return *this; } inline Observables & Observables::operator*= (const Observables &a) { *this = *this * a; return *this; } inline Observables & Observables::operator/= (double d) { *this = *this / d; return *this; } inline Observables & Observables::operator*= (double d) { *this = *this * d; return *this; } #endif // EXP2D_OBSERVABLE_H__
31503c900c27847c36659c483ea90357908aeb8c
749f3d84569bf9de824d9b5d941a1c3030c6fb8a
/Ch3_Oscillation/Forces_withAngularMotion/xcode/Attractor.hpp
7f4414a4953a12dec1d43242dd3088afdebc6e0f
[]
no_license
jefarrell/NatureOfCode_Cinder
1da74b6d1f3680f2fcd0883e3fa68c0d673225f0
54f096c0ab94663e6611b7b37acfa42822b1c864
refs/heads/master
2021-01-10T08:57:47.102139
2016-03-25T17:45:41
2016-03-25T17:45:41
50,674,906
0
0
null
null
null
null
UTF-8
C++
false
false
522
hpp
// // Attractor.hpp // Forces_withAngularMotion // // Created by John Farrell on 3/1/16. // // #ifndef Attractor_hpp #define Attractor_hpp #include <stdio.h> #include "Mover.hpp" #endif /* Attractor_hpp */ typedef std::shared_ptr<class Attractor> AttractorRef; class Attractor { public: static AttractorRef create(){ return AttractorRef(new Attractor()); } vec2 location_; float mass_; float G_; void draw(); vec2 attract(MoverRef m); private: Attractor(); };
d9532dc5e45a04d1d0e2cb54bb390f9e889f85da
7aef77f63c00258bf11ae2a85ec2a9723c98a834
/ShowRunner/src/CrossVisualization/screenCross.cpp
c7d39e8abb76356463824608938248efeac82df5
[]
no_license
moonmilk/BklynBalletVisualization
c55f55fac541d27cb242b345f9c350851f31bbbe
eaef35bdc6274485e1db307e9e924b6cf93fe440
refs/heads/master
2021-01-19T09:44:43.960596
2013-02-26T22:37:11
2013-02-26T22:37:11
7,949,106
1
0
null
null
null
null
UTF-8
C++
false
false
2,580
cpp
/* * screenCross.cpp * oscReceiveForTuio * * Created by Ranjit Bhatnagar on 1/30/13. * Copyright 2013 __MyCompanyName__. All rights reserved. * */ #include "math.h" #include <iostream> #include "screenCross.h" #define randf(LO, HI) (LO + (float)rand()/((float)RAND_MAX/(HI-LO))) #define fade (-0.9 ) #define gravity (0.02) screenCross::screenCross(float _x, float _y) : screenItem(_x, _y) { //radius = randf(4,16); radius = randf(3,8); dx = randf(-0.1,0.1); dy = randf(-0.02,0.02); flingable = (randf(0,1)<0.25); margin = randf(0,100); } screenCross::screenCross(float _x, float _y, float _dx, float _dy) : screenItem(_x, _y) { // radius = randf(4,16); radius = randf(3,8); flingable = (randf(0,1)<0.25); if (flingable) { dx = _dx * 0.025; dy = _dy * 0.025; } else { dx = randf(-0.1,0.1); dy = randf(-0.02,0.02); } margin = randf(0,100); } // update returns false if it's time to die bool screenCross::update() { screenItem::update(); tilt += randf(-2, 2); x += dx; y += dy; if (age > 0.1){ dy *=0.95; dy += gravity; dx*=0.95; } return (age < 3.0); } void screenCross::draw() { //int r,g,b; //colorTemp(9000.0 * exp(fade*(age)), r, g, b); //ofSetColor(r, g, b, (flingable?30:50)*exp(fade*age)); ofNoFill(); ofSetLineWidth(1); ofColor drawColor = ofColor::fromHsb(colorH,colorS,colorB); ofSetColor(drawColor,static_cast<int>(xalpha*exp(fade*age))); ofLine(margin, y-tilt, ofGetViewportWidth()-margin, y+tilt); ofSetColor(drawColor,static_cast<int>(yalpha*exp(fade*age))); ofLine(x+tilt, margin, x-tilt, ofGetViewportHeight()-margin); } void screenCross::colorTemp(int k, int &r, int &g, int &b) { // color temp converter from http://www.tannerhelland.com/4435/convert-temperature-rgb-algorithm-code/ // works for 1000 to 40000 K, white point at about 6500-6600K double tmpCalc; if (k < 1000) k = 1000; else if (k > 40000) k = 40000; k /= 100; if (k <= 66) r = 255; else { tmpCalc = k - 60; tmpCalc = 329.698727446 * pow(tmpCalc, -0.1332047592); r = tmpCalc; if (r < 0) r = 0; else if (r > 255) r = 255; } if (k <= 66) { tmpCalc = k; tmpCalc = 99.4708025861 * log(tmpCalc) - 161.1195681661; } else { tmpCalc = k - 60; tmpCalc = 288.1221695283 * pow(tmpCalc, -0.0755148492); } g = tmpCalc; if (g < 0) g = 0; else if (g > 255) g = 255; if (k >= 66) { b = 255; } else if (k <= 19) { b = 0; } else { tmpCalc = k - 10; tmpCalc = 138.5177312231 * log(tmpCalc) - 305.0447927307; b = tmpCalc; if (b < 0) b = 0; else if (b > 255) b = 255; } }
7498851245336b5a23d00089bc493461191b33ab
ce9cb2399093d6d44ed8e7caf67060195d423a3e
/src/Game_Object.cpp
2cc14f256571e40c2e81bd2f9a9cf53910660f49
[]
no_license
YevgenyBorko/Digger_Game_Remake
e32da85cfafe67d79dfa21f85cadec45b77eac38
318a00ca0b74ebbd45e0c2979c634a52100862e7
refs/heads/main
2023-03-15T17:28:32.925648
2021-03-17T11:34:24
2021-03-17T11:34:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
710
cpp
#include "Game_Object.h" Game_Object::Game_Object(sf::Vector2f position, char c) : m_position(position),m_type(c) {} Game_Object::Game_Object() : m_type( 0 ) {} //---------gets the object picture---------- const sf::Sprite& Game_Object::get_pic() const { return m_object_pic; } //-------get the object type------ char Game_Object::get_type() const { return m_type; } //---------------set the object position-------------- void Game_Object::set_position(sf::Vector2f new_position) { m_position = new_position; } //-----------get the object position---------- sf::Vector2f Game_Object::get_position() const { return m_position; } Game_Object::~Game_Object() {}
3806ae2d9044f793cdeb75959c04fa8facfdfdc8
b78d73bd67c9990b3603dd495a38b8360f6712cb
/branch/lidl/sHome/Main/Video/JConfig/PowerSocket_BanLed.h
31217e6cec2cafd6d33c46a055f7d754d937f969
[]
no_license
Siterwell/familywell-lidl-ios
9bbbea611b52e58d753b8f8bdde79ba6fe745a44
11d55dadffee58246bc196a19bd9b9f094b0f845
refs/heads/master
2021-06-15T03:17:53.219494
2018-10-31T00:57:53
2018-10-31T00:57:53
155,319,438
0
0
null
null
null
null
UTF-8
C++
false
false
370
h
#pragma once #include "FunSDK/JObject.h" #define JK_PowerSocket_BanLed "PowerSocket.BanLed" class PowerSocket_BanLed : public JObject { public: JIntObj Banstatus; public: PowerSocket_BanLed(JObject *pParent = NULL, const char *szName = JK_PowerSocket_BanLed): JObject(pParent,szName), Banstatus(this, "Banstatus"){ }; ~PowerSocket_BanLed(void){}; };
f19f5a5c08366715e465d3042c9c619d052fa2c6
184180d341d2928ab7c5a626d94f2a9863726c65
/issuestests/expperm/src/RcppExports.cpp
d5c11c39866ea796a9a805579f1dd5ff05e6a491
[]
no_license
akhikolla/RcppDeepStateTest
f102ddf03a22b0fc05e02239d53405c8977cbc2b
97e73fe4f8cb0f8e5415f52a2474c8bc322bbbe5
refs/heads/master
2023-03-03T12:19:31.725234
2021-02-12T21:50:12
2021-02-12T21:50:12
254,214,504
2
1
null
null
null
null
UTF-8
C++
false
false
2,080
cpp
// Generated by using Rcpp::compileAttributes() -> do not edit by hand // Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 #include <Rcpp.h> using namespace Rcpp; // BG_cpp NumericMatrix BG_cpp(NumericMatrix A); RcppExport SEXP _expperm_BG_cpp(SEXP ASEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< NumericMatrix >::type A(ASEXP); rcpp_result_gen = Rcpp::wrap(BG_cpp(A)); return rcpp_result_gen; END_RCPP } // brute_cpp NumericMatrix brute_cpp(NumericMatrix A); RcppExport SEXP _expperm_brute_cpp(SEXP ASEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< NumericMatrix >::type A(ASEXP); rcpp_result_gen = Rcpp::wrap(brute_cpp(A)); return rcpp_result_gen; END_RCPP } // ryser_cpp NumericMatrix ryser_cpp(NumericMatrix A); RcppExport SEXP _expperm_ryser_cpp(SEXP ASEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< NumericMatrix >::type A(ASEXP); rcpp_result_gen = Rcpp::wrap(ryser_cpp(A)); return rcpp_result_gen; END_RCPP } // sink_cpp NumericMatrix sink_cpp(NumericMatrix A, int maxit); RcppExport SEXP _expperm_sink_cpp(SEXP ASEXP, SEXP maxitSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< NumericMatrix >::type A(ASEXP); Rcpp::traits::input_parameter< int >::type maxit(maxitSEXP); rcpp_result_gen = Rcpp::wrap(sink_cpp(A, maxit)); return rcpp_result_gen; END_RCPP } static const R_CallMethodDef CallEntries[] = { {"_expperm_BG_cpp", (DL_FUNC) &_expperm_BG_cpp, 1}, {"_expperm_brute_cpp", (DL_FUNC) &_expperm_brute_cpp, 1}, {"_expperm_ryser_cpp", (DL_FUNC) &_expperm_ryser_cpp, 1}, {"_expperm_sink_cpp", (DL_FUNC) &_expperm_sink_cpp, 2}, {NULL, NULL, 0} }; RcppExport void R_init_expperm(DllInfo *dll) { R_registerRoutines(dll, NULL, CallEntries, NULL, NULL); R_useDynamicSymbols(dll, FALSE); }
47dbd3972d65b578c3dc82119e70045c2efde09f
e8fe13c01ee25b2de549b8d09cfd7832c974aab0
/JJune/Level_2/행렬의곱셈.cpp
26ceef39ebe38442f33e91663d2beb4284c848ab
[ "MIT" ]
permissive
algorithm-maintain-box/Programers
7136aba4fa8b7ad0e9129535eb18d607d767f885
5c596617739e37ad2430c5b9c9e4660233ef2684
refs/heads/master
2021-02-12T23:42:30.118393
2020-04-19T01:07:26
2020-04-19T01:07:26
244,643,089
0
1
MIT
2020-04-17T15:39:23
2020-03-03T13:28:15
C++
UTF-8
C++
false
false
1,111
cpp
#include <string> #include <vector> using namespace std; vector<vector<int>> solution(vector<vector<int>> arr1, vector<vector<int>> arr2) { vector<vector<int>> answer; answer.resize(arr1.size()); for (auto j = 0; j < arr1.size(); j++) { for (auto i = 0; i < arr2[0].size(); i++) { int sum = 0; for (auto k = 0; k < arr2.size(); k++) { sum += arr1[j][k] * arr2[k][i]; } answer[j].push_back(sum); } } return answer; } #include <iostream> template <typename T> void vector_printer(vector<T> vec) { for (auto iter : vec) { for (auto iter_ : iter) { cout << iter_ << " "; } cout << ", "; } cout << endl; } int main() { vector_printer(solution({{1, 4}, {3, 2}, {4, 1}}, {{3, 3}, {3, 3}})); cout << "A : {{15,15},{15,15},{15,15}}" << endl; vector_printer(solution({{2, 3, 2}, {4, 2, 4}, {3, 1, 4}}, {{5, 4, 3}, {2, 4, 1}, {3, 1, 1}})); cout << "A : {{22,22,11},{36,28,18},{29,20,14}}" << endl; return 0; }
5a6b7d739399452d5288663bc348fe885149211c
bd729ef9fcd96ea62e82bb684c831d9917017d0e
/keche/trunk/comm_app/ctfolibs/include/utils/tools.h
d7c928621b884a7f06a25fab4ee1c652f05174bd
[]
no_license
shanghaif/workspace-kepler
849c7de67b1f3ee5e7da55199c05c737f036780c
ac1644be26a21f11a3a4a00319c450eb590c1176
refs/heads/master
2023-03-22T03:38:55.103692
2018-03-24T02:39:41
2018-03-24T02:39:41
null
0
0
null
null
null
null
GB18030
C++
false
false
1,574
h
/** * Name: * Copyright: * Author: [email protected] * Date: 2009-11-3 下午 3:42:52 * Description: * Modification: **/ #ifndef __TOOLS_H__ #define __TOOLS_H__ #include <string> #include <vector> #include <stdio.h> using namespace std; //UNICODE码转为GB2312码 int u2g(char *inbuf, int inlen, char *outbuf, int& outlen); //GB2312码转为UNICODE码 int g2u(char *inbuf, size_t inlen, char *outbuf, int& outlen); // 检测IP的有效性 bool check_addr( const char *ip ) ; // 安全内存拷贝 char * safe_memncpy( char *dest, const char *src, int len ) ; // 自动拆分前多个分割符处理 bool splitvector( const string &str, std::vector<std::string> &vec, const std::string &split , const int count ) ; // 这里主要处理分析路径中带有 env:LBS_ROOT/lbs 之类的路径 bool getenvpath( const char *value, char *szbuf ) ; /** * 取得当前环境对象路径, * env 为环境对象名称,buf 存放路径的缓存, sz 为附加后缀, def 默认的中径 */ const char * getrunpath( const char *env, char *buf, const char *sz, const char *def ) ; // 取得默认的CONF路径 const char * getconfpath( const char *env, char *buf, const char *sz, const char *def, const char *conf ) ; // 追加写入文件操作 bool AppendFile( const char *szName, const char *szBuffer, const int nLen ) ; // 创建新文件写入 bool WriteFile( const char *szName, const char *szBuffer, const int nLen ) ; // 读取文件 char *ReadFile( const char *szFile , int &nLen ) ; // 释放数据 void FreeBuffer( char *buf ) ; #endif
16cfb53a4f69dda84bcfd01b637553f639367804
275bf9e939c32c41edde80c2898fda7103448718
/atem-gvg200/gvg200-programKeys.ino
1bca812a1e68d76fcd0606c46b817d283afcf740
[]
no_license
scnmtv/GVG200
cb256d354bea4b4550a3d0e524370199c3e75d6f
29150a923922a740c138f39977380c49f7f6d256
refs/heads/master
2021-09-24T22:55:58.554211
2018-10-15T15:27:42
2018-10-15T15:27:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,142
ino
//pripravljeno za GVG200 XPT PANEL MODULE //Program tipke - 5. vrstica: //01010000 01010001 01010010 byte pressedKeysProgram_OLD[6] = { 0, 0, 0, 0, 0, 0 }; byte pressedKeysProgram = 0; uint16_t programInput[3][8] = { {1,2,3,4,5,6,7,8}, {1000,2001,2002,3010,3011,3020,3021,0}, {4010,5010,5020,7001,7002,99999,99999,99999} }; byte matricaPregramLedke[6][8] = { {1,2,4,8,16,32,64,128}, {1,2,4,8,16,32,64,128}, {1,2,4,8,16,32,64,128}, {1,2,4,8,16,32,64,128}, {1,2,4,8,16,32,64,128}, {1,2,4,8,16,32,64,128}, }; byte currentProgramTallyKey[2]; uint16_t currentProgramTallyInput = 9696; byte muxProgram = 0b10000; void readProgramKeys(){ // Serial.println("Debug: Zagnana funckcija readProgramKeys"); for(uint8_t column=0;column<3;column++){ readingProgramKeys = true; izhod = bigBoard + muxPreview + column; PORTC = izhod; delay(0.1); pressedKey = PINA; if(pressedKey != pressedKeysProgram_OLD[column]){ if (pressedKey != 0b11111111){ if (serialDebugProgram && serialDebugALL) { Serial.println(F("########## PROGRAM KEY ###########")); Serial.print(F("PORTC: ")); Serial.println(PORTC,BIN); Serial.print(F("Selected column ")); Serial.print(column); Serial.print(F(" and pressed key: ")); } invertedKeys = ~pressedKey; pressedKeyPosition=(int)(log(invertedKeys)/log(2)); if (serialDebugProgram && serialDebugALL) { Serial.println(invertedKeys,BIN); Serial.print(F("Pressed key in column in program matrix: ")); Serial.println(pressedKeyPosition); Serial.print(F("Sent atem Program input: ")); Serial.println(programInput[column][pressedKeyPosition]); } AtemSwitcher.setProgramInputVideoSource(0, programInput[column][pressedKeyPosition]); } pressedKeysProgram_OLD[column]=pressedKey; } readingProgramKeys = false; } } void setProgramTallyLights(uint16_t atemProgramTallySource){ //PROGRAM TALLY //resetBigBoardLightOutputs(); if(AtemSwitcher.getTransitionInTransition(0)){ if(currentProgramTallyKey[0] == currentPreviewTallyKey[0]-3){ PORTC = currentPreviewTallyKey[0]-3; delay(0.1); PORTL = currentPreviewTallyKey[1]+currentProgramTallyKey[1]; PORTG = 0b1; delay(0.1); PORTG = 0b0; } else { PORTC = currentPreviewTallyKey[0]-3; delay(0.1); PORTL = currentPreviewTallyKey[1]; PORTG = 0b1; delay(0.1); PORTG = 0b0; } } if (atemProgramTallySource != currentProgramTallyInput){ // Serial.println("Debug: Drugucen tally - Zagnana funckcija setProgramTallyLights"); for(int column=0;column<3;column++){ for (uint8_t keyNumber = 0; keyNumber < 8; keyNumber++) { if(atemProgramTallySource == programInput[column][keyNumber]){ brisiProgramLedke(); izhod = bigBoard + muxPreview + column; PORTC = izhod; delay(0.1); if (serialDebugProgram && serialDebugALL) { Serial.println(F("########## PROGRAM TALLY ###########")); Serial.print("Debug: Program je na inputu: "); Serial.println(programInput[column][keyNumber]); Serial.print("Debug: programTallyLights Stolpec: "); Serial.println(column); Serial.print("Debug: programTallyLights Tipka: "); Serial.println(keyNumber); Serial.print(F("Debug: Prižigam program lucko 1-8 v njenem stolpcu ")); Serial.print(column); Serial.print(F(": ")); Serial.println(0b1 << keyNumber); } currentProgramTallyKey[0] = izhod; currentProgramTallyKey[1] = 0b1 << keyNumber; PORTL = 0b1 << keyNumber; PORTG = 0b1; delay(0.1); PORTG = 0b0; } } } currentProgramTallyInput = atemProgramTallySource; } } //PROGRAM TALLY void brisiProgramLedke(){ for(int column=0;column<3;column++){ izhod = bigBoard + muxPreview + column; PORTC = izhod; delay(0.1); PORTL = 0b00000000; PORTG = 0b1; delay(0.1); PORTG = 0b0; } }
51151c88bc3a2625079ea970cd1ebe447ab5e09a
9ffee105d323f8f9c0cb8ac92d74ee3551ab5dfa
/Classes & Objects/Example_3.cpp
15572e3397a0cbcde88ac00650ae9fa2e4b2047b
[ "MIT" ]
permissive
Ahtisham-Shakir/CPP_OOP
2098f3bf4d965d26adee5585033d211e297f0003
308e7bdbd1e73c644a17f612fc5b919cb68c171c
refs/heads/main
2023-07-26T01:22:59.402548
2021-08-28T19:22:29
2021-08-28T19:22:29
375,672,983
0
0
null
null
null
null
UTF-8
C++
false
false
450
cpp
#include<iostream> using namespace std; class circle{ float r; public: void get_radius(float radius) { r = radius; } void area() { float a; a= 3.14*r*r; cout<<"Area= "<<a<<endl; } void circum() { float c; c= 2*3.14*r; cout<<"Circumference= "<<c<<endl; } }; int main() { circle obj; float radius; cout<<"Enter radius: "; cin>>radius; obj.get_radius(radius); obj.area(); obj.circum(); return 0; }
ca4421e9cf9141c42df223ac96636f78b5cdf4b5
ba14343d3545ca1b33626ca6c2f5aa486c88ef23
/EstructuraExamen2-master/main.cpp
fe7043541f2d1e71e7427c01cdc6fae2c83c69ad
[]
no_license
Driem/Archivos
04c3473b7d9319f5e18133eedfb123d0018458c9
99ce30a714b2cce527f4019eee33782d2c0768e5
refs/heads/master
2021-01-20T08:14:43.465656
2014-09-22T20:52:55
2014-09-22T20:52:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,314
cpp
#include "Evaluador.h" #include <iostream> // std::cin, std::cout #include <list> // std::list using namespace std; ////////////////////////////////////// ////////////ARBOL TRINARIO//////////// ////////////////////////////////////// class NodoTrinario { public: NodoTrinario* hijo_izq; NodoTrinario* hijo_der; NodoTrinario* hijo_medio; int num; NodoTrinario(int num) { this->num=num; hijo_der=NULL; hijo_izq=NULL; hijo_medio=NULL; } }; ////////////////////////////////////// ////////////GRAFO PONDERADO/////////// ////////////////////////////////////// class NodoGrafo; class AristaGrafo { public: int distancia;//peso NodoGrafo* destino; AristaGrafo(int distancia, NodoGrafo* destino) { this->distancia=distancia; this->destino=destino; } }; class NodoGrafo { public: list<AristaGrafo*> aristas; int num; NodoGrafo(int num) { this->num=num; } }; void Orden(NodoTrinario *raiz, list<int> *Enorden1) { if(raiz == NULL) { return; } Enorden1->push_back(raiz->num); Orden(raiz->hijo_izq,Enorden1); Orden(raiz->hijo_medio,Enorden1); Orden(raiz->hijo_der,Enorden1); } ////////////////////////////////////// //////////////EJERCICIOS////////////// ////////////////////////////////////// //Imprime todos los numeros de un arbol trinario dada su raiz //5pts void imprimir(NodoTrinario* raiz) { if(raiz == NULL) { return; } cout << raiz->num << endl; imprimir(raiz->hijo_izq); imprimir(raiz->hijo_medio); imprimir(raiz->hijo_der); } //Devuelve el numero mayor de un arbol trinario dada su raiz //5pts int getMayor(NodoTrinario* raiz) { list<int> orden; Orden(raiz,&orden); orden.sort(); int Mayor = orden.back(); return Mayor; } //Devuelve true si puedo llegar desde el nodo inicio hasta el nodo destino dada una distancia maxima del recorrido //5pts bool puedoLLegar(NodoGrafo* inicio, NodoGrafo* destino, int distancia_max) { AristaGrafo *Aux; for(list<AristaGrafo*> ::iterator i = inicio->aristas.begin(); i != inicio->aristas.end();i++ ) if(inicio->aristas.empty()) return false; return false; } int main () { ////////////////////////////////////// ////////////ARBOL TRINARIO//////////// ////////////////////////////////////// NodoTrinario *nt1 = new NodoTrinario(1); NodoTrinario *nt2 = new NodoTrinario(2); NodoTrinario *nt3 = new NodoTrinario(3); NodoTrinario *nt4 = new NodoTrinario(4); NodoTrinario *nt5 = new NodoTrinario(5); NodoTrinario *nt6 = new NodoTrinario(6); NodoTrinario *nt7 = new NodoTrinario(7); NodoTrinario *nt8 = new NodoTrinario(8); NodoTrinario *nt9 = new NodoTrinario(9); nt1->hijo_izq = nt2; nt1->hijo_medio = nt3; nt1->hijo_der = nt4; nt2->hijo_medio = nt5; nt2->hijo_der = nt6; nt4->hijo_izq = nt7; nt7->hijo_izq = nt8; nt7->hijo_medio = nt9; ////////////////////////////////////// ////////////GRAFO PONDERADO/////////// ////////////////////////////////////// NodoGrafo *ng1 = new NodoGrafo(1); NodoGrafo *ng2 = new NodoGrafo(2); NodoGrafo *ng3 = new NodoGrafo(3); NodoGrafo *ng4 = new NodoGrafo(4); NodoGrafo *ng5 = new NodoGrafo(5); NodoGrafo *ng6 = new NodoGrafo(6); ng1->aristas.push_back(new AristaGrafo(5,ng2)); ng1->aristas.push_back(new AristaGrafo(3,ng3)); ng2->aristas.push_back(new AristaGrafo(1,ng3)); ng2->aristas.push_back(new AristaGrafo(2,ng4)); ng4->aristas.push_back(new AristaGrafo(6,ng5)); ////////////////////////////////////// //////////////EJERCICIOS////////////// ////////////////////////////////////// cout<<"Ejercicio1"<<endl; imprimir(nt1); cout<<"Ejercicio2"<<endl; cout<<getMayor(nt1)<<"\tSe espera: 9"<<endl; cout<<getMayor(nt2)<<"\tSe espera: 6"<<endl; cout<<getMayor(nt5)<<"\tSe espera: 5"<<endl; cout<<"Ejercicio3"<<endl; cout<<puedoLLegar(ng1,ng2,5)<<"\tSe espera: 1"<<endl; cout<<puedoLLegar(ng1,ng2,4)<<"\tSe espera: 0"<<endl; cout<<puedoLLegar(ng4,ng3,10000)<<"\tSe espera: 0"<<endl; cout<<puedoLLegar(ng1,ng5,12)<<"\tSe espera: 0"<<endl; cout<<puedoLLegar(ng1,ng5,13)<<"\tSe espera: 1"<<endl; return 1; }
0fff2bbe7de5a942efaab46b6bbf1edb512b3f7f
55d560fe6678a3edc9232ef14de8fafd7b7ece12
/libs/hana/test/ext/boost/tuple/tag_of.cpp
d53efe2fd4b90e6c5fdfca0c07de30aa62cf71ec
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
stardog-union/boost
ec3abeeef1b45389228df031bf25b470d3d123c5
caa4a540db892caa92e5346e0094c63dea51cbfb
refs/heads/stardog/develop
2021-06-25T02:15:10.697006
2020-11-17T19:50:35
2020-11-17T19:50:35
148,681,713
0
0
BSL-1.0
2020-11-17T19:50:36
2018-09-13T18:38:54
C++
UTF-8
C++
false
false
2,132
cpp
// Copyright Louis Dionne 2013-2017 // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) #include <boost/hana/core/tag_of.hpp> #include <boost/hana/ext/boost/tuple.hpp> #include <boost/tuple/tuple.hpp> #include <type_traits> namespace hana = boost::hana; int main() { ////////////////////////////////////////////////////////////////////////// // make sure the tag is correct ////////////////////////////////////////////////////////////////////////// { auto make_cons = [](auto x, auto xs) { return boost::tuples::cons<decltype(x), decltype(xs)>{x, xs}; }; static_assert(std::is_same< hana::tag_of_t<decltype(boost::make_tuple())>, hana::ext::boost::tuple_tag >::value, ""); static_assert(std::is_same< hana::tag_of_t<decltype(boost::make_tuple(1))>, hana::ext::boost::tuple_tag >::value, ""); static_assert(std::is_same< hana::tag_of_t<decltype(boost::make_tuple(1, '2'))>, hana::ext::boost::tuple_tag >::value, ""); static_assert(std::is_same< hana::tag_of_t<decltype(boost::make_tuple(1, '2', 3.3))>, hana::ext::boost::tuple_tag >::value, ""); static_assert(std::is_same< hana::tag_of_t<decltype(make_cons(1, boost::tuples::null_type{}))>, hana::ext::boost::tuple_tag >::value, ""); static_assert(std::is_same< hana::tag_of_t<decltype(make_cons(1, make_cons('2', boost::tuples::null_type{})))>, hana::ext::boost::tuple_tag >::value, ""); static_assert(std::is_same< hana::tag_of_t<decltype(make_cons(1, boost::make_tuple('2', 3.3)))>, hana::ext::boost::tuple_tag >::value, ""); static_assert(std::is_same< hana::tag_of_t<boost::tuples::null_type>, hana::ext::boost::tuple_tag >::value, ""); } }
9318c1b6518e58382834cfb85e0973d4f53662f5
7ef4576a0ca2feed8c513263752672073254d7ed
/MultiThreading/IntegratorPool.cpp
9f7d62b600ba7a9215c5125d8827afe931f21066
[]
no_license
Axymerion/PO
5e3a40430f82b15b72935b23d0e8b62ac4e88d65
3c59ca16c4496e69b5ae41101f9c13d792b95cd8
refs/heads/master
2021-01-14T16:09:43.395083
2020-07-13T15:21:26
2020-07-13T15:21:26
242,674,458
1
0
null
null
null
null
UTF-8
C++
false
false
720
cpp
#include "IntegratorPool.hpp" IntegratorPool::IntegratorPool(size_t param) { for (size_t i = 0; i < param; i++) { pool.push_back(new Integrator()); pool.back()->Start(); } } IntegratorPool::~IntegratorPool() { for (size_t i = 0; i < pool.size(); i++) { pool[i]->Stop(); delete pool[i]; } pool.clear(); } Integrator* IntegratorPool::GetInstance() { while (true) { for (size_t i = 0; i < pool.size(); i++) { if(pool[i]->GetStatus() == Integrator::Status::IDLE) { return pool[i]; } } } } size_t IntegratorPool::GetLoad() { size_t load = 0; for (size_t i = 0; i < pool.size(); i++) { if (pool[i]->GetStatus() == Integrator::Status::WORKING) { load++; } } return load; }
c6b380d130180bb108b8eb0446e7f868d6360f78
e0242089d4f342c74bc0a681ecc6fd364f8f9af1
/src/poly/threading.h
a82eb61385a51287e00ff5117b0c4eaafa15911f
[]
no_license
atupac/xenia
9d99c06e5f6a0636f0e0e7ab96b7cbb5c9bc75e6
3658e710d2e4de6c323b5b74dbac21925875e8f3
refs/heads/master
2021-01-18T12:45:15.801267
2015-01-06T08:13:27
2015-01-06T08:13:27
28,930,404
1
0
null
2015-01-07T19:36:24
2015-01-07T19:36:24
null
UTF-8
C++
false
false
2,015
h
/** ****************************************************************************** * Xenia : Xbox 360 Emulator Research Project * ****************************************************************************** * Copyright 2014 Ben Vanik. All rights reserved. * * Released under the BSD license - see LICENSE in the root for more details. * ****************************************************************************** */ #ifndef POLY_THREADING_H_ #define POLY_THREADING_H_ #include <atomic> #include <chrono> #include <condition_variable> #include <cstdint> #include <mutex> #include <string> #include <thread> #include <poly/config.h> namespace poly { namespace threading { class Fence { public: Fence() : signaled_(false) {} void Signal() { std::unique_lock<std::mutex> lock(mutex_); signaled_.store(true); cond_.notify_all(); } void Wait() { std::unique_lock<std::mutex> lock(mutex_); while (!signaled_.load()) { cond_.wait(lock); } } private: std::mutex mutex_; std::condition_variable cond_; std::atomic<bool> signaled_; }; // Gets the current high-performance tick count. uint64_t ticks(); // TODO(benvanik): processor info API. // Gets a stable thread-specific ID, but may not be. Use for informative // purposes only. uint32_t current_thread_id(); // Sets the current thread name. void set_name(const std::string& name); // Sets the target thread name. void set_name(std::thread::native_handle_type handle, const std::string& name); // Yields the current thread to the scheduler. Maybe. void MaybeYield(); // Sleeps the current thread for at least as long as the given duration. void Sleep(std::chrono::microseconds duration); template <typename Rep, typename Period> void Sleep(std::chrono::duration<Rep, Period> duration) { Sleep(std::chrono::duration_cast<std::chrono::microseconds>(duration)); } } // namespace threading } // namespace poly #endif // POLY_THREADING_H_
fd3e64211e7a99453bb3761defb21d81f946194b
dfcfe76be57f2cbe948de8e6e28a8bbc10bac211
/Exam - 28 May 2017/Calculator (E2-Task-4-Calculator)/InputInterpreter.h
85a3e3a6dae14e3b361e08c3fe1e114adf4afe4d
[]
no_license
AleksievAleksandar/Cpp-Fundamentals
6cbbfb76e9235698c1734874279c896ed3bc342e
c0050360eaa3cdf94e0256389553e80a934fe058
refs/heads/master
2022-06-18T13:50:57.082207
2022-06-01T09:24:26
2022-06-01T09:24:26
236,202,743
2
1
null
null
null
null
UTF-8
C++
false
false
859
h
#pragma once #include <memory> #include <string> #include <vector> #include "Operation.h" #include "CalculationEngine.h" #include "MultiplicationOperation.h" class InputInterpreter { CalculationEngine& engine; public: InputInterpreter(CalculationEngine& engine) : engine(engine) {} bool interpret(std::string input) { std::istringstream numberParseStream(input); int number; if (numberParseStream >> number) { engine.pushNumber(number); } else { engine.pushOperation(this->getOperation(input)); } return true; } virtual std::shared_ptr<Operation> getOperation(std::string operation) { if (operation == "*") { return std::make_shared<MultiplicationOperation>(); } return std::shared_ptr<Operation>(nullptr); } };
ec2569136b57edf07dbd73c5ce7e50298bb793c1
13e11e1019914694d202b4acc20ea1ff14345159
/Back-end/src/LogParser/HistoryLogParser.h
87f12a5d52591476172793009f655f632bbc20ee
[ "Apache-2.0", "BSL-1.0" ]
permissive
lee-novobi/Frameworks
e5ef6afdf866bb119e41f5a627e695a89c561703
016efe98a42e0b6a8ee09feea08aa52343bb90e4
refs/heads/master
2021-05-28T19:03:02.806782
2014-07-19T09:14:48
2014-07-19T09:14:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,239
h
#pragma once #include "LogParser.h" class CHistoryData; class CConfigFileParse; class CMongodbController; class CMongodbModel; struct ConnectInfo; struct HostInfo { long long lServerId; int iZbxServerId; long lHostId; long lItemId; string strSerialNumber; string strHost; string strHostName; string strZbIpAddress; int iMaintainance; long long lClock; string strKey_; string strValue; }; class CHistoryLogParser: public LogParser { public: CHistoryLogParser(void); CHistoryLogParser(string strCfgFile); ~CHistoryLogParser(void); MA_RESULT ProcessParse(); protected: MA_RESULT ParseLog(); IP_TYPE GetIPType(string strIP); ConnectInfo GetConnectInfo(string DBType); void Init(); void Destroy(); void ResetHostInfo(HostInfo& tagHostInfo); bool CheckStop(); virtual bool ControllerConnect() = 0; virtual void ParseSystemInfo(const char* Buffer, int& iPosition, int iLength, long long lServerId, map<long long,string> &mapHostMacDict, const HostInfo& tagHostInfo) { GetValueBlock(Buffer, iPosition, iLength); } virtual void ParseWebInfo(const HostInfo& tagHostInfo, string &strSuffix) { //GetValueBlock(pBuffer, &iPosition, (iLength); } CHistoryData *m_pDataObj; CConfigFileParse *m_pConfigFile; };
e61e7c87c7b6ec8fc2acdc42000b1ed8627001f9
80a6dcd8e0e55b1ec225e4e82d8b1bed100fdcd5
/Demux/20.05.04/472.cpp
afb20e39f6c1abc5b6ec7add2c752a86204509fd
[]
no_license
arnabs542/competitive-programming-1
58b54f54cb0b009f1dac600ca1bac5a4c1d7a523
3fa3a62277e5cd8a94d1baebb9ac26fe89211da3
refs/heads/master
2023-08-14T23:53:22.941834
2021-10-14T11:26:21
2021-10-14T11:26:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,748
cpp
// https://leetcode.com/problems/concatenated-words/ struct TrieNode{ bool is_word; TrieNode * next[26]; TrieNode(){ is_word = false; for(int i = 0; i<26; i++){ next[i] = NULL; } } }; class Solution { public: bool findHelper(TrieNode * root, TrieNode * curr, string & word, int index, int count){ if(curr == NULL) return false; if(index == word.length()) if(count>1 and curr->is_word){ return true; } else return false; if(curr->is_word) if(findHelper(root, root->next[word[index]-'a'], word, index+1, count+1)){ return true; } return findHelper(root, curr->next[word[index]-'a'], word, index+1, count); } vector<string> findAllConcatenatedWordsInADict(vector<string>& words) { TrieNode * root = new TrieNode(); TrieNode * curr = root; int n = words.size(), m; // Insertion for(int i = 0; i< n; i++){ curr = root; m = words[i].size(); for(int j = 0; j<m; j++){ if(curr->next[words[i][j]-'a'] == NULL) curr->next[words[i][j]-'a'] = new TrieNode(); curr = curr->next[words[i][j]-'a']; } if(m) curr->is_word = true; } // Searching vector<string> ans; for(int i = 0; i< n; i++){ if(findHelper(root, root, words[i], 0, 1)){ ans.push_back(words[i]); } } return ans; } };
d0748197dd5be7c7203b00e42add638b021cf6c9
333d8619759431ce03e8949722d264c017ff7af8
/Playground/Src/Engine/ImGui/UIManager.h
6693fceb1b29ba9c3839b8aaa104559ac0f4827d
[ "MIT" ]
permissive
TheOrestes/PlaygroundRTX
d5cbf18025d74454555b1564c92875b13a0b438e
82d3acf08bc5dcdcf3f0e39ca6a9e0bae524bc27
refs/heads/master
2023-08-01T17:54:34.523298
2021-10-03T10:27:06
2021-10-03T10:27:06
377,834,100
0
0
null
null
null
null
UTF-8
C++
false
false
1,484
h
#pragma once #include "vulkan/vulkan.h" #define GLFW_INCLUDE_VULKAN #include "GLFW/glfw3.h" class VulkanDevice; class VulkanSwapChain; class VulkanFrameBuffer; class Scene; class UIManager { public: ~UIManager(); static UIManager& getInstance() { static UIManager manager; return manager; } void Initialize(GLFWwindow* pWindow, VkInstance instance, VulkanDevice* pDevice, VulkanSwapChain* pSwapchain); void HandleWindowResize(GLFWwindow* pWindow, VkInstance instance, VulkanDevice* pDevice, VulkanSwapChain* pSwapchain); void Cleanup(VulkanDevice* pDevice); void CleanupOnWindowResize(VulkanDevice* pDevice); void BeginRender(); void EndRender(VulkanSwapChain* pSwapchain, uint32_t imageIndex); void RenderSceneUI(Scene* pScene); void RenderDebugStats(); private: UIManager(); UIManager(const UIManager&); void operator=(const UIManager&); void InitDescriptorPool(VulkanDevice* pDevice); void InitCommandBuffers(VulkanDevice* pDevice, VulkanSwapChain* pSwapchain); void InitFramebuffers(VulkanDevice* pDevice, VulkanSwapChain* pSwapchain); void InitRenderPass(VulkanDevice* pDevice, VulkanSwapChain* pSwapchain); private: VkDescriptorPool m_vkDescriptorPool; VkRenderPass m_vkRenderPass; std::vector<VkFramebuffer> m_vecFramebuffers; VkCommandPool m_vkCommandPool; public: std::vector<VkCommandBuffer> m_vecCommandBuffers; public: int m_iPassID; };
ceb83f2ac4337192fc534b1f5dc41e4276fec436
07ba86aee8532f6a5b2bfcdc30f8c2e8234751bc
/LeetCode/Problems/C++/852. Peak Index in a Mountain Array.cpp
2992352c07f772efffd0f701c46f6eee1582303d
[]
no_license
yukai-chiu/CodingPractice
1b7d4b0ffe9a8583091a8165976f71c7b3df41b5
3390a0ca4eceff72c69721bdc425a3099670faff
refs/heads/master
2022-12-14T05:35:38.336552
2020-08-30T22:56:20
2020-08-30T22:56:20
263,502,418
0
0
null
null
null
null
UTF-8
C++
false
false
713
cpp
//binary search class Solution { public: int peakIndexInMountainArray(vector<int>& A) { if(!A.size()) return -1; int N = A.size(); int l = 0, r = N-1; while(l<r){ int mid = l + (r-l)/2; if(A[mid]<A[mid+1]){ l = mid+1; } else{ r = mid; } } //cout << l << r; return r; } }; //linear search lass Solution { public: int peakIndexInMountainArray(vector<int>& A) { if(!A.size()) return -1; for(int i=0;i<A.size();i++){ if(A[i]>A[i+1]){ return i; } } return 0; } };
191e367a49055e197f5a23cfaf73f6ac4344df6b
fd728573c692402d88e311beb44559e8e0f0621c
/src/process/ProcessManager.h
60dff0fcbf0772bd996765f6b7fdee83d39c5846
[ "MIT", "BSD-3-Clause", "BSL-1.0", "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause" ]
permissive
diamante-block/Diamante-Core
de9b7fe977952b8232c262b571bb2448064d05d4
ddfc81379426143a22091fa4da17b3983d055713
refs/heads/master
2021-04-08T14:25:05.998926
2020-12-24T06:04:03
2020-12-24T06:04:03
248,783,093
0
0
null
null
null
null
UTF-8
C++
false
false
2,198
h
#pragma once // Copyright 2014 DiamNet Development Foundation and contributors. Licensed // under the Apache License, Version 2.0. See the COPYING file at the root // of this distribution or at http://www.apache.org/licenses/LICENSE-2.0 #include "util/NonCopyable.h" #include "util/Timer.h" #include <functional> #include <memory> #include <string> namespace DiamNet { class RealTimer; /** * This module exists because asio doesn't know much about subprocesses, * so we provide a little machinery for running subprocesses and waiting * on their results, intermixed with normal asio primitives. * * No facilities exist for reading or writing to the subprocess I/O ports. This * is strictly for "run a command, wait to see if it worked"; a glorified * asynchronous version of system(). */ // Wrap a platform-specific Impl strategy that monitors process-exits in a // helper simulating an event-notifier, via a general asio timer set to maximum // duration. Clients can register handlers on this and they are wrapped into // handlers on the timer, with impls that cancel the timer and pass back an // appropriate error code when the process exits. class ProcessExitEvent { class Impl; std::shared_ptr<RealTimer> mTimer; std::shared_ptr<Impl> mImpl; std::shared_ptr<asio::error_code> mEc; ProcessExitEvent(asio::io_context& io_context); friend class ProcessManagerImpl; public: ~ProcessExitEvent(); void async_wait(std::function<void(asio::error_code)> const& handler); }; class ProcessManager : public std::enable_shared_from_this<ProcessManager>, public NonMovableOrCopyable { public: static std::shared_ptr<ProcessManager> create(Application& app); virtual std::weak_ptr<ProcessExitEvent> runProcess(std::string const& cmdLine, std::string outputFile) = 0; virtual size_t getNumRunningProcesses() = 0; virtual bool isShutdown() const = 0; virtual void shutdown() = 0; // Depending on the state of the process, either kill the process nicely // or force shutdown it virtual bool tryProcessShutdown(std::shared_ptr<ProcessExitEvent> pe) = 0; virtual ~ProcessManager() { } }; }
e37b92e1695f011fdf7b9ebf592c26db2ebf7f1c
ae3b01cde0a051d17454ff6079338adb6871bc8c
/profit n loss.cpp
ff66104aea708419940a975a6952690deb96c89f
[]
no_license
Pratiksha-chokhar/Pg-Dac-CPP
0b1ce0855ec602e2455a25680fef4d485e0168f3
b9ede29a2aafd4546e09e98ae0857fd6d24431d5
refs/heads/master
2020-05-15T17:49:35.704553
2019-04-20T13:39:12
2019-04-20T13:39:12
182,411,334
0
0
null
null
null
null
UTF-8
C++
false
false
330
cpp
//program for cost price and selling price //pratiksha chokhar #include<stdio.h> int main() { int a, b, amount; printf("enter an costprice:"); scanf("%d", &a); printf("enter an sellingprice:"); scanf("%d", &b); if(a<b) { amount=b-a; printf("profit is:%d\n", amount); } else { amount=a-b; printf("loss is %d\n", amount); } }
15c089214c00cdf16cf0a8017994488d60e32129
2b6808de2b45c1af9dbfa4febc8b0d8124dd5020
/abc144/E.cpp
8c6ecacea3939edafbd3d5ad20904625195ad71a
[]
no_license
aki0214/kyo-pro
360f819ea7b113cc6c9c20b9ede011b56a92b36d
1c73aa67e9fa34b99add751bc4670a104ca477fb
refs/heads/master
2022-11-03T19:03:57.993730
2022-10-29T14:42:09
2022-10-29T14:42:09
253,325,299
0
0
null
null
null
null
UTF-8
C++
false
false
279
cpp
#include <bits/stdc++.h> using namespace std; #define rep(i,n) for (int i = 0;i<n;i++) int main(){ int n, k,tem; cin >> n >> k; vector<int> a(n); vector<int> f(n); rep(i ,n)cin >> a[i]; rep(i ,n)cin >> f[i]; sort(a.begin(), a.end()); sort(f.begin(), f.end()); }
a8866bb69a1b3377e5f1a50007ba43a1d50eb203
53e5698f899750b717a1a3a4d205af422990b4a2
/examples/template/potential.cpp
23e236f45fcb454c61c9977dd6b99b075436b535
[]
no_license
kvantetore/PyProp
e25f07e670369ad774aee6f47115e1ec0ad680d0
0fcdd3d5944de5c54c43a5205eb6e830f5edbf4c
refs/heads/master
2016-09-10T21:17:56.054886
2011-05-30T08:52:44
2011-05-30T08:52:44
462,062
7
7
null
null
null
null
UTF-8
C++
false
false
1,003
cpp
#include <core/wavefunction.h> #include <core/potential/dynamicpotentialevaluator.h> template<int Rank> class PotentialTemplate : public PotentialBase<Rank> { public: //Required by DynamicPotentialEvaluator cplx TimeStep; double CurTime; //Potential parameters double param; /* * Called once with the corresponding config section * from the configuration file. Do all one time set up routines * here. */ void ApplyConfigSection(const ConfigSection &config) { config.Get("param", param); } /* * Called for every grid point at every time step. * * Some general tips for max efficiency: * - If possible, move static computations to ApplyConfigSection. * - Minimize the number of branches ("if"-statements are bad) * - Minimize the number of function calls (sin, cos, exp, are bad) * - Long statements can confuse the compiler, consider making more * simpler statements */ inline double GetPotentialValue(const blitz::TinyVector<double, Rank> &pos) { } };
[ "tore.birkeland@354cffb3-6528-0410-8d42-45ce437ad3c5" ]
tore.birkeland@354cffb3-6528-0410-8d42-45ce437ad3c5
e8dde5727c789a568b8a6c7b64235a34d049dd97
112d4a263c3e9fc775fa82288a20a34b1efbe52d
/Material/CPP_Primer_Plus_Book/Ch.12.2/Ch.12_2 - Exercise 03 - Stock/stock20.h
c6ece0e18122fbab89c78d459d2f2c7a7eaf4da0
[ "MIT" ]
permissive
hpaucar/OOP-C-plus-plus-repo
369e788eb451f7d5804aadc1eb5bd2afb0758100
e1fedd376029996a53d70d452b7738d9c43173c0
refs/heads/main
2023-02-03T12:23:19.095175
2020-12-26T03:07:54
2020-12-26T03:07:54
324,466,086
4
0
null
null
null
null
UTF-8
C++
false
false
756
h
// stock20.h -- augmented version #ifndef STOCK20_H_ #define STOCK20_H_ #include <cstring> using namespace std; class Stock { private: char * m_company; // string company; int shares; double share_val; double total_val; void set_tot() { total_val = shares * share_val; } public: // Constructors Stock(); // default constructor Stock(const char * co, long n = 0, double pr = 0.0); ~Stock(); // do-something destructor // Methods void buy(long num, double price); void sell(long num, double price); void update(double price); //void show()const; const Stock & topval(const Stock & s) const; // friend functions friend ostream & operator<<(ostream & os, const Stock & s); }; #endif
cf0f5681eb78235b1355e97aa4f5c324113c2739
947800329125b7757b27d1cab086eff4cf78df5c
/Types.h
1dbd520f4249bbd6d9d2b2c97e3f3648e3ca3f0d
[]
no_license
cekaem/chess3.0
efd93e6cfd36b083c17d8e17540fc24383c216da
626742a886b90d8513d8d8a9da3f3f312cd44e40
refs/heads/main
2023-04-10T16:49:02.863736
2021-04-05T09:43:33
2021-04-05T09:43:33
346,135,309
0
0
null
null
null
null
UTF-8
C++
false
false
526
h
#ifndef TYPES_H #define TYPES_H #include <iostream> enum class GameResult { NONE, WHITE_WON, BLACK_WON, DRAW }; inline std::ostream& operator<<(std::ostream& ostr, GameResult result) { switch (result) { case GameResult::NONE: ostr << "NONE"; break; case GameResult::WHITE_WON: ostr << "WHITE_WON"; break; case GameResult::BLACK_WON: ostr << "BLACK WON"; break; case GameResult::DRAW: ostr << "DRAW"; break; } return ostr; } #endif // TYPES_H
65a4a1fd038fc38588aecfb65b8e1a0454611931
64b2f7cba464812e85e1bf619d29f2dcdae97d31
/firmware/devices/ExpiratoryMembrane.cpp
da267f011214528ee8f390bc427d8245e99c225a
[ "MIT" ]
permissive
Danfx/BR-Ventilador
9c2ec456829dfa9d9e30259f335451347acefe36
052524803e35a8e5db8b1c3f72c16dc91c19ca54
refs/heads/master
2021-05-20T11:46:43.968755
2020-04-18T02:51:35
2020-04-18T02:51:35
252,282,222
0
0
null
null
null
null
UTF-8
C++
false
false
1,590
cpp
/* * LICENSE MIT - https://tldrlegal.com/license/mit-license * * Copyright Daniel Fussia, https://github.com/Danfx * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "../hdr/devices/ExpiratoryMembrane.h" #include "../hdr/hardware.h" #include "Arduino.h" ExpiratoryMembrane::ExpiratoryMembrane() { } ExpiratoryMembrane::~ExpiratoryMembrane() { } void ExpiratoryMembrane::begin() { sm.attach(PIN_EXP_MEMBRANE); open(); } void ExpiratoryMembrane::open() { sm.write(EX_MEMB_OPEN); } void ExpiratoryMembrane::close() { sm.write(EX_MEMB_CLOSE); }
849fca21df095e488e3a262755f0d13379bd5b19
95a43c10c75b16595c30bdf6db4a1c2af2e4765d
/codecrawler/_code/hdu2193/16210026.cpp
f89aac630214f0ea7bd1f8f0d4946003c179a4a3
[]
no_license
kunhuicho/crawl-tools
945e8c40261dfa51fb13088163f0a7bece85fc9d
8eb8c4192d39919c64b84e0a817c65da0effad2d
refs/heads/master
2021-01-21T01:05:54.638395
2016-08-28T17:01:37
2016-08-28T17:01:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
548
cpp
#include<iostream> #include<string> #include<cstdio> #include<cstring> #include<queue> #include<map> #include<cmath> #include<stack> #include<set> #include<vector> #include<algorithm> #define LL long long #define inf 1<<30 #define s(a) scanf("%d",&a) #define CL(a,b) memset(a,b,sizeof(a)) using namespace std; const int N=45; int n,a[N],b; int main() { a[0]=1;a[1]=2; for(int i=2;i<=44;i++) a[i]=a[i-1]+a[i-2]+1; while(~scanf("%d",&n)&&n){ int i=0; while(a[i]<=n) i++; printf("%d\n",--i); } return 0; }
736b39432238faa77e380b6cbff833c6dd5b7e75
ed5926ae512e238af0f14655a3187d7e7fbf7ef7
/chromium2/net/http/http_cache_transaction.cc
82720c03dfd58ac27ddd20f7a5df329dfb8b0053
[ "BSD-3-Clause" ]
permissive
slimsag/mega
82595cd443d466f39836e24e28fc86d3f2f1aefd
37ef02d1818ae263956b7c8bc702b85cdbc83d20
refs/heads/master
2023-08-16T22:36:25.860917
2023-08-15T23:40:31
2023-08-15T23:40:31
41,717,977
5
1
null
null
null
null
UTF-8
C++
false
false
145,077
cc
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/http/http_cache_transaction.h" #include "build/build_config.h" // For IS_POSIX #if BUILDFLAG(IS_POSIX) #include <unistd.h> #endif #include <algorithm> #include <memory> #include <string> #include <type_traits> #include <utility> #include "base/auto_reset.h" #include "base/compiler_specific.h" #include "base/containers/fixed_flat_set.h" #include "base/feature_list.h" #include "base/format_macros.h" #include "base/functional/bind.h" #include "base/functional/callback_helpers.h" #include "base/location.h" #include "base/memory/raw_ptr_exclusion.h" #include "base/metrics/histogram_functions.h" #include "base/metrics/histogram_macros.h" #include "base/power_monitor/power_monitor.h" #include "base/strings/string_piece.h" #include "base/strings/string_util.h" // For EqualsCaseInsensitiveASCII. #include "base/task/single_thread_task_runner.h" #include "base/time/clock.h" #include "base/trace_event/common/trace_event_common.h" #include "base/values.h" #include "net/base/auth.h" #include "net/base/cache_metrics.h" #include "net/base/features.h" #include "net/base/load_flags.h" #include "net/base/load_timing_info.h" #include "net/base/trace_constants.h" #include "net/base/tracing.h" #include "net/base/transport_info.h" #include "net/base/upload_data_stream.h" #include "net/cert/cert_status_flags.h" #include "net/cert/x509_certificate.h" #include "net/disk_cache/disk_cache.h" #include "net/http/http_cache_writers.h" #include "net/http/http_log_util.h" #include "net/http/http_network_session.h" #include "net/http/http_request_info.h" #include "net/http/http_response_headers.h" #include "net/http/http_status_code.h" #include "net/http/http_util.h" #include "net/log/net_log_event_type.h" #include "net/ssl/ssl_cert_request_info.h" #include "net/ssl/ssl_config_service.h" using base::Time; using base::TimeTicks; namespace net { using CacheEntryStatus = HttpResponseInfo::CacheEntryStatus; namespace { constexpr base::TimeDelta kStaleRevalidateTimeout = base::Seconds(60); uint64_t GetNextTraceId(HttpCache* cache) { static uint32_t sNextTraceId = 0; DCHECK(cache); return (reinterpret_cast<uint64_t>(cache) << 32) | sNextTraceId++; } // From http://tools.ietf.org/html/draft-ietf-httpbis-p6-cache-21#section-6 // a "non-error response" is one with a 2xx (Successful) or 3xx // (Redirection) status code. bool NonErrorResponse(int status_code) { int status_code_range = status_code / 100; return status_code_range == 2 || status_code_range == 3; } bool IsOnBatteryPower() { if (base::PowerMonitor::IsInitialized()) return base::PowerMonitor::IsOnBatteryPower(); return false; } enum ExternallyConditionalizedType { EXTERNALLY_CONDITIONALIZED_CACHE_REQUIRES_VALIDATION, EXTERNALLY_CONDITIONALIZED_CACHE_USABLE, EXTERNALLY_CONDITIONALIZED_MISMATCHED_VALIDATORS, EXTERNALLY_CONDITIONALIZED_MAX }; // These values are persisted to logs. Entries should not be renumbered and // numeric values should never be reused. enum class RestrictedPrefetchReused { kNotReused = 0, kReused = 1, kMaxValue = kReused }; bool ShouldByPassCacheForFirstPartySets( const absl::optional<int64_t>& clear_at_run_id, const absl::optional<int64_t>& written_at_run_id) { return clear_at_run_id.has_value() && (!written_at_run_id.has_value() || written_at_run_id.value() < clear_at_run_id.value()); } struct HeaderNameAndValue { const char* name; const char* value; }; // If the request includes one of these request headers, then avoid caching // to avoid getting confused. constexpr HeaderNameAndValue kPassThroughHeaders[] = { {"if-unmodified-since", nullptr}, // causes unexpected 412s {"if-match", nullptr}, // causes unexpected 412s {"if-range", nullptr}, {nullptr, nullptr}}; struct ValidationHeaderInfo { const char* request_header_name; const char* related_response_header_name; }; constexpr ValidationHeaderInfo kValidationHeaders[] = { {"if-modified-since", "last-modified"}, {"if-none-match", "etag"}, }; // If the request includes one of these request headers, then avoid reusing // our cached copy if any. constexpr HeaderNameAndValue kForceFetchHeaders[] = { {"cache-control", "no-cache"}, {"pragma", "no-cache"}, {nullptr, nullptr}}; // If the request includes one of these request headers, then force our // cached copy (if any) to be revalidated before reusing it. constexpr HeaderNameAndValue kForceValidateHeaders[] = { {"cache-control", "max-age=0"}, {nullptr, nullptr}}; bool HeaderMatches(const HttpRequestHeaders& headers, const HeaderNameAndValue* search) { for (; search->name; ++search) { std::string header_value; if (!headers.GetHeader(search->name, &header_value)) continue; if (!search->value) { return true; } HttpUtil::ValuesIterator v(header_value.begin(), header_value.end(), ','); while (v.GetNext()) { if (base::EqualsCaseInsensitiveASCII(v.value_piece(), search->value)) { return true; } } } return false; } // These values are persisted to logs. Entries should not be renumbered and // numeric values should never be reused. enum class PrefetchReuseState : uint8_t { kNone = 0, // Bit 0 represents if it's reused first time kFirstReuse = 1 << 0, // Bit 1 represents if it's reused within the time window kReusedWithinTimeWindow = 1 << 1, // Bit 2-3 represents the freshness based on cache headers kFresh = 0 << 2, kAlwaysValidate = 1 << 2, kExpired = 2 << 2, kStale = 3 << 2, // histograms require a named max value kBitMaskForAllAttributes = kStale | kReusedWithinTimeWindow | kFirstReuse, kMaxValue = kBitMaskForAllAttributes }; using PrefetchReuseStateUnderlyingType = std::underlying_type_t<PrefetchReuseState>; PrefetchReuseStateUnderlyingType ToUnderlying(PrefetchReuseState state) { DCHECK_LE(PrefetchReuseState::kNone, state); DCHECK_LE(state, PrefetchReuseState::kMaxValue); return static_cast<PrefetchReuseStateUnderlyingType>(state); } PrefetchReuseState ToReuseState(PrefetchReuseStateUnderlyingType value) { PrefetchReuseState state = static_cast<PrefetchReuseState>(value); DCHECK_LE(PrefetchReuseState::kNone, state); DCHECK_LE(state, PrefetchReuseState::kMaxValue); return state; } PrefetchReuseState ComputePrefetchReuseState(ValidationType type, bool first_reuse, bool reused_within_time_window, bool validate_flag) { PrefetchReuseStateUnderlyingType reuse_state = ToUnderlying(PrefetchReuseState::kNone); if (first_reuse) { reuse_state |= ToUnderlying(PrefetchReuseState::kFirstReuse); } if (reused_within_time_window) { reuse_state |= ToUnderlying(PrefetchReuseState::kReusedWithinTimeWindow); } if (validate_flag) { reuse_state |= ToUnderlying(PrefetchReuseState::kAlwaysValidate); } else { switch (type) { case VALIDATION_SYNCHRONOUS: reuse_state |= ToUnderlying(PrefetchReuseState::kExpired); break; case VALIDATION_ASYNCHRONOUS: reuse_state |= ToUnderlying(PrefetchReuseState::kStale); break; case VALIDATION_NONE: reuse_state |= ToUnderlying(PrefetchReuseState::kFresh); break; } } return ToReuseState(reuse_state); } } // namespace #define CACHE_STATUS_HISTOGRAMS(type) \ UMA_HISTOGRAM_ENUMERATION("HttpCache.Pattern" type, cache_entry_status_, \ CacheEntryStatus::ENTRY_MAX) #define IS_NO_STORE_HISTOGRAMS(type, is_no_store) \ base::UmaHistogramBoolean("HttpCache.IsNoStore" type, is_no_store) //----------------------------------------------------------------------------- HttpCache::Transaction::Transaction(RequestPriority priority, HttpCache* cache) : trace_id_(GetNextTraceId(cache)), priority_(priority), cache_(cache->GetWeakPtr()) { static_assert(HttpCache::Transaction::kNumValidationHeaders == std::size(kValidationHeaders), "invalid number of validation headers"); io_callback_ = base::BindRepeating(&Transaction::OnIOComplete, weak_factory_.GetWeakPtr()); cache_io_callback_ = base::BindRepeating(&Transaction::OnCacheIOComplete, weak_factory_.GetWeakPtr()); } HttpCache::Transaction::~Transaction() { TRACE_EVENT_END("net", perfetto::Track(trace_id_)); RecordHistograms(); // We may have to issue another IO, but we should never invoke the callback_ // after this point. callback_.Reset(); if (cache_) { if (entry_) { DoneWithEntry(false /* entry_is_complete */); } else if (cache_pending_) { cache_->RemovePendingTransaction(this); } } } HttpCache::Transaction::Mode HttpCache::Transaction::mode() const { return mode_; } LoadState HttpCache::Transaction::GetWriterLoadState() const { const HttpTransaction* transaction = network_transaction(); if (transaction) return transaction->GetLoadState(); if (entry_ || !request_) return LOAD_STATE_IDLE; return LOAD_STATE_WAITING_FOR_CACHE; } const NetLogWithSource& HttpCache::Transaction::net_log() const { return net_log_; } int HttpCache::Transaction::Start(const HttpRequestInfo* request, CompletionOnceCallback callback, const NetLogWithSource& net_log) { DCHECK(request); DCHECK(request->IsConsistent()); DCHECK(!callback.is_null()); TRACE_EVENT_BEGIN("net", "HttpCacheTransaction", perfetto::Track(trace_id_), "url", request->url.spec()); // Ensure that we only have one asynchronous call at a time. DCHECK(callback_.is_null()); DCHECK(!reading_); DCHECK(!network_trans_.get()); DCHECK(!entry_); DCHECK_EQ(next_state_, STATE_NONE); if (!cache_.get()) return ERR_UNEXPECTED; initial_request_ = request; SetRequest(net_log); // We have to wait until the backend is initialized so we start the SM. next_state_ = STATE_GET_BACKEND; int rv = DoLoop(OK); // Setting this here allows us to check for the existence of a callback_ to // determine if we are still inside Start. if (rv == ERR_IO_PENDING) callback_ = std::move(callback); return rv; } int HttpCache::Transaction::RestartIgnoringLastError( CompletionOnceCallback callback) { DCHECK(!callback.is_null()); // Ensure that we only have one asynchronous call at a time. DCHECK(callback_.is_null()); if (!cache_.get()) return ERR_UNEXPECTED; int rv = RestartNetworkRequest(); if (rv == ERR_IO_PENDING) callback_ = std::move(callback); return rv; } int HttpCache::Transaction::RestartWithCertificate( scoped_refptr<X509Certificate> client_cert, scoped_refptr<SSLPrivateKey> client_private_key, CompletionOnceCallback callback) { DCHECK(!callback.is_null()); // Ensure that we only have one asynchronous call at a time. DCHECK(callback_.is_null()); if (!cache_.get()) return ERR_UNEXPECTED; int rv = RestartNetworkRequestWithCertificate(std::move(client_cert), std::move(client_private_key)); if (rv == ERR_IO_PENDING) callback_ = std::move(callback); return rv; } int HttpCache::Transaction::RestartWithAuth(const AuthCredentials& credentials, CompletionOnceCallback callback) { DCHECK(auth_response_.headers.get()); DCHECK(!callback.is_null()); // Ensure that we only have one asynchronous call at a time. DCHECK(callback_.is_null()); if (!cache_.get()) return ERR_UNEXPECTED; // Clear the intermediate response since we are going to start over. SetAuthResponse(HttpResponseInfo()); int rv = RestartNetworkRequestWithAuth(credentials); if (rv == ERR_IO_PENDING) callback_ = std::move(callback); return rv; } bool HttpCache::Transaction::IsReadyToRestartForAuth() { if (!network_trans_.get()) return false; return network_trans_->IsReadyToRestartForAuth(); } int HttpCache::Transaction::Read(IOBuffer* buf, int buf_len, CompletionOnceCallback callback) { TRACE_EVENT_INSTANT("net", "HttpCacheTransaction::Read", perfetto::Track(trace_id_), "buf_len", buf_len); DCHECK_EQ(next_state_, STATE_NONE); DCHECK(buf); // TODO(https://crbug.com/1335423): Change to DCHECK_GT() or remove after bug // is fixed. CHECK_GT(buf_len, 0); DCHECK(!callback.is_null()); DCHECK(callback_.is_null()); if (!cache_.get()) return ERR_UNEXPECTED; // If we have an intermediate auth response at this point, then it means the // user wishes to read the network response (the error page). If there is a // previous response in the cache then we should leave it intact. if (auth_response_.headers.get() && mode_ != NONE) { UpdateCacheEntryStatus(CacheEntryStatus::ENTRY_OTHER); DCHECK(mode_ & WRITE); bool stopped = StopCachingImpl(mode_ == READ_WRITE); DCHECK(stopped); } reading_ = true; read_buf_ = buf; read_buf_len_ = buf_len; int rv = TransitionToReadingState(); if (rv != OK || next_state_ == STATE_NONE) return rv; rv = DoLoop(OK); if (rv == ERR_IO_PENDING) { DCHECK(callback_.is_null()); callback_ = std::move(callback); } return rv; } int HttpCache::Transaction::TransitionToReadingState() { if (!entry_) { if (network_trans_) { // This can happen when the request should be handled exclusively by // the network layer (skipping the cache entirely using // LOAD_DISABLE_CACHE) or there was an error during the headers phase // due to which the transaction cannot write to the cache or the consumer // is reading the auth response from the network. // TODO(http://crbug.com/740947) to get rid of this state in future. next_state_ = STATE_NETWORK_READ; return OK; } // If there is no network, and no cache entry, then there is nothing to read // from. next_state_ = STATE_NONE; // An error state should be set for the next read, else this transaction // should have been terminated once it reached this state. To assert we // could dcheck that shared_writing_error_ is set to a valid error value but // in some specific conditions (http://crbug.com/806344) it's possible that // the consumer does an extra Read in which case the assert will fail. return shared_writing_error_; } // If entry_ is present, the transaction is either a member of entry_->writers // or readers. if (!InWriters()) { // Since transaction is not a writer and we are in Read(), it must be a // reader. DCHECK(entry_->TransactionInReaders(this)); DCHECK(mode_ == READ || (mode_ == READ_WRITE && partial_)); next_state_ = STATE_CACHE_READ_DATA; return OK; } DCHECK(mode_ & WRITE || mode_ == NONE); // If it's a writer and it is partial then it may need to read from the cache // or from the network based on whether network transaction is present or not. if (partial_) { if (entry_->writers->network_transaction()) next_state_ = STATE_NETWORK_READ_CACHE_WRITE; else next_state_ = STATE_CACHE_READ_DATA; return OK; } // Full request. // If it's a writer and a full request then it may read from the cache if its // offset is behind the current offset else from the network. int disk_entry_size = entry_->GetEntry()->GetDataSize(kResponseContentIndex); if (read_offset_ == disk_entry_size || entry_->writers->network_read_only()) { next_state_ = STATE_NETWORK_READ_CACHE_WRITE; } else { DCHECK_LT(read_offset_, disk_entry_size); next_state_ = STATE_CACHE_READ_DATA; } return OK; } void HttpCache::Transaction::StopCaching() { // We really don't know where we are now. Hopefully there is no operation in // progress, but nothing really prevents this method to be called after we // returned ERR_IO_PENDING. We cannot attempt to truncate the entry at this // point because we need the state machine for that (and even if we are really // free, that would be an asynchronous operation). In other words, keep the // entry how it is (it will be marked as truncated at destruction), and let // the next piece of code that executes know that we are now reading directly // from the net. if (cache_.get() && (mode_ & WRITE) && !is_sparse_ && !range_requested_ && network_transaction()) { StopCachingImpl(false); } } int64_t HttpCache::Transaction::GetTotalReceivedBytes() const { int64_t total_received_bytes = network_transaction_info_.total_received_bytes; const HttpTransaction* transaction = GetOwnedOrMovedNetworkTransaction(); if (transaction) total_received_bytes += transaction->GetTotalReceivedBytes(); return total_received_bytes; } int64_t HttpCache::Transaction::GetTotalSentBytes() const { int64_t total_sent_bytes = network_transaction_info_.total_sent_bytes; const HttpTransaction* transaction = GetOwnedOrMovedNetworkTransaction(); if (transaction) total_sent_bytes += transaction->GetTotalSentBytes(); return total_sent_bytes; } void HttpCache::Transaction::DoneReading() { if (cache_.get() && entry_) { DCHECK_NE(mode_, UPDATE); DoneWithEntry(true); } } const HttpResponseInfo* HttpCache::Transaction::GetResponseInfo() const { // Null headers means we encountered an error or haven't a response yet if (auth_response_.headers.get()) { DCHECK_EQ(cache_entry_status_, auth_response_.cache_entry_status) << "These must be in sync via SetResponse and SetAuthResponse."; return &auth_response_; } // TODO(https://crbug.com/1219402): This should check in `response_` return &response_; } LoadState HttpCache::Transaction::GetLoadState() const { // If there's no pending callback, the ball is not in the // HttpCache::Transaction's court, whatever else may be going on. if (!callback_) return LOAD_STATE_IDLE; LoadState state = GetWriterLoadState(); if (state != LOAD_STATE_WAITING_FOR_CACHE) return state; if (cache_.get()) return cache_->GetLoadStateForPendingTransaction(this); return LOAD_STATE_IDLE; } void HttpCache::Transaction::SetQuicServerInfo( QuicServerInfo* quic_server_info) {} bool HttpCache::Transaction::GetLoadTimingInfo( LoadTimingInfo* load_timing_info) const { const HttpTransaction* transaction = GetOwnedOrMovedNetworkTransaction(); if (transaction) return transaction->GetLoadTimingInfo(load_timing_info); if (network_transaction_info_.old_network_trans_load_timing) { *load_timing_info = *network_transaction_info_.old_network_trans_load_timing; return true; } if (first_cache_access_since_.is_null()) return false; // If the cache entry was opened, return that time. load_timing_info->send_start = first_cache_access_since_; // This time doesn't make much sense when reading from the cache, so just use // the same time as send_start. load_timing_info->send_end = first_cache_access_since_; // Provide the time immediately before parsing a cached entry. load_timing_info->receive_headers_start = read_headers_since_; return true; } bool HttpCache::Transaction::GetRemoteEndpoint(IPEndPoint* endpoint) const { const HttpTransaction* transaction = GetOwnedOrMovedNetworkTransaction(); if (transaction) return transaction->GetRemoteEndpoint(endpoint); if (!network_transaction_info_.old_remote_endpoint.address().empty()) { *endpoint = network_transaction_info_.old_remote_endpoint; return true; } return false; } void HttpCache::Transaction::PopulateNetErrorDetails( NetErrorDetails* details) const { const HttpTransaction* transaction = GetOwnedOrMovedNetworkTransaction(); if (transaction) return transaction->PopulateNetErrorDetails(details); return; } void HttpCache::Transaction::SetPriority(RequestPriority priority) { priority_ = priority; if (network_trans_) network_trans_->SetPriority(priority_); if (InWriters()) { DCHECK(!network_trans_ || partial_); entry_->writers->UpdatePriority(); } } void HttpCache::Transaction::SetWebSocketHandshakeStreamCreateHelper( WebSocketHandshakeStreamBase::CreateHelper* create_helper) { websocket_handshake_stream_base_create_helper_ = create_helper; // TODO(shivanisha). Since this function must be invoked before Start() as // per the API header, a network transaction should not exist at that point. HttpTransaction* transaction = network_transaction(); if (transaction) transaction->SetWebSocketHandshakeStreamCreateHelper(create_helper); } void HttpCache::Transaction::SetBeforeNetworkStartCallback( BeforeNetworkStartCallback callback) { DCHECK(!network_trans_); before_network_start_callback_ = std::move(callback); } void HttpCache::Transaction::SetConnectedCallback( const ConnectedCallback& callback) { DCHECK(!network_trans_); connected_callback_ = callback; } void HttpCache::Transaction::SetRequestHeadersCallback( RequestHeadersCallback callback) { DCHECK(!network_trans_); request_headers_callback_ = std::move(callback); } void HttpCache::Transaction::SetResponseHeadersCallback( ResponseHeadersCallback callback) { DCHECK(!network_trans_); response_headers_callback_ = std::move(callback); } void HttpCache::Transaction::SetEarlyResponseHeadersCallback( ResponseHeadersCallback callback) { DCHECK(!network_trans_); early_response_headers_callback_ = std::move(callback); } void HttpCache::Transaction::SetModifyRequestHeadersCallback( base::RepeatingCallback<void(net::HttpRequestHeaders*)> callback) { // This method should not be called for this class. NOTREACHED(); } void HttpCache::Transaction::SetIsSharedDictionaryReadAllowedCallback( base::RepeatingCallback<bool()> callback) { DCHECK(!network_trans_); is_shared_dictionary_read_allowed_callback_ = std::move(callback); } int HttpCache::Transaction::ResumeNetworkStart() { if (network_trans_) return network_trans_->ResumeNetworkStart(); return ERR_UNEXPECTED; } ConnectionAttempts HttpCache::Transaction::GetConnectionAttempts() const { ConnectionAttempts attempts; const HttpTransaction* transaction = GetOwnedOrMovedNetworkTransaction(); if (transaction) attempts = transaction->GetConnectionAttempts(); attempts.insert(attempts.begin(), network_transaction_info_.old_connection_attempts.begin(), network_transaction_info_.old_connection_attempts.end()); return attempts; } void HttpCache::Transaction::CloseConnectionOnDestruction() { if (network_trans_) { network_trans_->CloseConnectionOnDestruction(); } else if (InWriters()) { entry_->writers->CloseConnectionOnDestruction(); } } void HttpCache::Transaction::SetValidatingCannotProceed() { DCHECK(!reading_); // Ensure this transaction is waiting for a callback. DCHECK_NE(STATE_UNSET, next_state_); next_state_ = STATE_HEADERS_PHASE_CANNOT_PROCEED; entry_ = nullptr; } void HttpCache::Transaction::WriterAboutToBeRemovedFromEntry(int result) { TRACE_EVENT_INSTANT("net", "HttpCacheTransaction::WriterAboutToBeRemovedFromEntry", perfetto::Track(trace_id_)); // Since the transaction can no longer access the network transaction, save // all network related info now. if (moved_network_transaction_to_writers_ && entry_->writers->network_transaction()) { SaveNetworkTransactionInfo(*(entry_->writers->network_transaction())); } entry_ = nullptr; mode_ = NONE; // Transactions in the midst of a Read call through writers will get any error // code through the IO callback but for idle transactions/transactions reading // from the cache, the error for a future Read must be stored here. if (result < 0) shared_writing_error_ = result; } void HttpCache::Transaction::WriteModeTransactionAboutToBecomeReader() { TRACE_EVENT_INSTANT( "net", "HttpCacheTransaction::WriteModeTransactionAboutToBecomeReader", perfetto::Track(trace_id_)); mode_ = READ; if (moved_network_transaction_to_writers_ && entry_->writers->network_transaction()) { SaveNetworkTransactionInfo(*(entry_->writers->network_transaction())); } } void HttpCache::Transaction::AddDiskCacheWriteTime(base::TimeDelta elapsed) { total_disk_cache_write_time_ += elapsed; } //----------------------------------------------------------------------------- // A few common patterns: (Foo* means Foo -> FooComplete) // // 1. Not-cached entry: // Start(): // GetBackend* -> InitEntry -> OpenOrCreateEntry* -> AddToEntry* -> // SendRequest* -> SuccessfulSendRequest -> OverwriteCachedResponse -> // CacheWriteResponse* -> TruncateCachedData* -> PartialHeadersReceived -> // FinishHeaders* // // Read(): // NetworkReadCacheWrite*/CacheReadData* (if other writers are also writing to // the cache) // // 2. Cached entry, no validation: // Start(): // GetBackend* -> InitEntry -> OpenOrCreateEntry* -> AddToEntry* -> // CacheReadResponse* -> CacheDispatchValidation -> // BeginPartialCacheValidation() -> BeginCacheValidation() -> // ConnectedCallback* -> SetupEntryForRead() -> FinishHeaders* // // Read(): // CacheReadData* // // 3. Cached entry, validation (304): // Start(): // GetBackend* -> InitEntry -> OpenOrCreateEntry* -> AddToEntry* -> // CacheReadResponse* -> CacheDispatchValidation -> // BeginPartialCacheValidation() -> BeginCacheValidation() -> SendRequest* -> // SuccessfulSendRequest -> UpdateCachedResponse -> CacheWriteUpdatedResponse* // -> UpdateCachedResponseComplete -> OverwriteCachedResponse -> // PartialHeadersReceived -> FinishHeaders* // // Read(): // CacheReadData* // // 4. Cached entry, validation and replace (200): // Start(): // GetBackend* -> InitEntry -> OpenOrCreateEntry* -> AddToEntry* -> // CacheReadResponse* -> CacheDispatchValidation -> // BeginPartialCacheValidation() -> BeginCacheValidation() -> SendRequest* -> // SuccessfulSendRequest -> OverwriteCachedResponse -> CacheWriteResponse* -> // DoTruncateCachedData* -> PartialHeadersReceived -> FinishHeaders* // // Read(): // NetworkReadCacheWrite*/CacheReadData* (if other writers are also writing to // the cache) // // 5. Sparse entry, partially cached, byte range request: // Start(): // GetBackend* -> InitEntry -> OpenOrCreateEntry* -> AddToEntry* -> // CacheReadResponse* -> CacheDispatchValidation -> // BeginPartialCacheValidation() -> CacheQueryData* -> // ValidateEntryHeadersAndContinue() -> StartPartialCacheValidation -> // CompletePartialCacheValidation -> BeginCacheValidation() -> SendRequest* -> // SuccessfulSendRequest -> UpdateCachedResponse -> CacheWriteUpdatedResponse* // -> UpdateCachedResponseComplete -> OverwriteCachedResponse -> // PartialHeadersReceived -> FinishHeaders* // // Read() 1: // NetworkReadCacheWrite* // // Read() 2: // NetworkReadCacheWrite* -> StartPartialCacheValidation -> // CompletePartialCacheValidation -> ConnectedCallback* -> CacheReadData* // // Read() 3: // CacheReadData* -> StartPartialCacheValidation -> // CompletePartialCacheValidation -> BeginCacheValidation() -> SendRequest* -> // SuccessfulSendRequest -> UpdateCachedResponse* -> OverwriteCachedResponse // -> PartialHeadersReceived -> NetworkReadCacheWrite* // // 6. HEAD. Not-cached entry: // Pass through. Don't save a HEAD by itself. // Start(): // GetBackend* -> InitEntry -> OpenOrCreateEntry* -> SendRequest* // // 7. HEAD. Cached entry, no validation: // Start(): // The same flow as for a GET request (example #2) // // Read(): // CacheReadData (returns 0) // // 8. HEAD. Cached entry, validation (304): // The request updates the stored headers. // Start(): Same as for a GET request (example #3) // // Read(): // CacheReadData (returns 0) // // 9. HEAD. Cached entry, validation and replace (200): // Pass through. The request dooms the old entry, as a HEAD won't be stored by // itself. // Start(): // GetBackend* -> InitEntry -> OpenOrCreateEntry* -> AddToEntry* -> // CacheReadResponse* -> CacheDispatchValidation -> // BeginPartialCacheValidation() -> BeginCacheValidation() -> SendRequest* -> // SuccessfulSendRequest -> OverwriteCachedResponse -> FinishHeaders* // // 10. HEAD. Sparse entry, partially cached: // Serve the request from the cache, as long as it doesn't require // revalidation. Ignore missing ranges when deciding to revalidate. If the // entry requires revalidation, ignore the whole request and go to full pass // through (the result of the HEAD request will NOT update the entry). // // Start(): Basically the same as example 7, as we never create a partial_ // object for this request. // // 11. Prefetch, not-cached entry: // The same as example 1. The "unused_since_prefetch" bit is stored as true in // UpdateCachedResponse. // // 12. Prefetch, cached entry: // Like examples 2-4, only CacheWriteUpdatedPrefetchResponse* is inserted // between CacheReadResponse* and CacheDispatchValidation if the // unused_since_prefetch bit is unset. // // 13. Cached entry less than 5 minutes old, unused_since_prefetch is true: // Skip validation, similar to example 2. // GetBackend* -> InitEntry -> OpenOrCreateEntry* -> AddToEntry* -> // CacheReadResponse* -> CacheToggleUnusedSincePrefetch* -> // CacheDispatchValidation -> BeginPartialCacheValidation() -> // BeginCacheValidation() -> ConnectedCallback* -> SetupEntryForRead() -> // FinishHeaders* // // Read(): // CacheReadData* // // 14. Cached entry more than 5 minutes old, unused_since_prefetch is true: // Like examples 2-4, only CacheToggleUnusedSincePrefetch* is inserted between // CacheReadResponse* and CacheDispatchValidation. int HttpCache::Transaction::DoLoop(int result) { DCHECK_NE(STATE_UNSET, next_state_); DCHECK_NE(STATE_NONE, next_state_); DCHECK(!in_do_loop_); int rv = result; State state = next_state_; do { state = next_state_; next_state_ = STATE_UNSET; base::AutoReset<bool> scoped_in_do_loop(&in_do_loop_, true); switch (state) { case STATE_GET_BACKEND: DCHECK_EQ(OK, rv); rv = DoGetBackend(); break; case STATE_GET_BACKEND_COMPLETE: rv = DoGetBackendComplete(rv); break; case STATE_INIT_ENTRY: DCHECK_EQ(OK, rv); rv = DoInitEntry(); break; case STATE_OPEN_OR_CREATE_ENTRY: DCHECK_EQ(OK, rv); rv = DoOpenOrCreateEntry(); break; case STATE_OPEN_OR_CREATE_ENTRY_COMPLETE: rv = DoOpenOrCreateEntryComplete(rv); break; case STATE_DOOM_ENTRY: DCHECK_EQ(OK, rv); rv = DoDoomEntry(); break; case STATE_DOOM_ENTRY_COMPLETE: rv = DoDoomEntryComplete(rv); break; case STATE_CREATE_ENTRY: DCHECK_EQ(OK, rv); rv = DoCreateEntry(); break; case STATE_CREATE_ENTRY_COMPLETE: rv = DoCreateEntryComplete(rv); break; case STATE_ADD_TO_ENTRY: DCHECK_EQ(OK, rv); rv = DoAddToEntry(); break; case STATE_ADD_TO_ENTRY_COMPLETE: rv = DoAddToEntryComplete(rv); break; case STATE_DONE_HEADERS_ADD_TO_ENTRY_COMPLETE: rv = DoDoneHeadersAddToEntryComplete(rv); break; case STATE_CACHE_READ_RESPONSE: DCHECK_EQ(OK, rv); rv = DoCacheReadResponse(); break; case STATE_CACHE_READ_RESPONSE_COMPLETE: rv = DoCacheReadResponseComplete(rv); break; case STATE_WRITE_UPDATED_PREFETCH_RESPONSE: DCHECK_EQ(OK, rv); rv = DoCacheWriteUpdatedPrefetchResponse(rv); break; case STATE_WRITE_UPDATED_PREFETCH_RESPONSE_COMPLETE: rv = DoCacheWriteUpdatedPrefetchResponseComplete(rv); break; case STATE_CACHE_DISPATCH_VALIDATION: DCHECK_EQ(OK, rv); rv = DoCacheDispatchValidation(); break; case STATE_CACHE_QUERY_DATA: DCHECK_EQ(OK, rv); rv = DoCacheQueryData(); break; case STATE_CACHE_QUERY_DATA_COMPLETE: rv = DoCacheQueryDataComplete(rv); break; case STATE_START_PARTIAL_CACHE_VALIDATION: DCHECK_EQ(OK, rv); rv = DoStartPartialCacheValidation(); break; case STATE_COMPLETE_PARTIAL_CACHE_VALIDATION: rv = DoCompletePartialCacheValidation(rv); break; case STATE_CACHE_UPDATE_STALE_WHILE_REVALIDATE_TIMEOUT: DCHECK_EQ(OK, rv); rv = DoCacheUpdateStaleWhileRevalidateTimeout(); break; case STATE_CACHE_UPDATE_STALE_WHILE_REVALIDATE_TIMEOUT_COMPLETE: rv = DoCacheUpdateStaleWhileRevalidateTimeoutComplete(rv); break; case STATE_CONNECTED_CALLBACK: rv = DoConnectedCallback(); break; case STATE_CONNECTED_CALLBACK_COMPLETE: rv = DoConnectedCallbackComplete(rv); break; case STATE_SETUP_ENTRY_FOR_READ: DCHECK_EQ(OK, rv); rv = DoSetupEntryForRead(); break; case STATE_SEND_REQUEST: DCHECK_EQ(OK, rv); rv = DoSendRequest(); break; case STATE_SEND_REQUEST_COMPLETE: rv = DoSendRequestComplete(rv); break; case STATE_SUCCESSFUL_SEND_REQUEST: DCHECK_EQ(OK, rv); rv = DoSuccessfulSendRequest(); break; case STATE_UPDATE_CACHED_RESPONSE: DCHECK_EQ(OK, rv); rv = DoUpdateCachedResponse(); break; case STATE_CACHE_WRITE_UPDATED_RESPONSE: DCHECK_EQ(OK, rv); rv = DoCacheWriteUpdatedResponse(); break; case STATE_CACHE_WRITE_UPDATED_RESPONSE_COMPLETE: rv = DoCacheWriteUpdatedResponseComplete(rv); break; case STATE_UPDATE_CACHED_RESPONSE_COMPLETE: rv = DoUpdateCachedResponseComplete(rv); break; case STATE_OVERWRITE_CACHED_RESPONSE: DCHECK_EQ(OK, rv); rv = DoOverwriteCachedResponse(); break; case STATE_CACHE_WRITE_RESPONSE: DCHECK_EQ(OK, rv); rv = DoCacheWriteResponse(); break; case STATE_CACHE_WRITE_RESPONSE_COMPLETE: rv = DoCacheWriteResponseComplete(rv); break; case STATE_TRUNCATE_CACHED_DATA: DCHECK_EQ(OK, rv); rv = DoTruncateCachedData(); break; case STATE_TRUNCATE_CACHED_DATA_COMPLETE: rv = DoTruncateCachedDataComplete(rv); break; case STATE_PARTIAL_HEADERS_RECEIVED: DCHECK_EQ(OK, rv); rv = DoPartialHeadersReceived(); break; case STATE_HEADERS_PHASE_CANNOT_PROCEED: rv = DoHeadersPhaseCannotProceed(rv); break; case STATE_FINISH_HEADERS: rv = DoFinishHeaders(rv); break; case STATE_FINISH_HEADERS_COMPLETE: rv = DoFinishHeadersComplete(rv); break; case STATE_NETWORK_READ_CACHE_WRITE: DCHECK_EQ(OK, rv); rv = DoNetworkReadCacheWrite(); break; case STATE_NETWORK_READ_CACHE_WRITE_COMPLETE: rv = DoNetworkReadCacheWriteComplete(rv); break; case STATE_CACHE_READ_DATA: DCHECK_EQ(OK, rv); rv = DoCacheReadData(); break; case STATE_CACHE_READ_DATA_COMPLETE: rv = DoCacheReadDataComplete(rv); break; case STATE_NETWORK_READ: DCHECK_EQ(OK, rv); rv = DoNetworkRead(); break; case STATE_NETWORK_READ_COMPLETE: rv = DoNetworkReadComplete(rv); break; default: NOTREACHED() << "bad state " << state; rv = ERR_FAILED; break; } DCHECK(next_state_ != STATE_UNSET) << "Previous state was " << state; } while (rv != ERR_IO_PENDING && next_state_ != STATE_NONE); // Assert Start() state machine's allowed last state in successful cases when // caching is happening. DCHECK(reading_ || rv != OK || !entry_ || state == STATE_FINISH_HEADERS_COMPLETE); if (rv != ERR_IO_PENDING && !callback_.is_null()) { read_buf_ = nullptr; // Release the buffer before invoking the callback. std::move(callback_).Run(rv); } return rv; } int HttpCache::Transaction::DoGetBackend() { cache_pending_ = true; TransitionToState(STATE_GET_BACKEND_COMPLETE); net_log_.BeginEvent(NetLogEventType::HTTP_CACHE_GET_BACKEND); return cache_->GetBackendForTransaction(this); } int HttpCache::Transaction::DoGetBackendComplete(int result) { DCHECK(result == OK || result == ERR_FAILED); net_log_.EndEventWithNetErrorCode(NetLogEventType::HTTP_CACHE_GET_BACKEND, result); cache_pending_ = false; // Reset mode_ that might get set in this function. This is done because this // function can be invoked multiple times for a transaction. mode_ = NONE; const bool should_pass_through = ShouldPassThrough(); if (!should_pass_through) { cache_key_ = *cache_->GenerateCacheKeyForRequest(request_); // Requested cache access mode. if (effective_load_flags_ & LOAD_ONLY_FROM_CACHE) { if (effective_load_flags_ & LOAD_BYPASS_CACHE) { // The client has asked for nonsense. TransitionToState(STATE_FINISH_HEADERS); return ERR_CACHE_MISS; } mode_ = READ; } else if (effective_load_flags_ & LOAD_BYPASS_CACHE) { mode_ = WRITE; } else { mode_ = READ_WRITE; } // Downgrade to UPDATE if the request has been externally conditionalized. if (external_validation_.initialized) { if (mode_ & WRITE) { // Strip off the READ_DATA bit (and maybe add back a READ_META bit // in case READ was off). mode_ = UPDATE; } else { mode_ = NONE; } } } // Use PUT, DELETE, and PATCH only to invalidate existing stored entries. if ((method_ == "PUT" || method_ == "DELETE" || method_ == "PATCH") && mode_ != READ_WRITE && mode_ != WRITE) { mode_ = NONE; } // Note that if mode_ == UPDATE (which is tied to external_validation_), the // transaction behaves the same for GET and HEAD requests at this point: if it // was not modified, the entry is updated and a response is not returned from // the cache. If we receive 200, it doesn't matter if there was a validation // header or not. if (method_ == "HEAD" && mode_ == WRITE) mode_ = NONE; // If must use cache, then we must fail. This can happen for back/forward // navigations to a page generated via a form post. if (!(mode_ & READ) && effective_load_flags_ & LOAD_ONLY_FROM_CACHE) { TransitionToState(STATE_FINISH_HEADERS); return ERR_CACHE_MISS; } if (mode_ == NONE) { if (partial_) { partial_->RestoreHeaders(&custom_request_->extra_headers); partial_.reset(); } TransitionToState(STATE_SEND_REQUEST); } else { TransitionToState(STATE_INIT_ENTRY); } // This is only set if we have something to do with the response. range_requested_ = (partial_.get() != nullptr); TRACE_EVENT_INSTANT("net", "HttpCacheTransaction::DoGetBackendComplete", perfetto::Track(trace_id_), "mode", mode_, "should_pass_through", should_pass_through); return OK; } int HttpCache::Transaction::DoInitEntry() { TRACE_EVENT_INSTANT("net", "HttpCacheTransaction::DoInitEntry", perfetto::Track(trace_id_)); DCHECK(!new_entry_); if (!cache_.get()) { TransitionToState(STATE_FINISH_HEADERS); return ERR_UNEXPECTED; } if (mode_ == WRITE) { TransitionToState(STATE_DOOM_ENTRY); return OK; } TransitionToState(STATE_OPEN_OR_CREATE_ENTRY); return OK; } int HttpCache::Transaction::DoOpenOrCreateEntry() { TRACE_EVENT_INSTANT("net", "HttpCacheTransaction::DoOpenOrCreateEntry", perfetto::Track(trace_id_)); DCHECK(!new_entry_); TransitionToState(STATE_OPEN_OR_CREATE_ENTRY_COMPLETE); cache_pending_ = true; net_log_.BeginEvent(NetLogEventType::HTTP_CACHE_OPEN_OR_CREATE_ENTRY); first_cache_access_since_ = TimeTicks::Now(); const bool has_opened_or_created_entry = has_opened_or_created_entry_; has_opened_or_created_entry_ = true; record_entry_open_or_creation_time_ = false; // See if we already have something working with this cache key. new_entry_ = cache_->FindActiveEntry(cache_key_); if (new_entry_) return OK; // See if we could potentially doom the entry based on hints the backend keeps // in memory. // Currently only SimpleCache utilizes in memory hints. If an entry is found // unsuitable, and thus Doomed, SimpleCache can also optimize the // OpenOrCreateEntry() call to reduce the overhead of trying to open an entry // we know is doomed. uint8_t in_memory_info = cache_->GetCurrentBackend()->GetEntryInMemoryData(cache_key_); bool entry_not_suitable = false; if (MaybeRejectBasedOnEntryInMemoryData(in_memory_info)) { cache_->GetCurrentBackend()->DoomEntry(cache_key_, priority_, base::DoNothing()); entry_not_suitable = true; // Documents the case this applies in DCHECK_EQ(mode_, READ_WRITE); // Record this as CantConditionalize, but otherwise proceed as we would // below --- as we've already dropped the old entry. couldnt_conditionalize_request_ = true; validation_cause_ = VALIDATION_CAUSE_ZERO_FRESHNESS; UpdateCacheEntryStatus(CacheEntryStatus::ENTRY_CANT_CONDITIONALIZE); } if (!has_opened_or_created_entry) { record_entry_open_or_creation_time_ = true; } // mode_ can be anything but NONE or WRITE at this point (READ, UPDATE, or // READ_WRITE). // READ, UPDATE, certain READ_WRITEs, and some methods shouldn't create, so // try only opening. if (mode_ != READ_WRITE || ShouldOpenOnlyMethods()) { if (entry_not_suitable) { // The entry isn't suitable and we can't create a new one. return net::ERR_CACHE_ENTRY_NOT_SUITABLE; } return cache_->OpenEntry(cache_key_, &new_entry_, this); } return cache_->OpenOrCreateEntry(cache_key_, &new_entry_, this); } int HttpCache::Transaction::DoOpenOrCreateEntryComplete(int result) { TRACE_EVENT_INSTANT( "net", "HttpCacheTransaction::DoOpenOrCreateEntryComplete", perfetto::Track(trace_id_), "result", (result == OK ? (new_entry_->opened ? "opened" : "created") : "failed")); const bool record_uma = record_entry_open_or_creation_time_ && cache_ && cache_->GetCurrentBackend() && cache_->GetCurrentBackend()->GetCacheType() != MEMORY_CACHE; record_entry_open_or_creation_time_ = false; // It is important that we go to STATE_ADD_TO_ENTRY whenever the result is // OK, otherwise the cache will end up with an active entry without any // transaction attached. net_log_.EndEvent(NetLogEventType::HTTP_CACHE_OPEN_OR_CREATE_ENTRY, [&] { base::Value::Dict params; if (result == OK) { params.Set("result", new_entry_->opened ? "opened" : "created"); } else { params.Set("net_error", result); } return params; }); cache_pending_ = false; if (result == OK) { if (new_entry_->opened) { if (record_uma) { base::UmaHistogramTimes( "HttpCache.OpenDiskEntry", base::TimeTicks::Now() - first_cache_access_since_); } } else { if (record_uma) { base::UmaHistogramTimes( "HttpCache.CreateDiskEntry", base::TimeTicks::Now() - first_cache_access_since_); } // Entry was created so mode changes to WRITE. mode_ = WRITE; } TransitionToState(STATE_ADD_TO_ENTRY); return OK; } if (result == ERR_CACHE_RACE) { TransitionToState(STATE_HEADERS_PHASE_CANNOT_PROCEED); return OK; } // No need to explicitly handle ERR_CACHE_ENTRY_NOT_SUITABLE as the // ShouldOpenOnlyMethods() check will handle it. // We were unable to open or create an entry. DLOG(WARNING) << "Unable to open or create cache entry"; if (ShouldOpenOnlyMethods()) { // These methods, on failure, should bypass the cache. mode_ = NONE; TransitionToState(STATE_SEND_REQUEST); return OK; } // Since the operation failed, what we do next depends on the mode_ which can // be the following: READ, READ_WRITE, or UPDATE. Note: mode_ cannot be WRITE // or NONE at this point as DoInitEntry() handled those cases. switch (mode_) { case READ: // The entry does not exist, and we are not permitted to create a new // entry, so we must fail. TransitionToState(STATE_FINISH_HEADERS); return ERR_CACHE_MISS; case READ_WRITE: // Unable to open or create; set the mode to NONE in order to bypass the // cache entry and read from the network directly. mode_ = NONE; if (partial_) partial_->RestoreHeaders(&custom_request_->extra_headers); TransitionToState(STATE_SEND_REQUEST); break; case UPDATE: // There is no cache entry to update; proceed without caching. DCHECK(!partial_); mode_ = NONE; TransitionToState(STATE_SEND_REQUEST); break; default: NOTREACHED(); } return OK; } int HttpCache::Transaction::DoDoomEntry() { TRACE_EVENT_INSTANT("net", "HttpCacheTransaction::DoDoomEntry", perfetto::Track(trace_id_)); TransitionToState(STATE_DOOM_ENTRY_COMPLETE); cache_pending_ = true; if (first_cache_access_since_.is_null()) first_cache_access_since_ = TimeTicks::Now(); net_log_.BeginEvent(NetLogEventType::HTTP_CACHE_DOOM_ENTRY); return cache_->DoomEntry(cache_key_, this); } int HttpCache::Transaction::DoDoomEntryComplete(int result) { TRACE_EVENT_INSTANT("net", "HttpCacheTransaction::DoDoomEntryComplete", perfetto::Track(trace_id_), "result", result); net_log_.EndEventWithNetErrorCode(NetLogEventType::HTTP_CACHE_DOOM_ENTRY, result); cache_pending_ = false; TransitionToState(result == ERR_CACHE_RACE ? STATE_HEADERS_PHASE_CANNOT_PROCEED : STATE_CREATE_ENTRY); return OK; } int HttpCache::Transaction::DoCreateEntry() { TRACE_EVENT_INSTANT("net", "HttpCacheTransaction::DoCreateEntry", perfetto::Track(trace_id_)); DCHECK(!new_entry_); TransitionToState(STATE_CREATE_ENTRY_COMPLETE); cache_pending_ = true; net_log_.BeginEvent(NetLogEventType::HTTP_CACHE_CREATE_ENTRY); return cache_->CreateEntry(cache_key_, &new_entry_, this); } int HttpCache::Transaction::DoCreateEntryComplete(int result) { TRACE_EVENT_INSTANT("net", "HttpCacheTransaction::DoCreateEntryComplete", perfetto::Track(trace_id_), "result", result); // It is important that we go to STATE_ADD_TO_ENTRY whenever the result is // OK, otherwise the cache will end up with an active entry without any // transaction attached. net_log_.EndEventWithNetErrorCode(NetLogEventType::HTTP_CACHE_CREATE_ENTRY, result); cache_pending_ = false; switch (result) { case OK: TransitionToState(STATE_ADD_TO_ENTRY); break; case ERR_CACHE_RACE: TransitionToState(STATE_HEADERS_PHASE_CANNOT_PROCEED); break; default: DLOG(WARNING) << "Unable to create cache entry"; // Set the mode to NONE in order to bypass the cache entry and read from // the network directly. mode_ = NONE; if (!done_headers_create_new_entry_) { if (partial_) partial_->RestoreHeaders(&custom_request_->extra_headers); TransitionToState(STATE_SEND_REQUEST); return OK; } // The headers have already been received as a result of validation, // triggering the doom of the old entry. So no network request needs to // be sent. Note that since mode_ is NONE, the response won't be written // to cache. Transition to STATE_CACHE_WRITE_RESPONSE as that's the state // the transaction left off on when it tried to create the new entry. done_headers_create_new_entry_ = false; TransitionToState(STATE_CACHE_WRITE_RESPONSE); } return OK; } int HttpCache::Transaction::DoAddToEntry() { TRACE_EVENT_INSTANT("net", "HttpCacheTransaction::DoAddToEntry", perfetto::Track(trace_id_)); DCHECK(new_entry_); cache_pending_ = true; net_log_.BeginEvent(NetLogEventType::HTTP_CACHE_ADD_TO_ENTRY); DCHECK(entry_lock_waiting_since_.is_null()); // By this point whether the entry was created or opened is no longer relevant // for this transaction. However there may be queued transactions that want to // use this entry and from their perspective the entry was opened, so change // the flag to reflect that. new_entry_->opened = true; int rv = cache_->AddTransactionToEntry(new_entry_, this); CHECK_EQ(rv, ERR_IO_PENDING); // If headers phase is already done then we are here because of validation not // matching and creating a new entry. This transaction should be the // first transaction of that new entry and thus it will not have cache lock // delays, thus returning early from here. if (done_headers_create_new_entry_) { DCHECK_EQ(mode_, WRITE); TransitionToState(STATE_DONE_HEADERS_ADD_TO_ENTRY_COMPLETE); return rv; } TransitionToState(STATE_ADD_TO_ENTRY_COMPLETE); // For a very-select case of creating a new non-range request entry, run the // AddTransactionToEntry in parallel with sending the network request to // hide the latency. This will run until the next ERR_IO_PENDING (or // failure). if (!partial_ && mode_ == WRITE && base::FeatureList::IsEnabled(features::kAsyncCacheLock)) { CHECK(!waiting_for_cache_io_); waiting_for_cache_io_ = true; rv = OK; } entry_lock_waiting_since_ = TimeTicks::Now(); AddCacheLockTimeoutHandler(new_entry_); return rv; } void HttpCache::Transaction::AddCacheLockTimeoutHandler(ActiveEntry* entry) { CHECK(next_state_ == STATE_ADD_TO_ENTRY_COMPLETE || next_state_ == STATE_FINISH_HEADERS_COMPLETE); if ((bypass_lock_for_test_ && next_state_ == STATE_ADD_TO_ENTRY_COMPLETE) || (bypass_lock_after_headers_for_test_ && next_state_ == STATE_FINISH_HEADERS_COMPLETE)) { base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( FROM_HERE, base::BindOnce(&HttpCache::Transaction::OnCacheLockTimeout, weak_factory_.GetWeakPtr(), entry_lock_waiting_since_)); } else { int timeout_milliseconds = 20 * 1000; if (partial_ && entry->writers && !entry->writers->IsEmpty() && entry->writers->IsExclusive()) { // Even though entry_->writers takes care of allowing multiple writers to // simultaneously govern reading from the network and writing to the cache // for full requests, partial requests are still blocked by the // reader/writer lock. // Bypassing the cache after 25 ms of waiting for the cache lock // eliminates a long running issue, http://crbug.com/31014, where // two of the same media resources could not be played back simultaneously // due to one locking the cache entry until the entire video was // downloaded. // Bypassing the cache is not ideal, as we are now ignoring the cache // entirely for all range requests to a resource beyond the first. This // is however a much more succinct solution than the alternatives, which // would require somewhat significant changes to the http caching logic. // // Allow some timeout slack for the entry addition to complete in case // the writer lock is imminently released; we want to avoid skipping // the cache if at all possible. See http://crbug.com/408765 timeout_milliseconds = 25; } base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask( FROM_HERE, base::BindOnce(&HttpCache::Transaction::OnCacheLockTimeout, weak_factory_.GetWeakPtr(), entry_lock_waiting_since_), base::Milliseconds(timeout_milliseconds)); } } int HttpCache::Transaction::DoAddToEntryComplete(int result) { TRACE_EVENT_INSTANT("net", "HttpCacheTransaction::DoAddToEntryComplete", perfetto::Track(trace_id_), "result", result); net_log_.EndEventWithNetErrorCode(NetLogEventType::HTTP_CACHE_ADD_TO_ENTRY, result); if (cache_ && cache_->GetCurrentBackend() && cache_->GetCurrentBackend()->GetCacheType() != MEMORY_CACHE) { const base::TimeDelta entry_lock_wait = TimeTicks::Now() - entry_lock_waiting_since_; base::UmaHistogramTimes("HttpCache.AddTransactionToEntry", entry_lock_wait); } DCHECK(new_entry_); if (!waiting_for_cache_io_) { entry_lock_waiting_since_ = TimeTicks(); cache_pending_ = false; if (result == OK) { entry_ = new_entry_; } // If there is a failure, the cache should have taken care of new_entry_. new_entry_ = nullptr; } if (result == ERR_CACHE_RACE) { TransitionToState(STATE_HEADERS_PHASE_CANNOT_PROCEED); return OK; } if (result == ERR_CACHE_LOCK_TIMEOUT) { if (mode_ == READ) { TransitionToState(STATE_FINISH_HEADERS); return ERR_CACHE_MISS; } // The cache is busy, bypass it for this transaction. mode_ = NONE; TransitionToState(STATE_SEND_REQUEST); if (partial_) { partial_->RestoreHeaders(&custom_request_->extra_headers); partial_.reset(); } return OK; } // TODO(crbug.com/713354) Access timestamp for histograms only if entry is // already written, to avoid data race since cache thread can also access // this. if (entry_ && !cache_->IsWritingInProgress(entry())) { open_entry_last_used_ = entry_->GetEntry()->GetLastUsed(); } // TODO(jkarlin): We should either handle the case or DCHECK. if (result != OK) { NOTREACHED(); TransitionToState(STATE_FINISH_HEADERS); return result; } if (mode_ == WRITE) { if (partial_) partial_->RestoreHeaders(&custom_request_->extra_headers); TransitionToState(STATE_SEND_REQUEST); } else { // We have to read the headers from the cached entry. DCHECK(mode_ & READ_META); TransitionToState(STATE_CACHE_READ_RESPONSE); } return OK; } int HttpCache::Transaction::DoDoneHeadersAddToEntryComplete(int result) { TRACE_EVENT_INSTANT("net", "HttpCacheTransaction::DoDoneHeadersAddToEntryComplete", perfetto::Track(trace_id_), "result", result); // This transaction's response headers did not match its ActiveEntry so it // created a new ActiveEntry (new_entry_) to write to (and doomed the old // one). Now that the new entry has been created, start writing the response. DCHECK_EQ(result, OK); DCHECK_EQ(mode_, WRITE); DCHECK(new_entry_); DCHECK(response_.headers); cache_pending_ = false; done_headers_create_new_entry_ = false; // It is unclear exactly how this state is reached with an ERR_CACHE_RACE, but // this check appears to fix a rare crash. See crbug.com/959194. if (result == ERR_CACHE_RACE) { TransitionToState(STATE_HEADERS_PHASE_CANNOT_PROCEED); return OK; } entry_ = new_entry_; DCHECK_NE(response_.headers->response_code(), net::HTTP_NOT_MODIFIED); DCHECK(cache_->CanTransactionWriteResponseHeaders( entry_, this, partial_ != nullptr, false)); TransitionToState(STATE_CACHE_WRITE_RESPONSE); return OK; } int HttpCache::Transaction::DoCacheReadResponse() { TRACE_EVENT_INSTANT("net", "HttpCacheTransaction::DoCacheReadResponse", perfetto::Track(trace_id_)); DCHECK(entry_); TransitionToState(STATE_CACHE_READ_RESPONSE_COMPLETE); io_buf_len_ = entry_->GetEntry()->GetDataSize(kResponseInfoIndex); read_buf_ = base::MakeRefCounted<IOBuffer>(io_buf_len_); net_log_.BeginEvent(NetLogEventType::HTTP_CACHE_READ_INFO); BeginDiskCacheAccessTimeCount(); return entry_->GetEntry()->ReadData(kResponseInfoIndex, 0, read_buf_.get(), io_buf_len_, io_callback_); } int HttpCache::Transaction::DoCacheReadResponseComplete(int result) { TRACE_EVENT_INSTANT( "net", "HttpCacheTransaction::DoCacheReadResponseComplete", perfetto::Track(trace_id_), "result", result, "io_buf_len", io_buf_len_); net_log_.EndEventWithNetErrorCode(NetLogEventType::HTTP_CACHE_READ_INFO, result); EndDiskCacheAccessTimeCount(DiskCacheAccessType::kRead); // Record the time immediately before the cached response is parsed. read_headers_since_ = TimeTicks::Now(); if (result != io_buf_len_ || !HttpCache::ParseResponseInfo(read_buf_->data(), io_buf_len_, &response_, &truncated_)) { return OnCacheReadError(result, true); } // If the read response matches the clearing filter of FPS, doom the entry // and restart transaction. if (ShouldByPassCacheForFirstPartySets(initial_request_->fps_cache_filter, response_.browser_run_id)) { result = ERR_CACHE_ENTRY_NOT_SUITABLE; return OnCacheReadError(result, true); } // TODO(crbug.com/713354) Only get data size if there is no other transaction // currently writing the response body due to the data race mentioned in the // associated bug. if (!cache_->IsWritingInProgress(entry())) { int current_size = entry_->GetEntry()->GetDataSize(kResponseContentIndex); int64_t full_response_length = response_.headers->GetContentLength(); // Some resources may have slipped in as truncated when they're not. if (full_response_length == current_size) truncated_ = false; // The state machine's handling of StopCaching unfortunately doesn't deal // well with resources that are larger than 2GB when there is a truncated or // sparse cache entry. While the state machine is reworked to resolve this, // the following logic is put in place to defer such requests to the // network. The cache should not be storing multi gigabyte resources. See // http://crbug.com/89567. if ((truncated_ || response_.headers->response_code() == net::HTTP_PARTIAL_CONTENT) && !range_requested_ && full_response_length > std::numeric_limits<int32_t>::max()) { DCHECK(!partial_); // Doom the entry so that no other transaction gets added to this entry // and avoid a race of not being able to check this condition because // writing is in progress. DoneWithEntry(false); TransitionToState(STATE_SEND_REQUEST); return OK; } } if (response_.restricted_prefetch && !(request_->load_flags & LOAD_CAN_USE_RESTRICTED_PREFETCH)) { TransitionToState(STATE_SEND_REQUEST); return OK; } // When a restricted prefetch is reused, we lift its reuse restriction. bool restricted_prefetch_reuse = response_.restricted_prefetch && request_->load_flags & LOAD_CAN_USE_RESTRICTED_PREFETCH; DCHECK(!restricted_prefetch_reuse || response_.unused_since_prefetch); if (response_.unused_since_prefetch != !!(request_->load_flags & LOAD_PREFETCH)) { // Either this is the first use of an entry since it was prefetched XOR // this is a prefetch. The value of response.unused_since_prefetch is // valid for this transaction but the bit needs to be flipped in storage. DCHECK(!updated_prefetch_response_); updated_prefetch_response_ = std::make_unique<HttpResponseInfo>(response_); updated_prefetch_response_->unused_since_prefetch = !response_.unused_since_prefetch; if (response_.restricted_prefetch && request_->load_flags & LOAD_CAN_USE_RESTRICTED_PREFETCH) { updated_prefetch_response_->restricted_prefetch = false; } base::UmaHistogramEnumeration("HttpCache.RestrictedPrefetchReuse", restricted_prefetch_reuse ? RestrictedPrefetchReused::kReused : RestrictedPrefetchReused::kNotReused); TransitionToState(STATE_WRITE_UPDATED_PREFETCH_RESPONSE); return OK; } TransitionToState(STATE_CACHE_DISPATCH_VALIDATION); return OK; } int HttpCache::Transaction::DoCacheWriteUpdatedPrefetchResponse(int result) { TRACE_EVENT_INSTANT( "net", "HttpCacheTransaction::DoCacheWriteUpdatedPrefetchResponse", perfetto::Track(trace_id_), "result", result); DCHECK(updated_prefetch_response_); // TODO(jkarlin): If DoUpdateCachedResponse is also called for this // transaction then metadata will be written to cache twice. If prefetching // becomes more common, consider combining the writes. TransitionToState(STATE_WRITE_UPDATED_PREFETCH_RESPONSE_COMPLETE); return WriteResponseInfoToEntry(*updated_prefetch_response_.get(), truncated_); } int HttpCache::Transaction::DoCacheWriteUpdatedPrefetchResponseComplete( int result) { TRACE_EVENT_INSTANT( "net", "HttpCacheTransaction::DoCacheWriteUpdatedPrefetchResponseComplete", perfetto::Track(trace_id_), "result", result); updated_prefetch_response_.reset(); TransitionToState(STATE_CACHE_DISPATCH_VALIDATION); return OnWriteResponseInfoToEntryComplete(result); } int HttpCache::Transaction::DoCacheDispatchValidation() { TRACE_EVENT_INSTANT("net", "HttpCacheTransaction::DoCacheDispatchValidation", perfetto::Track(trace_id_)); if (!entry_) { // Entry got destroyed when twiddling unused-since-prefetch bit. TransitionToState(STATE_HEADERS_PHASE_CANNOT_PROCEED); return OK; } // We now have access to the cache entry. // // o if we are a reader for the transaction, then we can start reading the // cache entry. // // o if we can read or write, then we should check if the cache entry needs // to be validated and then issue a network request if needed or just read // from the cache if the cache entry is already valid. // // o if we are set to UPDATE, then we are handling an externally // conditionalized request (if-modified-since / if-none-match). We check // if the request headers define a validation request. // int result = ERR_FAILED; switch (mode_) { case READ: UpdateCacheEntryStatus(CacheEntryStatus::ENTRY_USED); result = BeginCacheRead(); break; case READ_WRITE: result = BeginPartialCacheValidation(); break; case UPDATE: result = BeginExternallyConditionalizedRequest(); break; case WRITE: default: NOTREACHED(); } return result; } int HttpCache::Transaction::DoCacheQueryData() { TransitionToState(STATE_CACHE_QUERY_DATA_COMPLETE); return entry_->GetEntry()->ReadyForSparseIO(io_callback_); } int HttpCache::Transaction::DoCacheQueryDataComplete(int result) { DCHECK_EQ(OK, result); if (!cache_.get()) { TransitionToState(STATE_FINISH_HEADERS); return ERR_UNEXPECTED; } return ValidateEntryHeadersAndContinue(); } // We may end up here multiple times for a given request. int HttpCache::Transaction::DoStartPartialCacheValidation() { if (mode_ == NONE) { TransitionToState(STATE_FINISH_HEADERS); return OK; } TransitionToState(STATE_COMPLETE_PARTIAL_CACHE_VALIDATION); return partial_->ShouldValidateCache(entry_->GetEntry(), io_callback_); } int HttpCache::Transaction::DoCompletePartialCacheValidation(int result) { if (!result && reading_) { // This is the end of the request. DoneWithEntry(true); TransitionToState(STATE_FINISH_HEADERS); return result; } if (result < 0) { TransitionToState(STATE_FINISH_HEADERS); return result; } partial_->PrepareCacheValidation(entry_->GetEntry(), &custom_request_->extra_headers); if (reading_ && partial_->IsCurrentRangeCached()) { // We're about to read a range of bytes from the cache. Signal it to the // consumer through the "connected" callback. TransitionToState(STATE_CONNECTED_CALLBACK); return OK; } return BeginCacheValidation(); } int HttpCache::Transaction::DoCacheUpdateStaleWhileRevalidateTimeout() { TRACE_EVENT_INSTANT( "net", "HttpCacheTransaction::DoCacheUpdateStaleWhileRevalidateTimeout", perfetto::Track(trace_id_)); response_.stale_revalidate_timeout = cache_->clock_->Now() + kStaleRevalidateTimeout; TransitionToState(STATE_CACHE_UPDATE_STALE_WHILE_REVALIDATE_TIMEOUT_COMPLETE); // We shouldn't be using stale truncated entries; if we did, the false below // would be wrong. DCHECK(!truncated_); return WriteResponseInfoToEntry(response_, false); } int HttpCache::Transaction::DoCacheUpdateStaleWhileRevalidateTimeoutComplete( int result) { TRACE_EVENT_INSTANT( "net", "HttpCacheTransaction::DoCacheUpdateStaleWhileRevalidateTimeoutComplete", perfetto::Track(trace_id_), "result", result); DCHECK(!reading_); TransitionToState(STATE_CONNECTED_CALLBACK); return OnWriteResponseInfoToEntryComplete(result); } int HttpCache::Transaction::DoSendRequest() { TRACE_EVENT_INSTANT("net", "HttpCacheTransaction::DoSendRequest", perfetto::Track(trace_id_)); DCHECK(mode_ & WRITE || mode_ == NONE); DCHECK(!network_trans_.get()); send_request_since_ = TimeTicks::Now(); // Create a network transaction. int rv = cache_->network_layer_->CreateTransaction(priority_, &network_trans_); if (rv != OK) { TransitionToState(STATE_FINISH_HEADERS); return rv; } network_trans_->SetBeforeNetworkStartCallback( std::move(before_network_start_callback_)); network_trans_->SetConnectedCallback(connected_callback_); network_trans_->SetRequestHeadersCallback(request_headers_callback_); network_trans_->SetEarlyResponseHeadersCallback( early_response_headers_callback_); network_trans_->SetResponseHeadersCallback(response_headers_callback_); if (is_shared_dictionary_read_allowed_callback_) { network_trans_->SetIsSharedDictionaryReadAllowedCallback( is_shared_dictionary_read_allowed_callback_); } // Old load timing information, if any, is now obsolete. network_transaction_info_.old_network_trans_load_timing.reset(); network_transaction_info_.old_remote_endpoint = IPEndPoint(); if (websocket_handshake_stream_base_create_helper_) network_trans_->SetWebSocketHandshakeStreamCreateHelper( websocket_handshake_stream_base_create_helper_); TransitionToState(STATE_SEND_REQUEST_COMPLETE); rv = network_trans_->Start(request_, io_callback_, net_log_); if (rv != ERR_IO_PENDING && waiting_for_cache_io_) { // queue the state transition until the HttpCache transaction completes DCHECK(!pending_io_result_); pending_io_result_ = rv; rv = ERR_IO_PENDING; } return rv; } int HttpCache::Transaction::DoSendRequestComplete(int result) { TRACE_EVENT_INSTANT("net", "HttpCacheTransaction::DoSendRequestComplete", perfetto::Track(trace_id_), "result", result, "elapsed", base::TimeTicks::Now() - send_request_since_); if (!cache_.get()) { TransitionToState(STATE_FINISH_HEADERS); return ERR_UNEXPECTED; } // If we tried to conditionalize the request and failed, we know // we won't be reading from the cache after this point. if (couldnt_conditionalize_request_) mode_ = WRITE; if (result == OK) { TransitionToState(STATE_SUCCESSFUL_SEND_REQUEST); return OK; } const HttpResponseInfo* response = network_trans_->GetResponseInfo(); response_.network_accessed = response->network_accessed; response_.was_fetched_via_proxy = response->was_fetched_via_proxy; response_.proxy_server = response->proxy_server; response_.restricted_prefetch = response->restricted_prefetch; response_.resolve_error_info = response->resolve_error_info; // Do not record requests that have network errors or restarts. UpdateCacheEntryStatus(CacheEntryStatus::ENTRY_OTHER); if (IsCertificateError(result)) { // If we get a certificate error, then there is a certificate in ssl_info, // so GetResponseInfo() should never return NULL here. DCHECK(response); response_.ssl_info = response->ssl_info; } else if (result == ERR_SSL_CLIENT_AUTH_CERT_NEEDED) { DCHECK(response); response_.cert_request_info = response->cert_request_info; } else if (result == ERR_INCONSISTENT_IP_ADDRESS_SPACE) { DoomInconsistentEntry(); } else if (response_.was_cached) { DoneWithEntry(/*entry_is_complete=*/true); } TransitionToState(STATE_FINISH_HEADERS); return result; } // We received the response headers and there is no error. int HttpCache::Transaction::DoSuccessfulSendRequest() { DCHECK(!new_response_); const HttpResponseInfo* new_response = network_trans_->GetResponseInfo(); TRACE_EVENT_INSTANT("net", "HttpCacheTransaction::DoSuccessfulSendRequest", perfetto::Track(trace_id_), "response_code", new_response->headers->response_code()); if (new_response->headers->response_code() == net::HTTP_UNAUTHORIZED || new_response->headers->response_code() == net::HTTP_PROXY_AUTHENTICATION_REQUIRED) { SetAuthResponse(*new_response); if (!reading_) { TransitionToState(STATE_FINISH_HEADERS); return OK; } // We initiated a second request the caller doesn't know about. We should be // able to authenticate this request because we should have authenticated // this URL moments ago. if (IsReadyToRestartForAuth()) { TransitionToState(STATE_SEND_REQUEST_COMPLETE); // In theory we should check to see if there are new cookies, but there // is no way to do that from here. return network_trans_->RestartWithAuth(AuthCredentials(), io_callback_); } // We have to perform cleanup at this point so that at least the next // request can succeed. We do not retry at this point, because data // has been read and we have no way to gather credentials. We would // fail again, and potentially loop. This can happen if the credentials // expire while chrome is suspended. if (entry_) DoomPartialEntry(false); mode_ = NONE; partial_.reset(); ResetNetworkTransaction(); TransitionToState(STATE_FINISH_HEADERS); return ERR_CACHE_AUTH_FAILURE_AFTER_READ; } new_response_ = new_response; if (!ValidatePartialResponse() && !auth_response_.headers.get()) { // Something went wrong with this request and we have to restart it. // If we have an authentication response, we are exposed to weird things // hapenning if the user cancels the authentication before we receive // the new response. net_log_.AddEvent(NetLogEventType::HTTP_CACHE_RE_SEND_PARTIAL_REQUEST); UpdateCacheEntryStatus(CacheEntryStatus::ENTRY_OTHER); SetResponse(HttpResponseInfo()); ResetNetworkTransaction(); new_response_ = nullptr; TransitionToState(STATE_SEND_REQUEST); return OK; } if (handling_206_ && mode_ == READ_WRITE && !truncated_ && !is_sparse_) { // We have stored the full entry, but it changed and the server is // sending a range. We have to delete the old entry. UpdateCacheEntryStatus(CacheEntryStatus::ENTRY_OTHER); DoneWithEntry(false); } if (mode_ == WRITE && cache_entry_status_ != CacheEntryStatus::ENTRY_CANT_CONDITIONALIZE) { UpdateCacheEntryStatus(CacheEntryStatus::ENTRY_NOT_IN_CACHE); } // Invalidate any cached GET with a successful PUT, DELETE, or PATCH. if (mode_ == WRITE && (method_ == "PUT" || method_ == "DELETE" || method_ == "PATCH")) { if (NonErrorResponse(new_response_->headers->response_code()) && (entry_ && !entry_->doomed)) { int ret = cache_->DoomEntry(cache_key_, nullptr); DCHECK_EQ(OK, ret); } // Do not invalidate the entry if the request failed. DoneWithEntry(true); } // Invalidate any cached GET with a successful POST. If the network isolation // key isn't populated with the split cache active, there will be nothing to // invalidate in the cache. if (!(effective_load_flags_ & LOAD_DISABLE_CACHE) && method_ == "POST" && NonErrorResponse(new_response_->headers->response_code()) && (!HttpCache::IsSplitCacheEnabled() || request_->network_isolation_key.IsFullyPopulated())) { cache_->DoomMainEntryForUrl(request_->url, request_->network_isolation_key, request_->is_subframe_document_resource); } if (new_response_->headers->response_code() == net::HTTP_REQUESTED_RANGE_NOT_SATISFIABLE && (method_ == "GET" || method_ == "POST")) { // If there is an active entry it may be destroyed with this transaction. SetResponse(*new_response_); TransitionToState(STATE_FINISH_HEADERS); return OK; } // Are we expecting a response to a conditional query? if (mode_ == READ_WRITE || mode_ == UPDATE) { if (new_response->headers->response_code() == net::HTTP_NOT_MODIFIED || handling_206_) { UpdateCacheEntryStatus(CacheEntryStatus::ENTRY_VALIDATED); TransitionToState(STATE_UPDATE_CACHED_RESPONSE); return OK; } UpdateCacheEntryStatus(CacheEntryStatus::ENTRY_UPDATED); mode_ = WRITE; } TransitionToState(STATE_OVERWRITE_CACHED_RESPONSE); return OK; } // We received 304 or 206 and we want to update the cached response headers. int HttpCache::Transaction::DoUpdateCachedResponse() { TRACE_EVENT_INSTANT("net", "HttpCacheTransaction::DoUpdateCachedResponse", perfetto::Track(trace_id_)); int rv = OK; // Update the cached response based on the headers and properties of // new_response_. response_.headers->Update(*new_response_->headers.get()); response_.stale_revalidate_timeout = base::Time(); response_.response_time = new_response_->response_time; response_.request_time = new_response_->request_time; response_.network_accessed = new_response_->network_accessed; response_.unused_since_prefetch = new_response_->unused_since_prefetch; response_.restricted_prefetch = new_response_->restricted_prefetch; response_.ssl_info = new_response_->ssl_info; response_.dns_aliases = new_response_->dns_aliases; // If the new response didn't have a vary header, we continue to use the // header from the stored response per the effect of headers->Update(). // Update the data with the new/updated request headers. response_.vary_data.Init(*request_, *response_.headers); if (ShouldDisableCaching(*response_.headers)) { if (!entry_->doomed) { int ret = cache_->DoomEntry(cache_key_, nullptr); DCHECK_EQ(OK, ret); } TransitionToState(STATE_UPDATE_CACHED_RESPONSE_COMPLETE); } else { // If we are already reading, we already updated the headers for this // request; doing it again will change Content-Length. if (!reading_) { TransitionToState(STATE_CACHE_WRITE_UPDATED_RESPONSE); rv = OK; } else { TransitionToState(STATE_UPDATE_CACHED_RESPONSE_COMPLETE); } } return rv; } int HttpCache::Transaction::DoCacheWriteUpdatedResponse() { TRACE_EVENT_INSTANT("net", "HttpCacheTransaction::DoCacheWriteUpdatedResponse", perfetto::Track(trace_id_)); TransitionToState(STATE_CACHE_WRITE_UPDATED_RESPONSE_COMPLETE); return WriteResponseInfoToEntry(response_, false); } int HttpCache::Transaction::DoCacheWriteUpdatedResponseComplete(int result) { TRACE_EVENT_INSTANT( "net", "HttpCacheTransaction::DoCacheWriteUpdatedResponseComplete", perfetto::Track(trace_id_), "result", result); TransitionToState(STATE_UPDATE_CACHED_RESPONSE_COMPLETE); return OnWriteResponseInfoToEntryComplete(result); } int HttpCache::Transaction::DoUpdateCachedResponseComplete(int result) { TRACE_EVENT_INSTANT("net", "HttpCacheTransaction::DoUpdateCachedResponseComplete", perfetto::Track(trace_id_), "result", result); if (mode_ == UPDATE) { DCHECK(!handling_206_); // We got a "not modified" response and already updated the corresponding // cache entry above. // // By stopping to write to the cache now, we make sure that the 304 rather // than the cached 200 response, is what will be returned to the user. UpdateSecurityHeadersBeforeForwarding(); DoneWithEntry(true); } else if (entry_ && !handling_206_) { DCHECK_EQ(READ_WRITE, mode_); if ((!partial_ && !cache_->IsWritingInProgress(entry_)) || (partial_ && partial_->IsLastRange())) { mode_ = READ; } // We no longer need the network transaction, so destroy it. if (network_trans_) ResetNetworkTransaction(); } else if (entry_ && handling_206_ && truncated_ && partial_->initial_validation()) { // We just finished the validation of a truncated entry, and the server // is willing to resume the operation. Now we go back and start serving // the first part to the user. if (network_trans_) ResetNetworkTransaction(); new_response_ = nullptr; TransitionToState(STATE_START_PARTIAL_CACHE_VALIDATION); partial_->SetRangeToStartDownload(); return OK; } TransitionToState(STATE_OVERWRITE_CACHED_RESPONSE); return OK; } int HttpCache::Transaction::DoOverwriteCachedResponse() { TRACE_EVENT_INSTANT("net", "HttpCacheTransaction::DoOverwriteCachedResponse", perfetto::Track(trace_id_)); if (mode_ & READ) { TransitionToState(STATE_PARTIAL_HEADERS_RECEIVED); return OK; } // We change the value of Content-Length for partial content. if (handling_206_ && partial_) partial_->FixContentLength(new_response_->headers.get()); SetResponse(*new_response_); if (method_ == "HEAD") { // This response is replacing the cached one. DoneWithEntry(false); new_response_ = nullptr; TransitionToState(STATE_FINISH_HEADERS); return OK; } if (handling_206_ && !CanResume(false)) { // There is no point in storing this resource because it will never be used. // This may change if we support LOAD_ONLY_FROM_CACHE with sparse entries. DoneWithEntry(false); if (partial_) partial_->FixResponseHeaders(response_.headers.get(), true); TransitionToState(STATE_PARTIAL_HEADERS_RECEIVED); return OK; } // Mark the response with browser_run_id before it gets written. if (initial_request_->browser_run_id.has_value()) response_.browser_run_id = initial_request_->browser_run_id; TransitionToState(STATE_CACHE_WRITE_RESPONSE); return OK; } int HttpCache::Transaction::DoCacheWriteResponse() { TRACE_EVENT_INSTANT("net", "HttpCacheTransaction::DoCacheWriteResponse", perfetto::Track(trace_id_)); DCHECK(response_.headers); // Invalidate any current entry with a successful response if this transaction // cannot write to this entry. This transaction then continues to read from // the network without writing to the backend. bool is_match = response_.headers->response_code() == net::HTTP_NOT_MODIFIED; if (entry_ && !cache_->CanTransactionWriteResponseHeaders( entry_, this, partial_ != nullptr, is_match)) { done_headers_create_new_entry_ = true; // The transaction needs to overwrite this response. Doom the current entry, // create a new one (by going to STATE_INIT_ENTRY), and then jump straight // to writing out the response, bypassing the headers checks. The mode_ is // set to WRITE in order to doom any other existing entries that might exist // so that this transaction can go straight to writing a response. mode_ = WRITE; TransitionToState(STATE_INIT_ENTRY); cache_->DoomEntryValidationNoMatch(entry_); entry_ = nullptr; return OK; } TransitionToState(STATE_CACHE_WRITE_RESPONSE_COMPLETE); return WriteResponseInfoToEntry(response_, truncated_); } int HttpCache::Transaction::DoCacheWriteResponseComplete(int result) { TRACE_EVENT_INSTANT("net", "HttpCacheTransaction::DoCacheWriteResponseComplete", perfetto::Track(trace_id_), "result", result); TransitionToState(STATE_TRUNCATE_CACHED_DATA); return OnWriteResponseInfoToEntryComplete(result); } int HttpCache::Transaction::DoTruncateCachedData() { TRACE_EVENT_INSTANT("net", "HttpCacheTransaction::DoTruncateCachedData", perfetto::Track(trace_id_)); TransitionToState(STATE_TRUNCATE_CACHED_DATA_COMPLETE); if (!entry_) return OK; net_log_.BeginEvent(NetLogEventType::HTTP_CACHE_WRITE_DATA); BeginDiskCacheAccessTimeCount(); // Truncate the stream. return entry_->GetEntry()->WriteData(kResponseContentIndex, /*offset=*/0, /*buf=*/nullptr, /*buf_len=*/0, io_callback_, /*truncate=*/true); } int HttpCache::Transaction::DoTruncateCachedDataComplete(int result) { TRACE_EVENT_INSTANT("net", "HttpCacheTransaction::DoTruncateCachedDataComplete", perfetto::Track(trace_id_), "result", result); EndDiskCacheAccessTimeCount(DiskCacheAccessType::kWrite); if (entry_) { net_log_.EndEventWithNetErrorCode(NetLogEventType::HTTP_CACHE_WRITE_DATA, result); } TransitionToState(STATE_PARTIAL_HEADERS_RECEIVED); return OK; } int HttpCache::Transaction::DoPartialHeadersReceived() { TRACE_EVENT_INSTANT("net", "HttpCacheTransaction::DoPartialHeadersReceived", perfetto::Track(trace_id_)); new_response_ = nullptr; if (partial_ && mode_ != NONE && !reading_) { // We are about to return the headers for a byte-range request to the user, // so let's fix them. partial_->FixResponseHeaders(response_.headers.get(), true); } TransitionToState(STATE_FINISH_HEADERS); return OK; } int HttpCache::Transaction::DoHeadersPhaseCannotProceed(int result) { // If its the Start state machine and it cannot proceed due to a cache // failure, restart this transaction. DCHECK(!reading_); // Reset before invoking SetRequest() which can reset the request info sent to // network transaction. if (network_trans_) network_trans_.reset(); new_response_ = nullptr; SetRequest(net_log_); entry_ = nullptr; new_entry_ = nullptr; last_disk_cache_access_start_time_ = TimeTicks(); // TODO(https://crbug.com/1219402): This should probably clear `response_`, // too, once things are fixed so it's safe to do so. // Bypass the cache for timeout scenario. if (result == ERR_CACHE_LOCK_TIMEOUT) effective_load_flags_ |= LOAD_DISABLE_CACHE; TransitionToState(STATE_GET_BACKEND); return OK; } int HttpCache::Transaction::DoFinishHeaders(int result) { TRACE_EVENT_INSTANT("net", "HttpCacheTransaction::DoFinishHeaders", perfetto::Track(trace_id_), "result", result); if (!cache_.get() || !entry_ || result != OK) { TransitionToState(STATE_NONE); return result; } TransitionToState(STATE_FINISH_HEADERS_COMPLETE); // If it was an auth failure, this transaction should continue to be // headers_transaction till consumer takes an action, so no need to do // anything now. // TODO(crbug.com/740947). See the issue for a suggestion for cleaning the // state machine to be able to remove this condition. if (auth_response_.headers.get()) return OK; // If the transaction needs to wait because another transaction is still // writing the response body, it will return ERR_IO_PENDING now and the // cache_io_callback_ will be invoked when the wait is done. int rv = cache_->DoneWithResponseHeaders(entry_, this, partial_ != nullptr); DCHECK(!reading_ || rv == OK) << "Expected OK, but got " << rv; if (rv == ERR_IO_PENDING) { DCHECK(entry_lock_waiting_since_.is_null()); entry_lock_waiting_since_ = TimeTicks::Now(); AddCacheLockTimeoutHandler(entry_); } return rv; } int HttpCache::Transaction::DoFinishHeadersComplete(int rv) { TRACE_EVENT_INSTANT("net", "HttpCacheTransaction::DoFinishHeadersComplete", perfetto::Track(trace_id_), "result", rv); entry_lock_waiting_since_ = TimeTicks(); if (rv == ERR_CACHE_RACE || rv == ERR_CACHE_LOCK_TIMEOUT) { TransitionToState(STATE_HEADERS_PHASE_CANNOT_PROCEED); return rv; } if (network_trans_ && InWriters()) { entry_->writers->SetNetworkTransaction(this, std::move(network_trans_)); moved_network_transaction_to_writers_ = true; } // If already reading, that means it is a partial request coming back to the // headers phase, continue to the appropriate reading state. if (reading_) { int reading_state_rv = TransitionToReadingState(); DCHECK_EQ(OK, reading_state_rv); return OK; } TransitionToState(STATE_NONE); return rv; } int HttpCache::Transaction::DoNetworkReadCacheWrite() { TRACE_EVENT_INSTANT("net", "HttpCacheTransaction::DoNetworkReadCacheWrite", perfetto::Track(trace_id_), "read_offset", read_offset_, "read_buf_len", read_buf_len_); DCHECK(InWriters()); TransitionToState(STATE_NETWORK_READ_CACHE_WRITE_COMPLETE); return entry_->writers->Read(read_buf_, read_buf_len_, io_callback_, this); } int HttpCache::Transaction::DoNetworkReadCacheWriteComplete(int result) { TRACE_EVENT_INSTANT("net", "HttpCacheTransaction::DoNetworkReadCacheWriteComplete", perfetto::Track(trace_id_), "result", result); if (!cache_.get()) { TransitionToState(STATE_NONE); return ERR_UNEXPECTED; } // |result| will be error code in case of network read failure and |this| // cannot proceed further, so set entry_ to null. |result| will not be error // in case of cache write failure since |this| can continue to read from the // network. If response is completed, then also set entry to null. if (result < 0) { // We should have discovered this error in WriterAboutToBeRemovedFromEntry DCHECK_EQ(result, shared_writing_error_); DCHECK_EQ(NONE, mode_); DCHECK(!entry_); TransitionToState(STATE_NONE); return result; } if (partial_) { return DoPartialNetworkReadCompleted(result); } if (result == 0) { DCHECK_EQ(NONE, mode_); DCHECK(!entry_); } else { read_offset_ += result; } TransitionToState(STATE_NONE); return result; } int HttpCache::Transaction::DoPartialNetworkReadCompleted(int result) { DCHECK(partial_); // Go to the next range if nothing returned or return the result. // TODO(shivanisha) Simplify this condition if possible. It was introduced // in https://codereview.chromium.org/545101 if (result != 0 || truncated_ || !(partial_->IsLastRange() || mode_ == WRITE)) { partial_->OnNetworkReadCompleted(result); if (result == 0) { // We need to move on to the next range. if (network_trans_) { ResetNetworkTransaction(); } else if (InWriters() && entry_->writers->network_transaction()) { SaveNetworkTransactionInfo(*(entry_->writers->network_transaction())); entry_->writers->ResetNetworkTransaction(); } TransitionToState(STATE_START_PARTIAL_CACHE_VALIDATION); } else { TransitionToState(STATE_NONE); } return result; } // Request completed. if (result == 0) { DoneWithEntry(true); } TransitionToState(STATE_NONE); return result; } int HttpCache::Transaction::DoNetworkRead() { TRACE_EVENT_INSTANT("net", "HttpCacheTransaction::DoNetworkRead", perfetto::Track(trace_id_), "read_offset", read_offset_, "read_buf_len", read_buf_len_); TransitionToState(STATE_NETWORK_READ_COMPLETE); return network_trans_->Read(read_buf_.get(), read_buf_len_, io_callback_); } int HttpCache::Transaction::DoNetworkReadComplete(int result) { TRACE_EVENT_INSTANT("net", "HttpCacheTransaction::DoNetworkReadComplete", perfetto::Track(trace_id_), "result", result); if (!cache_.get()) { TransitionToState(STATE_NONE); return ERR_UNEXPECTED; } if (partial_) return DoPartialNetworkReadCompleted(result); TransitionToState(STATE_NONE); return result; } int HttpCache::Transaction::DoCacheReadData() { if (entry_) { DCHECK(InWriters() || entry_->TransactionInReaders(this)); } TRACE_EVENT_INSTANT("net", "HttpCacheTransaction::DoCacheReadData", perfetto::Track(trace_id_), "read_offset", read_offset_, "read_buf_len", read_buf_len_); if (method_ == "HEAD") { TransitionToState(STATE_NONE); return 0; } DCHECK(entry_); TransitionToState(STATE_CACHE_READ_DATA_COMPLETE); net_log_.BeginEvent(NetLogEventType::HTTP_CACHE_READ_DATA); if (partial_) { return partial_->CacheRead(entry_->GetEntry(), read_buf_.get(), read_buf_len_, io_callback_); } BeginDiskCacheAccessTimeCount(); return entry_->GetEntry()->ReadData(kResponseContentIndex, read_offset_, read_buf_.get(), read_buf_len_, io_callback_); } int HttpCache::Transaction::DoCacheReadDataComplete(int result) { EndDiskCacheAccessTimeCount(DiskCacheAccessType::kRead); if (entry_) { DCHECK(InWriters() || entry_->TransactionInReaders(this)); } TRACE_EVENT_INSTANT("net", "HttpCacheTransaction::DoCacheReadDataComplete", perfetto::Track(trace_id_), "result", result); net_log_.EndEventWithNetErrorCode(NetLogEventType::HTTP_CACHE_READ_DATA, result); if (!cache_.get()) { TransitionToState(STATE_NONE); return ERR_UNEXPECTED; } if (partial_) { // Partial requests are confusing to report in histograms because they may // have multiple underlying requests. UpdateCacheEntryStatus(CacheEntryStatus::ENTRY_OTHER); return DoPartialCacheReadCompleted(result); } if (result > 0) { read_offset_ += result; } else if (result == 0) { // End of file. DoneWithEntry(true); } else { return OnCacheReadError(result, false); } TransitionToState(STATE_NONE); return result; } //----------------------------------------------------------------------------- void HttpCache::Transaction::SetRequest(const NetLogWithSource& net_log) { net_log_ = net_log; // Reset the variables that might get set in this function. This is done // because this function can be invoked multiple times for a transaction. cache_entry_status_ = CacheEntryStatus::ENTRY_UNDEFINED; external_validation_.Reset(); range_requested_ = false; partial_.reset(); request_ = initial_request_; custom_request_.reset(); effective_load_flags_ = request_->load_flags; method_ = request_->method; if (cache_->mode() == DISABLE) effective_load_flags_ |= LOAD_DISABLE_CACHE; // Some headers imply load flags. The order here is significant. // // LOAD_DISABLE_CACHE : no cache read or write // LOAD_BYPASS_CACHE : no cache read // LOAD_VALIDATE_CACHE : no cache read unless validation // // The former modes trump latter modes, so if we find a matching header we // can stop iterating kSpecialHeaders. // static const struct { // This field is not a raw_ptr<> because it was filtered by the rewriter // for: #global-scope RAW_PTR_EXCLUSION const HeaderNameAndValue* search; int load_flag; } kSpecialHeaders[] = { { kPassThroughHeaders, LOAD_DISABLE_CACHE }, { kForceFetchHeaders, LOAD_BYPASS_CACHE }, { kForceValidateHeaders, LOAD_VALIDATE_CACHE }, }; bool range_found = false; bool external_validation_error = false; bool special_headers = false; if (request_->extra_headers.HasHeader(HttpRequestHeaders::kRange)) range_found = true; for (const auto& special_header : kSpecialHeaders) { if (HeaderMatches(request_->extra_headers, special_header.search)) { effective_load_flags_ |= special_header.load_flag; special_headers = true; break; } } // Check for conditionalization headers which may correspond with a // cache validation request. for (size_t i = 0; i < std::size(kValidationHeaders); ++i) { const ValidationHeaderInfo& info = kValidationHeaders[i]; std::string validation_value; if (request_->extra_headers.GetHeader( info.request_header_name, &validation_value)) { if (!external_validation_.values[i].empty() || validation_value.empty()) { external_validation_error = true; } external_validation_.values[i] = validation_value; external_validation_.initialized = true; } } if (range_found || special_headers || external_validation_.initialized) { // Log the headers before request_ is modified. std::string empty; NetLogRequestHeaders(net_log_, NetLogEventType::HTTP_CACHE_CALLER_REQUEST_HEADERS, empty, &request_->extra_headers); } // We don't support ranges and validation headers. if (range_found && external_validation_.initialized) { LOG(WARNING) << "Byte ranges AND validation headers found."; effective_load_flags_ |= LOAD_DISABLE_CACHE; } // If there is more than one validation header, we can't treat this request as // a cache validation, since we don't know for sure which header the server // will give us a response for (and they could be contradictory). if (external_validation_error) { LOG(WARNING) << "Multiple or malformed validation headers found."; effective_load_flags_ |= LOAD_DISABLE_CACHE; } if (range_found && !(effective_load_flags_ & LOAD_DISABLE_CACHE)) { UpdateCacheEntryStatus(CacheEntryStatus::ENTRY_OTHER); partial_ = std::make_unique<PartialData>(); if (method_ == "GET" && partial_->Init(request_->extra_headers)) { // We will be modifying the actual range requested to the server, so // let's remove the header here. // Note that custom_request_ is a shallow copy so will keep the same // pointer to upload data stream as in the original request. custom_request_ = std::make_unique<HttpRequestInfo>(*request_); custom_request_->extra_headers.RemoveHeader(HttpRequestHeaders::kRange); request_ = custom_request_.get(); partial_->SetHeaders(custom_request_->extra_headers); } else { // The range is invalid or we cannot handle it properly. VLOG(1) << "Invalid byte range found."; effective_load_flags_ |= LOAD_DISABLE_CACHE; partial_.reset(nullptr); } } } bool HttpCache::Transaction::ShouldPassThrough() { bool cacheable = true; // We may have a null disk_cache if there is an error we cannot recover from, // like not enough disk space, or sharing violations. if (!cache_->disk_cache_.get()) { cacheable = false; } else if (effective_load_flags_ & LOAD_DISABLE_CACHE) { cacheable = false; } // Prevent resources whose origin is opaque from being cached. Blink's memory // cache should take care of reusing resources within the current page load, // but otherwise a resource with an opaque top-frame origin won’t be used // again. Also, if the request does not have a top frame origin, bypass the // cache otherwise resources from different pages could share a cached entry // in such cases. else if (HttpCache::IsSplitCacheEnabled() && request_->network_isolation_key.IsTransient()) { cacheable = false; } else if (method_ == "GET" || method_ == "HEAD") { } else if (method_ == "POST" && request_->upload_data_stream && request_->upload_data_stream->identifier()) { } else if (method_ == "PUT" && request_->upload_data_stream) { } // DELETE and PATCH requests may result in invalidating the cache, so cannot // just pass through. else if (method_ == "DELETE" || method_ == "PATCH") { } else { cacheable = false; } return !cacheable; } int HttpCache::Transaction::BeginCacheRead() { // We don't support any combination of LOAD_ONLY_FROM_CACHE and byte ranges. // It's possible to trigger this from JavaScript using the Fetch API with // `cache: 'only-if-cached'` so ideally we should support it. // TODO(ricea): Correctly read from the cache in this case. if (response_.headers->response_code() == net::HTTP_PARTIAL_CONTENT || partial_) { TransitionToState(STATE_FINISH_HEADERS); return ERR_CACHE_MISS; } // We don't have the whole resource. if (truncated_) { TransitionToState(STATE_FINISH_HEADERS); return ERR_CACHE_MISS; } if (RequiresValidation() != VALIDATION_NONE) { TransitionToState(STATE_FINISH_HEADERS); return ERR_CACHE_MISS; } if (method_ == "HEAD") FixHeadersForHead(); TransitionToState(STATE_FINISH_HEADERS); return OK; } int HttpCache::Transaction::BeginCacheValidation() { DCHECK_EQ(mode_, READ_WRITE); ValidationType required_validation = RequiresValidation(); bool skip_validation = (required_validation == VALIDATION_NONE); bool needs_stale_while_revalidate_cache_update = false; if ((effective_load_flags_ & LOAD_SUPPORT_ASYNC_REVALIDATION) && required_validation == VALIDATION_ASYNCHRONOUS) { DCHECK_EQ(request_->method, "GET"); skip_validation = true; response_.async_revalidation_requested = true; needs_stale_while_revalidate_cache_update = response_.stale_revalidate_timeout.is_null(); } if (method_ == "HEAD" && (truncated_ || response_.headers->response_code() == net::HTTP_PARTIAL_CONTENT)) { DCHECK(!partial_); if (skip_validation) { DCHECK(!reading_); TransitionToState(STATE_CONNECTED_CALLBACK); return OK; } // Bail out! TransitionToState(STATE_SEND_REQUEST); mode_ = NONE; return OK; } if (truncated_) { // Truncated entries can cause partial gets, so we shouldn't record this // load in histograms. UpdateCacheEntryStatus(CacheEntryStatus::ENTRY_OTHER); skip_validation = !partial_->initial_validation(); } // If this is the first request (!reading_) of a 206 entry (is_sparse_) that // doesn't actually cover the entire file (which with !reading would require // partial->IsLastRange()), and the user is requesting the whole thing // (!partial_->range_requested()), make sure to validate the first chunk, // since afterwards it will be too late if it's actually out-of-date (or the // server bungles invalidation). This is limited to the whole-file request // as a targeted fix for https://crbug.com/888742 while avoiding extra // requests in other cases, but the problem can occur more generally as well; // it's just a lot less likely with applications actively using ranges. // See https://crbug.com/902724 for the more general case. bool first_read_of_full_from_partial = is_sparse_ && !reading_ && (partial_ && !partial_->range_requested() && !partial_->IsLastRange()); if (partial_ && (is_sparse_ || truncated_) && (!partial_->IsCurrentRangeCached() || invalid_range_ || first_read_of_full_from_partial)) { // Force revalidation for sparse or truncated entries. Note that we don't // want to ignore the regular validation logic just because a byte range was // part of the request. skip_validation = false; } if (skip_validation) { UpdateCacheEntryStatus(CacheEntryStatus::ENTRY_USED); DCHECK(!reading_); TransitionToState(needs_stale_while_revalidate_cache_update ? STATE_CACHE_UPDATE_STALE_WHILE_REVALIDATE_TIMEOUT : STATE_CONNECTED_CALLBACK); return OK; } else { // Make the network request conditional, to see if we may reuse our cached // response. If we cannot do so, then we just resort to a normal fetch. // Our mode remains READ_WRITE for a conditional request. Even if the // conditionalization fails, we don't switch to WRITE mode until we // know we won't be falling back to using the cache entry in the // LOAD_FROM_CACHE_IF_OFFLINE case. if (!ConditionalizeRequest()) { couldnt_conditionalize_request_ = true; UpdateCacheEntryStatus(CacheEntryStatus::ENTRY_CANT_CONDITIONALIZE); if (partial_) return DoRestartPartialRequest(); DCHECK_NE(net::HTTP_PARTIAL_CONTENT, response_.headers->response_code()); } TransitionToState(STATE_SEND_REQUEST); } return OK; } int HttpCache::Transaction::BeginPartialCacheValidation() { DCHECK_EQ(mode_, READ_WRITE); if (response_.headers->response_code() != net::HTTP_PARTIAL_CONTENT && !partial_ && !truncated_) return BeginCacheValidation(); // Partial requests should not be recorded in histograms. UpdateCacheEntryStatus(CacheEntryStatus::ENTRY_OTHER); if (method_ == "HEAD") return BeginCacheValidation(); if (!range_requested_) { // The request is not for a range, but we have stored just ranges. partial_ = std::make_unique<PartialData>(); partial_->SetHeaders(request_->extra_headers); if (!custom_request_.get()) { custom_request_ = std::make_unique<HttpRequestInfo>(*request_); request_ = custom_request_.get(); } } TransitionToState(STATE_CACHE_QUERY_DATA); return OK; } // This should only be called once per request. int HttpCache::Transaction::ValidateEntryHeadersAndContinue() { DCHECK_EQ(mode_, READ_WRITE); if (!partial_->UpdateFromStoredHeaders( response_.headers.get(), entry_->GetEntry(), truncated_, cache_->IsWritingInProgress(entry()))) { return DoRestartPartialRequest(); } if (response_.headers->response_code() == net::HTTP_PARTIAL_CONTENT) is_sparse_ = true; if (!partial_->IsRequestedRangeOK()) { // The stored data is fine, but the request may be invalid. invalid_range_ = true; } TransitionToState(STATE_START_PARTIAL_CACHE_VALIDATION); return OK; } bool HttpCache::Transaction:: ExternallyConditionalizedValidationHeadersMatchEntry() const { DCHECK(external_validation_.initialized); for (size_t i = 0; i < std::size(kValidationHeaders); i++) { if (external_validation_.values[i].empty()) continue; // Retrieve either the cached response's "etag" or "last-modified" header. std::string validator; response_.headers->EnumerateHeader( nullptr, kValidationHeaders[i].related_response_header_name, &validator); if (validator != external_validation_.values[i]) { return false; } } return true; } int HttpCache::Transaction::BeginExternallyConditionalizedRequest() { DCHECK_EQ(UPDATE, mode_); if (response_.headers->response_code() != net::HTTP_OK || truncated_ || !ExternallyConditionalizedValidationHeadersMatchEntry()) { // The externally conditionalized request is not a validation request // for our existing cache entry. Proceed with caching disabled. UpdateCacheEntryStatus(CacheEntryStatus::ENTRY_OTHER); DoneWithEntry(true); } TransitionToState(STATE_SEND_REQUEST); return OK; } int HttpCache::Transaction::RestartNetworkRequest() { DCHECK(mode_ & WRITE || mode_ == NONE); DCHECK(network_trans_.get()); DCHECK_EQ(STATE_NONE, next_state_); next_state_ = STATE_SEND_REQUEST_COMPLETE; int rv = network_trans_->RestartIgnoringLastError(io_callback_); if (rv != ERR_IO_PENDING) return DoLoop(rv); return rv; } int HttpCache::Transaction::RestartNetworkRequestWithCertificate( scoped_refptr<X509Certificate> client_cert, scoped_refptr<SSLPrivateKey> client_private_key) { DCHECK(mode_ & WRITE || mode_ == NONE); DCHECK(network_trans_.get()); DCHECK_EQ(STATE_NONE, next_state_); next_state_ = STATE_SEND_REQUEST_COMPLETE; int rv = network_trans_->RestartWithCertificate( std::move(client_cert), std::move(client_private_key), io_callback_); if (rv != ERR_IO_PENDING) return DoLoop(rv); return rv; } int HttpCache::Transaction::RestartNetworkRequestWithAuth( const AuthCredentials& credentials) { DCHECK(mode_ & WRITE || mode_ == NONE); DCHECK(network_trans_.get()); DCHECK_EQ(STATE_NONE, next_state_); next_state_ = STATE_SEND_REQUEST_COMPLETE; int rv = network_trans_->RestartWithAuth(credentials, io_callback_); if (rv != ERR_IO_PENDING) return DoLoop(rv); return rv; } ValidationType HttpCache::Transaction::RequiresValidation() { // TODO(darin): need to do more work here: // - make sure we have a matching request method // - watch out for cached responses that depend on authentication if (!(effective_load_flags_ & LOAD_SKIP_VARY_CHECK) && response_.vary_data.is_valid() && !response_.vary_data.MatchesRequest(*request_, *response_.headers.get())) { vary_mismatch_ = true; validation_cause_ = VALIDATION_CAUSE_VARY_MISMATCH; return VALIDATION_SYNCHRONOUS; } if (effective_load_flags_ & LOAD_SKIP_CACHE_VALIDATION) return VALIDATION_NONE; if (method_ == "PUT" || method_ == "DELETE" || method_ == "PATCH") return VALIDATION_SYNCHRONOUS; bool validate_flag = effective_load_flags_ & LOAD_VALIDATE_CACHE; ValidationType validation_required_by_headers = validate_flag ? VALIDATION_SYNCHRONOUS : response_.headers->RequiresValidation( response_.request_time, response_.response_time, cache_->clock_->Now()); base::TimeDelta response_time_in_cache = cache_->clock_->Now() - response_.response_time; if (!base::FeatureList::IsEnabled( features::kPrefetchFollowsNormalCacheSemantics) && !(effective_load_flags_ & LOAD_PREFETCH) && (response_time_in_cache >= base::TimeDelta())) { bool reused_within_time_window = response_time_in_cache < base::Minutes(kPrefetchReuseMins); bool first_reuse = response_.unused_since_prefetch; base::UmaHistogramLongTimes("HttpCache.PrefetchReuseTime", response_time_in_cache); if (first_reuse) { base::UmaHistogramLongTimes("HttpCache.PrefetchFirstReuseTime", response_time_in_cache); } base::UmaHistogramEnumeration( "HttpCache.PrefetchReuseState", ComputePrefetchReuseState(validation_required_by_headers, first_reuse, reused_within_time_window, validate_flag)); // The first use of a resource after prefetch within a short window skips // validation. if (first_reuse && reused_within_time_window) { return VALIDATION_NONE; } } if (validate_flag) { validation_cause_ = VALIDATION_CAUSE_VALIDATE_FLAG; return VALIDATION_SYNCHRONOUS; } if (validation_required_by_headers != VALIDATION_NONE) { HttpResponseHeaders::FreshnessLifetimes lifetimes = response_.headers->GetFreshnessLifetimes(response_.response_time); if (lifetimes.freshness == base::TimeDelta()) { validation_cause_ = VALIDATION_CAUSE_ZERO_FRESHNESS; } else { validation_cause_ = VALIDATION_CAUSE_STALE; } } if (validation_required_by_headers == VALIDATION_ASYNCHRONOUS) { // Asynchronous revalidation is only supported for GET methods. if (request_->method != "GET") return VALIDATION_SYNCHRONOUS; // If the timeout on the staleness revalidation is set don't hand out // a resource that hasn't been async validated. if (!response_.stale_revalidate_timeout.is_null() && response_.stale_revalidate_timeout < cache_->clock_->Now()) { return VALIDATION_SYNCHRONOUS; } } return validation_required_by_headers; } bool HttpCache::Transaction::IsResponseConditionalizable( std::string* etag_value, std::string* last_modified_value) const { DCHECK(response_.headers.get()); // This only makes sense for cached 200 or 206 responses. if (response_.headers->response_code() != net::HTTP_OK && response_.headers->response_code() != net::HTTP_PARTIAL_CONTENT) { return false; } // Just use the first available ETag and/or Last-Modified header value. // TODO(darin): Or should we use the last? if (response_.headers->GetHttpVersion() >= HttpVersion(1, 1)) response_.headers->EnumerateHeader(nullptr, "etag", etag_value); response_.headers->EnumerateHeader(nullptr, "last-modified", last_modified_value); if (etag_value->empty() && last_modified_value->empty()) return false; return true; } bool HttpCache::Transaction::ShouldOpenOnlyMethods() const { // These methods indicate that we should only try to open an entry and not // fallback to create. return method_ == "PUT" || method_ == "DELETE" || method_ == "PATCH" || (method_ == "HEAD" && mode_ == READ_WRITE); } bool HttpCache::Transaction::ConditionalizeRequest() { DCHECK(response_.headers.get()); if (method_ == "PUT" || method_ == "DELETE" || method_ == "PATCH") return false; if (fail_conditionalization_for_test_) return false; std::string etag_value; std::string last_modified_value; if (!IsResponseConditionalizable(&etag_value, &last_modified_value)) return false; DCHECK(response_.headers->response_code() != net::HTTP_PARTIAL_CONTENT || response_.headers->HasStrongValidators()); if (vary_mismatch_) { // Can't rely on last-modified if vary is different. last_modified_value.clear(); if (etag_value.empty()) return false; } if (!partial_) { // Need to customize the request, so this forces us to allocate :( custom_request_ = std::make_unique<HttpRequestInfo>(*request_); request_ = custom_request_.get(); } DCHECK(custom_request_.get()); bool use_if_range = partial_ && !partial_->IsCurrentRangeCached() && !invalid_range_; if (!etag_value.empty()) { if (use_if_range) { // We don't want to switch to WRITE mode if we don't have this block of a // byte-range request because we may have other parts cached. custom_request_->extra_headers.SetHeader( HttpRequestHeaders::kIfRange, etag_value); } else { custom_request_->extra_headers.SetHeader( HttpRequestHeaders::kIfNoneMatch, etag_value); } // For byte-range requests, make sure that we use only one way to validate // the request. if (partial_ && !partial_->IsCurrentRangeCached()) return true; } if (!last_modified_value.empty()) { if (use_if_range) { custom_request_->extra_headers.SetHeader( HttpRequestHeaders::kIfRange, last_modified_value); } else { custom_request_->extra_headers.SetHeader( HttpRequestHeaders::kIfModifiedSince, last_modified_value); } } return true; } bool HttpCache::Transaction::MaybeRejectBasedOnEntryInMemoryData( uint8_t in_memory_info) { // Not going to be clever with those... if (partial_) return false; // Avoiding open based on in-memory hints requires us to be permitted to // modify the cache, including deleting an old entry. Only the READ_WRITE // and WRITE modes permit that... and WRITE never tries to open entries in the // first place, so we shouldn't see it here. DCHECK_NE(mode_, WRITE); if (mode_ != READ_WRITE) return false; // If we are loading ignoring cache validity (aka back button), obviously // can't reject things based on it. Also if LOAD_ONLY_FROM_CACHE there is no // hope of network offering anything better. if (effective_load_flags_ & LOAD_SKIP_CACHE_VALIDATION || effective_load_flags_ & LOAD_ONLY_FROM_CACHE) return false; return (in_memory_info & HINT_UNUSABLE_PER_CACHING_HEADERS) == HINT_UNUSABLE_PER_CACHING_HEADERS; } bool HttpCache::Transaction::ComputeUnusablePerCachingHeaders() { // unused_since_prefetch overrides some caching headers, so it may be useful // regardless of what they say. if (response_.unused_since_prefetch) return false; // Has an e-tag or last-modified: we can probably send a conditional request, // so it's potentially useful. std::string etag_ignored, last_modified_ignored; if (IsResponseConditionalizable(&etag_ignored, &last_modified_ignored)) return false; // If none of the above is true and the entry has zero freshness, then it // won't be usable absent load flag override. return response_.headers->GetFreshnessLifetimes(response_.response_time) .freshness.is_zero(); } // We just received some headers from the server. We may have asked for a range, // in which case partial_ has an object. This could be the first network request // we make to fulfill the original request, or we may be already reading (from // the net and / or the cache). If we are not expecting a certain response, we // just bypass the cache for this request (but again, maybe we are reading), and // delete partial_ (so we are not able to "fix" the headers that we return to // the user). This results in either a weird response for the caller (we don't // expect it after all), or maybe a range that was not exactly what it was asked // for. // // If the server is simply telling us that the resource has changed, we delete // the cached entry and restart the request as the caller intended (by returning // false from this method). However, we may not be able to do that at any point, // for instance if we already returned the headers to the user. // // WARNING: Whenever this code returns false, it has to make sure that the next // time it is called it will return true so that we don't keep retrying the // request. bool HttpCache::Transaction::ValidatePartialResponse() { const HttpResponseHeaders* headers = new_response_->headers.get(); int response_code = headers->response_code(); bool partial_response = (response_code == net::HTTP_PARTIAL_CONTENT); handling_206_ = false; if (!entry_ || method_ != "GET") return true; if (invalid_range_) { // We gave up trying to match this request with the stored data. If the // server is ok with the request, delete the entry, otherwise just ignore // this request DCHECK(!reading_); if (partial_response || response_code == net::HTTP_OK) { DoomPartialEntry(true); mode_ = NONE; } else { if (response_code == net::HTTP_NOT_MODIFIED) { // Change the response code of the request to be 416 (Requested range // not satisfiable). SetResponse(*new_response_); partial_->FixResponseHeaders(response_.headers.get(), false); } IgnoreRangeRequest(); } return true; } if (!partial_) { // We are not expecting 206 but we may have one. if (partial_response) IgnoreRangeRequest(); return true; } // TODO(rvargas): Do we need to consider other results here?. bool failure = response_code == net::HTTP_OK || response_code == net::HTTP_REQUESTED_RANGE_NOT_SATISFIABLE; if (partial_->IsCurrentRangeCached()) { // We asked for "If-None-Match: " so a 206 means a new object. if (partial_response) failure = true; if (response_code == net::HTTP_NOT_MODIFIED && partial_->ResponseHeadersOK(headers)) return true; } else { // We asked for "If-Range: " so a 206 means just another range. if (partial_response) { if (partial_->ResponseHeadersOK(headers)) { handling_206_ = true; return true; } else { failure = true; } } if (!reading_ && !is_sparse_ && !partial_response) { // See if we can ignore the fact that we issued a byte range request. // If the server sends 200, just store it. If it sends an error, redirect // or something else, we may store the response as long as we didn't have // anything already stored. if (response_code == net::HTTP_OK || (!truncated_ && response_code != net::HTTP_NOT_MODIFIED && response_code != net::HTTP_REQUESTED_RANGE_NOT_SATISFIABLE)) { // The server is sending something else, and we can save it. DCHECK((truncated_ && !partial_->IsLastRange()) || range_requested_); partial_.reset(); truncated_ = false; return true; } } // 304 is not expected here, but we'll spare the entry (unless it was // truncated). if (truncated_) failure = true; } if (failure) { // We cannot truncate this entry, it has to be deleted. UpdateCacheEntryStatus(CacheEntryStatus::ENTRY_OTHER); mode_ = NONE; if (is_sparse_ || truncated_) { // There was something cached to start with, either sparsed data (206), or // a truncated 200, which means that we probably modified the request, // adding a byte range or modifying the range requested by the caller. if (!reading_ && !partial_->IsLastRange()) { // We have not returned anything to the caller yet so it should be safe // to issue another network request, this time without us messing up the // headers. ResetPartialState(true); return false; } LOG(WARNING) << "Failed to revalidate partial entry"; } DoomPartialEntry(true); return true; } IgnoreRangeRequest(); return true; } void HttpCache::Transaction::IgnoreRangeRequest() { // We have a problem. We may or may not be reading already (in which case we // returned the headers), but we'll just pretend that this request is not // using the cache and see what happens. Most likely this is the first // response from the server (it's not changing its mind midway, right?). UpdateCacheEntryStatus(CacheEntryStatus::ENTRY_OTHER); DoneWithEntry(mode_ != WRITE); partial_.reset(nullptr); } // Called to signal to the consumer that we are about to read headers from a // cached entry originally read from a given IP endpoint. int HttpCache::Transaction::DoConnectedCallback() { TransitionToState(STATE_CONNECTED_CALLBACK_COMPLETE); if (connected_callback_.is_null()) { return OK; } auto type = response_.was_fetched_via_proxy ? TransportType::kCachedFromProxy : TransportType::kCached; return connected_callback_.Run( TransportInfo(type, response_.remote_endpoint, ""), io_callback_); } int HttpCache::Transaction::DoConnectedCallbackComplete(int result) { if (result != OK) { if (result == ERR_CACHED_IP_ADDRESS_SPACE_BLOCKED_BY_PRIVATE_NETWORK_ACCESS_POLICY) { DoomInconsistentEntry(); UpdateCacheEntryStatus(CacheEntryStatus::ENTRY_OTHER); TransitionToState(reading_ ? STATE_SEND_REQUEST : STATE_HEADERS_PHASE_CANNOT_PROCEED); return OK; } if (result == ERR_INCONSISTENT_IP_ADDRESS_SPACE) { DoomInconsistentEntry(); } else { // Release the entry for further use - we are done using it. DoneWithEntry(/*entry_is_complete=*/true); } TransitionToState(STATE_NONE); return result; } if (reading_) { // We can only get here if we're reading a partial range of bytes from the // cache. In that case, proceed to read the bytes themselves. DCHECK(partial_); TransitionToState(STATE_CACHE_READ_DATA); } else { // Otherwise, we have just read headers from the cache. TransitionToState(STATE_SETUP_ENTRY_FOR_READ); } return OK; } void HttpCache::Transaction::DoomInconsistentEntry() { // Explicitly call `DoomActiveEntry()` ourselves before calling // `DoneWithEntry()` because we cannot rely on the latter doing it for us. // Indeed, `DoneWithEntry(false)` does not call `DoomActiveEntry()` if either // of the following conditions hold: // // - the transaction uses the cache in read-only mode // - the transaction has passed the headers phase and is reading // // Inconsistent cache entries can cause deterministic failures even in // read-only mode, so they should be doomed anyway. They can also be detected // during the reading phase in the case of split range requests, since those // requests can result in multiple connections being obtained to different // remote endpoints. cache_->DoomActiveEntry(cache_key_); DoneWithEntry(/*entry_is_complete=*/false); } void HttpCache::Transaction::FixHeadersForHead() { if (response_.headers->response_code() == net::HTTP_PARTIAL_CONTENT) { response_.headers->RemoveHeader("Content-Range"); response_.headers->ReplaceStatusLine("HTTP/1.1 200 OK"); } } int HttpCache::Transaction::DoSetupEntryForRead() { TRACE_EVENT_INSTANT("net", "HttpCacheTransaction::DoSetupEntryForRead", perfetto::Track(trace_id_)); if (network_trans_) ResetNetworkTransaction(); if (!entry_) { // Entry got destroyed when twiddling SWR bits. TransitionToState(STATE_HEADERS_PHASE_CANNOT_PROCEED); return OK; } if (partial_) { if (truncated_ || is_sparse_ || (!invalid_range_ && (response_.headers->response_code() == net::HTTP_OK || response_.headers->response_code() == net::HTTP_PARTIAL_CONTENT))) { // We are going to return the saved response headers to the caller, so // we may need to adjust them first. In cases we are handling a range // request to a regular entry, we want the response to be a 200 or 206, // since others can't really be turned into a 206. TransitionToState(STATE_PARTIAL_HEADERS_RECEIVED); return OK; } else { partial_.reset(); } } if (!cache_->IsWritingInProgress(entry_)) mode_ = READ; if (method_ == "HEAD") FixHeadersForHead(); TransitionToState(STATE_FINISH_HEADERS); return OK; } int HttpCache::Transaction::WriteResponseInfoToEntry( const HttpResponseInfo& response, bool truncated) { DCHECK(response.headers); TRACE_EVENT_INSTANT("net", "HttpCacheTransaction::WriteResponseInfoToEntry", perfetto::Track(trace_id_), "truncated", truncated); if (!entry_) return OK; net_log_.BeginEvent(NetLogEventType::HTTP_CACHE_WRITE_INFO); // Do not cache content with cert errors. This is to prevent not reporting net // errors when loading a resource from the cache. When we load a page over // HTTPS with a cert error we show an SSL blocking page. If the user clicks // proceed we reload the resource ignoring the errors. The loaded resource is // then cached. If that resource is subsequently loaded from the cache, no // net error is reported (even though the cert status contains the actual // errors) and no SSL blocking page is shown. An alternative would be to // reverse-map the cert status to a net error and replay the net error. if (IsCertStatusError(response.ssl_info.cert_status) || ShouldDisableCaching(*response.headers)) { if (partial_) partial_->FixResponseHeaders(response_.headers.get(), true); bool stopped = StopCachingImpl(false); DCHECK(stopped); net_log_.EndEventWithNetErrorCode(NetLogEventType::HTTP_CACHE_WRITE_INFO, OK); return OK; } if (truncated) DCHECK_EQ(net::HTTP_OK, response.headers->response_code()); // When writing headers, we normally only write the non-transient headers. bool skip_transient_headers = true; auto data = base::MakeRefCounted<PickledIOBuffer>(); response.Persist(data->pickle(), skip_transient_headers, truncated); data->Done(); io_buf_len_ = data->pickle()->size(); // Summarize some info on cacheability in memory. Don't do it if doomed // since then |entry_| isn't definitive for |cache_key_|. if (!entry_->doomed) { cache_->GetCurrentBackend()->SetEntryInMemoryData( cache_key_, ComputeUnusablePerCachingHeaders() ? HINT_UNUSABLE_PER_CACHING_HEADERS : 0); } BeginDiskCacheAccessTimeCount(); return entry_->disk_entry->WriteData(kResponseInfoIndex, 0, data.get(), io_buf_len_, io_callback_, true); } int HttpCache::Transaction::OnWriteResponseInfoToEntryComplete(int result) { TRACE_EVENT_INSTANT( "net", "HttpCacheTransaction::OnWriteResponseInfoToEntryComplete", perfetto::Track(trace_id_), "result", result); EndDiskCacheAccessTimeCount(DiskCacheAccessType::kWrite); if (!entry_) return OK; net_log_.EndEventWithNetErrorCode(NetLogEventType::HTTP_CACHE_WRITE_INFO, result); if (result != io_buf_len_) { DLOG(ERROR) << "failed to write response info to cache"; DoneWithEntry(false); } return OK; } bool HttpCache::Transaction::StopCachingImpl(bool success) { bool stopped = false; // Let writers know so that it doesn't attempt to write to the cache. if (InWriters()) { stopped = entry_->writers->StopCaching(success /* keep_entry */); if (stopped) mode_ = NONE; } else if (entry_) { stopped = true; DoneWithEntry(success /* entry_is_complete */); } return stopped; } void HttpCache::Transaction::DoneWithEntry(bool entry_is_complete) { TRACE_EVENT_INSTANT("net", "HttpCacheTransaction::DoneWithEntry", perfetto::Track(trace_id_), "entry_is_complete", entry_is_complete); if (!entry_) return; cache_->DoneWithEntry(entry_, this, entry_is_complete, partial_ != nullptr); entry_ = nullptr; mode_ = NONE; // switch to 'pass through' mode } int HttpCache::Transaction::OnCacheReadError(int result, bool restart) { DLOG(ERROR) << "ReadData failed: " << result; // Avoid using this entry in the future. if (cache_.get()) cache_->DoomActiveEntry(cache_key_); if (restart) { DCHECK(!reading_); DCHECK(!network_trans_.get()); // Since we are going to add this to a new entry, not recording histograms // or setting mode to NONE at this point by invoking the wrapper // DoneWithEntry. cache_->DoneWithEntry(entry_, this, true /* entry_is_complete */, partial_ != nullptr); entry_ = nullptr; is_sparse_ = false; // It's OK to use PartialData::RestoreHeaders here as |restart| is only set // when the HttpResponseInfo couldn't even be read, at which point it's // too early for range info in |partial_| to have changed. if (partial_) partial_->RestoreHeaders(&custom_request_->extra_headers); partial_.reset(); TransitionToState(STATE_GET_BACKEND); return OK; } TransitionToState(STATE_NONE); return ERR_CACHE_READ_FAILURE; } void HttpCache::Transaction::OnCacheLockTimeout(base::TimeTicks start_time) { if (entry_lock_waiting_since_ != start_time) return; DCHECK(next_state_ == STATE_ADD_TO_ENTRY_COMPLETE || next_state_ == STATE_FINISH_HEADERS_COMPLETE || waiting_for_cache_io_); if (!cache_) return; if (next_state_ == STATE_ADD_TO_ENTRY_COMPLETE || waiting_for_cache_io_) { cache_->RemovePendingTransaction(this); } else { DoneWithEntry(false /* entry_is_complete */); } OnCacheIOComplete(ERR_CACHE_LOCK_TIMEOUT); } void HttpCache::Transaction::DoomPartialEntry(bool delete_object) { DVLOG(2) << "DoomPartialEntry"; if (entry_ && !entry_->doomed) { int rv = cache_->DoomEntry(cache_key_, nullptr); DCHECK_EQ(OK, rv); } cache_->DoneWithEntry(entry_, this, false /* entry_is_complete */, partial_ != nullptr); entry_ = nullptr; is_sparse_ = false; truncated_ = false; if (delete_object) partial_.reset(nullptr); } int HttpCache::Transaction::DoPartialCacheReadCompleted(int result) { partial_->OnCacheReadCompleted(result); if (result == 0 && mode_ == READ_WRITE) { // We need to move on to the next range. TransitionToState(STATE_START_PARTIAL_CACHE_VALIDATION); } else if (result < 0) { return OnCacheReadError(result, false); } else { TransitionToState(STATE_NONE); } return result; } int HttpCache::Transaction::DoRestartPartialRequest() { // The stored data cannot be used. Get rid of it and restart this request. net_log_.AddEvent(NetLogEventType::HTTP_CACHE_RESTART_PARTIAL_REQUEST); // WRITE + Doom + STATE_INIT_ENTRY == STATE_CREATE_ENTRY (without an attempt // to Doom the entry again). ResetPartialState(!range_requested_); // Change mode to WRITE after ResetPartialState as that may have changed the // mode to NONE. mode_ = WRITE; TransitionToState(STATE_CREATE_ENTRY); return OK; } void HttpCache::Transaction::ResetPartialState(bool delete_object) { partial_->RestoreHeaders(&custom_request_->extra_headers); DoomPartialEntry(delete_object); if (!delete_object) { // The simplest way to re-initialize partial_ is to create a new object. partial_ = std::make_unique<PartialData>(); // Reset the range header to the original value (http://crbug.com/820599). custom_request_->extra_headers.RemoveHeader(HttpRequestHeaders::kRange); if (partial_->Init(initial_request_->extra_headers)) partial_->SetHeaders(custom_request_->extra_headers); else partial_.reset(); } } void HttpCache::Transaction::ResetNetworkTransaction() { SaveNetworkTransactionInfo(*network_trans_); network_trans_.reset(); } const HttpTransaction* HttpCache::Transaction::network_transaction() const { if (network_trans_) return network_trans_.get(); if (InWriters()) return entry_->writers->network_transaction(); return nullptr; } const HttpTransaction* HttpCache::Transaction::GetOwnedOrMovedNetworkTransaction() const { if (network_trans_) return network_trans_.get(); if (InWriters() && moved_network_transaction_to_writers_) return entry_->writers->network_transaction(); return nullptr; } HttpTransaction* HttpCache::Transaction::network_transaction() { return const_cast<HttpTransaction*>( static_cast<const Transaction*>(this)->network_transaction()); } // Histogram data from the end of 2010 show the following distribution of // response headers: // // Content-Length............... 87% // Date......................... 98% // Last-Modified................ 49% // Etag......................... 19% // Accept-Ranges: bytes......... 25% // Accept-Ranges: none.......... 0.4% // Strong Validator............. 50% // Strong Validator + ranges.... 24% // Strong Validator + CL........ 49% // bool HttpCache::Transaction::CanResume(bool has_data) { // Double check that there is something worth keeping. if (has_data && !entry_->GetEntry()->GetDataSize(kResponseContentIndex)) return false; if (method_ != "GET") return false; // Note that if this is a 206, content-length was already fixed after calling // PartialData::ResponseHeadersOK(). if (response_.headers->GetContentLength() <= 0 || response_.headers->HasHeaderValue("Accept-Ranges", "none") || !response_.headers->HasStrongValidators()) { return false; } return true; } void HttpCache::Transaction::SetResponse(const HttpResponseInfo& response) { response_ = response; if (response_.headers) { DCHECK(request_); response_.vary_data.Init(*request_, *response_.headers); } SyncCacheEntryStatusToResponse(); } void HttpCache::Transaction::SetAuthResponse( const HttpResponseInfo& auth_response) { auth_response_ = auth_response; SyncCacheEntryStatusToResponse(); } void HttpCache::Transaction::UpdateCacheEntryStatus( CacheEntryStatus new_cache_entry_status) { DCHECK_NE(CacheEntryStatus::ENTRY_UNDEFINED, new_cache_entry_status); if (cache_entry_status_ == CacheEntryStatus::ENTRY_OTHER) return; DCHECK(cache_entry_status_ == CacheEntryStatus::ENTRY_UNDEFINED || new_cache_entry_status == CacheEntryStatus::ENTRY_OTHER); cache_entry_status_ = new_cache_entry_status; SyncCacheEntryStatusToResponse(); } void HttpCache::Transaction::SyncCacheEntryStatusToResponse() { if (cache_entry_status_ == CacheEntryStatus::ENTRY_UNDEFINED) return; response_.cache_entry_status = cache_entry_status_; if (auth_response_.headers.get()) { auth_response_.cache_entry_status = cache_entry_status_; } } void HttpCache::Transaction::RecordHistograms() { DCHECK(!recorded_histograms_); recorded_histograms_ = true; if (CacheEntryStatus::ENTRY_UNDEFINED == cache_entry_status_) return; if (!cache_.get() || !cache_->GetCurrentBackend() || cache_->GetCurrentBackend()->GetCacheType() != DISK_CACHE || cache_->mode() != NORMAL || method_ != "GET") { return; } bool is_third_party = false; // Given that cache_entry_status_ is not ENTRY_UNDEFINED, the request must // have started and so request_ should exist. DCHECK(request_); if (request_->possibly_top_frame_origin) { is_third_party = !request_->possibly_top_frame_origin->IsSameOriginWith(request_->url); } std::string mime_type; HttpResponseHeaders* response_headers = GetResponseInfo()->headers.get(); const bool is_no_store = response_headers && response_headers->HasHeaderValue( "cache-control", "no-store"); if (response_headers && response_headers->GetMimeType(&mime_type)) { // Record the cache pattern by resource type. The type is inferred by // response header mime type, which could be incorrect, so this is just an // estimate. if (mime_type == "text/html" && (effective_load_flags_ & LOAD_MAIN_FRAME_DEPRECATED)) { CACHE_STATUS_HISTOGRAMS(".MainFrameHTML"); IS_NO_STORE_HISTOGRAMS(".MainFrameHTML", is_no_store); } else if (mime_type == "text/html") { CACHE_STATUS_HISTOGRAMS(".NonMainFrameHTML"); } else if (mime_type == "text/css") { if (is_third_party) { CACHE_STATUS_HISTOGRAMS(".CSSThirdParty"); } CACHE_STATUS_HISTOGRAMS(".CSS"); } else if (base::StartsWith(mime_type, "image/", base::CompareCase::SENSITIVE)) { int64_t content_length = response_headers->GetContentLength(); if (content_length >= 0 && content_length < 100) { CACHE_STATUS_HISTOGRAMS(".TinyImage"); } else if (content_length >= 100) { CACHE_STATUS_HISTOGRAMS(".NonTinyImage"); } CACHE_STATUS_HISTOGRAMS(".Image"); } else if (base::EndsWith(mime_type, "javascript", base::CompareCase::SENSITIVE) || base::EndsWith(mime_type, "ecmascript", base::CompareCase::SENSITIVE)) { if (is_third_party) { CACHE_STATUS_HISTOGRAMS(".JavaScriptThirdParty"); } CACHE_STATUS_HISTOGRAMS(".JavaScript"); } else if (mime_type.find("font") != std::string::npos) { if (is_third_party) { CACHE_STATUS_HISTOGRAMS(".FontThirdParty"); } CACHE_STATUS_HISTOGRAMS(".Font"); } else if (base::StartsWith(mime_type, "audio/", base::CompareCase::SENSITIVE)) { CACHE_STATUS_HISTOGRAMS(".Audio"); } else if (base::StartsWith(mime_type, "video/", base::CompareCase::SENSITIVE)) { CACHE_STATUS_HISTOGRAMS(".Video"); } } CACHE_STATUS_HISTOGRAMS(""); IS_NO_STORE_HISTOGRAMS("", is_no_store); if (cache_entry_status_ == CacheEntryStatus::ENTRY_OTHER) return; DCHECK(!range_requested_) << "Cache entry status " << cache_entry_status_; DCHECK(!first_cache_access_since_.is_null()); base::TimeTicks now = base::TimeTicks::Now(); base::TimeDelta total_time = now - first_cache_access_since_; UMA_HISTOGRAM_TIMES("HttpCache.AccessToDone", total_time); bool did_send_request = !send_request_since_.is_null(); // It's not clear why `did_send_request` can be true when status is // ENTRY_USED. See https://crbug.com/1409150. // TODO(ricea): Maybe remove ENTRY_USED from the `did_send_request` true // branch once that issue is resolved. DCHECK( (did_send_request && (cache_entry_status_ == CacheEntryStatus::ENTRY_NOT_IN_CACHE || cache_entry_status_ == CacheEntryStatus::ENTRY_VALIDATED || cache_entry_status_ == CacheEntryStatus::ENTRY_UPDATED || cache_entry_status_ == CacheEntryStatus::ENTRY_CANT_CONDITIONALIZE || cache_entry_status_ == CacheEntryStatus::ENTRY_USED)) || (!did_send_request && (cache_entry_status_ == CacheEntryStatus::ENTRY_USED || cache_entry_status_ == CacheEntryStatus::ENTRY_CANT_CONDITIONALIZE))); if (!did_send_request) { if (cache_entry_status_ == CacheEntryStatus::ENTRY_USED) UMA_HISTOGRAM_TIMES("HttpCache.AccessToDone.Used", total_time); return; } base::TimeDelta before_send_time = send_request_since_ - first_cache_access_since_; UMA_HISTOGRAM_TIMES("HttpCache.AccessToDone.SentRequest", total_time); UMA_HISTOGRAM_TIMES("HttpCache.BeforeSend", before_send_time); // TODO(gavinp): Remove or minimize these histograms, particularly the ones // below this comment after we have received initial data. switch (cache_entry_status_) { case CacheEntryStatus::ENTRY_CANT_CONDITIONALIZE: { UMA_HISTOGRAM_TIMES("HttpCache.BeforeSend.CantConditionalize", before_send_time); break; } case CacheEntryStatus::ENTRY_NOT_IN_CACHE: { UMA_HISTOGRAM_TIMES("HttpCache.BeforeSend.NotCached", before_send_time); break; } case CacheEntryStatus::ENTRY_VALIDATED: { UMA_HISTOGRAM_TIMES("HttpCache.BeforeSend.Validated", before_send_time); break; } case CacheEntryStatus::ENTRY_UPDATED: { UMA_HISTOGRAM_TIMES("HttpCache.BeforeSend.Updated", before_send_time); break; } default: // STATUS_UNDEFINED and STATUS_OTHER are explicitly handled earlier in // the function so shouldn't reach here. STATUS_MAX should never be set. // Originally it was asserted that STATUS_USED couldn't happen here, but // it turns out that it can. We don't have histograms for it, so just // ignore it. DCHECK_EQ(cache_entry_status_, CacheEntryStatus::ENTRY_USED); break; } if (!total_disk_cache_read_time_.is_zero()) { base::UmaHistogramTimes("HttpCache.TotalDiskCacheTimePerTransaction.Read", total_disk_cache_read_time_); } if (!total_disk_cache_write_time_.is_zero()) { base::UmaHistogramTimes("HttpCache.TotalDiskCacheTimePerTransaction.Write", total_disk_cache_write_time_); } } bool HttpCache::Transaction::InWriters() const { return entry_ && entry_->writers && entry_->writers->HasTransaction(this); } HttpCache::Transaction::NetworkTransactionInfo::NetworkTransactionInfo() = default; HttpCache::Transaction::NetworkTransactionInfo::~NetworkTransactionInfo() = default; void HttpCache::Transaction::SaveNetworkTransactionInfo( const HttpTransaction& transaction) { DCHECK(!network_transaction_info_.old_network_trans_load_timing); LoadTimingInfo load_timing; if (transaction.GetLoadTimingInfo(&load_timing)) { network_transaction_info_.old_network_trans_load_timing = std::make_unique<LoadTimingInfo>(load_timing); } network_transaction_info_.total_received_bytes += transaction.GetTotalReceivedBytes(); network_transaction_info_.total_sent_bytes += transaction.GetTotalSentBytes(); ConnectionAttempts attempts = transaction.GetConnectionAttempts(); for (const auto& attempt : attempts) network_transaction_info_.old_connection_attempts.push_back(attempt); network_transaction_info_.old_remote_endpoint = IPEndPoint(); transaction.GetRemoteEndpoint(&network_transaction_info_.old_remote_endpoint); } void HttpCache::Transaction::OnIOComplete(int result) { if (waiting_for_cache_io_) { CHECK_NE(result, ERR_CACHE_RACE); // If the HttpCache IO hasn't completed yet, queue the IO result // to be processed when the HttpCache IO completes (or times out). pending_io_result_ = result; } else { DoLoop(result); } } void HttpCache::Transaction::OnCacheIOComplete(int result) { if (waiting_for_cache_io_) { // Handle the case of parallel HttpCache transactions being run against // network IO. waiting_for_cache_io_ = false; cache_pending_ = false; entry_lock_waiting_since_ = TimeTicks(); if (result == OK) { entry_ = new_entry_; if (!cache_->IsWritingInProgress(entry())) { open_entry_last_used_ = entry_->GetEntry()->GetLastUsed(); } } else { // The HttpCache transaction failed or timed out. Bypass the cache in // this case independent of the state of the network IO callback. mode_ = NONE; } new_entry_ = nullptr; // See if there is a pending IO result that completed while the HttpCache // transaction was being processed that now needs to be processed. if (pending_io_result_) { int stored_result = pending_io_result_.value(); pending_io_result_ = absl::nullopt; OnIOComplete(stored_result); } } else { DoLoop(result); } } void HttpCache::Transaction::TransitionToState(State state) { // Ensure that the state is only set once per Do* state. DCHECK(in_do_loop_); DCHECK_EQ(STATE_UNSET, next_state_) << "Next state is " << state; next_state_ = state; } bool HttpCache::Transaction::ShouldDisableCaching( const HttpResponseHeaders& headers) const { // Do not cache no-store content. if (headers.HasHeaderValue("cache-control", "no-store")) { return true; } bool disable_caching = false; if (base::FeatureList::IsEnabled( features::kTurnOffStreamingMediaCachingAlways) || (base::FeatureList::IsEnabled( features::kTurnOffStreamingMediaCachingOnBattery) && IsOnBatteryPower())) { // If the feature is always enabled or enabled while we're running on // battery, and the acquired content is 'large' and not already cached, and // we have a MIME type of audio or video, then disable the cache for this // response. We based our initial definition of 'large' on the disk cache // maximum block size of 16K, which we observed captures the majority of // responses from various MSE implementations. static constexpr int kMaxContentSize = 4096 * 4; std::string mime_type; base::CompareCase insensitive_ascii = base::CompareCase::INSENSITIVE_ASCII; if (headers.GetContentLength() > kMaxContentSize && headers.response_code() != net::HTTP_NOT_MODIFIED && headers.GetMimeType(&mime_type) && (base::StartsWith(mime_type, "video", insensitive_ascii) || base::StartsWith(mime_type, "audio", insensitive_ascii))) { disable_caching = true; MediaCacheStatusResponseHistogram( MediaResponseCacheType::kMediaResponseTransactionCacheDisabled); } else { MediaCacheStatusResponseHistogram( MediaResponseCacheType::kMediaResponseTransactionCacheEnabled); } } return disable_caching; } void HttpCache::Transaction::UpdateSecurityHeadersBeforeForwarding() { // Because of COEP, we need to add CORP to the 304 of resources that set it // previously. It will be blocked in the network service otherwise. std::string stored_corp_header; response_.headers->GetNormalizedHeader("Cross-Origin-Resource-Policy", &stored_corp_header); if (!stored_corp_header.empty()) { new_response_->headers->SetHeader("Cross-Origin-Resource-Policy", stored_corp_header); } return; } void HttpCache::Transaction::BeginDiskCacheAccessTimeCount() { DCHECK(last_disk_cache_access_start_time_.is_null()); if (partial_) { return; } last_disk_cache_access_start_time_ = TimeTicks::Now(); } void HttpCache::Transaction::EndDiskCacheAccessTimeCount( DiskCacheAccessType type) { // We may call this function without actual disk cache access as a result of // state change. if (last_disk_cache_access_start_time_.is_null()) { return; } base::TimeDelta elapsed = TimeTicks::Now() - last_disk_cache_access_start_time_; switch (type) { case DiskCacheAccessType::kRead: total_disk_cache_read_time_ += elapsed; break; case DiskCacheAccessType::kWrite: total_disk_cache_write_time_ += elapsed; break; } last_disk_cache_access_start_time_ = TimeTicks(); } } // namespace net
9d367878d013ef4864502fd005e324776207578d
64c27514d5d29150121ca2b97b43b042f706cd5f
/20181018/BCCOMMAS/main.cpp
f43229472bceb252f876ef10ea34bc75d3fec133
[]
no_license
tienit150198/ACM
f4fdb8eaeccd3db02624c593e56f0fa5d233bee1
a17c9ae1402376167dec5dd49a8aa508ad824285
refs/heads/master
2020-06-12T09:50:50.137304
2019-06-28T13:27:48
2019-06-28T13:27:48
194,261,865
1
0
null
null
null
null
UTF-8
C++
false
false
1,612
cpp
#include <bits/stdc++.h> #include <cstdio> #define ll long long int #define fo(i,a,n) for(i = 0 ; i < n ; i++) cin >> a[i]; #define fo1(i,a,b) for(int i = a ; i < b ; i++) #define out(i,a,n) for(i = 0; i < n ; i++) {cout << a[i] << " ";} cout << endl; using namespace std; #define MOD 5 inline ll isPow(ll n, ll k, ll p = MOD) {ll r = 1; for (; k; k >>= 1LL) {if (k & 1LL) r = r * n % p; n = n * n % p;} return r;} void quickSort(int *array, int low, int high) { int i = low; int j = high; int pivot = array[(i + j) / 2]; int temp; while (i <= j) { while (array[i] < pivot) i++; while (array[j] > pivot) j--; if (i <= j) { temp = array[i]; array[i] = array[j]; array[j] = temp; i++; j--; } } if (j > low) quickSort(array, low, j); if (i < high) quickSort(array, i, high); } unsigned int gcd (unsigned int n1, unsigned int n2) { return (n2 == 0) ? n1 : gcd (n2, n1 % n2); } bool isPrime(int a){ if(a<2) return 0; int tmp = sqrt(a); for(int i = 2 ; i <= tmp ; i++) if(!(a%i)) return 0; return 1; } bool isPrime(ll a){ if(a < 2) return false; ll tmp = sqrt(a); for(ll i = 2 ; i <= tmp ; i++) if(!(a%i)) return false; return true; } int main(){ ios::sync_with_stdio(0); string str; cin >> str; ll count = 0; for(ll i = str.length() - 1 ; i> 0 ; i--){ count++; if(!(count%3)) str.insert(i,","); } cout << str; return 0; }
3155950a03911ae2f192024fe23a9b2016698860
1f8ef1e95ae470e36eaa4d9c4a70c84f8e2f8514
/TestBed/Testbed/testBMP/HandlerBmp/Bmp.cpp
47288a223bbc7d552f38a02d9c8aeb94253271fe
[]
no_license
nhuallpa/random-fiuba-game
0c00a1c652e1b459e723ab8b6c6d75446631ad7c
42bf9c0740393979dce9e146c65dc022abc201af
refs/heads/master
2021-01-10T19:55:46.285979
2014-06-25T22:41:30
2014-06-25T22:41:30
32,127,857
0
0
null
null
null
null
UTF-8
C++
false
false
1,498
cpp
#include "Bmp.h" Bmp::Bmp(char* path) { fileBmp = fopen(path, "rb"); if (fileBmp==NULL) { /* Cargar el archivo por default //fileBmp = fopen(pathDefault, "rb"); if (fileBmp==NULL) //Si el archivo por default tambien es erroneo, sale. { fputs ("Default Bmp File Error",stderr); exit (1); } */ fputs ("File error",stderr); exit (1); } // obtain file size: fseek (fileBmp , 0 , SEEK_END); long lSize = ftell (fileBmp); rewind (fileBmp); unsigned char info[54]; fread(info, sizeof(unsigned char), 54, fileBmp); // read the 54-byte header // extract image height and width from header int width = *(int*)&info[18]; int height = *(int*)&info[22]; int row_padded = (width*3 + 3) & (~3); unsigned char* data = new unsigned char[width*3*row_padded]; fread(data, sizeof(unsigned char), row_padded*height, fileBmp); fclose(fileBmp); aDataBmp = new DataBmp(data,row_padded,height,width); } Bmp::~Bmp() { delete aDataBmp; } bool Bmp::getBit(int posX, int posY) { return aDataBmp->getBit(posX,posY); } list<Position*>* Bmp::getBlackPositions() { return aDataBmp->getBlackPositions(); } bool Bmp::posValid(int posX, int posY) { return aDataBmp->posValid(posX,posY); } int Bmp::getHeight() { return aDataBmp->getHeight(); } int Bmp::getWidth() { return aDataBmp->getWidth(); } void Bmp::showBitmap() { this->aDataBmp->showBitmap(); }
[ "[email protected]@658c8fdb-a348-8819-cda3-7219524bffda" ]
[email protected]@658c8fdb-a348-8819-cda3-7219524bffda
9267beb93b00095507cbbb315f35cc50192655cf
154ad9b7b26b5c52536bbd83cdaf0a359e6125c3
/components/sync/sessions/model_neutral_state.cc
6b8f7d8f770e3117c578be58c236f2ca86362591
[ "BSD-3-Clause" ]
permissive
bopopescu/jstrace
6cc239d57e3a954295b67fa6b8875aabeb64f3e2
2069a7b0a2e507a07cd9aacec4d9290a3178b815
refs/heads/master
2021-06-14T09:08:34.738245
2017-05-03T23:17:06
2017-05-03T23:17:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,393
cc
// 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 "components/sync/sessions/model_neutral_state.h" namespace syncer { namespace sessions { ModelNeutralState::ModelNeutralState() : num_successful_commits(0), num_successful_bookmark_commits(0), num_updates_downloaded_total(0), num_tombstone_updates_downloaded_total(0), num_reflected_updates_downloaded_total(0), num_updates_applied(0), num_encryption_conflicts(0), num_server_conflicts(0), num_hierarchy_conflicts(0), num_local_overwrites(0), num_server_overwrites(0), last_get_key_result(UNSET), last_download_updates_result(UNSET), commit_result(UNSET), items_committed(false) {} ModelNeutralState::ModelNeutralState(const ModelNeutralState& other) = default; ModelNeutralState::~ModelNeutralState() {} bool HasSyncerError(const ModelNeutralState& state) { const bool get_key_error = SyncerErrorIsError(state.last_get_key_result); const bool download_updates_error = SyncerErrorIsError(state.last_download_updates_result); const bool commit_error = SyncerErrorIsError(state.commit_result); return get_key_error || download_updates_error || commit_error; } } // namespace sessions } // namespace syncer
d6d4a74bffdc00ba4a6df9a1f4b8bac01b6af523
697d8dcb9b39ef858cad57d7eced694590821ded
/Equal.cpp
7313122d7e053f51def94e88a5bdfe117469d3e2
[]
no_license
KevinMathewT/Competitive-Programming
e1dcdffd087f8a1d5ca29ae6189ca7fddbdc7754
e7805fe870ad9051d53cafcba4ce109488bc212d
refs/heads/master
2022-02-14T09:37:31.637330
2020-09-26T16:15:26
2020-09-26T16:15:26
147,362,660
4
4
null
2022-02-07T11:13:38
2018-09-04T14:52:29
C++
UTF-8
C++
false
false
1,527
cpp
#include <bits/stdc++.h> #include <iostream> #include <vector> #include <string> #include <algorithm> using namespace std; typedef long long ll; typedef long double ld; typedef vector<ll> vl; typedef vector<vl> vvl; #define F0(i,n) for (ll i = 0; i < n; i++) #define F1(i,n) for (ll i = 1; i <= n; i++) #define CL(a,x) memset(x, a, sizeof(x)); #define SZ(x) ((int)x.size()) void read(ll &x){ cin >> x; } void read(ll &x,ll &y){ cin >> x >> y; } void read(ll &x,ll &y,ll &z){ cin >> x >> y >> z; } void read(ll &x,ll &y,ll &z,ll &w){ cin >> x >> y >> z >> w; } clock_t t_start,t_end; void start_clock(){ t_start = clock(); } void end_clock(){ t_end = clock(); ld timeis = t_end - t_start; printf("\n\nTime taken : %f s", ((float)timeis)/CLOCKS_PER_SEC); } bool IsOdd(ll n){ return n % 2 == 1; } void te(){ ll n; read(n); ll a[n]; for(ll i=0;i<n;i++) read(a[i]); ll mn = LLONG_MAX; for(ll i=0;i<n;i++) mn = min(mn, a[i]); ll finans = LLONG_MAX; for(ll i=0;i<=1000;i++){ ll ans = 0; ll z = (mn-i); for(ll i=0;i<n;i++) ans += ((a[i] - z) / 5) + (((a[i] - z) % 5) / 3) + (((a[i] - z) % 5) % 3); // cout << ans << "\n"; finans = min(finans, ans); } cout << finans << "\n"; } int main() { freopen("input.txt", "r", stdin); //Comment freopen("output.txt", "w", stdout); //this start_clock(); //out. ios::sync_with_stdio(false); //Not cin.tie(NULL); //this. cout.tie(0); //or this. ll T; read(T); while(T--) te(); end_clock(); //This too. return 0; }
a6924292a38b4f488ddd1924a8c5f5f9bfa9ba63
388550fe6530d442ce42b5b5e6efdcfcc5696c86
/src/qt/bitcoinstrings.cpp
a2b5ebbe544b67ff46a6f8c0b92a8617666ada3d
[ "MIT" ]
permissive
tstarcoin/tristarsourcecode
689107a9de53e805ee267986d994bb52646e5854
6c00572ce2aba3e2faa7dc73901960b2fd5991e5
refs/heads/master
2020-12-31T07:56:00.558705
2017-05-03T20:43:55
2017-05-03T20:43:55
85,419,255
0
1
null
null
null
null
UTF-8
C++
false
false
13,606
cpp
#include <QtGlobal> // Automatically generated by extract_strings.py #ifdef __GNUC__ #define UNUSED __attribute__((unused)) #else #define UNUSED #endif static const char UNUSED *bitcoin_strings[] = { QT_TRANSLATE_NOOP("bitcoin-core", "" "%s, you must set a rpcpassword in the configuration file:\n" "%s\n" "It is recommended you use the following random password:\n" "rpcuser=tristarrpc\n" "rpcpassword=%s\n" "(you do not need to remember this password)\n" "The username and password MUST NOT be the same.\n" "If the file does not exist, create it with owner-readable-only file " "permissions.\n" "It is also recommended to set alertnotify so you are notified of problems;\n" "for example: alertnotify=echo %%s | mail -s \"tristar Alert\" [email protected]\n"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:" "@STRENGTH)"), QT_TRANSLATE_NOOP("bitcoin-core", "" "An error occurred while setting up the RPC port %u for listening on IPv4: %s"), QT_TRANSLATE_NOOP("bitcoin-core", "" "An error occurred while setting up the RPC port %u for listening on IPv6, " "falling back to IPv4: %s"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Bind to given address and always listen on it. Use [host]:port notation for " "IPv6"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Cannot obtain a lock on data directory %s. tristar is probably already " "running."), QT_TRANSLATE_NOOP("bitcoin-core", "" "Error: The transaction was rejected! This might happen if some of the coins " "in your wallet were already spent, such as if you used a copy of wallet.dat " "and coins were spent in the copy but not marked as spent here."), QT_TRANSLATE_NOOP("bitcoin-core", "" "Error: This transaction requires a transaction fee of at least %s because of " "its amount, complexity, or use of recently received funds!"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Execute command when a relevant alert is received (%s in cmd is replaced by " "message)"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Execute command when a wallet transaction changes (%s in cmd is replaced by " "TxID)"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Execute command when the best block changes (%s in cmd is replaced by block " "hash)"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Listen for JSON-RPC connections on <port> (default: 42883 or testnet: 142883)"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Number of seconds to keep misbehaving peers from reconnecting (default: " "86400)"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Set maximum size of high-priority/low-fee transactions in bytes (default: " "27000)"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Set the number of script verification threads (up to 16, 0 = auto, <0 = " "leave that many cores free, default: 0)"), QT_TRANSLATE_NOOP("bitcoin-core", "" "This is a pre-release test build - use at your own risk - do not use for " "mining or merchant applications"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Unable to bind to %s on this computer. tristar is probably already running."), QT_TRANSLATE_NOOP("bitcoin-core", "" "Warning: -paytxfee is set very high! This is the transaction fee you will " "pay if you send a transaction."), QT_TRANSLATE_NOOP("bitcoin-core", "" "Warning: Displayed transactions may not be correct! You may need to upgrade, " "or other nodes may need to upgrade."), QT_TRANSLATE_NOOP("bitcoin-core", "" "Warning: Please check that your computer's date and time are correct! If " "your clock is wrong tristar will not work properly."), QT_TRANSLATE_NOOP("bitcoin-core", "" "Warning: error reading wallet.dat! All keys read correctly, but transaction " "data or address book entries might be missing or incorrect."), QT_TRANSLATE_NOOP("bitcoin-core", "" "Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as " "wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect " "you should restore from a backup."), QT_TRANSLATE_NOOP("bitcoin-core", "" "You must set rpcpassword=<password> in the configuration file:\n" "%s\n" "If the file does not exist, create it with owner-readable-only file " "permissions."), QT_TRANSLATE_NOOP("bitcoin-core", "Accept command line and JSON-RPC commands"), QT_TRANSLATE_NOOP("bitcoin-core", "Accept connections from outside (default: 1 if no -proxy or -connect)"), QT_TRANSLATE_NOOP("bitcoin-core", "Add a node to connect to and attempt to keep the connection open"), QT_TRANSLATE_NOOP("bitcoin-core", "Allow DNS lookups for -addnode, -seednode and -connect"), QT_TRANSLATE_NOOP("bitcoin-core", "Allow JSON-RPC connections from specified IP address"), QT_TRANSLATE_NOOP("bitcoin-core", "Attempt to recover private keys from a corrupt wallet.dat"), QT_TRANSLATE_NOOP("bitcoin-core", "tristar version"), QT_TRANSLATE_NOOP("bitcoin-core", "Block creation options:"), QT_TRANSLATE_NOOP("bitcoin-core", "Cannot downgrade wallet"), QT_TRANSLATE_NOOP("bitcoin-core", "Cannot resolve -bind address: '%s'"), QT_TRANSLATE_NOOP("bitcoin-core", "Cannot resolve -externalip address: '%s'"), QT_TRANSLATE_NOOP("bitcoin-core", "Cannot write default address"), QT_TRANSLATE_NOOP("bitcoin-core", "Connect only to the specified node(s)"), QT_TRANSLATE_NOOP("bitcoin-core", "Connect through socks proxy"), QT_TRANSLATE_NOOP("bitcoin-core", "Connect to a node to retrieve peer addresses, and disconnect"), QT_TRANSLATE_NOOP("bitcoin-core", "Corrupted block database detected"), QT_TRANSLATE_NOOP("bitcoin-core", "Discover own IP address (default: 1 when listening and no -externalip)"), QT_TRANSLATE_NOOP("bitcoin-core", "Do you want to rebuild the block database now?"), QT_TRANSLATE_NOOP("bitcoin-core", "Done loading"), QT_TRANSLATE_NOOP("bitcoin-core", "Error initializing block database"), QT_TRANSLATE_NOOP("bitcoin-core", "Error initializing wallet database environment %s!"), QT_TRANSLATE_NOOP("bitcoin-core", "Error loading block database"), QT_TRANSLATE_NOOP("bitcoin-core", "Error loading wallet.dat"), QT_TRANSLATE_NOOP("bitcoin-core", "Error loading wallet.dat: Wallet corrupted"), QT_TRANSLATE_NOOP("bitcoin-core", "Error loading wallet.dat: Wallet requires newer version of tristar"), QT_TRANSLATE_NOOP("bitcoin-core", "Error opening block database"), QT_TRANSLATE_NOOP("bitcoin-core", "Error"), QT_TRANSLATE_NOOP("bitcoin-core", "Error: Disk space is low!"), QT_TRANSLATE_NOOP("bitcoin-core", "Error: Wallet locked, unable to create transaction!"), QT_TRANSLATE_NOOP("bitcoin-core", "Error: system error: "), QT_TRANSLATE_NOOP("bitcoin-core", "Failed to listen on any port. Use -listen=0 if you want this."), QT_TRANSLATE_NOOP("bitcoin-core", "Failed to read block info"), QT_TRANSLATE_NOOP("bitcoin-core", "Failed to read block"), QT_TRANSLATE_NOOP("bitcoin-core", "Failed to sync block index"), QT_TRANSLATE_NOOP("bitcoin-core", "Failed to write block index"), QT_TRANSLATE_NOOP("bitcoin-core", "Failed to write block info"), QT_TRANSLATE_NOOP("bitcoin-core", "Failed to write block"), QT_TRANSLATE_NOOP("bitcoin-core", "Failed to write file info"), QT_TRANSLATE_NOOP("bitcoin-core", "Failed to write to coin database"), QT_TRANSLATE_NOOP("bitcoin-core", "Failed to write transaction index"), QT_TRANSLATE_NOOP("bitcoin-core", "Failed to write undo data"), QT_TRANSLATE_NOOP("bitcoin-core", "Fee per KB to add to transactions you send"), QT_TRANSLATE_NOOP("bitcoin-core", "Find peers using DNS lookup (default: 1 unless -connect)"), QT_TRANSLATE_NOOP("bitcoin-core", "Generate coins (default: 0)"), QT_TRANSLATE_NOOP("bitcoin-core", "Get help for a command"), QT_TRANSLATE_NOOP("bitcoin-core", "How many blocks to check at startup (default: 288, 0 = all)"), QT_TRANSLATE_NOOP("bitcoin-core", "How thorough the block verification is (0-4, default: 3)"), QT_TRANSLATE_NOOP("bitcoin-core", "Imports blocks from external blk000??.dat file"), QT_TRANSLATE_NOOP("bitcoin-core", "Information"), QT_TRANSLATE_NOOP("bitcoin-core", "Insufficient funds"), QT_TRANSLATE_NOOP("bitcoin-core", "Invalid -proxy address: '%s'"), QT_TRANSLATE_NOOP("bitcoin-core", "Invalid -tor address: '%s'"), QT_TRANSLATE_NOOP("bitcoin-core", "Invalid amount for -minrelaytxfee=<amount>: '%s'"), QT_TRANSLATE_NOOP("bitcoin-core", "Invalid amount for -mintxfee=<amount>: '%s'"), QT_TRANSLATE_NOOP("bitcoin-core", "Invalid amount for -paytxfee=<amount>: '%s'"), QT_TRANSLATE_NOOP("bitcoin-core", "Invalid amount"), QT_TRANSLATE_NOOP("bitcoin-core", "List commands"), QT_TRANSLATE_NOOP("bitcoin-core", "Listen for connections on <port> (default: 42881 or testnet: 142881)"), QT_TRANSLATE_NOOP("bitcoin-core", "Loading addresses..."), QT_TRANSLATE_NOOP("bitcoin-core", "Loading block index..."), QT_TRANSLATE_NOOP("bitcoin-core", "Loading wallet..."), QT_TRANSLATE_NOOP("bitcoin-core", "Maintain a full transaction index (default: 0)"), QT_TRANSLATE_NOOP("bitcoin-core", "Maintain at most <n> connections to peers (default: 125)"), QT_TRANSLATE_NOOP("bitcoin-core", "Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)"), QT_TRANSLATE_NOOP("bitcoin-core", "Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)"), QT_TRANSLATE_NOOP("bitcoin-core", "Not enough file descriptors available."), QT_TRANSLATE_NOOP("bitcoin-core", "Only accept block chain matching built-in checkpoints (default: 1)"), QT_TRANSLATE_NOOP("bitcoin-core", "Only connect to nodes in network <net> (IPv4, IPv6 or Tor)"), QT_TRANSLATE_NOOP("bitcoin-core", "Options:"), QT_TRANSLATE_NOOP("bitcoin-core", "Output extra debugging information. Implies all other -debug* options"), QT_TRANSLATE_NOOP("bitcoin-core", "Output extra network debugging information"), QT_TRANSLATE_NOOP("bitcoin-core", "Password for JSON-RPC connections"), QT_TRANSLATE_NOOP("bitcoin-core", "Prepend debug output with timestamp"), QT_TRANSLATE_NOOP("bitcoin-core", "Rebuild block chain index from current blk000??.dat files"), QT_TRANSLATE_NOOP("bitcoin-core", "Rescan the block chain for missing wallet transactions"), QT_TRANSLATE_NOOP("bitcoin-core", "Rescanning..."), QT_TRANSLATE_NOOP("bitcoin-core", "Run in the background as a daemon and accept commands"), QT_TRANSLATE_NOOP("bitcoin-core", "SSL options: (see the tristar Wiki for SSL setup instructions)"), QT_TRANSLATE_NOOP("bitcoin-core", "Select the version of socks proxy to use (4-5, default: 5)"), QT_TRANSLATE_NOOP("bitcoin-core", "Send command to -server or tristard"), QT_TRANSLATE_NOOP("bitcoin-core", "Send commands to node running on <ip> (default: 127.0.0.1)"), QT_TRANSLATE_NOOP("bitcoin-core", "Send trace/debug info to console instead of debug.log file"), QT_TRANSLATE_NOOP("bitcoin-core", "Send trace/debug info to debugger"), QT_TRANSLATE_NOOP("bitcoin-core", "Server certificate file (default: server.cert)"), QT_TRANSLATE_NOOP("bitcoin-core", "Server private key (default: server.pem)"), QT_TRANSLATE_NOOP("bitcoin-core", "Set database cache size in megabytes (default: 25)"), QT_TRANSLATE_NOOP("bitcoin-core", "Set key pool size to <n> (default: 100)"), QT_TRANSLATE_NOOP("bitcoin-core", "Set maximum block size in bytes (default: 250000)"), QT_TRANSLATE_NOOP("bitcoin-core", "Set minimum block size in bytes (default: 0)"), QT_TRANSLATE_NOOP("bitcoin-core", "Set the number of threads to service RPC calls (default: 4)"), QT_TRANSLATE_NOOP("bitcoin-core", "Shrink debug.log file on client startup (default: 1 when no -debug)"), QT_TRANSLATE_NOOP("bitcoin-core", "Signing transaction failed"), QT_TRANSLATE_NOOP("bitcoin-core", "Specify configuration file (default: tristar.conf)"), QT_TRANSLATE_NOOP("bitcoin-core", "Specify connection timeout in milliseconds (default: 5000)"), QT_TRANSLATE_NOOP("bitcoin-core", "Specify data directory"), QT_TRANSLATE_NOOP("bitcoin-core", "Specify pid file (default: tristard.pid)"), QT_TRANSLATE_NOOP("bitcoin-core", "Specify your own public address"), QT_TRANSLATE_NOOP("bitcoin-core", "System error: "), QT_TRANSLATE_NOOP("bitcoin-core", "This help message"), QT_TRANSLATE_NOOP("bitcoin-core", "Threshold for disconnecting misbehaving peers (default: 100)"), QT_TRANSLATE_NOOP("bitcoin-core", "To use the %s option"), QT_TRANSLATE_NOOP("bitcoin-core", "Transaction amount too small"), QT_TRANSLATE_NOOP("bitcoin-core", "Transaction amounts must be positive"), QT_TRANSLATE_NOOP("bitcoin-core", "Transaction too large"), QT_TRANSLATE_NOOP("bitcoin-core", "Unable to bind to %s on this computer (bind returned error %d, %s)"), QT_TRANSLATE_NOOP("bitcoin-core", "Unknown -socks proxy version requested: %i"), QT_TRANSLATE_NOOP("bitcoin-core", "Unknown network specified in -onlynet: '%s'"), QT_TRANSLATE_NOOP("bitcoin-core", "Upgrade wallet to latest format"), QT_TRANSLATE_NOOP("bitcoin-core", "Usage:"), QT_TRANSLATE_NOOP("bitcoin-core", "Use OpenSSL (https) for JSON-RPC connections"), QT_TRANSLATE_NOOP("bitcoin-core", "Use UPnP to map the listening port (default: 0)"), QT_TRANSLATE_NOOP("bitcoin-core", "Use UPnP to map the listening port (default: 1 when listening)"), QT_TRANSLATE_NOOP("bitcoin-core", "Use proxy to reach tor hidden services (default: same as -proxy)"), QT_TRANSLATE_NOOP("bitcoin-core", "Use the test network"), QT_TRANSLATE_NOOP("bitcoin-core", "Username for JSON-RPC connections"), QT_TRANSLATE_NOOP("bitcoin-core", "Verifying blocks..."), QT_TRANSLATE_NOOP("bitcoin-core", "Verifying wallet..."), QT_TRANSLATE_NOOP("bitcoin-core", "Wallet needed to be rewritten: restart tristar to complete"), QT_TRANSLATE_NOOP("bitcoin-core", "Warning"), QT_TRANSLATE_NOOP("bitcoin-core", "Warning: This version is obsolete, upgrade required!"), QT_TRANSLATE_NOOP("bitcoin-core", "You need to rebuild the database using -reindex to change -txindex"), QT_TRANSLATE_NOOP("bitcoin-core", "wallet.dat corrupt, salvage failed"), };
5d79fc9eb95f13561f828cdcef61ebeb602e3abb
69fe376f63cf4347bbda41d69c2d2964e53188d5
/Common/PJNMD5.h
faf83bda5fc3b09788c042ab6c861114ed0aca74
[ "Apache-2.0" ]
permissive
radtek/IMClassic
d71875ecb7fcff65383fe56c8512d060ca09c099
419721dacda467f796842c1a43a3bb90467f82fc
refs/heads/master
2020-05-29T14:05:56.423961
2018-01-06T14:43:17
2018-01-06T14:43:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,480
h
/* Module : PJNMD5.H Purpose: Defines the interface for some MFC class which encapsulate calculating MD5 hashes and HMACS using the MS CryptoAPI Created: PJN / 23-04-2005 History: PJN / 18-05-2005 1. Fixed a compiler warning when compiled using Visual Studio .NET 2003. Thanks to Alexey Kuznetsov for reporting this issue. PJN / 29-09-2005 1. Format method now allows you to specify an uppercase or lower case string for the hash. This is necessary since the CRAM-MD5 authentication mechanism requires a lowercase MD5 hash. Thanks to Jian Peng for reporting this issue. Copyright (c) 2005 - 2010 by PJ Naughter (Web: www.naughter.com, Email: [email protected]) All rights reserved. Copyright / Usage Details: You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) when your product is released in binary form. You are allowed to modify the source code in any way you want except you cannot modify the copyright details at the top of each module. If you want to distribute source code with your application, then you are only allowed to distribute versions released by the author. This is to maintain a single distribution point for the source code. */ ////////////////////////////// Macros / Defines /////////////////////////////// #pragma once #ifndef __PJNMD5_H__ #define __PJNMD5_H__ ////////////////////////////// Includes /////////////////////////////////////// #ifndef __WINCRYPT_H__ #pragma message("To avoid this message, put wincrypt.h in your pre compiled header (usually stdafx.h)") #include <wincrypt.h> #endif ////////////////////////////// Classes //////////////////////////////////////// ////// A simple wrapper class which contains a MD5 hash i.e. a 16 byte blob /// class CPJNMD5Hash { public: //Constructors / Destructors CPJNMD5Hash() { memset(m_byHash, 0, sizeof(m_byHash)); } //methods operator BYTE*() { return m_byHash; }; CString Format(BOOL bUppercase) { //What will be the return value CString sRet; LPTSTR pString = sRet.GetBuffer(33); DWORD i; for (i=0; i<16; i++) { int nChar = (m_byHash[i] & 0xF0) >> 4; if (nChar <= 9) pString[i*2] = static_cast<TCHAR>(nChar + _T('0')); else pString[i*2] = static_cast<TCHAR>(nChar - 10 + (bUppercase ? _T('A') : _T('a'))); nChar = m_byHash[i] & 0x0F; if (nChar <= 9) pString[i*2 + 1] = static_cast<TCHAR>(nChar + _T('0')); else pString[i*2 + 1] = static_cast<TCHAR>(nChar - 10 + (bUppercase ? _T('A') : _T('a'))); } pString[i*2] = _T('\0'); sRet.ReleaseBuffer(); return sRet; } //Member variables BYTE m_byHash[16]; }; ////// Class which calculates MD5 Hashes and MD5 HMACS //////////////////////// class CPJNMD5 { public: //Constructors / Destructors CPJNMD5() { //Acquire the RSA CSP m_hProv = NULL; CryptAcquireContext(&m_hProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT); } virtual ~CPJNMD5() { //Release the CSP if (m_hProv) CryptReleaseContext(m_hProv, 0); } //Methods //Simple MD5 hash function which hashes a blob of data and returns //the results encapsulated in the "hash" parameter BOOL Hash(const BYTE* pbyData, DWORD dwDataSize, CPJNMD5Hash& hash) { //Call the Helper Hash function which returns a HCRYPTHASH handle //which contains the hash HCRYPTHASH hHash = NULL; BOOL bSuccess = Hash(pbyData, dwDataSize, hHash); if (bSuccess) { //Get the actual hash value DWORD dwHashSize = sizeof(hash); bSuccess = CryptGetHashParam(hHash, HP_HASHVAL, hash, &dwHashSize, 0); } //Free up the hash handle now that we are finished with it if (hHash) CryptDestroyHash(hHash); return bSuccess; } //Function which returns a hash encoded as a HCRYPTHASH. If hHash is //NULL on entry then a new HCRYPTHASH is created. If hHash is non-null //then this existing hash is used and the data to hash is included into //the current hash. The client is responsible for freeing the hash handle BOOL Hash(const BYTE* pbyData, DWORD dwDataSize, HCRYPTHASH& hHash) //If you get a compilation error on this line, then you need to download, install and configure the MS Platform SDK if you are compiling the code under Visual C++ 6 { //Create the hash object if required to if (hHash == NULL) if (!CryptCreateHash(m_hProv, CALG_MD5, 0, 0, &hHash)) return FALSE; //Hash in the data return CryptHashData(hHash, pbyData, dwDataSize, 0); } //Function which calculates a keyed MD5 HMAC according to RFC 2104 BOOL HMAC(const BYTE* pbyData, DWORD dwDataSize, const BYTE* pbyKey, DWORD dwKeySize, CPJNMD5Hash& hash) { //if key is longer than 64 bytes then reset it to the MD5 hash of the key const BYTE* pbyLocalKey; DWORD dwLocalKeySize; CPJNMD5Hash keyHash; if (dwKeySize > 64) { if (!Hash(pbyKey, dwKeySize, keyHash)) return FALSE; dwLocalKeySize = sizeof(keyHash); pbyLocalKey = keyHash; } else { dwLocalKeySize = dwKeySize; pbyLocalKey = pbyKey; } //start out by storing key in pads BYTE k_ipad[64]; //KEY XORd with ipad memset(k_ipad, 0, 64); BYTE k_opad[64]; //KEY XORd with opad memset(k_opad, 0, 64); memcpy_s(k_ipad, sizeof(k_ipad), pbyLocalKey, dwLocalKeySize); memcpy_s(k_opad, sizeof(k_opad), pbyLocalKey, dwLocalKeySize); //XOR key with ipad and opad values for (int i=0; i<64; i++) { k_ipad[i] ^= 0x36; k_opad[i] ^= 0x5c; } //perform inner MD5 HCRYPTHASH hInnerHash = NULL; if (!Hash(k_ipad, 64, hInnerHash)) { //Free up the hash before we return if (hInnerHash) CryptDestroyHash(hInnerHash); return FALSE; } if (!Hash(pbyData, dwDataSize, hInnerHash)) { //Free up the hash before we return CryptDestroyHash(hInnerHash); return FALSE; } //Get the inner hash result CPJNMD5Hash InnerHash; DWORD dwHashSize = sizeof(InnerHash); if (!CryptGetHashParam(hInnerHash, HP_HASHVAL, InnerHash, &dwHashSize, 0)) { //Free up the hash before we return CryptDestroyHash(hInnerHash); return FALSE; } //Free up the inner hash now that we are finished with it CryptDestroyHash(hInnerHash); //Perform outter MD5 HCRYPTHASH hOuterHash = NULL; if (!Hash(k_opad, 64, hOuterHash)) { //Free up the hash before we return if (hOuterHash) CryptDestroyHash(hOuterHash); return FALSE; } if (!Hash(InnerHash, sizeof(InnerHash), hOuterHash)) { //Free up the hash before we return CryptDestroyHash(hOuterHash); return FALSE; } //Finally get the hash result dwHashSize = sizeof(hash); BOOL bSuccess = CryptGetHashParam(hOuterHash, HP_HASHVAL, hash, &dwHashSize, 0); //Free up the hash before we return CryptDestroyHash(hOuterHash); return bSuccess; } protected: //Member variables HCRYPTPROV m_hProv; }; #endif //__PJNMD5_H__
dcc07ccb2f160dd7810961b9fe067d20d765ae1a
484145ec441345903e32301887c2a51925a346e2
/Zap/cocos2d-x-2.1.4/Zap/Classes/Utilities/GameManager.cpp
3b80a456ce40398b73002bd340bc3cafe0262305
[ "MIT" ]
permissive
seanfoo73/alns-zap
5a34b6026fe55520baa425b724a3450004d0b6dd
af8f75e73dda2f2584b00d46a7d9818249f6edb9
refs/heads/master
2020-05-30T03:29:17.172419
2014-03-19T00:51:57
2014-03-19T00:51:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,662
cpp
#include "GameManager.h" #include "../Scenes/GameWorldScene.h" #include "cocos2d.h" /* defines NULL */ using namespace cocos2d; GameManager* GameManager::m_pInstance = NULL; GameManager* GameManager::Instance() { if( !m_pInstance ) { m_pInstance = new GameManager; m_pInstance->init(); } return m_pInstance; } bool GameManager::init() { m_CurrentChainType = BugType_None; m_BugsDeleted = 0; m_NumReachedOutOfBounds = 0; m_Score = 0; this->initData(); m_Bugs = new std::vector<BugBase*>(); m_BugsToDelete = new std::vector<BugBase*>(); m_BugsHitByLightning = new std::vector<BugBase*>(); return true; } void GameManager::initData() { m_GameDuration = 60.0f; m_MaxNextBugTime = 2.0f; m_MaxBlueChainLength = 10; m_MaxRedChainLength = 10; m_MaxGreenChainLength = 5; m_BaseBluePoints = 10; m_BaseRedPoints = 30; m_BaseGreenPoints = 20; m_LightningRecalcInterval = 0.5f; } void GameManager::setGameLayer( cocos2d::CCLayer* gameLayer ) { m_pGameLayer = gameLayer; } void GameManager::AddBugHit( BugBase* bug ) { if( dynamic_cast<BlueBug*>(bug) ) { if( m_CurrentChainType == BugType_None ) { m_CurrentChainType = BugType_Blue; bug->SetPointValue( m_BaseBluePoints*m_BugsHitByLightning->size() ); } else if( m_CurrentChainType == BugType_Blue ) { bug->SetPointValue( m_BaseBluePoints*m_BugsHitByLightning->size() ); } else { bug->SetPointValue( m_BaseBluePoints ); DestroyChain(); m_CurrentChainType = BugType_None; } } else if( dynamic_cast<RedBug*>(bug) ) { if( m_CurrentChainType == BugType_None ) { m_CurrentChainType = BugType_Red; bug->SetPointValue( m_BaseRedPoints ); } else if( m_CurrentChainType == BugType_Red ) { bug->SetPointValue( m_BaseRedPoints ); } else { bug->SetPointValue( m_BaseRedPoints ); DestroyChain(); m_CurrentChainType = BugType_None; } } else if( dynamic_cast<GreenBug*>(bug) ) { if( m_CurrentChainType == BugType_None ) { bug->SetPointValue( m_BaseGreenPoints ); m_CurrentChainType = BugType_Green; } else if( m_CurrentChainType == BugType_Green ) { bug->SetPointValue( m_BaseGreenPoints ); } else { bug->SetPointValue( m_BaseGreenPoints ); DestroyChain(); m_CurrentChainType = BugType_None; } } } const char* GameManager::GetChainTypeString() { if( m_CurrentChainType == BugType_Blue ) { return "BugType_Blue"; } else if( m_CurrentChainType == BugType_Red ) { return "BugType_Red"; } else if( m_CurrentChainType == BugType_Green ) { return "BugType_Green"; } else { return "BugType_None"; } } void GameManager::DestroyChain() { int numToDestroy = m_BugsHitByLightning->size(); BugBase* bugToDelete; CalculateChainPoints(); for( int i = 0; i < numToDestroy; i++ ) { bugToDelete = (*m_BugsHitByLightning)[0]; m_BugsHitByLightning->erase(m_BugsHitByLightning->begin()); bugToDelete->SetBugState( BugBase::BugState_Dead_KILLED ); m_BugsToDelete->push_back( bugToDelete ); } m_CurrentChainType = BugType_None; } void GameManager::CalculateChainPoints() { int numBlueBugs = 0; int numRedBugs = 0; int numGreenBugs = 0; for( int i = 0; i < m_BugsHitByLightning->size(); i++ ) { if( ReturnBugType( (*m_BugsHitByLightning)[i] ) == BugType_Blue ) { numBlueBugs++; } else if( ReturnBugType( (*m_BugsHitByLightning)[i] ) == BugType_Red ) { numRedBugs++; } else if( ReturnBugType( (*m_BugsHitByLightning)[i] ) == BugType_Green ) { numGreenBugs++; } m_Score += (*m_BugsHitByLightning)[i]->GetPointValue(); } /**/ if( numBlueBugs >= m_MaxBlueChainLength ) { ApplyBlueBonus(); } else if( numRedBugs >= m_MaxRedChainLength ) { ApplyRedBonus(); } else if( numGreenBugs >= m_MaxGreenChainLength ) { ApplyGreenBonus(); } /**/ } void GameManager::ApplyBlueBonus() { //Need to think of a bonus m_Score += 1000; CCSize size = CCDirector::sharedDirector()->getWinSize(); char buf[64]; sprintf( buf, "Chain Bonus: 1000 points!" ); if( m_pGameLayer ) { static_cast<GameWorld*>(m_pGameLayer)->addFloatingText( buf, size.width/2, size.height/4, 48.0f, 2.0f ); } } void GameManager::ApplyRedBonus() { //score x2 m_Score *= 2; CCSize size = CCDirector::sharedDirector()->getWinSize(); char buf[64]; sprintf( buf, "Chain Bonus: Score x2!" ); if( m_pGameLayer ) { static_cast<GameWorld*>(m_pGameLayer)->addFloatingText( buf, size.width/2, size.height/4, 48.0f, 2.0f ); } } void GameManager::ApplyGreenBonus() { //Grant extra time if( m_pGameLayer ) static_cast<GameWorld*>(m_pGameLayer)->addGameTime( 5.0f ); CCSize size = CCDirector::sharedDirector()->getWinSize(); char buf[64]; sprintf( buf, "Chain Bonus: +5 sec!" ); if( m_pGameLayer ) { static_cast<GameWorld*>(m_pGameLayer)->addFloatingText( buf, size.width/2, size.height/4, 48.0f, 2.0f ); } } enum GameManager::EBugType GameManager::ReturnBugType( BugBase* bug ) { if( dynamic_cast<BlueBug*>(bug) ) { return BugType_Blue; } else if( dynamic_cast<RedBug*>(bug) ) { return BugType_Red; } else if( dynamic_cast<GreenBug*>(bug) ) { return BugType_Green; } else { return BugType_None; } } GameManager::~GameManager() { delete m_Bugs; delete m_BugsToDelete; delete m_BugsHitByLightning; }
bc53804ae97b1499c29d191e8d265814021bf36c
abe2c978f240a5508f6ec842c9e7a6ab50d4f205
/libs/corelib/futureprogress.cpp
1c246f6eba1b0166a69b2257e1a6cc9e1cf8a71d
[]
no_license
kai66673/QWorkNew
48cdb76edafc36468a9b89a1509db8511f890a42
de485ae2fff0fa2d0c5274a5c51712896d98c311
refs/heads/master
2021-08-26T00:33:25.273835
2021-08-25T18:13:13
2021-08-25T18:13:13
98,813,428
1
0
null
null
null
null
UTF-8
C++
false
false
10,837
cpp
/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** **************************************************************************/ #include "futureprogress.h" #include "progressbar.h" #include <QtCore/QFutureWatcher> #include <QtCore/QTimer> #include <QtCore/QCoreApplication> #include <QtCore/QPropertyAnimation> #include <QtCore/QSequentialAnimationGroup> #include <QColor> #include <QVBoxLayout> #include <QMenu> #include <QProgressBar> #include <QHBoxLayout> #include <QPainter> #include <QMouseEvent> #include <utils/stylehelper.h> const int notificationTimeout = 8000; const int shortNotificationTimeout = 1000; namespace Core { namespace Internal { class FadeWidgetHack : public QWidget { Q_OBJECT Q_PROPERTY(float opacity READ opacity WRITE setOpacity) public: FadeWidgetHack(QWidget *parent):QWidget(parent), m_opacity(0){ setAttribute(Qt::WA_TransparentForMouseEvents); } void paintEvent(QPaintEvent *); void setOpacity(float o) { m_opacity = o; update(); } float opacity() const { return m_opacity; } private: float m_opacity; }; void FadeWidgetHack::paintEvent(QPaintEvent *) { if (m_opacity == 0) return; QPainter p(this); p.setOpacity(m_opacity); if (m_opacity > 0) Utils::StyleHelper::verticalGradient(&p, rect(), rect()); } } // namespace Internal struct FutureProgressPrivate { explicit FutureProgressPrivate(FutureProgress *q); void tryToFadeAway(); QFutureWatcher<void> m_watcher; Internal::ProgressBar *m_progress; QWidget *m_widget; QHBoxLayout *m_widgetLayout; QString m_type; FutureProgress::KeepOnFinishType m_keep; bool m_waitingForUserInteraction; Internal::FadeWidgetHack *m_faderWidget; FutureProgress *m_q; bool m_isFading; }; FutureProgressPrivate::FutureProgressPrivate(FutureProgress *q) : m_progress(new Internal::ProgressBar), m_widget(0), m_widgetLayout(new QHBoxLayout), m_keep(FutureProgress::DontKeepOnFinish), m_waitingForUserInteraction(false), m_faderWidget(new Internal::FadeWidgetHack(q)), m_q(q), m_isFading(false) { } /*! \mainclass \class Core::FutureProgress \brief The FutureProgress class is used to adapt the appearance of progress indicators that were created through the ProgressManager class. Use the instance of this class that was returned by ProgressManager::addTask() to define a widget that should be shown below the progress bar, or to change the progress title. Also use it to react on the event that the user clicks on the progress indicator (which can be used to e.g. open a more detailed view, or the results of the task). */ /*! \fn void FutureProgress::clicked() Connect to this signal to get informed when the user clicks on the progress indicator. */ /*! \fn void FutureProgress::finished() Another way to get informed when the task has finished. */ /*! \fn QWidget FutureProgress::widget() const Returns the custom widget that is shown below the progress indicator. */ /*! \fn FutureProgress::FutureProgress(QWidget *parent) \internal */ FutureProgress::FutureProgress(QWidget *parent) : QWidget(parent), d(new FutureProgressPrivate(this)) { QVBoxLayout *layout = new QVBoxLayout; setLayout(layout); layout->addWidget(d->m_progress); layout->setMargin(0); layout->setSpacing(0); layout->addLayout(d->m_widgetLayout); d->m_widgetLayout->setContentsMargins(7, 0, 7, 2); d->m_widgetLayout->setSpacing(0); connect(&d->m_watcher, SIGNAL(started()), this, SLOT(setStarted())); connect(&d->m_watcher, SIGNAL(finished()), this, SLOT(setFinished())); connect(&d->m_watcher, SIGNAL(progressRangeChanged(int,int)), this, SLOT(setProgressRange(int,int))); connect(&d->m_watcher, SIGNAL(progressValueChanged(int)), this, SLOT(setProgressValue(int))); connect(&d->m_watcher, SIGNAL(progressTextChanged(const QString&)), this, SLOT(setProgressText(const QString&))); connect(d->m_progress, SIGNAL(clicked()), this, SLOT(cancel())); } /*! \fn FutureProgress::~FutureProgress() \internal */ FutureProgress::~FutureProgress() { if (d->m_widget) delete d->m_widget; } /*! \fn void FutureProgress::setWidget(QWidget *widget) Sets the \a widget to show below the progress bar. This will be destroyed when the progress indicator is destroyed. Default is to show no widget below the progress indicator. */ void FutureProgress::setWidget(QWidget *widget) { if (d->m_widget) delete d->m_widget; QSizePolicy sp = widget->sizePolicy(); sp.setHorizontalPolicy(QSizePolicy::Ignored); widget->setSizePolicy(sp); d->m_widget = widget; if (d->m_widget) d->m_widgetLayout->addWidget(d->m_widget); } /*! \fn void FutureProgress::setTitle(const QString &title) Changes the \a title of the progress indicator. */ void FutureProgress::setTitle(const QString &title) { d->m_progress->setTitle(title); } /*! \fn QString FutureProgress::title() const Returns the title of the progress indicator. */ QString FutureProgress::title() const { return d->m_progress->title(); } void FutureProgress::cancel() { d->m_watcher.future().cancel(); } void FutureProgress::updateToolTip(const QString &text) { setToolTip("<b>" + title() + "</b><br>" + text); } void FutureProgress::setStarted() { d->m_progress->reset(); d->m_progress->setError(false); d->m_progress->setRange(d->m_watcher.progressMinimum(), d->m_watcher.progressMaximum()); d->m_progress->setValue(d->m_watcher.progressValue()); } bool FutureProgress::eventFilter(QObject *, QEvent *e) { if (d->m_keep != KeepOnFinish && d->m_waitingForUserInteraction && (e->type() == QEvent::MouseMove || e->type() == QEvent::KeyPress)) { qApp->removeEventFilter(this); QTimer::singleShot(notificationTimeout, this, SLOT(fadeAway())); } return false; } void FutureProgress::setFinished() { updateToolTip(d->m_watcher.future().progressText()); // Special case for concurrent jobs that don't use QFutureInterface to report progress if (d->m_watcher.progressMinimum() == 0 && d->m_watcher.progressMaximum() == 0) { d->m_progress->setRange(0, 1); d->m_progress->setValue(1); } if (d->m_watcher.future().isCanceled()) { d->m_progress->setError(true); } else { d->m_progress->setError(false); } emit finished(); d->tryToFadeAway(); } void FutureProgressPrivate::tryToFadeAway() { if (m_isFading) return; if (m_keep == FutureProgress::KeepOnFinishTillUserInteraction) { m_waitingForUserInteraction = true; //eventfilter is needed to get user interaction //events to start QTimer::singleShot later qApp->installEventFilter(m_q); m_isFading = true; } else if (m_keep == FutureProgress::DontKeepOnFinish && !m_progress->hasError()) { QTimer::singleShot(shortNotificationTimeout, m_q, SLOT(fadeAway())); m_isFading = true; } } void FutureProgress::setProgressRange(int min, int max) { d->m_progress->setRange(min, max); } void FutureProgress::setProgressValue(int val) { d->m_progress->setValue(val); } void FutureProgress::setProgressText(const QString &text) { updateToolTip(text); } /*! \fn void FutureProgress::setFuture(const QFuture<void> &future) \internal */ void FutureProgress::setFuture(const QFuture<void> &future) { d->m_watcher.setFuture(future); } /*! \fn QFuture<void> FutureProgress::future() const Returns a QFuture object that represents this running task. */ QFuture<void> FutureProgress::future() const { return d->m_watcher.future(); } /*! \fn void FutureProgress::mousePressEvent(QMouseEvent *event) \internal */ void FutureProgress::mousePressEvent(QMouseEvent *event) { if (event->button() == Qt::LeftButton) emit clicked(); QWidget::mousePressEvent(event); } void FutureProgress::resizeEvent(QResizeEvent *) { d->m_faderWidget->setGeometry(rect()); } /*! \fn bool FutureProgress::hasError() const Returns the error state of this progress indicator. */ bool FutureProgress::hasError() const { return d->m_progress->hasError(); } void FutureProgress::fadeAway() { d->m_faderWidget->raise(); QSequentialAnimationGroup *group = new QSequentialAnimationGroup(this); QPropertyAnimation *animation = new QPropertyAnimation(d->m_faderWidget, "opacity"); animation->setDuration(600); animation->setEndValue(1.0); group->addAnimation(animation); animation = new QPropertyAnimation(this, "maximumHeight"); animation->setDuration(120); animation->setEasingCurve(QEasingCurve::InCurve); animation->setStartValue(sizeHint().height()); animation->setEndValue(0.0); group->addAnimation(animation); group->start(QAbstractAnimation::DeleteWhenStopped); connect(group, SIGNAL(finished()), this, SIGNAL(removeMe())); } void FutureProgress::setType(const QString &type) { d->m_type = type; } QString FutureProgress::type() const { return d->m_type; } void FutureProgress::setKeepOnFinish(KeepOnFinishType keepType) { if (d->m_keep == keepType) { return; } d->m_keep = keepType; //if it is not finished tryToFadeAway is called by setFinished at the end if (d->m_watcher.isFinished()) { d->tryToFadeAway(); } } bool FutureProgress::keepOnFinish() const { return d->m_keep; } QWidget *FutureProgress::widget() const { return d->m_widget; } } // namespace Core #include "futureprogress.moc"
5063808e29e99f547cf0ce9fe398a68a484c9c50
7d530bec74c03cc39af245975c5d0a91a7c10128
/src/qt/editaddressdialog.cpp
810e9f8309abea2882d47c8e9579e0059ea1d570
[ "MIT" ]
permissive
gravitondev/graviton
b33dc99e60507374e7891d7b6309eb68193c206c
02984b0447c6570cb40e1f1a7f9d1b2e30dc5d76
refs/heads/master
2020-12-24T13:21:09.064340
2015-06-15T20:15:50
2015-06-15T20:15:50
34,936,558
1
2
null
2015-05-22T12:04:07
2015-05-02T05:17:49
C++
UTF-8
C++
false
false
4,277
cpp
#include "editaddressdialog.h" #include "ui_editaddressdialog.h" #include "addresstablemodel.h" #include "guiutil.h" #include <QDataWidgetMapper> #include <QMessageBox> EditAddressDialog::EditAddressDialog(Mode mode, QWidget *parent) : QDialog(parent), ui(new Ui::EditAddressDialog), mapper(0), mode(mode), model(0) { ui->setupUi(this); GUIUtil::setupAddressWidget(ui->addressEdit, this); switch(mode) { case NewReceivingAddress: setWindowTitle(tr("New receiving address")); ui->addressEdit->setEnabled(false); ui->addressEdit->setVisible(false); ui->stealthCB->setEnabled(true); ui->stealthCB->setVisible(true); break; case NewSendingAddress: setWindowTitle(tr("New sending address")); ui->stealthCB->setVisible(false); break; case EditReceivingAddress: setWindowTitle(tr("Edit receiving address")); ui->addressEdit->setEnabled(false); ui->addressEdit->setVisible(true); ui->stealthCB->setEnabled(false); ui->stealthCB->setVisible(true); break; case EditSendingAddress: setWindowTitle(tr("Edit sending address")); ui->stealthCB->setVisible(false); break; } mapper = new QDataWidgetMapper(this); mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit); } EditAddressDialog::~EditAddressDialog() { delete ui; } void EditAddressDialog::setModel(AddressTableModel *model) { this->model = model; if(!model) return; mapper->setModel(model); mapper->addMapping(ui->labelEdit, AddressTableModel::Label); mapper->addMapping(ui->addressEdit, AddressTableModel::Address); mapper->addMapping(ui->stealthCB, AddressTableModel::Type); } void EditAddressDialog::loadRow(int row) { mapper->setCurrentIndex(row); } bool EditAddressDialog::saveCurrentRow() { if(!model) return false; switch(mode) { case NewReceivingAddress: case NewSendingAddress: { int typeInd = ui->stealthCB->isChecked() ? AddressTableModel::AT_Stealth : AddressTableModel::AT_Normal; address = model->addRow( mode == NewSendingAddress ? AddressTableModel::Send : AddressTableModel::Receive, ui->labelEdit->text(), ui->addressEdit->text(), typeInd); } break; case EditReceivingAddress: case EditSendingAddress: if(mapper->submit()) { address = ui->addressEdit->text(); } break; } return !address.isEmpty(); } void EditAddressDialog::accept() { if(!model) return; if(!saveCurrentRow()) { switch(model->getEditStatus()) { case AddressTableModel::OK: // Failed with unknown reason. Just reject. break; case AddressTableModel::NO_CHANGES: // No changes were made during edit operation. Just reject. break; case AddressTableModel::INVALID_ADDRESS: QMessageBox::warning(this, windowTitle(), tr("The entered address \"%1\" is not a valid Graviton address.").arg(ui->addressEdit->text()), QMessageBox::Ok, QMessageBox::Ok); break; case AddressTableModel::DUPLICATE_ADDRESS: QMessageBox::warning(this, windowTitle(), tr("The entered address \"%1\" is already in the address book.").arg(ui->addressEdit->text()), QMessageBox::Ok, QMessageBox::Ok); break; case AddressTableModel::WALLET_UNLOCK_FAILURE: QMessageBox::critical(this, windowTitle(), tr("Could not unlock wallet."), QMessageBox::Ok, QMessageBox::Ok); break; case AddressTableModel::KEY_GENERATION_FAILURE: QMessageBox::critical(this, windowTitle(), tr("New key generation failed."), QMessageBox::Ok, QMessageBox::Ok); break; } return; } QDialog::accept(); } QString EditAddressDialog::getAddress() const { return address; } void EditAddressDialog::setAddress(const QString &address) { this->address = address; ui->addressEdit->setText(address); }
be2d11f5ba364c1fce136e3405505ac6840cabfa
ad2d392f73f6e26b4f082fb0251b241a7ebf85a8
/abc/reiwa/176/b.cpp
5337ae15d7bf5a478a56ecf65deac79fd9606909
[]
no_license
miyamotononno/atcoder
b293ac3b25397567aa93a179d1af34add492518b
cf29d48c7448464d33a9d7ad69affd771319fe3c
refs/heads/master
2022-01-09T23:03:07.022772
2022-01-08T14:12:13
2022-01-08T14:12:13
187,175,157
0
0
null
2019-06-12T16:03:24
2019-05-17T08:11:58
Python
UTF-8
C++
false
false
736
cpp
#include <algorithm> #include <iostream> #include <iomanip> #include <cassert> #include <cstring> #include <string> #include <vector> #include <random> #include <bitset> #include <queue> #include <cmath> #include <unordered_map> #include <set> #include <map> #define INCANT cin.tie(0), cout.tie(0), ios::sync_with_stdio(0), cout << fixed << setprecision(20); #define rep(i,n) for (int i=0; i<n;++i) #define ALL(a) (a).begin(),(a).end() #define PI 3.14159265358979 typedef long long ll; using namespace std; const ll MOD = 1e9+7LL; const int INF = 2e9; string N; int main() { INCANT; cin >> N; int md=0; rep(i, N.size()) { md+=N[i]-'0'; md%=9; } string ans = md%9==0?"Yes":"No"; cout << ans << "\n"; return 0; }
84cce6cc1bfe7f5272158fe363a0d155cfc8f3e6
ef6549894c18da58d643f41b1aae85b5b47ef662
/node_modules/opencv4nodejs/cc/modules/objdetect/HOGDescriptor.h
052e679493a41565c44a47234681a83c81ec9291
[ "MIT" ]
permissive
iqbalbaharum/ImageRecognition
270154776ade8c39a4cfcd601aa9302ba4bbb4f3
0c1d70cdcfdf9384a008adf532e825ccaeb298a6
refs/heads/master
2021-05-06T18:19:34.617729
2017-11-25T08:59:08
2017-11-25T08:59:08
111,975,706
1
0
null
null
null
null
UTF-8
C++
false
false
2,596
h
#include "macros.h" #include <opencv2/core.hpp> #include <opencv2/objdetect.hpp> #include "Size.h" #ifndef __FF_HOGDESCRIPTOR_H__ #define __FF_HOGDESCRIPTOR_H__ class HOGDescriptor : public Nan::ObjectWrap { public: cv::HOGDescriptor hog; static FF_GETTER_JSOBJ(HOGDescriptor, winSize, hog.winSize, FF_UNWRAP_SIZE_AND_GET, Size::constructor); static FF_GETTER_JSOBJ(HOGDescriptor, blockSize, hog.blockSize, FF_UNWRAP_SIZE_AND_GET, Size::constructor); static FF_GETTER_JSOBJ(HOGDescriptor, blockStride, hog.blockStride, FF_UNWRAP_SIZE_AND_GET, Size::constructor); static FF_GETTER_JSOBJ(HOGDescriptor, cellSize, hog.cellSize, FF_UNWRAP_SIZE_AND_GET, Size::constructor); static FF_GETTER(HOGDescriptor, nbins, hog.nbins); static FF_GETTER(HOGDescriptor, derivAperture, hog.derivAperture); static FF_GETTER(HOGDescriptor, histogramNormType, hog.histogramNormType); static FF_GETTER(HOGDescriptor, nlevels, hog.nlevels); static FF_GETTER(HOGDescriptor, winSigma, hog.winSigma); static FF_GETTER(HOGDescriptor, L2HysThreshold, hog.L2HysThreshold); static FF_GETTER(HOGDescriptor, gammaCorrection, hog.gammaCorrection); static FF_GETTER(HOGDescriptor, signedGradient, hog.signedGradient); static NAN_MODULE_INIT(Init); static NAN_METHOD(New); struct ComputeWorker; static NAN_METHOD(Compute); static NAN_METHOD(ComputeAsync); struct ComputeGradientWorker; static NAN_METHOD(ComputeGradient); static NAN_METHOD(ComputeGradientAsync); struct DetectWorker; static NAN_METHOD(Detect); static NAN_METHOD(DetectAsync); struct DetectROIWorker; static NAN_METHOD(DetectROI); static NAN_METHOD(DetectROIAsync); struct DetectMultiScaleWorker; static NAN_METHOD(DetectMultiScale); static NAN_METHOD(DetectMultiScaleAsync); struct DetectMultiScaleROIWorker; static NAN_METHOD(DetectMultiScaleROI); static NAN_METHOD(DetectMultiScaleROIAsync); struct GroupRectanglesWorker; static NAN_METHOD(GroupRectangles); static NAN_METHOD(GroupRectanglesAsync); static NAN_METHOD(GetDaimlerPeopleDetector); static NAN_METHOD(GetDefaultPeopleDetector); static NAN_METHOD(CheckDetectorSize); static NAN_METHOD(SetSVMDetector); static NAN_METHOD(Save); static NAN_METHOD(Load); static Nan::Persistent<v8::FunctionTemplate> constructor; cv::HOGDescriptor* getNativeObjectPtr() { return &hog; } cv::HOGDescriptor getNativeObject() { return hog; } typedef InstanceConverter<HOGDescriptor, cv::HOGDescriptor> Converter; static const char* getClassName() { return "HOGDescriptor"; } }; #endif
4f1978d997748d3506e69e7b6c9fe18cd90c4bbb
04b1803adb6653ecb7cb827c4f4aa616afacf629
/remoting/host/it2me/it2me_confirmation_dialog_proxy.h
1fbf6c6fa201ce4c442fddb62cecb701c4202733
[ "BSD-3-Clause" ]
permissive
Samsung/Castanets
240d9338e097b75b3f669604315b06f7cf129d64
4896f732fc747dfdcfcbac3d442f2d2d42df264a
refs/heads/castanets_76_dev
2023-08-31T09:01:04.744346
2021-07-30T04:56:25
2021-08-11T05:45:21
125,484,161
58
49
BSD-3-Clause
2022-10-16T19:31:26
2018-03-16T08:07:37
null
UTF-8
C++
false
false
1,606
h
// 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. #ifndef REMOTING_HOST_IT2ME_IT2ME_CONFIRMATION_DIALOG_PROXY_H_ #define REMOTING_HOST_IT2ME_IT2ME_CONFIRMATION_DIALOG_PROXY_H_ #include "base/callback.h" #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" #include "base/single_thread_task_runner.h" #include "remoting/host/it2me/it2me_confirmation_dialog.h" namespace remoting { // A helper class to use an It2MeConfirmationDialog from a non-UI thread. class It2MeConfirmationDialogProxy : public It2MeConfirmationDialog { public: // |ui_task_runner| must be the UI thread. It will be used to call into the // wrapped dialog. // |dialog| is the dialog being wrapped. It2MeConfirmationDialogProxy( scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner, std::unique_ptr<It2MeConfirmationDialog> dialog); ~It2MeConfirmationDialogProxy() override; // It2MeConfirmationDialog implementation. void Show(const std::string& remote_user_email, const It2MeConfirmationDialog::ResultCallback& callback) override; private: class Core; void ReportResult(It2MeConfirmationDialog::Result result); std::unique_ptr<Core> core_; It2MeConfirmationDialog::ResultCallback callback_; base::WeakPtrFactory<It2MeConfirmationDialogProxy> weak_factory_; DISALLOW_COPY_AND_ASSIGN(It2MeConfirmationDialogProxy); }; } // namespace remoting #endif // REMOTING_HOST_IT2ME_IT2ME_CONFIRMATION_DIALOG_PROXY_H_
42b169e017cd0b5b92086b38bd29061952b3031f
e8700bccba49b3c7307d2fe98fe60f30e58debdf
/src/libtsduck/dtv/descriptors/tsATSCAC3AudioStreamDescriptor.cpp
30da37f7bf9b51578aa5489ff6de859d1ed23c7b
[ "BSD-2-Clause" ]
permissive
moveman/tsduck
f120e292355227276b893cba3cba989e01e10b5c
2e5095d2384de07f04c285cf051dfa1523d05fc2
refs/heads/master
2023-08-22T06:10:17.046301
2021-09-26T20:59:02
2021-09-26T20:59:02
411,141,449
0
0
null
null
null
null
UTF-8
C++
false
false
13,108
cpp
//---------------------------------------------------------------------------- // // TSDuck - The MPEG Transport Stream Toolkit // Copyright (c) 2005-2021, Thierry Lelegard // 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 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 "tsATSCAC3AudioStreamDescriptor.h" #include "tsDescriptor.h" #include "tsTablesDisplay.h" #include "tsPSIRepository.h" #include "tsPSIBuffer.h" #include "tsDuckContext.h" #include "tsxmlElement.h" #include "tsNames.h" #include "tsDVBCharTableUTF16.h" #include "tsDVBCharTableSingleByte.h" TSDUCK_SOURCE; #define MY_XML_NAME u"ATSC_AC3_audio_stream_descriptor" #define MY_CLASS ts::ATSCAC3AudioStreamDescriptor #define MY_DID ts::DID_ATSC_AC3 #define MY_PDS ts::PDS_ATSC #define MY_STD ts::Standards::ATSC TS_REGISTER_DESCRIPTOR(MY_CLASS, ts::EDID::Private(MY_DID, MY_PDS), MY_XML_NAME, MY_CLASS::DisplayDescriptor); //---------------------------------------------------------------------------- // Constructors //---------------------------------------------------------------------------- ts::ATSCAC3AudioStreamDescriptor::ATSCAC3AudioStreamDescriptor() : AbstractDescriptor(MY_DID, MY_XML_NAME, MY_STD, 0), sample_rate_code(0), bsid(0), bit_rate_code(0), surround_mode(0), bsmod(0), num_channels(0), full_svc(false), mainid(0), priority(0), asvcflags(0), text(), language(), language_2(), additional_info() { } ts::ATSCAC3AudioStreamDescriptor::ATSCAC3AudioStreamDescriptor(DuckContext& duck, const Descriptor& desc) : ATSCAC3AudioStreamDescriptor() { deserialize(duck, desc); } //---------------------------------------------------------------------------- // Clear the content of this object. //---------------------------------------------------------------------------- void ts::ATSCAC3AudioStreamDescriptor::clearContent() { sample_rate_code = 0; bsid = 0; bit_rate_code = 0; surround_mode = 0; bsmod = 0; num_channels = 0; full_svc = false; mainid = 0; priority = 0; asvcflags = 0; text.clear(); language.clear(); language_2.clear(); additional_info.clear(); } //---------------------------------------------------------------------------- // Serialization //---------------------------------------------------------------------------- void ts::ATSCAC3AudioStreamDescriptor::serializePayload(PSIBuffer& buf) const { buf.putBits(sample_rate_code, 3); buf.putBits(bsid, 5); buf.putBits(bit_rate_code, 6); buf.putBits(surround_mode, 2); buf.putBits(bsmod, 3); buf.putBits(num_channels, 4); buf.putBit(full_svc); buf.putUInt8(0xFF); // langcod, deprecated if (num_channels == 0) { buf.putUInt8(0xFF); // langcod2, deprecated } if (bsmod < 2) { buf.putBits(mainid, 3); buf.putBits(priority, 2); buf.putBits(0xFF, 3); } else { buf.putUInt8(asvcflags); } // Check if text shall be encoded in ISO Latin-1 (ISO 8859-1) or UTF-16. const bool latin1 = DVBCharTableSingleByte::RAW_ISO_8859_1.canEncode(text); // Encode the text. The resultant size must fit on 7 bits. The max size is then 127 characters with Latin-1 and 63 with UTF-16. const ByteBlock bb(latin1 ? DVBCharTableSingleByte::RAW_ISO_8859_1.encoded(text, 0, 127) : DVBCharTableUTF16::RAW_UNICODE.encoded(text, 0, 63)); // Serialize the text. buf.putBits(bb.size(), 7); buf.putBit(latin1); buf.putBytes(bb); // Serialize the languages. buf.putBit(!language.empty()); buf.putBit(!language_2.empty()); buf.putBits(0xFF, 6); if (!language.empty()) { buf.putLanguageCode(language); } if (!language_2.empty()) { buf.putLanguageCode(language_2); } // Trailing info. buf.putBytes(additional_info); } //---------------------------------------------------------------------------- // Deserialization //---------------------------------------------------------------------------- void ts::ATSCAC3AudioStreamDescriptor::deserializePayload(PSIBuffer& buf) { buf.getBits(sample_rate_code, 3); buf.getBits(bsid, 5); buf.getBits(bit_rate_code, 6); buf.getBits(surround_mode, 2); buf.getBits(bsmod, 3); buf.getBits(num_channels, 4); full_svc = buf.getBool(); // End of descriptor allowed here if (buf.endOfRead()) { return; } // Ignore langcode, deprecated buf.skipBits(8); // End of descriptor allowed here if (buf.endOfRead()) { return; } // Ignore langcode2, deprecated if (num_channels == 0) { buf.skipBits(8); } // End of descriptor allowed here if (buf.endOfRead()) { return; } // Decode one byte depending on bsmod. if (bsmod < 2) { buf.getBits(mainid, 3); buf.getBits(priority, 2); buf.skipBits(3); } else { asvcflags = buf.getUInt8(); } // End of descriptor allowed here if (buf.endOfRead()) { return; } // Deserialize text. Can be ISO Latin-1 or UTF-16. const size_t textlen = buf.getBits<size_t>(7); const bool latin1 = buf.getBool(); buf.getString(text, textlen, latin1 ? static_cast<const Charset*>(&DVBCharTableSingleByte::RAW_ISO_8859_1) : static_cast<const Charset*>(&DVBCharTableUTF16::RAW_UNICODE)); // End of descriptor allowed here if (buf.endOfRead()) { return; } // Decode one byte flags. const bool has_language = buf.getBool(); const bool has_language_2 = buf.getBool(); buf.skipBits(6); // End of descriptor allowed here if (buf.endOfRead()) { return; } // Deserialize languages. if (has_language) { buf.getLanguageCode(language); } if (has_language_2) { buf.getLanguageCode(language_2); } // Trailing info. buf.getBytes(additional_info); } //---------------------------------------------------------------------------- // Static method to display a descriptor. //---------------------------------------------------------------------------- void ts::ATSCAC3AudioStreamDescriptor::DisplayDescriptor(TablesDisplay& disp, PSIBuffer& buf, const UString& margin, DID did, TID tid, PDS pds) { if (buf.canReadBytes(3)) { // Fixed initial size: 3 bytes. disp << margin << "Sample rate: " << NameFromSection(u"ATSCAC3SampleRateCode", buf.getBits<uint8_t>(3), NamesFlags::VALUE) << std::endl; disp << margin << UString::Format(u"AC-3 coding version: 0x%X (%<d)", {buf.getBits<uint8_t>(5)}) << std::endl; const uint8_t bitrate = buf.getBits<uint8_t>(6); disp << margin << "Bit rate: " << NameFromSection(u"ATSCAC3BitRateCode", bitrate & 0x1F, NamesFlags::VALUE) << ((bitrate & 0x20) == 0 ? "" : " max") << std::endl; disp << margin << "Surround mode: " << NameFromSection(u"ATSCAC3SurroundMode", buf.getBits<uint8_t>(2), NamesFlags::VALUE) << std::endl; const uint8_t bsmod = buf.getBits<uint8_t>(3); disp << margin << "Bitstream mode: " << NameFromSection(u"AC3BitStreamMode", bsmod, NamesFlags::VALUE) << std::endl; const uint8_t channels = buf.getBits<uint8_t>(4); disp << margin << "Num. channels: " << NameFromSection(u"ATSCAC3NumChannels", channels, NamesFlags::VALUE) << std::endl; disp << margin << UString::Format(u"Full service: %s", {buf.getBool()}) << std::endl; // Ignore langcode and langcode2, deprecated buf.skipBits(8); if (channels == 0) { buf.skipBits(8); } // Decode one byte depending on bsmod. if (buf.canRead()) { if (bsmod < 2) { disp << margin << UString::Format(u"Main audio service id: %d", {buf.getBits<uint8_t>(3)}) << std::endl; disp << margin << UString::Format(u"Priority: %d", {buf.getBits<uint8_t>(2)}) << std::endl; buf.skipBits(3); } else { disp << margin << UString::Format(u"Associated services flags: 0x%X", {buf.getUInt8()}) << std::endl; } } // Decode text. if (buf.canRead()) { const size_t textlen = buf.getBits<size_t>(7); const bool latin1 = buf.getBool(); const Charset* charset = latin1 ? static_cast<const Charset*>(&DVBCharTableSingleByte::RAW_ISO_8859_1) : static_cast<const Charset*>(&DVBCharTableUTF16::RAW_UNICODE); disp << margin << "Text: \"" << buf.getString(textlen, charset) << "\"" << std::endl; } // Decode one byte flags. bool has_lang = false; bool has_lang2 = false; if (buf.canRead()) { has_lang = buf.getBool(); has_lang2 = buf.getBool(); buf.skipBits(6); } // Deserialize languages. if (has_lang) { disp << margin << "Language: \"" << buf.getLanguageCode() << "\"" << std::endl; } if (has_lang2) { disp << margin << "Language 2: \"" << buf.getLanguageCode() << "\"" << std::endl; } // Trailing info. disp.displayPrivateData(u"Additional information", buf, NPOS, margin); } } //---------------------------------------------------------------------------- // XML serialization //---------------------------------------------------------------------------- void ts::ATSCAC3AudioStreamDescriptor::buildXML(DuckContext& duck, xml::Element* root) const { root->setIntAttribute(u"sample_rate_code", sample_rate_code, true); root->setIntAttribute(u"bsid", bsid, true); root->setIntAttribute(u"bit_rate_code", bit_rate_code, true); root->setIntAttribute(u"surround_mode", surround_mode, true); root->setIntAttribute(u"bsmod", bsmod, true); root->setIntAttribute(u"num_channels", num_channels, true); root->setBoolAttribute(u"full_svc", full_svc); if ((bsmod & 0x07) < 2) { root->setIntAttribute(u"mainid", mainid, true); root->setIntAttribute(u"priority", priority, true); } else { root->setIntAttribute(u"asvcflags", asvcflags, true); } root->setAttribute(u"text", text, true); root->setAttribute(u"language", language, true); root->setAttribute(u"language_2", language_2, true); if (!additional_info.empty()) { root->addHexaTextChild(u"additional_info", additional_info); } } //---------------------------------------------------------------------------- // XML deserialization //---------------------------------------------------------------------------- bool ts::ATSCAC3AudioStreamDescriptor::analyzeXML(DuckContext& duck, const xml::Element* element) { return element->getIntAttribute(sample_rate_code, u"sample_rate_code", true, 0, 0, 0x07) && element->getIntAttribute(bsid, u"bsid", true, 0, 0, 0x1F) && element->getIntAttribute(bit_rate_code, u"bit_rate_code", true, 0, 0, 0x3F) && element->getIntAttribute(surround_mode, u"surround_mode", true, 0, 0, 0x03) && element->getIntAttribute(bsmod, u"bsmod", true, 0, 0, 0x07) && element->getIntAttribute(num_channels, u"num_channels", true, 0, 0, 0x0F) && element->getBoolAttribute(full_svc, u"full_svc", true) && element->getIntAttribute(mainid, u"mainid", bsmod < 2, 0, 0, 0x07) && element->getIntAttribute(priority, u"priority", bsmod < 2, 0, 0, 0x03) && element->getIntAttribute(asvcflags, u"asvcflags", bsmod >= 2, 0, 0, 0xFF) && element->getAttribute(text, u"text") && element->getAttribute(language, u"language") && element->getAttribute(language_2, u"language_2") && element->getHexaTextChild(additional_info, u"additional_info"); }
ae0f9391ff15a1daacdb219640e04045119c8a83
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5652388522229760_1/C++/JanKuipers/a.cc
50c091c74a48c6fb46afd15840f90705c25e8e76
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
1,523
cc
#include <stdlib.h> #include <stdio.h> #include <math.h> #include <ctype.h> #include <string.h> #include <string> #include <sstream> #include <iostream> #include <vector> #include <queue> #include <deque> #include <stack> #include <set> #include <map> #include <algorithm> #include <functional> using namespace std; #define PB push_back #define SZ size() #define ALL(x) x.begin(),x.end() #define SORT(x) sort(ALL(x)) #define UNIQUE(x) x.erase(unique(ALL(x)),x.end()) #define REP(x, hi) for (int x=0; x<(hi); x++) #define REPD(x, hi) for (int x=((hi)-1); x>=0; x--) #define FOR(x, lo, hi) for (int x=(lo); x<(hi); x++) #define FORD(x, lo, hi) for (int x=((hi)-1); x>=(lo); x--) typedef vector<int> VI; typedef vector<VI> VVI; typedef vector<VVI> VVVI; typedef long long LL; typedef vector<LL> VLL; typedef vector<VLL> VVLL; typedef vector<double> VD; typedef vector<VD> VVD; typedef vector<string> VS; const int inf = 999999999; //////////////////////////////////////////////////////////// void solve () { int n; cin >> n; if (n == 0) { cout << "INSOMNIA"; return; } vector<bool> seen(10, false); int num_seen = 0; int nn = 0; while (num_seen < 10) { nn += n; int x = nn; while (x > 0) { int d = x % 10; if (!seen[d]) { seen[d] = true; num_seen++; } x /= 10; } } cout << nn; } int main () { int runs; cin >> runs; for (int run=1; run<=runs; run++) { cout << "Case #" << run << ": "; solve(); cout << endl; } return 0; }
6c45cc1d25abdccaf8fbe7c3870678d978d58a4c
0389f4381dfe65d50d7b8dd912052a1d19a15bab
/angle_shooter_final/angle_shooter_final.ino
d626043afc77709cb10cb6712d7c8cae7110158a
[]
no_license
raghavmah/gyro_library
b96af5cd683a327dbaa47a2f142496c24227d903
a9696c76b020043be2702a1b695be82733bf0ade
refs/heads/main
2023-04-03T12:21:21.031076
2021-04-07T08:50:55
2021-04-07T08:50:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,055
ino
#include <EncoderMotor.h> #include <MPU6050_tockn.h> #include <Wire.h> #include <PID_v1.h> //#define Dir1 23 //#define Dir2 14 //#define pwm_pin 12 motor mY(0, 0, 14, 23, 12, 0); double Setpoint = 0, Input, Output; double Kp = 9, Ki = 3, Kd = 0; PID myPID(&Input, &Output, &Setpoint, Kp, Ki, Kd, DIRECT); MPU6050 mpu6050(Wire); void setup() { // put your setup code here, to run once: Serial.begin(115200); Serial.setTimeout(5); myPID.SetMode(AUTOMATIC); myPID.SetOutputLimits(-255, 255); myPID.SetSampleTime(1); Wire.begin(); mpu6050.begin(); mpu6050.calcGyroOffsets(true); Setpoint = getAngle(); Serial.println(Setpoint); delay(1000); } double getAngle(){ mpu6050.update(true); return mpu6050.getGyroAngleY(); } void updateSetpoint(){ if(Serial.available()){ Setpoint = Serial.parseInt(); } } void loop() { updateSetpoint(); Input = getAngle(); myPID.Compute(); mY.setPWM(Output); Serial.println(String(Input)+","+String(Setpoint)+","+String(Output)); }
ecc5e37c087f06bd87aab69c16b318aabb5b2d84
383e2f4cfcca36c17d9e87a03e1422ccb2303bcb
/hiho/等式填空.cpp
8a9f47a69fb60eee93fd2ada269b286aac0baa0a
[]
no_license
lawinse/AlgorithmExercises
28b1893ab2d5d300785edaf8bda7adb203a5e70c
3cbdd9ce4a4dfff0e1890819a2418a96346dae9a
refs/heads/master
2021-01-01T19:53:38.115873
2017-08-10T15:05:27
2017-08-10T15:05:27
98,711,898
0
0
null
null
null
null
UTF-8
C++
false
false
1,574
cpp
// http://hihocoder.com/problemset/problem/1367 #include <iostream> #include <cstdio> #include <cstring> using namespace std; const int MOD = 1e9+7; typedef long long LL; LL dp09[105][1005]; LL dp19[195][1005]; LL dp[105][10005]; LL tmp[10005]; LL tmp1[10005]; int bit09[105]; int bit19[105]; void init() { dp09[0][0] = dp19[0][0] = 1; for (int i=0; i<99; ++i) for (int j=0; j<10; ++j) for(int k=0; k<900; ++k) { dp09[i+1][k+j] = (dp09[i+1][k+j] + dp09[i][k])%MOD; if (j>0)dp19[i+1][k+j] = (dp19[i+1][k+j] + dp19[i][k])%MOD; } } int main(int argc, char const *argv[]) { string s; cin >> s; int len = s.length(); while(s[len] != '=')len--; int num = 1; for (int i=len-1; i>=0; --i) { if (s[i] == '?') { if (i==0 || (i>0&&s[i-1]=='+')) { bit19[num]++; } else bit09[num]++; num++; }else if (s[i]=='+') num=1; } init(); int tot_len = s.length(); dp[tot_len][0]=1; int carrymax = 0; for (int i=1; s[tot_len-i]!='=';++i) { int max09 = bit09[i]*9; int max19 = bit19[i]*9; int pos = tot_len-i; memset(tmp,0,sizeof(tmp)); memset(tmp1,0,sizeof(tmp1)); for(int j=0; j<=max09; ++j) for (int k=0; k<=max19; ++k){ tmp[j+k] = (tmp[j+k] + dp09[bit09[i]][j] * dp19[bit19[i]][k]) % MOD; } int max_num = max19 + max09; for (int k=0; k<=max_num; ++k) for (int j=0; j<=carrymax; ++j){ tmp1[k+j] = (tmp1[k+j] + tmp[k]*dp[pos+1][j]) % MOD; } max_num += carrymax; for (int j=s[pos]-'0'; j<=max_num; j+=10) dp[pos][j/10] = tmp1[j]; carrymax = max_num/10; } cout << dp[len+1][0] <<endl; return 0; }
00e9cbdbc05e95329805e99ffd5d127ce491449c
eb6870eecd07081285133e620c27c5fab744207f
/main.cpp
a8b26d95b6c3e7ef81ea49241062d067c394b859
[]
no_license
Magic3DPrinter/Bservers
4c01f3409ba598c85d390ea6a789700f3457c642
3004e109e4f5ca392235cfdf4792be10cd77a811
refs/heads/master
2021-01-10T16:17:18.840898
2015-11-23T03:56:31
2015-11-23T03:56:31
46,693,748
0
0
null
null
null
null
UTF-8
C++
false
false
201
cpp
#include "bserverwindow.h" #include <QApplication> #include <QMessageBox> int main(int argc, char *argv[]) { QApplication a(argc, argv); BserverWindow w; w.show(); return a.exec(); }
4905692c278149b54d5165100de94803cea9214a
cbc8239ed00b07267332d94461ef6d28085c71be
/src/controller/local_planner/teb_planner/include/teb_planner/teb_local_planner/teb_local_map.h
476edba2c6bc32e4aefc6e3fde203a3a05d921fa
[]
no_license
ColleyLi/path-paln
d27504bb871af8dd2b17739e28353e35a4fddae4
1e3ac8cb93969555d7f0ec8d7f935b6980f97e42
refs/heads/master
2023-05-13T03:00:01.907357
2021-06-03T09:17:03
2021-06-03T09:17:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,038
h
#ifndef _TEB_LOCAL_MAP_ #define _TEB_LOCAL_MAP_ #include "data/local_map_data.h" #include "data_center/data_center.h" #include "geometry/geometry_func.h" #include "misc/planning_typedefs.h" #include "teb_planner/costmap_2d/cost_values.h" #define TEB_LOCAL_MAP_WINDOW_SIZE 161 class TebLocalMap { private: /* data */ DataLocalMap m_local_map_data; RobotGrid m_origin_grid{80,80}; float m_resolution = 0.05; int m_size_x = TEB_LOCAL_MAP_WINDOW_SIZE; int m_size_y = TEB_LOCAL_MAP_WINDOW_SIZE; public: TebLocalMap(/* args */); ~TebLocalMap(); void update(); bool world2map(float wx, float wy, unsigned int* mx, unsigned int* my) const; bool map2world(unsigned int mx, unsigned int my, float* wx, float* wy) const; unsigned char getCost(unsigned int mx, unsigned int my) const; int size_x() const {return m_size_x;} int size_y() const {return m_size_y;} DataLocalMap* local_map_data() {return &m_local_map_data;} float resolution() const {return m_resolution;} }; #endif
ddda8f883f677c852f18acabc193bddd852cbc17
eb667f1737a67feb07bf2d1298ff6757526ee8fb
/110 Balanced Binary Tree/Balanced Binary Tree.cpp
56b00011fcaf92ee8552cdf7f063485e88ab4736
[]
no_license
yukeyi/LeetCode
bb3313a868e9aedada3fe157c6307b00d32a09c9
79d37be2aefd674e885a5bdc6dac0a5adf02f91c
refs/heads/master
2021-04-18T22:18:26.085485
2019-06-09T06:25:29
2019-06-09T06:25:29
126,930,413
0
1
null
null
null
null
UTF-8
C++
false
false
662
cpp
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: bool isBalanced(TreeNode* root) { int res = auxBalanced(root); if(res < 0) return false; else return true; } int auxBalanced(TreeNode* root) { if(root == NULL) return 0; int l = auxBalanced(root->left); int r = auxBalanced(root->right); if(l < 0 || r < 0 || abs(l-r)>1) return -1; return max(l,r)+1; } };
3e7891c5a66b40b011e6f5ff0cd42e10c38ce062
fded81a37e53d5fc31cacb9a0be86377825757b3
/buhg_g/xdkbanksw.h
ad8fc93e080a1463ded73d72c4cb61ffee700726
[]
no_license
iceblinux/iceBw_GTK
7bf28cba9d994e95bab0f5040fea1a54a477b953
a4f76e1fee29baa7dce79e8a4a309ae98ba504c2
refs/heads/main
2023-04-02T21:45:49.500587
2021-04-12T03:51:53
2021-04-12T03:51:53
356,744,886
0
0
null
null
null
null
UTF-8
C++
false
false
885
h
/*$Id: xdkbanksw.h,v 1.1 2013/08/13 06:23:37 sasa Exp $*/ /*18.07.2013 18.07.2013 Белых А.И. xdkbanksw.h */ class xdkbanksw_rr { public: class iceb_u_str shet; class iceb_u_str datas; class iceb_u_str kodkontr; class iceb_u_str kodgrkontr; class iceb_u_str shetk; class iceb_u_str datap; int metka; /*0-кредитовое 1-дебетовое*/ /*реквизиты платёжки*/ short dd,md,gd; class iceb_u_str nomdok; class iceb_u_str kodop; class iceb_u_str kodor; class iceb_u_str tabl; xdkbanksw_rr() { clear_data(); dd=md=gd=0; nomdok.plus(""); kodop.plus(""); kodor.plus(""); tabl.plus(""); } void clear_data() { shet.new_plus(""); datas.new_plus(""); kodkontr.new_plus(""); kodgrkontr.new_plus(""); shetk.new_plus(""); datap.new_plus(""); metka=0; } };
22c5d829ce76c3c91305a2c71ff0892ed5f779b3
fc74c5c7f44fbdff161b94a9bb3e2913a350a713
/Classes/Junior Year/January 2019/Assignment 3/Task 4/TUT3/constant/polyMesh/faceZones
d5d647eb5f535ddfe6059f96dd4e7b9871312238
[]
no_license
cjn1012/Charlie
1158a2e1322904b28e9f523dc21048f148a14fcf
738acb4c7a8330a64619d049ae81cfefdff7b367
refs/heads/master
2021-07-17T10:53:19.810054
2020-05-03T20:40:46
2020-05-03T20:40:46
146,947,278
0
0
null
null
null
null
UTF-8
C++
false
false
1,785
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: 5.x | | \\ / A nd | Web: www.OpenFOAM.org | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ /* Windows 32 and 64 bit porting by blueCAPE: http://www.bluecape.com.pt *\ | Based on Windows porting (2.0.x v4) by Symscape: http://www.symscape.com | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class regIOobject; location "constant/polyMesh"; object faceZones; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // 3 ( i2i10MasterZone { type faceZone; faceLabels List<label> 40 ( 99 102 105 108 110 210 213 216 219 221 321 324 327 330 332 396 398 400 402 403 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 ) ; flipMap List<bool> 40 ( 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ) ; } i2i10SlaveZone { type faceZone; faceLabels List<label> 20 ( 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 ) ; flipMap List<bool> 20{0}; } i2i10CutFaceZone { type faceZone; faceLabels 0(); flipMap 0(); } ) // ************************************************************************* //
f51a40f297cdcc06179ed46e213c2d6cab7b8d2e
6ee627018fff1b5865256e56f751125c86b7bea6
/JilGstPlayer/JilGstPlayer.h
56152689726b73cdc20193750ff2add334a834d1
[]
no_license
usingsky/JilGstPlayer
a3d14e6607c26a6b0c09a2f5d68a1e0cb256e623
6359c4b758501941ed1186e52d1878df41d4ea9d
refs/heads/master
2020-04-16T09:15:17.593253
2019-01-13T04:40:50
2019-01-13T04:40:50
165,457,434
0
0
null
null
null
null
UTF-8
C++
false
false
1,117
h
#ifndef SIMPLE_GST_PLAYER_H #define SIMPLE_GST_PLAYER_H #include <gst/gst.h> #include <string> #include <functional> #include "GstPlayerCommand.h" class JilGstPlayer { public: JilGstPlayer(); virtual ~JilGstPlayer(); bool Post(BASE_COMMAND* command); void SetOnGstMessage(std::function<void(GstMessage* message)> msg_callback); private: bool Execute(BASE_COMMAND* command); void Init(); bool Open(std::string pipeline); bool Play(); bool Pause(); bool Stop(); bool SetProperty(std::string name, std::function<void(GstElement* element)> callback); GstElement* GetGstElementByName(std::string name); bool RegisterWatchBus(); bool UnRegisterWatchBus(); static gboolean callback_func(GstBus* bus, GstMessage* message, gpointer data); static gpointer command_loop(gpointer data); GstElement* pipeline_; GstBus* bus_; guint bus_signal_id_; GAsyncQueue* command_queue_; GThread* command_thread_; bool thread_running_; std::function<void(GstMessage* message)> msg_callback_; }; #endif //SIMPLE_GST_PLAYER_H
4c26f0aa3f79a14b47791af662f27e9c020dcc13
af3cc7ce8693006620ef75e87f321a04421d8970
/VirtualVAMeter.ino
9a1ed3dcde701a4d72b6755170b28a36f928ee3d
[]
no_license
GeoKon/APPS-VirtualVAMeter
7948de624aca0be928a95a09fe74dde08a12a806
7f118f75d10256ca91bd0334544f073ce40e59cf
refs/heads/master
2020-06-19T19:33:47.563187
2019-07-21T14:26:03
2019-07-21T14:26:03
196,844,048
1
0
null
null
null
null
UTF-8
C++
false
false
8,755
ino
/* * --------------------------------------------------------------------------------- * Main setup() and loop() for VIRTUAL VA METER * * Files needed: * VirtualVAMeter.cpp // main setup and loop * cliHandlers.cpp // CLI command handlers * mscSupport.cpp // misc utility functions and classes * globals.cpp // global variables and structures used by all above * * Hierarchy: * VirtualVAMeter --> cliHandlers --> mscSupport --> globals * * Summary of Class definitions and Allocations * * BUF buf; // defined in bufClass.h, allocated in VirtualVAMeters.cpp * * PROF prf; // defined in ticClass.h, allocated in VirtualVAMeters.cpp * Ticker tic; // defined in esp8266, allocated in VirtualVAMeters.cpp * TCP tcp; // defined in tcpClass, allocated in cliHandlers.cpp * MGN mgn; // defined in mgnClass, allocated in cliHandlers.cpp * OLED oled; // defined in oledClass.h, allocated in mscSupport.cpp * ADS15 ads; // defined in ads15Class.h, allocated in mscSupport.cpp * DIIR qvolts12,qamps // defined in filtClass.h, allocated in mscSupport.cpp * SCAN scan; // defined and allocated in mscSupport.cpp/.h * CPU cpu; // defined in cpuClass.h, allocated in globals.cpp * CLI cli; // defined in cliClass.h, allocated in globals.cpp * EXE exe; // defined in cpuClass.h, allocated in globals.cpp * EEP eep; // defined in eepClass.h, allocated in globals.cpp * GLOBALS myp; // defined in global.h allocated in globals.cpp * * Copyright (c) George Kontopidis 2019, All Rights Reserved * ---------------------------------------------------------------------------------- */ #include <ticClass.h> // from GKE Lib1 #include <Ticker.h> // from Arduino library #include "mscSupport.h" // in this local directory #include "cliHandlers.h" // in this local directory #include "Globals.h" // includes also exports of <externIO.h> for cpu...eep // --------------- allocation of classes used only by this module ------------------- static BUF buf(1500); // defined in bufClass.h static PROF prf(20,30,50,75,90); // defined in ticClass.h static Ticker tic; // defined in esp8266 library // ----------------------------- main setup() ---------------------------------------------- static bool tic_ready = false; // Ticker flips this to 'true' every 20ms // A full scan is completed in 100ms void setup(void) { cpu.init(); pinMode( 14, OUTPUT ); initOLED(); // Initialze SSD1306 OLED dsp. In mscSupport.cpp myp.initAllParms( /*Magic Code*/0x4467 ); // Initialize global parameters. Fetch from EEPROM as appropriate ads.init( 0x48 ); // Initialize ADC. ADDR pin to GROUND for( int i=0; i<5; i++ ) // Initialize ADS channels ads.initChannel( i, myp.chn[i].fs ); scan.init( myp.mee.scanperiod ); // Initialize scanner. scan.ready() every scanperiod*100ms increment scan.reset( myp.mee.smoothvolts, myp.mee.smoothamps ); // Depth of amps queues exe.registerTable( CLIADC::Table ); exe.printTables( "See all tables" ); // instead of PF, you can optionally specify a Buf cli.init( ECHO_OFF, "cmd-buf:" ); cli.prompt(); #ifdef TCP_ACTIVE initWiFi(); //tcp.init( 23, ECHO_ON, "cmd-tcp:" ); tcp.init( 23, ECHO_OFF ); #endif STREAMCODE = SCMASK_NONE; tic_ready = false; tic.attach_ms( 20, [](){ tic_ready=true; } ); } // ----------------------------- main loop() ---------------------------------------------- /* * Every 20ms, Ticker makes tic_ready becomes TRUE * When tic_ready, we scan all channels and measure voltages; this is done by calling the * SCAN.update() in the main loop. * Measurements are averaged by the SCAN.update() and every 100ms (or so), the SCAN.ready() * triggers computation of the engineering values. */ void loop() { if( cli.ready() ) // check to see if a CLI command was entered { char *cmd = cli.gets(); // cmd points to the heap allocated by CLI CRLF(); exe.dispatchBuf( cmd, buf ); // using Serial.printf(); unbuffered version PR(!buf); // display the buffer if( buf.length() > buf.size() - 40 ) // running low in buffer PF("*** CLI BUFFER[%d] OVERFLOW\r\n", buf.size() ); cli.prompt(); } #ifdef TCP_ACTIVE if( tcp.ready() ) // check to see if a TCP command was received { char *cmd = tcp.gets(); // cmd points to the heap allocated by CLI exe.dispatchBuf( cmd, buf ); // using Serial.printf(); unbuffered version tcp.respond( !buf ); // display the buffer tcp.prompt(); } #endif if( tic_ready ) // come here every 20ms { scan.update(); // spin the state machine tic_ready = false; } if( scan.ready() ) // come here every scanperiod = 100ms, 200ms, etc { prf.start(); // start the profiler for( int i=0; i<5; i++ ) // copy the filtered measurements { myp.chn[i].reading = scan.reading[i]; myp.chn[i].volts = ads.toVolts( i, myp.chn[i].reading ); // convert to volts } M_ACSVAL = TOENG(0); M_ACSREF = TOENG(1); M_VOLTS1 = TOENG(2); M_VOLTS2 = TOENG(3); float x = ads.toVolts( 4, ADC_AMPS ); // convert to ADC volts float ref = M_ACSREF; // calibrate 5V if( (ref < 3.0) && (ref >2.0) ) // make sure correct reference x *= 2.5/ref; myp.chn[4].volts = x; M_AMPS = myp.chn[4].scale * (myp.chn[4].volts - myp.mee.acsoffset) + myp.chn[4].offset; digitalWrite( 14, setRelay() ); // check and activate if( scan.readyMod( myp.mee.meterperiod/myp.mee.scanperiod ) ) // update the METERS { static int mcount = 0; char *arg[1]; arg[0] = (char *)(&buf); buf.init(); // simulate CLI call arguments updateMeters( 1, arg ); // at return, 'buf' has been filled myp.power = M_AMPS * (myp.selectV1V2 ? M_VOLTS2 : M_VOLTS1 ); myp.energy += myp.power*((float)myp.mee.meterperiod)/10.0; myp.pduration++; if( myp.oledON && (mcount==0) ) // every second update the OLED, i.e. 11, 21, 31... updateOLED(1); if( myp.oledON && (mcount==1) ) // every second, 12, 22, 32... updateOLED(2); if( myp.oledON && (mcount==2) ) // every second, 13, 23, 33... updateOLED(3); mcount++; if( mcount>=3) mcount=0; #ifdef TCP_ACTIVE if( tcp.ready() ) tcp.respond( !buf ); else #endif PR( !buf ); } if( scan.readyMod( myp.mee.graphperiod/myp.mee.scanperiod ) ) // update the GRAPH { char *arg[1]; arg[0] = (char *)(&buf); buf.init(); // simulate CLI call arguments updateGraph( 1, arg ); // at return, 'buf' has been filled #ifdef TCP_ACTIVE if( tcp.ready() ) tcp.respond( !buf ); else #endif PR( !buf ); } prf.profile(); if( scan.readyMod( 100 ) ) // print profile every 10 sec { prf.report( true ); prf.reset(); } } /* if( tic_mod( 10, 0 ) ) // every 1sec update the Rin counters { if( rin.ready() ) rin.update(); } */ }
47a36de6ff7a1f3bdc33126b05e7cfcd34311ba2
65d5e0b4686d4b48c373825f7e9b9b2037f6242e
/elisa3/elisa3.ino
aca1532d4cc4c64599d1e6f9663fcd05afd76ff5
[]
no_license
Ex7755/elisa3
862eafd0808a001671b8dcf36ba5f6d61c2f8491
a8a60e7ea3483ef2da12cd41e6db02dd588c6547
refs/heads/master
2020-09-24T01:25:47.555750
2019-12-03T13:44:24
2019-12-03T13:44:24
225,629,546
1
0
null
null
null
null
UTF-8
C++
false
false
3,514
ino
#include <adc.h> #include <behaviors.h> #include <constants.h> #include <ir_remote_control.h> #include <leds.h> #include <mirf.h> #include <motors.h> #include <nRF24L01.h> #include <ports_io.h> #include <sensors.h> #include <speed_control.h> #include <spi.h> #include <twimaster.h> #include <usart.h> #include <utility.h> #include <variables.h> unsigned long int startTime = 0, endTime = 0; unsigned char prevSelector = 0; char temp = 0; void setup() { initPeripherals(); calibrateSensors(); initBehaviors(); startTime = getTime100MicroSec(); } void loop() { currentSelector = getSelector(); // update selector position readAccelXYZ(); // update accelerometer values to compute the angle computeAngle(); endTime = getTime100MicroSec(); if((endTime-startTime) >= (PAUSE_2_SEC)) { readBatteryLevel(); // the battery level is updated every two seconds if(currentSelector==4 || currentSelector==5) { pwm_red = rand() % 255; pwm_green = rand() % 255; pwm_blue = rand() % 255; } startTime = getTime100MicroSec(); } handleIRRemoteCommands(); usart0Transmit(' ',0); handleRFCommands(); // send the current selector position through uart as debug info switch(currentSelector) { case 0: // motors in direct power control (no speed control) handleMotorsWithNoController(); break; case 1: // obstacle avoidance enabled (the robot does not move untill commands are // received from the radio or tv remote) enableObstacleAvoidance(); break; case 2: // cliff avoidance enabled (the robot does not move untill commands are // received from the radio or tv remote) enableCliffAvoidance(); break; case 3: // both obstacle and cliff avoidance enabled (the robot does not move untill commands are // received from the radio or tv remote) enableObstacleAvoidance(); enableCliffAvoidance(); break; case 4: // random colors on RGB leds; small green leds turned on GREEN_LED0_ON; GREEN_LED1_ON; GREEN_LED2_ON; GREEN_LED3_ON; GREEN_LED4_ON; GREEN_LED5_ON; GREEN_LED6_ON; GREEN_LED7_ON; updateRedLed(pwm_red); updateGreenLed(pwm_green); updateBlueLed(pwm_blue); break; case 5: // random colors on RGB leds; obstacle avoidance enabled; robot start moving automatically // (motors speed setting) updateRedLed(pwm_red); updateGreenLed(pwm_green); updateBlueLed(pwm_blue); enableObstacleAvoidance(); setLeftSpeed(25); setRightSpeed(25); break; } if(currentSelector != 0) { handleMotorsWithSpeedController(); } if(prevSelector != currentSelector) { // in case the selector is changed, reset the robot state disableObstacleAvoidance(); disableCliffAvoidance(); GREEN_LED0_OFF; GREEN_LED1_OFF; GREEN_LED2_OFF; GREEN_LED3_OFF; GREEN_LED4_OFF; GREEN_LED5_OFF; GREEN_LED6_OFF; GREEN_LED7_OFF; pwm_red = 255; pwm_green = 255; pwm_blue = 255; updateRedLed(pwm_red); updateGreenLed(pwm_green); updateBlueLed(pwm_blue); } prevSelector = currentSelector; }
050ebfa1d13b61255ad9dd63bf74e00c90a0ba87
348b453ef04d65a66f098fdca90af28a943f3dfd
/W04/Notifications.h
d1e7e6e1c88c3a01df3b6ccc39c61c7e4211cc51
[ "MIT" ]
permissive
AriaAv/OOP345
f9a1eaa7fb67b6d2036f637b88371879a40020b6
934f5a63c5ea5659b3c927615bcdc38d96b469ad
refs/heads/master
2020-04-15T19:56:59.365885
2019-01-10T02:12:36
2019-01-10T02:12:36
164,972,245
1
0
null
null
null
null
UTF-8
C++
false
false
788
h
// Name: Aria Avazkhani // Seneca Student ID: 134465160 // Seneca email: [email protected] // Date of completion: 2018-10-04 // // I confirm that the content of this file is created by me, // with the exception of the parts provided to me by my professor. // Manages access to a set of up to 10 instances of the Message type #ifndef W4_NOTIFICATIONS_H #define W4_NOTIFICATIONS_H #include "Message.h" namespace w4 { class Notifications { Message* mesg; size_t loc; public: Notifications(); Notifications(const Notifications&); Notifications& operator=(const Notifications&); Notifications(Notifications&&); Notifications& operator=(Notifications&&); ~Notifications(); void operator+=(const Message& msg); void display(std::ostream& os) const; }; } #endif
f64a3efea503f0095fc2fe4614bf6871271ec2c4
329b67946a134b80643fcdb87ffbc74d8d51a68f
/iwesol/OF/OF-2.3.0/src/mesh/blockMesh/fundamentals/BlockConventions.H
d3f74db537ab191b7bcf276b5930d50fb9496d3f
[]
no_license
RafieeAshkan/terrainBlockMesher
41240a6456549db9ddf36f53d2324f6fe5839fae
90abd7bc6247667a9c9746ac7dcbb99d9ab69231
refs/heads/master
2023-03-15T21:49:34.538786
2015-01-12T08:20:38
2015-01-12T08:20:38
586,420,039
0
1
null
2023-01-08T04:03:33
2023-01-08T04:03:33
null
UTF-8
C++
false
false
5,114
h
/*---------------------------------------------------------------------------*\ | _____ _______ ____ | IWESOL: IWES Open Library |_ _\ \ / / ____/ ___| | | | \ \ /\ / /| _| \___ \ | Copyright: Fraunhofer Institute for Wind | | \ V V / | |___ ___) | | Energy and Energy System Technology IWES |___| \_/\_/ |_____|____/ | | http://www.iwes.fraunhofer.de | ------------------------------------------------------------------------------- ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | \\ / A nd | Copyright held by original author \\/ M anipulation | ------------------------------------------------------------------------------- License This file is part of IWESOL and it is based on OpenFOAM. IWESOL and OpenFOAM are free software: you can redistribute them and/or modify them under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. IWESOL and OpenFOAM are distributed in the hope that they will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>. Class Foam::oldev::BlockConventions Description SourceFiles BlockConventions.C \*---------------------------------------------------------------------------*/ #ifndef BlockConventions_H #define BlockConventions_H #include "labelList.H" #include "scalarList.H" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace Foam { namespace oldev { /*---------------------------------------------------------------------------*\ Class BlockConventions Declaration \*---------------------------------------------------------------------------*/ class BlockConventions { public: // Static data members /// define box corner labels: eg south-west-low = SWL static const label SWL, SWH, NWL, NWH, SEL, SEH, NEL, NEH; /// define x, y, z labels static const label X, Y, Z; /// define face labels static const label NONE, WEST, EAST, NORTH, SOUTH, GROUND, SKY; /// Define edge labels static const label SWL_SEL, SWL_NWL, SEL_NEL, NEL_NWL; static const label SEL_SWL, NWL_SWL, NEL_SEL, NWL_NEL; static const label SEH_NEH, SWH_NWH, NEH_SEH, NWH_SWH; static const label SEL_SEH, NEL_NEH, SEH_SEL, NEH_NEL; static const label SWH_SEH, SEH_SWH, NWH_NEH, NEH_NWH; static const label SWL_SWH, SWH_SWL, NWL_NWH, NWH_NWL; // Static functions /// transform grading factors into expandRatios static scalarList gradingFactors2ExpandRatios ( const scalarList & gradingFactors ); /// create labelList from labels static labelList vertices2vertexList ( const label & p_SWL,const label & p_SWH, const label & p_NWL,const label & p_NWH, const label & p_SEL,const label & p_SEH, const label & p_NEL,const label & p_NEH ); /// returns the constant direction of a face static label getConstantDirectionFace(label faceID); /// returns the opposite face static label getOppositeFace(label faceID); /// Returns edge label static label getEdgeLabel(label vertex1, label vertex2); /// Returns edge vertices labels static labelList getEdgeVerticesI(label edgeID); /// Returns the edge indices of a face static labelList getFaceEdgesI(label faceI); /// Returns the constant directions of an edge (ie a edge) static labelList getConstantDirectionsEdge(label edgeID); /// Returns the direction of a edge static label getDirectionEdge(label edgeID); /// Checks if an edge belongs to a face static bool edgeBelongsToFace(label edgeID, label faceID); /// Returns label of opposite edge static label switchedOrientationLabel(label edgeID); /// returns the sign of edge direction static label getEdgeDirectionSign(label edgeID); /// returns the signed edge direction static label getSignedEdgeDirection(label edgeID); /// returns the label of the face the edge starts from static label edgeStartFace(label edgeID); /// returns the label of the face the edge ends at static label edgeEndFace(label edgeID); /// maps block labels to model labels static labelList mapToHexModel(const labelList & vertices); }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace oldev } // End namespace Foam // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #endif // ************************************************************************* //
0907d3d94f02999ee58fb63e1d29a1cd70951368
f2723b5c578548bbff10340c168c88b95d909515
/ContainerWithMostWater.cpp
439ec8f6531dc785f4c2f4ab03d3c032ca879a33
[]
no_license
fenganli/Leetcode
20718b4820f8ccb69d842e475add4c0edcf2797e
d66bf923636125c642aa800961be1609e843264a
refs/heads/master
2021-05-28T07:09:48.872845
2014-10-18T22:58:00
2014-10-18T22:58:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
497
cpp
class Solution { public: int maxArea(vector<int> &height) { int size = height.size(); int maxArea = 0; int left = 0, right = size - 1; while (left < right) { if (height[left] == 0) left++; else if (height[right] == 0) right--; else if (height[left] <= height[right]) { maxArea = max(maxArea, (right - left) * height[left]); left++; } else { maxArea = max(maxArea, (right - left) * height[right]); right--; } } return maxArea; } };
be538255db7630bf64c7a9d15e9b915d5cef1a0f
9b818d2453437596f2163cad1445bcf1d01d8787
/version_004/pdb4dna_sourcefiles/src/PDBlib.cc
5f0fa156a28aa7977d20ee64ac02e7944d019e06
[]
no_license
edanielortiz/Leather_Simulations_Thingy
d7a64cd456557babe6cf32802812a999e7b4e299
fb8c7eb2a10bfd24fc4678b03b194bab037b916c
refs/heads/master
2020-05-18T02:55:25.280024
2019-04-30T08:04:39
2019-04-30T08:04:39
184,131,431
0
0
null
null
null
null
UTF-8
C++
false
false
28,287
cc
// // ******************************************************************** // * License and Disclaimer * // * * // * The Geant4 software is copyright of the Copyright Holders of * // * the Geant4 Collaboration. It is provided under the terms and * // * conditions of the Geant4 Software License, included in the file * // * LICENSE and available at http://cern.ch/geant4/license . These * // * include a list of copyright holders. * // * * // * Neither the authors of this software system, nor their employing * // * institutes,nor the agencies providing financial support for this * // * work make any representation or warranty, express or implied, * // * regarding this software system or assume any liability for its * // * use. Please see the license in the file LICENSE and URL above * // * for the full disclaimer and the limitation of liability. * // * * // * This code implementation is the result of the scientific and * // * technical work of the GEANT4 collaboration. * // * By using, copying, modifying or distributing the software (or * // * any work based on the software) you agree to acknowledge its * // * use in resulting scientific publications, and indicate your * // * acceptance of all terms of the Geant4 Software license. * // ******************************************************************** // // This example is provided by the Geant4-DNA collaboration // Any report or published results obtained using the Geant4-DNA software // shall cite the following Geant4-DNA collaboration publication: // Med. Phys. 37 (2010) 4692-4708 // Delage et al. PDB4DNA: implementation of DNA geometry from the Protein Data // Bank (PDB) description for Geant4-DNA Monte-Carlo // simulations (submitted to Comput. Phys. Commun.) // The Geant4-DNA web site is available at http://geant4-dna.org // // /// \file PDBlib.cc /// \brief Implementation file for PDBlib class #include "PDBlib.hh" //define if the program is running with Geant4 #define GEANT4 #ifdef GEANT4 //Specific to Geant4, globals.hh is used for G4cout #include "globals.hh" #else #define G4cout std::cout #define G4cerr std::cerr #define G4endl std::endl #define G4String std::string // string included in PDBatom.hh #include <cfloat> #endif #include <fstream> #include <iostream> #include <limits> #include <cmath> #include <sstream> #include <stdlib.h> using namespace std; //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... PDBlib::PDBlib() : fNbNucleotidsPerStrand(0) { } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... /** * \brief Load a PDB file into memory * \details molecule (polymer,?), * read line, key words * \param filename G4String for filename * \param isDNA * \param verbose * \return List of molecules */ Molecule * PDBlib::Load(const std::string& filename, unsigned short int& isDNA, unsigned short int verbose = 0) { G4String sLine = ""; ifstream infile; infile.open(filename.c_str()); if(!infile) { G4cout << "PDBlib::load >> file " << filename << " not found !!!!" << G4endl; } else { int nbAtomTot = 0; // total number of atoms int nbAtom = 0; // total number of atoms in a residue int numAtomInRes = 0; // number of an atom in a residue int nbResidue = 0; // total number of residues int nbMolecule = 0; // total number of molecule Atom * AtomicOld = nullptr; Atom * AtomicNext = nullptr; int serial; //Atom serial number G4String atomName; //Atom name G4String element; //Element Symbol G4String helper; G4String resName; //Residue name for this atom double x, y, z; //Orthogonal coordinates in Angstroms double occupancy; //Occupancy Residue * residueOld = nullptr; Residue * residueFirst = nullptr; Residue * residueNext = nullptr; Molecule * moleculeFirst = nullptr; Molecule * moleculeOld = nullptr; Molecule * moleculeNext = nullptr; ///////////////////////////////// //NEW variable to draw a fitting cylinder if z oriented //=> fitting box double minGlobZ, maxGlobZ; double minGlobX, maxGlobX; double minGlobY, maxGlobY; double minX, maxX, minY, maxY, minZ, maxZ; //Sort of 'mother volume' box minGlobZ = -DBL_MAX; minGlobX = -DBL_MAX; minGlobY = -DBL_MAX; maxGlobZ = DBL_MAX; maxGlobX = DBL_MAX; maxGlobY = DBL_MAX; minX = -DBL_MAX; minY = -DBL_MAX; minZ = -DBL_MAX; maxX = DBL_MAX; maxY = DBL_MAX; maxZ = DBL_MAX; int lastResSeq = -1; int resSeq = 0; G4String nameMol; unsigned short int numModel = 0; unsigned short int model = 0; //Number of TER int ter = 0; //Number of TER (chain) max for this file int terMax = INT_MAX; if(!infile.eof()) { getline(infile, sLine); std::size_t found = sLine.find("DNA"); if(found != G4String::npos) { terMax = 2; isDNA = 0; } else { G4cout<<"NOT DNA"; isDNA = 0; } //If PDB file have not a header line found = sLine.find("HEADER"); if(found == G4String::npos) { infile.close(); infile.open(filename.c_str()); G4cout << "PDBlib::load >> No header found !!!!" << G4endl; } } while(!infile.eof()) { getline(infile, sLine); //In the case of several models if((sLine.substr(0, 6)).compare("NUMMDL") == 0) { istringstream((sLine.substr(10, 4))) >> numModel; } if((numModel > 0) && ((sLine.substr(0, 6)).compare("MODEL ") == 0)) { istringstream((sLine.substr(10, 4))) >> model; ////////////////////////////////////////// if(model > 1) break; ////////////////////////////////////////// } //For verification of residue sequence if((sLine.substr(0, 6)).compare("SEQRES") == 0) { //Create list of molecule here if(verbose > 1) G4cout << sLine << G4endl; } //Coordinate section if((numModel > 0) && ((sLine.substr(0, 6)).compare("ENDMDL") == 0)) { ; } else if((sLine.substr(0, 6)).compare("TER ") == 0) //3 spaces { ////////////////////////////////////////// //Currently retrieve only the two first chains(TER) => two DNA strands ter++; if(ter > terMax) break; ////////////////////////////////////////// //if (verbose>1) G4cout << sLine << G4endl; /************ Begin TER ******************/ lastResSeq = -1; resSeq = 0; AtomicOld->SetNext(NULL); residueOld->SetNext(NULL); residueOld->fNbAtom = nbAtom; //Molecule creation: if(moleculeOld == NULL) { nameMol = filename; //+numModel moleculeOld = new Molecule(nameMol, nbMolecule); moleculeOld->SetFirst(residueFirst); moleculeOld->fNbResidue = nbResidue; moleculeFirst = moleculeOld; } else { moleculeNext = new Molecule(nameMol, nbMolecule); moleculeOld->SetNext(moleculeNext); moleculeNext->SetFirst(residueFirst); moleculeNext->fNbResidue = nbResidue; moleculeOld = moleculeNext; } nbMolecule++; moleculeOld->SetNext(NULL); moleculeOld->fCenterX = (int) ((minX + maxX) / 2.); moleculeOld->fCenterY = (int) ((minY + maxY) / 2.); moleculeOld->fCenterZ = (int) ((minZ + maxZ) / 2.); moleculeOld->fMaxGlobZ = maxGlobZ; moleculeOld->fMinGlobZ = minGlobZ; moleculeOld->fMaxGlobX = maxGlobX; moleculeOld->fMinGlobX = minGlobX; moleculeOld->fMaxGlobY = maxGlobY; moleculeOld->fMinGlobY = minGlobY; minGlobZ = -DBL_MAX; minGlobX = -DBL_MAX; minGlobY = -DBL_MAX; maxGlobZ = DBL_MAX; maxGlobX = DBL_MAX; maxGlobY = DBL_MAX; minX = -DBL_MAX; minY = -DBL_MAX; minZ = -DBL_MAX; maxX = DBL_MAX; maxY = DBL_MAX; maxZ = DBL_MAX; nbAtom = 0; numAtomInRes = 0; nbResidue = 0; AtomicOld = NULL; AtomicNext = NULL; residueOld = NULL; residueFirst = NULL; residueNext = NULL; ///////////// End TER /////////////////// } else if((sLine.substr(0, 6)).compare("ATOM ") == 0) { /************ Begin ATOM ******************/ //serial istringstream((sLine.substr(8, 20))) >> serial; //To be improved //atomName : //atomName = sLine.substr(12, 4); element = sLine.substr(sLine.length()-4, 1); helper = sLine; //if(atomName.substr(0, 1).compare(" ") == 0) element = sLine.substr(13, //1); //else element = sLine.substr(12, 1); // set Van der Waals radius expressed in Angstrom double vdwRadius = -1.; if(element == "H") { vdwRadius = 1.2; } else if(element == "C") { vdwRadius = 1.7; } else if(element == "N") { vdwRadius = 1.55; } else if(element == "O") { vdwRadius = 1.52; } else if(element == "P") { vdwRadius = 1.8; } else if(element == "S") { vdwRadius = 1.8; } else { #ifndef GEANT4 G4cerr << "Element not recognized : " << element << helper << G4endl; G4cerr << "Stop now" << G4endl; exit(1); #else G4ExceptionDescription errMsg; errMsg << "Element not recognized : " << element << helper << G4endl; G4Exception("PDBlib::Load", "ELEM_NOT_RECOGNIZED", FatalException, errMsg); #endif } { nbAtomTot++; //resName : resName = sLine.substr(17, 3); //resSeq : istringstream((sLine.substr(22, 4))) >> resSeq; //x,y,z : stringstream((sLine.substr(52, 20))) >> x; stringstream((sLine.substr(78, 20))) >> y; stringstream((sLine.substr(104, 20))) >> z; //occupancy : occupancy = 1.; if(minGlobZ < z) minGlobZ = z; if(maxGlobZ > z) maxGlobZ = z; if(minGlobX < x) minGlobX = x; if(maxGlobX > x) maxGlobX = x; if(minGlobY < y) minGlobY = y; if(maxGlobY > y) maxGlobY = y; if(minX > x) minX = x; if(maxX < x) maxX = x; if(minY > y) minY = y; if(maxY < y) maxY = y; if(minZ > z) minZ = z; if(maxZ < z) maxZ = z; //treatment for Atoms: if(AtomicOld == NULL) { AtomicOld = new Atom(serial, atomName, "", 0, 0, x, y, z, vdwRadius, occupancy, 0, element); AtomicOld->SetNext(NULL); //If only one Atom inside residue } else { AtomicNext = new Atom(serial, atomName, "", 0, 0, x, y, z, vdwRadius, occupancy, 0, element); AtomicOld->SetNext(AtomicNext); AtomicOld = AtomicNext; } nbAtom++; } //END if (element!="H") /****************************Begin Residue************************/ //treatment for residues: if(residueOld == NULL) { if(verbose > 2) G4cout << "residueOld == NULL" << G4endl; AtomicOld->fNumInRes = 0; residueOld = new Residue(resName, resSeq); residueOld->SetFirst(AtomicOld); residueOld->SetNext(NULL); residueFirst = residueOld; lastResSeq = resSeq; nbResidue++; } else { if(lastResSeq == resSeq) { numAtomInRes++; AtomicOld->fNumInRes = numAtomInRes; } else { numAtomInRes = 0; AtomicOld->fNumInRes = numAtomInRes; residueNext = new Residue(resName, resSeq); residueNext->SetFirst(AtomicOld); residueOld->SetNext(residueNext); residueOld->fNbAtom = nbAtom - 1; nbAtom = 1; residueOld = residueNext; lastResSeq = resSeq; nbResidue++; } } /////////////////////////End Residue//////////// ///////////// End ATOM /////////////////// } //END if Atom } //END while (!infile.eof()) infile.close(); return moleculeFirst; } //END else if (!infile) return NULL; } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... /** * \brief Compute barycenters * \details Compute barycenters and its coordinate * for nucleotides * \param moleculeListTemp * moleculeList * \return Barycenter * */ Barycenter * PDBlib::ComputeNucleotideBarycenters(Molecule * moleculeListTemp) { /////////////////////////////////////////////////////// //Placement and physical volume construction from memory Barycenter * BarycenterFirst = NULL; Barycenter * BarycenterOld = NULL; Barycenter * BarycenterNext = NULL; //Residue (Base, Phosphate,sugar) list Residue *residueListTemp; //Atom list inside a residu Atom *AtomTemp; int k = 0; int j_old = 0; while(moleculeListTemp) { residueListTemp = moleculeListTemp->GetFirst(); k++; int j = 0; //Check numerotation style (1->n per strand or 1->2n for two strand) int correctNumerotationNumber = 0; if(k == 2 && residueListTemp->fResSeq > 1) { correctNumerotationNumber = residueListTemp->fResSeq; } while(residueListTemp) { AtomTemp = residueListTemp->GetFirst(); j++; //Correction consequently to numerotation check if(correctNumerotationNumber != 0) { residueListTemp->fResSeq = residueListTemp->fResSeq - correctNumerotationNumber + 1; } //Barycenter computation double baryX = 0., baryY = 0., baryZ = 0.; double baryBaseX = 0., baryBaseY = 0., baryBaseZ = 0.; double barySugX = 0., barySugY = 0., barySugZ = 0.; double baryPhosX = 0., baryPhosY = 0., baryPhosZ = 0.; unsigned short int nbAtomInBase = 0; for(int i = 0; i < residueListTemp->fNbAtom; i++) { //Compute barycenter of the nucletotide baryX += AtomTemp->fX; baryY += AtomTemp->fY; baryZ += AtomTemp->fZ; //Compute barycenters for Base Sugar Phosphat if(residueListTemp->fResSeq == 1) { if(i == 0) { baryPhosX += AtomTemp->fX; baryPhosY += AtomTemp->fY; baryPhosZ += AtomTemp->fZ; } else if(i < 8) { barySugX += AtomTemp->fX; barySugY += AtomTemp->fY; barySugZ += AtomTemp->fZ; } else { //hydrogen are placed at the end of the residue in a PDB file //We don't want them for this calculation if(AtomTemp->fElement != "H") { baryBaseX += AtomTemp->fX; baryBaseY += AtomTemp->fY; baryBaseZ += AtomTemp->fZ; nbAtomInBase++; } } } else { if(i < 4) { baryPhosX += AtomTemp->fX; baryPhosY += AtomTemp->fY; baryPhosZ += AtomTemp->fZ; } else if(i < 11) { barySugX += AtomTemp->fX; barySugY += AtomTemp->fY; barySugZ += AtomTemp->fZ; } else { //hydrogen are placed at the end of the residue in a PDB file //We don't want them for this calculation if(AtomTemp->fElement != "H") { // break; baryBaseX += AtomTemp->fX; baryBaseY += AtomTemp->fY; baryBaseZ += AtomTemp->fZ; nbAtomInBase++; } } } AtomTemp = AtomTemp->GetNext(); } //end of for ( i=0 ; i < residueListTemp->nbAtom ; i++) baryX = baryX / (double) residueListTemp->fNbAtom; baryY = baryY / (double) residueListTemp->fNbAtom; baryZ = baryZ / (double) residueListTemp->fNbAtom; if(residueListTemp->fResSeq != 1) //Special case first Phosphate { baryPhosX = baryPhosX / 4.; baryPhosY = baryPhosY / 4.; baryPhosZ = baryPhosZ / 4.; } barySugX = barySugX / 7.; barySugY = barySugY / 7.; barySugZ = barySugZ / 7.; baryBaseX = baryBaseX / (double) nbAtomInBase; baryBaseY = baryBaseY / (double) nbAtomInBase; baryBaseZ = baryBaseZ / (double) nbAtomInBase; //Barycenter creation: if(BarycenterOld == NULL) { BarycenterOld = new Barycenter(j + j_old, baryX, baryY, baryZ, //j [1..n] baryBaseX, baryBaseY, baryBaseZ, barySugX, barySugY, barySugZ, baryPhosX, baryPhosY, baryPhosZ); BarycenterFirst = BarycenterOld; } else { BarycenterNext = new Barycenter(j + j_old, baryX, baryY, baryZ, baryBaseX, baryBaseY, baryBaseZ, barySugX, barySugY, barySugZ, baryPhosX, baryPhosY, baryPhosZ); BarycenterOld->SetNext(BarycenterNext); BarycenterOld = BarycenterNext; } ///////////////////////////////////////////////// //distance computation between all atoms inside //a residue and the barycenter AtomTemp = residueListTemp->GetFirst(); double dT3Dp; double max = 0.; for(int ii = 0; ii < residueListTemp->fNbAtom; ii++) { dT3Dp = DistanceTwo3Dpoints(AtomTemp->fX, BarycenterOld->fCenterX, AtomTemp->fY, BarycenterOld->fCenterY, AtomTemp->fZ, BarycenterOld->fCenterZ); BarycenterOld->SetDistance(ii, dT3Dp); if(dT3Dp > max) max = dT3Dp; AtomTemp = AtomTemp->GetNext(); } //end of for ( i=0 ; i < residueListTemp->nbAtom ; i++) BarycenterOld->SetRadius(max + 1.8); residueListTemp = residueListTemp->GetNext(); } //end of while sur residueListTemp j_old += j; ///molecs->push_back(*moleculeListTemp); moleculeListTemp = moleculeListTemp->GetNext(); } //end of while sur moleculeListTemp if(BarycenterNext != NULL) { BarycenterNext->SetNext(NULL); } return BarycenterFirst; } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... /** * \brief the corresponding bounding volume parameters * \details the corresponding bounding volume parameters * to build a box from atoms coordinates */ void PDBlib::ComputeBoundingVolumeParams(Molecule *moleculeListTemp, double &dX, double &dY, double &dZ, //Dimensions for bounding volume double &tX, double &tY, double &tZ) //Translation for bounding volume { double minminX, minminY, minminZ; //minimum minimorum double maxmaxX, maxmaxY, maxmaxZ; //maximum maximorum minminX = DBL_MAX; minminY = DBL_MAX; minminZ = DBL_MAX; maxmaxX = -DBL_MAX; maxmaxY = -DBL_MAX; maxmaxZ = -DBL_MAX; while(moleculeListTemp) { if(minminX > moleculeListTemp->fMaxGlobX) { minminX = moleculeListTemp->fMaxGlobX; } if(minminY > moleculeListTemp->fMaxGlobY) { minminY = moleculeListTemp->fMaxGlobY; } if(minminZ > moleculeListTemp->fMaxGlobZ) { minminZ = moleculeListTemp->fMaxGlobZ; } if(maxmaxX < moleculeListTemp->fMinGlobX) { maxmaxX = moleculeListTemp->fMinGlobX; } if(maxmaxY < moleculeListTemp->fMinGlobY) { maxmaxY = moleculeListTemp->fMinGlobY; } if(maxmaxZ < moleculeListTemp->fMinGlobZ) { maxmaxZ = moleculeListTemp->fMinGlobZ; } moleculeListTemp = moleculeListTemp->GetNext(); } //end of while sur moleculeListTemp dX = (maxmaxX - minminX) / 2. + 1.8; //1.8 => size of biggest radius for atoms dY = (maxmaxY - minminY) / 2. + 1.8; dZ = (maxmaxZ - minminZ) / 2. + 1.8; tX = minminX + (maxmaxX - minminX) / 2.; tY = minminY + (maxmaxY - minminY) / 2.; tZ = minminZ + (maxmaxZ - minminZ) / 2.; } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... /** * \brief Compute number of nucleotide per strand * \details Compute number of nucleotide per strand * for DNA */ void PDBlib::ComputeNbNucleotidsPerStrand(Molecule * moleculeListTemp) { Residue *residueListTemp; int k = 0; int j_old = 0; while(moleculeListTemp) { residueListTemp = moleculeListTemp->GetFirst(); k++; int j = 0; while(residueListTemp) { j++; residueListTemp = residueListTemp->GetNext(); } //end of while sur residueListTemp j_old += j; moleculeListTemp = moleculeListTemp->GetNext(); } //end of while sur moleculeListTemp fNbNucleotidsPerStrand = j_old / 2; } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... /** * \brief Compute barycenters * \details Compute barycenters and its coordinate * for nucleotides */ unsigned short int PDBlib::ComputeMatchEdepDNA(Barycenter *BarycenterList, Molecule *moleculeListTemp, double x, double y, double z, int &numStrand, int &numNucleotid, int &codeResidue) { unsigned short int matchFound = 0; Molecule *mLTsavedPointer = moleculeListTemp; Barycenter *BLsavedPointer = BarycenterList; short int strandNum = 0; //Strand number int residueNum = 1; //Residue (nucleotide) number G4String baseName; //Base name [A,C,T,G] unsigned short int BSP = 2; //Base (default value), Sugar, Phosphat double smallestDist; //smallest dist Atom <-> edep coordinates double distEdepDNA; double distEdepAtom; //Residue (Base, Phosphate,suggar) list Residue *residueListTemp; //Atom list inside a residue Atom *AtomTemp; int k = 0; //Molecule number moleculeListTemp = mLTsavedPointer; BarycenterList = BLsavedPointer; smallestDist = 33.0; //Sufficiently large value while(moleculeListTemp) { k++; residueListTemp = moleculeListTemp->GetFirst(); int j = 0; //Residue number int j_save = INT_MAX; //Saved res. number if match found while(residueListTemp) { j++; if(j - j_save > 2) break; distEdepDNA = DistanceTwo3Dpoints(x, BarycenterList->fCenterX, y, BarycenterList->fCenterY, z, BarycenterList->fCenterZ); if(distEdepDNA < BarycenterList->GetRadius()) { //Find the closest atom //Compute distance between energy deposited and atoms for a residue //if distance <1.8 then match OK but search inside 2 next residues AtomTemp = residueListTemp->GetFirst(); for(int iii = 0; iii < residueListTemp->fNbAtom; iii++) { distEdepAtom = DistanceTwo3Dpoints(x, AtomTemp->GetX(), y, AtomTemp->GetY(), z, AtomTemp->GetZ()); if((distEdepAtom < AtomTemp->GetVanDerWaalsRadius()) && (smallestDist > distEdepAtom)) { strandNum = k; if(k == 2) { residueNum = fNbNucleotidsPerStrand + 1 - residueListTemp->fResSeq; } else { residueNum = residueListTemp->fResSeq; } baseName = (residueListTemp->fResName)[2]; if(residueListTemp->fResSeq == 1) { if(iii == 0) BSP = 0; //"Phosphate" else if(iii < 8) BSP = 1; //"Sugar" else BSP = 2; //"Base" } else { if(iii < 4) BSP = 0; //"Phosphate" else if(iii < 11) BSP = 1; //"Sugar" else BSP = 2; //"Base" } smallestDist = distEdepAtom; int j_max_value = INT_MAX; if(j_save == j_max_value) j_save = j; matchFound = 1; } AtomTemp = AtomTemp->GetNext(); } //end of for ( iii=0 ; iii < residueListTemp->nbAtom ; iii++) } //end for if (distEdepDNA < BarycenterList->GetRadius()) BarycenterList = BarycenterList->GetNext(); residueListTemp = residueListTemp->GetNext(); } //end of while sur residueListTemp moleculeListTemp = moleculeListTemp->GetNext(); } //end of while sur moleculeListTemp numStrand = strandNum; numNucleotid = residueNum; codeResidue = BSP; return matchFound; } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... double PDBlib::DistanceTwo3Dpoints(double xA, double xB, double yA, double yB, double zA, double zB) { return sqrt((xA - xB) * (xA - xB) + (yA - yB) * (yA - yB) + (zA - zB) * (zA - zB)); }
eab846d15360118dbc7b2bcf58b2012df897dbac
39c885e8a20b9e7146f351fa43513837630f1ded
/webpagetest/agent/wptdriver/wptdriver.cc
5e4ffbac4c640335b2b8e63b489de99ad2346c2e
[]
no_license
youleiy/di
3f95ccef08708a48e7c265249b445bf1e80bdb06
a82782560b22df665575e662ea4c888d22e79f96
refs/heads/master
2021-01-14T09:41:57.667390
2014-01-01T04:27:20
2014-01-01T04:27:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,772
cc
/****************************************************************************** Copyright (c) 2010, 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 the <ORGANIZATION> 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. ******************************************************************************/ // wptdriver.cpp : Defines the entry point for the application. // #include "stdafx.h" #include "wptdriver.h" #include "wpt_driver_core.h" #define MAX_LOADSTRING 100 WptStatus * global_status = NULL; // Global Variables: HINSTANCE hInst; // current instance TCHAR szTitle[MAX_LOADSTRING]; // The title bar text const TCHAR * szWindowClass = _T("wptdriver_wnd");// the main window class name // Forward declarations of functions included in this code module: ATOM MyRegisterClass(HINSTANCE hInstance); HWND InitInstance(HINSTANCE, int); LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM); int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); // TODO: Place code here. MSG msg; HACCEL hAccelTable; // Initialize global strings LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); MyRegisterClass(hInstance); // Perform application initialization: HWND hWnd = InitInstance (hInstance, nCmdShow); if (!hWnd) { return FALSE; } hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_WPTDRIVER)); // initialize winsock WORD wVersionRequested = MAKEWORD(2, 2); WSADATA wsaData; WSAStartup(wVersionRequested, &wsaData); // start up the actual core code ClipCursor(NULL); SetCursorPos(0,0); WptStatus status(hWnd); global_status = &status; WptDriverCore core(status); core.Start(); // Main message loop: while (GetMessage(&msg, NULL, 0, 0)) { if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } core.Stop(); global_status = NULL; WSACleanup(); return (int) msg.wParam; } // // FUNCTION: MyRegisterClass() // // PURPOSE: Registers the window class. // ATOM MyRegisterClass(HINSTANCE hInstance) { WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_WPTDRIVER)); wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wcex.lpszMenuName = MAKEINTRESOURCE(IDC_WPTDRIVER); wcex.lpszClassName = szWindowClass; wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_WPTDRIVER)); return RegisterClassEx(&wcex); } // // FUNCTION: InitInstance(HINSTANCE, int) // // PURPOSE: Saves instance handle and creates main window // // COMMENTS: // // In this function, we save the instance handle in a global variable and // create and display the main program window. // HWND InitInstance(HINSTANCE hInstance, int nCmdShow) { HWND hWnd; hInst = hInstance; // Store instance handle in our global variable hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW, 0, 0, 500, 100, NULL, NULL, hInstance, NULL); if (hWnd) { ShowWindow(hWnd, SW_SHOWMINNOACTIVE); UpdateWindow(hWnd); } return hWnd; } // // FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM) // // PURPOSE: Processes messages for the main window. // // WM_COMMAND - process the application menu // WM_PAINT - Paint the main window // WM_DESTROY - post a quit message and return // // LRESULT CALLBACK WndProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { int wmId, wmEvent; switch (message) { case WM_COMMAND: wmId = LOWORD(wParam); wmEvent = HIWORD(wParam); // Parse the menu selections: switch (wmId) { case IDM_ABOUT: DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About); break; case IDM_EXIT: DestroyWindow(hWnd); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } break; case WM_PAINT: if( global_status ) global_status->OnPaint(hWnd); break; case WM_DESTROY: PostQuitMessage(0); break; case UWM_UPDATE_STATUS: if( global_status ) global_status->OnUpdateStatus(); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; } // Message handler for about box. INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { UNREFERENCED_PARAMETER(lParam); switch (message){ case WM_INITDIALOG: return (INT_PTR)TRUE; case WM_COMMAND: if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL){ EndDialog(hDlg, LOWORD(wParam)); return (INT_PTR)TRUE; } break; } return (INT_PTR)FALSE; }
bd85e64f604fb83cc4f5dc2ebc716f958f3b4b81
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/CMake/CMake-gumtree/Kitware_CMake_old_hunk_665.cpp
165ee2a834dd38fae35123d7279acd26b72077e0
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
102
cpp
} fprintf(out, "%s\n", format_ptr); free(format_ptr); co=co->next; } }
c15f1db951b1e2348379ea45e39baa0930876c4e
7f33e5d8b124f899ab3f3a7e72c4624f1ef6d7ef
/1503-StructByLightning-LostSamurai-StrawManProject/Lost Samurai/Last Samurai/FinalDoor.h
99d960d1bbfd80777db27f18c8d19680c596cdc5
[]
no_license
CnoteSBL43/StructByLightningLastSamurai
7c7fbb379257f75f57c33dd20979c6a1fe080138
d316eab9a5751c8cea252bc55be3f1d30a7dc26f
refs/heads/master
2021-01-13T02:09:05.875368
2015-04-25T16:30:45
2015-04-25T16:30:45
32,112,849
0
0
null
null
null
null
UTF-8
C++
false
false
292
h
#pragma once #include "Actor.h" class FinalDoor : public Actor { public: FinalDoor(); ~FinalDoor(); void Update(float elapsedTime); void Render(void); int GetType(void) const { return ENT_FINALDOOR; } SGD::Rectangle GetRect(void) const; void HandleCollision(IEntity* pOther); };
ee346face4187b940ba79fa8f14261e73fe03727
71734273f0efd015e771aeb8026e2cdb045870cc
/wke/wke2.cpp
b79a983e3c42277fdcf0a370c19ed4ce26c2c285
[ "Apache-2.0" ]
permissive
killvxk/miniblink49
6efc4ff4a65eaface992d6bf02e537caa9131ed2
ff3d0e133d18de1748c688b0c0e173965db17033
refs/heads/master
2020-03-18T01:43:40.001114
2019-04-27T12:11:45
2019-04-27T12:11:45
134,156,673
1
0
MIT
2019-04-27T12:11:46
2018-05-20T14:17:42
C++
GB18030
C++
false
false
17,841
cpp
#include "wke/wke2.h" #include "wke/wkeString.h" #include "wke/wkeWebView.h" #include "wke/wkeWebWindow.h" #include "wke/wkeGlobalVar.h" #include "content/browser/WebPage.h" #include "content/web_impl_win/BlinkPlatformImpl.h" #include "content/web_impl_win/WebThreadImpl.h" #include "content/resources/HeaderFooterHtml.h" #include "third_party/WebKit/Source/web/WebViewImpl.h" #include "third_party/WebKit/Source/web/WebSettingsImpl.h" #include "third_party/WebKit/public/web/WebPrintScalingOption.h" #include "third_party/WebKit/public/web/WebPrintParams.h" #include "third_party/WebKit/public/web/WebLocalFrame.h" #include "third_party/WebKit/public/web/WebScriptSource.h" #include "third_party/WebKit/public/web/WebDocument.h" #include "third_party/skia/include/core/SkStream.h" #include "third_party/skia/include/core/SkDocument.h" #include "third_party/skia/include/core/SkPicture.h" #include "third_party/skia/include/core/SkPictureRecorder.h" #include "skia/ext/refptr.h" #include "wtf/text/WTFString.h" #include "wtf/text/WTFStringUtil.h" #include "base/values.h" #include "base/json/json_writer.h" #include "net/WebURLLoaderInternal.h" #include "net/InitializeHandleInfo.h" #include <v8.h> #include <shlwapi.h> namespace wke { void printingTest(wkeWebView webview); wkeMemBuf* printingTest2(wkeWebView webview); const int kPointsPerInch = 72; // Length of an inch in CSS's 1px unit. // http://dev.w3.org/csswg/css3-values/#the-px-unit const int kPixelsPerInch = 96; const float kPrintingMinimumShrinkFactor = 1.25f; void changeRequestUrl(wkeNetJob jobPtr, const char* url) { wke::checkThreadCallIsValid(__FUNCTION__); net::WebURLLoaderInternal* job = (net::WebURLLoaderInternal*)jobPtr; blink::KURL newUrl(blink::ParsedURLString, url); job->m_response.setURL(newUrl); job->firstRequest()->setURL(newUrl); job->m_initializeHandleInfo->url = url; ASSERT(!job->m_url); } bool setDebugConfig(wkeWebView webview, const char* debugString, const char* param) { if (0 == strcmp(debugString, "changeRequestUrl")) { wkeNetJob job = (wkeNetJob)webview; changeRequestUrl(job, param); return true; } content::WebPage* webpage = nullptr; blink::WebViewImpl* webViewImpl = nullptr; blink::WebSettingsImpl* settings = nullptr; if (webview) webpage = webview->getWebPage(); if (webpage) webViewImpl = webpage->webViewImpl(); if (webViewImpl) settings = webViewImpl->settingsImpl(); String stringDebug(debugString); Vector<String> result; stringDebug.split(",", result); if (result.size() == 0) return true; String item = result[0]; if ("setCookieJarPath" == item || "setCookieJarFullPath" == item) { std::string pathStr(param); if (pathStr.size() == 0) return true; if ("setCookieJarPath" == item) { if (pathStr[pathStr.size() - 1] != '\\' && pathStr[pathStr.size() - 1] != '/') pathStr += '\\'; pathStr += "cookies.dat"; } std::vector<char> result; WTF::Utf8ToMByte(pathStr.c_str(), pathStr.size(), &result, CP_ACP); if (0 == result.size()) return true; result.push_back('\0'); webview->setCookieJarFullPath(&result[0]); return true; } else if ("setLocalStorageFullPath" == item) { std::string pathStr(param); if (pathStr.size() == 0) return true; webview->setLocalStorageFullPath(pathStr.c_str()); return true; } else if ("smootTextEnable" == item) { wke::g_smootTextEnable = atoi(param) == 1; } return false; } void printingTest(wkeWebView webview) { content::WebPage* webpage = webview->getWebPage(); blink::WebFrame* frame = webpage->mainFrame(); blink::WebRect printContentArea(0, 0, 500, 600); blink::WebRect printableArea(0, 0, 500, 600); blink::WebSize paperSize(500, 600); const int kPointsPerInch = 72; int printerDPI = kPointsPerInch; blink::WebPrintScalingOption printScalingOption = blink::WebPrintScalingOptionSourceSize; blink::WebPrintParams webkitParams(printContentArea, printableArea, paperSize, printerDPI, printScalingOption); blink::WebView* blinkWebView = frame->view(); blinkWebView->settings()->setShouldPrintBackgrounds(false); int pageCount = frame->printBegin(webkitParams); double cssScaleFactor = 1.0f; float webkitPageShrinkFactor = frame->getPrintPageShrink(0); float scaleFactor = cssScaleFactor * webkitPageShrinkFactor; SkPictureRecorder recorder; recorder.beginRecording(500 / scaleFactor, 600 / scaleFactor, NULL, 0); SkCanvas* canvas = recorder.getRecordingCanvas(); frame->printPage(0, canvas); frame->printEnd(); skia::RefPtr<SkPicture> content = skia::AdoptRef(recorder.endRecordingAsPicture()); SkDynamicMemoryWStream pdfStream; skia::RefPtr<SkDocument> pdfDoc = skia::AdoptRef(SkDocument::CreatePDF(&pdfStream)); SkRect contentArea = SkRect::MakeIWH(500, 600); SkCanvas* pdfCanvas = pdfDoc->beginPage(500, 600, nullptr); pdfCanvas->scale(scaleFactor, scaleFactor); pdfCanvas->drawPicture(content.get()); pdfCanvas->flush(); pdfDoc->endPage(); pdfDoc->close(); SkData* pdfData = (pdfStream.copyToData()); HANDLE hFile = CreateFileW(L"D:\\1.pdf", GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (!hFile || INVALID_HANDLE_VALUE == hFile) return; DWORD numberOfBytesWritten = 0; ::WriteFile(hFile, pdfData->data(), pdfData->size(), &numberOfBytesWritten, NULL); ::CloseHandle(hFile); pdfData->unref(); } void readFile(const wchar_t* path, std::vector<char>* buffer) { HANDLE hFile = CreateFileW(path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (INVALID_HANDLE_VALUE == hFile) return; DWORD fileSizeHigh; const DWORD bufferSize = ::GetFileSize(hFile, &fileSizeHigh); DWORD numberOfBytesRead = 0; buffer->resize(bufferSize); BOOL b = ::ReadFile(hFile, &buffer->at(0), bufferSize, &numberOfBytesRead, nullptr); ::CloseHandle(hFile); b = b; } static void executeScript(blink::WebFrame* frame, const char* scriptFormat, const base::Value& parameters) { std::string json; base::JSONWriter::Write(parameters, &json); const int strSize = 2 * (strlen(scriptFormat) + json.size()); char* script = (char*)malloc(strSize); sprintf(script, scriptFormat, json.c_str()); blink::WebScriptSource source(blink::WebString::fromUTF8(script)); frame->executeScript(source); free(script); } const char kPageLoadScriptFormat[] = "document.open(); document.write(%s); document.close();"; const char kSettingHeaderFooterDate[] = "date"; const char kPageSetupScriptFormat[] = "setup(%s);"; static int getWindowDPI(HWND hWnd) { HDC screenDC = ::GetDC(hWnd); int dpiX = ::GetDeviceCaps(screenDC, LOGPIXELSX);//96是100%、120是125% ::ReleaseDC(nullptr, screenDC); return dpiX; } int convertUnit(int value, int oldUnit, int newUnit) { // With integer arithmetic, to divide a value with correct rounding, you need // to add half of the divisor value to the dividend value. You need to do the // reverse with negative number. if (value >= 0) { return ((value * newUnit) + (oldUnit / 2)) / oldUnit; } else { return ((value * newUnit) - (oldUnit / 2)) / oldUnit; } } void printHeaderAndFooter( bool isPrintPageHeadAndFooter, blink::WebCanvas* canvas, int windowDPI, int pageNumber, int totalPages, const blink::WebFrame& sourceFrame, float webkitScaleFactor, blink::WebSize pageSizeInPt, int topMargin, int bottomMargin ) { blink::WebSize pageSizeInPx(convertUnit(pageSizeInPt.width, kPointsPerInch, windowDPI), convertUnit(pageSizeInPt.height, kPointsPerInch, windowDPI)); SkAutoCanvasRestore autoRestore(canvas, true); canvas->scale(1 / webkitScaleFactor, 1 / webkitScaleFactor); blink::WebView* webView = blink::WebView::create(NULL); webView->settings()->setJavaScriptEnabled(true); blink::WebLocalFrame* frame = blink::WebLocalFrame::create(blink::WebTreeScopeType::Document, NULL); webView->setMainFrame(frame); #if 0 std::vector<char> buffer; readFile(L"E:\\mycode\\miniblink49\\trunk\\content\\resources\\HeaderFooterHtml.htm", &buffer); base::StringValue html(std::string(buffer.data(), buffer.size())); #else base::StringValue html(std::string(content::kHeaderFooterHtml, sizeof(content::kHeaderFooterHtml))); #endif // Load page with script to avoid async operations. executeScript(frame, kPageLoadScriptFormat, html); SYSTEMTIME st = { 0 }; ::GetLocalTime(&st); char dataBuffer[0x100]; sprintf(dataBuffer, "%d-%d-%d", st.wYear, st.wMonth, st.wDay); base::DictionaryValue* options = new base::DictionaryValue(); options->SetBoolean("isPrintPageHeadAndFooter", isPrintPageHeadAndFooter); options->SetString("date", dataBuffer); options->SetDouble("width", pageSizeInPt.width); options->SetDouble("height", pageSizeInPt.height); options->SetDouble("topMargin", topMargin); options->SetDouble("bottomMargin", bottomMargin); char* pageNumberStr = (char*)malloc(0x100); sprintf(pageNumberStr, "%d/%d", pageNumber, totalPages); options->SetString("pageNumber", pageNumberStr); free(pageNumberStr); blink::KURL kurl = sourceFrame.document().url(); options->SetString("url", kurl.getUTF8String().utf8().data()); std::string title = sourceFrame.document().title().utf8(); options->SetString("title", title.empty() ? "print document" : title); executeScript(frame, kPageSetupScriptFormat, *options); blink::WebPrintParams webkitParams(pageSizeInPt); webkitParams.printerDPI = windowDPI; frame->printBegin(webkitParams); frame->printPage(0, canvas); frame->printEnd(); webView->close(); frame->close(); delete options; } const wkePdfDatas* printToPdf(wkeWebView webView, blink::WebFrame* webFrame, const wkePrintSettings* params) { content::WebPage* webpage = webView->getWebPage(); if (!webpage) return nullptr; blink::WebFrame* frame = webFrame; if (!frame) frame = webpage->mainFrame(); if (!frame) return nullptr; int windowDPI = 72; // chromium是用desired_dpi=72硬编码,而不是getWindowDPI(webView->windowHandle()); int dpi = params->dpi; int srcWidth = convertUnit(params->width, dpi, kPointsPerInch); // 转换成pt,但由于DPI是72,所以也可以说是px int srcHeight = convertUnit(params->height, dpi, kPointsPerInch); int marginTop = convertUnit(params->marginTop, dpi, kPointsPerInch); int marginBottom = convertUnit(params->marginBottom, dpi, kPointsPerInch); int marginLeft = convertUnit(params->marginLeft, dpi, kPointsPerInch); int marginRight = convertUnit(params->marginRight, dpi, kPointsPerInch); // PrepareFrameAndViewForPrint, ComputeWebKitPrintParamsInDesiredDpi blink::WebSize printContentSize(srcWidth - marginLeft - marginRight, srcHeight - marginTop - marginBottom); blink::WebRect printContentArea(0, 0, (printContentSize.width) /*/ kPrintingMinimumShrinkFactor*/, (printContentSize.height) /*/ kPrintingMinimumShrinkFactor*/); blink::WebSize paperSize(srcWidth, srcHeight); blink::WebRect printableArea(0, 0, paperSize.width, paperSize.height); SkRect clipRect = SkRect::MakeIWH(printContentSize.width, printContentSize.height); float webkitScaleFactor = 1.0 / kPrintingMinimumShrinkFactor; blink::WebPrintScalingOption printScalingOption = blink::WebPrintScalingOptionSourceSize; blink::WebPrintParams webkitParams(printContentArea, printableArea, paperSize, dpi, printScalingOption); blink::WebView* blinkWebView = frame->view(); blink::WebSize oldSize = webpage->viewportSize(); blink::WebSize printLayoutSize(printContentArea.width, printContentArea.height); if (params->isLandscape) printLayoutSize.width = ((int)((printLayoutSize.width) * kPrintingMinimumShrinkFactor)); else printLayoutSize.height = ((int)((printLayoutSize.height) * kPrintingMinimumShrinkFactor)); printLayoutSize.width = printLayoutSize.width; // convertUnit(printLayoutSize.width, kPointsPerInch, windowDPI); // pt -> px printLayoutSize.height = printLayoutSize.height; // convertUnit(printLayoutSize.height, kPointsPerInch, windowDPI); webpage->setViewportSize(printLayoutSize); // paperSize // double oldZoom = blinkWebView->zoomLevel(); // double zoomLevel = blink::WebView::zoomFactorToZoomLevel(0.5); // blinkWebView->setZoomLevel(zoomLevel); // float oldZoom = blinkWebView->pageScaleFactor(); // blinkWebView->setDefaultPageScaleLimits(0.5, 1.5); // blinkWebView->setPageScaleFactor(0.5); int pageCount = frame->printBegin(webkitParams); if (0 == pageCount) return nullptr; blinkWebView->settings()->setShouldPrintBackgrounds(params->isPrintBackgroud); wkePdfDatas* result = new wkePdfDatas(); result->count = pageCount; result->sizes = (size_t*)malloc(pageCount * sizeof(size_t*)); result->datas = (const void**)malloc(pageCount * sizeof(void*)); for (int i = 0; i < pageCount; ++i) { float webkitPageShrinkFactor = frame->getPrintPageShrink(i); SkDynamicMemoryWStream pdfStream; skia::RefPtr<SkDocument> document = skia::AdoptRef(SkDocument::CreatePDF(&pdfStream, kPointsPerInch)); SkCanvas* canvas = document->beginPage(srcWidth / webkitPageShrinkFactor, srcHeight / webkitPageShrinkFactor); canvas->scale(webkitPageShrinkFactor, webkitPageShrinkFactor); printHeaderAndFooter(params->isPrintPageHeadAndFooter, canvas, windowDPI, i + 1, pageCount, *frame, webkitPageShrinkFactor, paperSize, marginTop, marginBottom); SkRect clipRectTemp = SkRect::MakeIWH(clipRect.width() / webkitPageShrinkFactor, clipRect.height() / webkitPageShrinkFactor); canvas->save(); canvas->translate(marginLeft / webkitPageShrinkFactor, marginTop / webkitPageShrinkFactor); canvas->clipRect(clipRectTemp); frame->printPage(i, canvas); canvas->restore(); canvas->flush(); document->endPage(); document->close(); SkData* pdfData = pdfStream.copyToData(); result->sizes[i] = pdfData->size(); result->datas[i] = malloc(pdfData->size()); memcpy((void*)(result->datas[i]), pdfData->data(), pdfData->size()); pdfData->unref(); } frame->printEnd(); //blinkWebView->setZoomLevel(oldZoom); //blinkWebView->setPageScaleFactor(oldZoom); webpage->setViewportSize(oldSize); return result; } const wkeMemBuf* printToBitmap(wkeWebView webView, const wkeScreenshotSettings* settings) { content::WebPage* webpage = webView->getWebPage(); if (!webpage) return nullptr; blink::WebFrame* webFrame = webpage->mainFrame(); if (!webFrame) return nullptr; blink::WebSize contentsSize = webFrame->contentsSize(); int width = contentsSize.width; int height = contentsSize.height; if (width <= 0 || height <= 0) return nullptr; SkBitmap bitmap; bitmap.allocN32Pixels(width + 0.5, height + 0.5); SkCanvas canvas(bitmap); blink::WebString css; webFrame->drawInCanvas(blink::WebRect(0, 0, width, height), css, &canvas); canvas.flush(); size_t size = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + bitmap.getSize(); BITMAPFILEHEADER fileHeader = { 0x4d42, sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + size, 0, 0, sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) }; BITMAPINFOHEADER bmiHeader = { sizeof(BITMAPINFOHEADER), width, -height, 1, 32, BI_RGB, }; std::vector<char> bmpData; bmpData.resize(size); char* destBuffer = reinterpret_cast<char*>(&bmpData.at(0)); size_t offset = 0; memcpy(destBuffer, &fileHeader, sizeof(fileHeader)); offset += sizeof(fileHeader); memcpy(destBuffer + offset, &bmiHeader, sizeof(bmiHeader)); offset += sizeof(bmiHeader); bitmap.copyPixelsTo(destBuffer + offset, size); wkeMemBuf* result = wkeCreateMemBuf(nullptr, destBuffer, size); return result; } } void wkeUtilRelasePrintPdfDatas(const wkePdfDatas* datas) { for (int i = 0; i < datas->count; ++i) { free((void *)(datas->datas[i])); } free((void *)(datas->sizes)); free((void *)(datas->datas)); delete datas; } const wkePdfDatas* wkeUtilPrintToPdf(wkeWebView webView, wkeWebFrameHandle frameId, const wkePrintSettings* settings) { content::WebPage* webPage = webView->webPage(); blink::WebFrame* webFrame = webPage->getWebFrameFromFrameId(wke::CWebView::wkeWebFrameHandleToFrameId(webPage, frameId)); return wke::printToPdf(webView, webFrame, settings); } const wkeMemBuf* wkePrintToBitmap(wkeWebView webView, wkeWebFrameHandle frameId, const wkeScreenshotSettings* settings) { return wke::printToBitmap(webView, settings); }
0e0bb7824794f8a8baec9ea331f30de4ee78a776
af21c75b8f8d6edec51184b2c1dc0c427c7611ed
/palindromePermutation.c++
0ff8e4eb04018e6c2347bdaaa616dc435776efa3
[]
no_license
pkrc267/100-days-of-code-2
d054fa97960fad71290bd29449da1e3438856e2c
b02622d0444c976bfccdfbfbc51da22cb49a780a
refs/heads/master
2021-09-04T04:11:17.193917
2018-01-15T18:10:03
2018-01-15T18:10:03
115,356,281
0
0
null
null
null
null
UTF-8
C++
false
false
616
#include <iostream> #include <string> using namespace std; bool checkSingleOdd(int b){ return ((b & (b-1)) == 0); } int toggleBit(char c, int bv){ int mask = 1 << (c-'a'); if((bv & mask) == 0){ bv |= mask; } else{ bv &= (~mask); } return bv; } int createBitVector(string s){ int bv = 0; for(char c: s){ bv = toggleBit(c, bv); } return bv; } bool isPalindrome(string phrase){ int bitvector = createBitVector(phrase); return bitvector == 0 || checkSingleOdd(bitvector); } int main(){ string phrase; getline(cin, phrase); cout << (isPalindrome(phrase)? "true" : "false")<<'\n'; return 0; }
d8c1c11fee04e6e50e77b67ebb9c101e6c49678b
009e4a86676988858bdcc15ddf4d59ecf7d237f8
/lib/generate.h
08994cdefd585a22981f4e1245651bbe9c78b0ce
[]
no_license
santoshF/block_cipher
e47ebb90ebd7abd62a0699c06815e0dfbf31f446
0bbc3273cfe4349339acad872ba4f6fb6c88ff66
refs/heads/master
2021-01-10T21:43:47.372580
2013-05-30T11:41:34
2013-05-30T11:41:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,386
h
/* * ===================================================================================== * * Filename: generate.cpp * * Description: To generate random sequence of and ,or and not * * Version: 1.0 * Created: Wednesday 08 May 2013 11:00:31 IST * Revision: none * Compiler: gcc * * Author: Santosh Fernandes (), [email protected] * Organization: ISSC * * ===================================================================================== */ #ifndef GENERATE_H_ #define GENERATE_H_ #include <fstream> #include <iostream> #include <cstdlib> #include <ctime> #include "binary.h" using namespace std; void randomBit(int * randomArray,int numBits){ for(int i = 0 ; i < numBits ; i++) { randomArray[i] = rand()%2 + 0; // cout << randomArray[i]; //0001 } } string boolExp(int a) { string es; if( a == 0 ) es += " && "; else if( a == 1) es += " || "; return es; } /* * === FUNCTION ====================================================================== * Name: main * Description: * ===================================================================================== */ void randomFunc(int, ofstream & fout); int generate ( int numBits ) { // int numBits = 128; // binary(argc,argv); // char ch; // int i = 0; ofstream fout("generate.txt"); // Seed for random function is time i // int numBits = 64; // cout << time(NULL) <<endl; randomFunc(numBits,fout); fout<<"#"<<endl; randomFunc(numBits,fout); return EXIT_SUCCESS; } void randomFunc(int numBits , ofstream & fout) { int i = 0; srand( time(NULL) ); // Position of value int *randomArray = new int [numBits]; string res,es; string rest; int a; int j; //Number of Bit equals Number of Expressions for(j =0 ; j < numBits; j++) { //Number of Boolean Expression is n -2 for(i = 0 ; i < numBits-2 ; i++) { //Create Random bit array with numbits randomBit(randomArray,numBits); a = randomArray[i] ; // cout << a <<endl; //Choose Random bool expression es = boolExp(a); // cout << es; res += es; rest = res; } fout <<rest << endl; // fout <<rest << endl; res= " "; } return ; } #endif /* ---------- end of function main ---------- */
5734f40ba2f7b67d7633eb32c18f597f923450de
b1e50bfb9a67a052147aca076dfa0d4ec6c65aa1
/src/rpcdump.cpp
8ef8497ef29e9d1e6dea8a04eaefaac27a855d5d
[ "MIT" ]
permissive
solltex/clovercoin
3c7fc774aa346ffaee532e6964eb14dd995380a1
324c810e1bb8e593914d027e2eea4f6e6f4b15fe
refs/heads/master
2016-09-10T17:53:21.634945
2014-05-02T04:44:59
2014-05-02T04:44:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,114
cpp
// Copyright (c) 2009-2012 Bitcoin Developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "init.h" // for pwalletMain #include "bitcoinrpc.h" #include "ui_interface.h" #include "base58.h" #include <boost/lexical_cast.hpp> #define printf OutputDebugStringF using namespace json_spirit; using namespace std; class CTxDump { public: CBlockIndex *pindex; int64 nValue; bool fSpent; CWalletTx* ptx; int nOut; CTxDump(CWalletTx* ptx = NULL, int nOut = -1) { pindex = NULL; nValue = 0; fSpent = false; this->ptx = ptx; this->nOut = nOut; } }; Value importprivkey(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "importprivkey <CloverCoinprivkey> [label]\n" "Adds a private key (as returned by dumpprivkey) to your wallet."); string strSecret = params[0].get_str(); string strLabel = ""; if (params.size() > 1) strLabel = params[1].get_str(); CBitcoinSecret vchSecret; bool fGood = vchSecret.SetString(strSecret); if (!fGood) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key"); if (fWalletUnlockMintOnly) // ppcoin: no importprivkey in mint-only mode throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Wallet is unlocked for minting only."); CKey key; bool fCompressed; CSecret secret = vchSecret.GetSecret(fCompressed); key.SetSecret(secret, fCompressed); CKeyID vchAddress = key.GetPubKey().GetID(); { LOCK2(cs_main, pwalletMain->cs_wallet); pwalletMain->MarkDirty(); pwalletMain->SetAddressBookName(vchAddress, strLabel); if (!pwalletMain->AddKey(key)) throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet"); pwalletMain->ScanForWalletTransactions(pindexGenesisBlock, true); pwalletMain->ReacceptWalletTransactions(); } return Value::null; } Value dumpprivkey(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "dumpprivkey <CloverCoinaddress>\n" "Reveals the private key corresponding to <CloverCoinaddress>."); string strAddress = params[0].get_str(); CBitcoinAddress address; if (!address.SetString(strAddress)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid CloverCoin address"); if (fWalletUnlockMintOnly) // ppcoin: no dumpprivkey in mint-only mode throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Wallet is unlocked for minting only."); CKeyID keyID; if (!address.GetKeyID(keyID)) throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to a key"); CSecret vchSecret; bool fCompressed; if (!pwalletMain->GetSecret(keyID, vchSecret, fCompressed)) throw JSONRPCError(RPC_WALLET_ERROR, "Private key for address " + strAddress + " is not known"); return CBitcoinSecret(vchSecret, fCompressed).ToString(); }
174552dd8a5452c27a33c9e953dacd1adb44ea0c
98548e83dffc231000afdd6e1ffe978f1e94119b
/src/B0KstMuMu.cc
c87b02e4d654403efd9f6823dd0139474723d09a
[]
no_license
lixfrank/B0KstMuMuNtuple
720d3e7b8287b81278e234ab313ba3fb3dc70bc5
2cbc3384eadbc512a2ebf6417ce63ed8225c4dca
refs/heads/master
2020-05-21T03:00:39.563081
2018-12-06T14:02:29
2018-12-06T14:02:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
118,772
cc
// ################################################## // # Description: # // # Make rootTuple for b --> s mu+ mu- analysis # // # Original Author: Mauro Dinardo # // # Created: Mon Apr 27 09:53:19 MDT 2011 # // ################################################## // System include files #include <memory> // User include files #include "../interface/B0KstMuMu.h" #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/EDAnalyzer.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/EventSetup.h" #include "FWCore/Framework/interface/ESHandle.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/Common/interface/TriggerNames.h" #include "FWCore/ServiceRegistry/interface/Service.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "RecoVertex/AdaptiveVertexFit/interface/AdaptiveVertexFitter.h" #include "RecoVertex/KinematicFit/interface/KinematicConstrainedVertexFitter.h" #include "RecoVertex/KinematicFit/interface/TwoTrackMassKinematicConstraint.h" #include "RecoVertex/KinematicFitPrimitives/interface/MultiTrackKinematicConstraint.h" #include "RecoVertex/KinematicFit/interface/MassKinematicConstraint.h" #include "RecoVertex/KinematicFitPrimitives/interface/KinematicParticle.h" #include "RecoVertex/KinematicFitPrimitives/interface/RefCountedKinematicParticle.h" #include "RecoVertex/KinematicFitPrimitives/interface/TransientTrackKinematicParticle.h" #include "TrackingTools/Records/interface/TransientTrackRecord.h" #include "TrackingTools/IPTools/interface/IPTools.h" #include "HLTrigger/HLTcore/interface/HLTConfigProvider.h" #include "CommonTools/UtilAlgos/interface/TFileService.h" #include "DataFormats/Math/interface/LorentzVector.h" #include "TMath.h" #include <sstream> #include <utility> // #################### // # Global constants # // #################### #define TRKMAXR 110.0 // [cm] #define TRKMAXZ 280.0 // [cm] #define PRIVTXNDOF 4.0 #define PRIVTXMAXZ 50.0 // [cm] #define PRIVTXMAXR 2.0 // [cm] #define MUVARTOLE 0.01 // [From 0 to 1] #define HADVARTOLE 0.10 // [From 0 to 1] // ####################### // # Truth matching cuts # // ####################### #define RCUTMU 0.004 // [eta-phi] #define RCUTTRK 0.3 // [eta-phi] float mumasserr = 3.5e-9; B0KstMuMu::B0KstMuMu (const edm::ParameterSet& iConfig) : hltTriggerResults_ ( iConfig.getUntrackedParameter<std::string>("HLTriggerResults", std::string("HLT")) ), vtxSampleTag_ ( iConfig.getParameter<edm::InputTag>("VtxSample")), vtxSampleToken_ (consumes<reco::VertexCollection>(vtxSampleTag_)), beamSpotTag_ ( iConfig.getParameter<edm::InputTag>("BeamSpot")), beamSpotToken_ (consumes<reco::BeamSpot>(beamSpotTag_)), genParticlesTag_ ( iConfig.getUntrackedParameter<edm::InputTag>("GenParticles")), genParticlesToken_ (consumes<reco::GenParticleCollection>(genParticlesTag_)), muonTypeTag_ ( iConfig.getUntrackedParameter<edm::InputTag>("MuonType")), muonTypeToken_ (consumes< std::vector<pat::Muon> >(muonTypeTag_)), trackTypeTag_ ( iConfig.getUntrackedParameter<edm::InputTag>("TrackType")), trackTypeToken_ (consumes< std::vector<pat::GenericParticle> >(trackTypeTag_)), triggerResultTag_ (iConfig.getUntrackedParameter<edm::InputTag>("TriggerResult")), triggerResultToken_ (consumes<edm::TriggerResults>(triggerResultTag_)), puTag_ (iConfig.getUntrackedParameter<edm::InputTag>("PuInfoTag")), puToken_ (consumes<std::vector< PileupSummaryInfo>>(puTag_)), genFilterTag_ (iConfig.getUntrackedParameter<edm::InputTag>("GenFilterTag")), genFilterToken_ (consumes<GenFilterInfo,edm::InLumi>(genFilterTag_)), doGenReco_ ( iConfig.getUntrackedParameter<unsigned int>("doGenReco", 1) ), TrigTable_ ( iConfig.getParameter<std::vector<std::string> >("TriggerNames")), // # Load HLT-trigger cuts # CLMUMUVTX ( iConfig.getUntrackedParameter<double>("MuMuVtxCL") ), LSMUMUBS ( iConfig.getUntrackedParameter<double>("MuMuLsBS") ), DCAMUMU ( iConfig.getUntrackedParameter<double>("DCAMuMu") ), DCAMUBS ( iConfig.getUntrackedParameter<double>("DCAMuBS") ), COSALPHAMUMUBS ( iConfig.getUntrackedParameter<double>("cosAlphaMuMuBS") ), MUMINPT ( iConfig.getUntrackedParameter<double>("MinMupT") ), MUMAXETA ( iConfig.getUntrackedParameter<double>("MuEta") ), MINMUMUPT ( iConfig.getUntrackedParameter<double>("MuMupT") ), MINMUMUINVMASS ( iConfig.getUntrackedParameter<double>("MinMuMuMass") ), MAXMUMUINVMASS ( iConfig.getUntrackedParameter<double>("MaxMuMuMass") ), // # Load pre-selection cuts # B0MASSLOWLIMIT ( iConfig.getUntrackedParameter<double>("MinB0Mass") ), B0MASSUPLIMIT ( iConfig.getUntrackedParameter<double>("MaxB0Mass") ), CLB0VTX ( iConfig.getUntrackedParameter<double>("B0VtxCL") ), KSTMASSWINDOW ( iConfig.getUntrackedParameter<double>("KstMass") ), HADDCASBS ( iConfig.getUntrackedParameter<double>("HadDCASBS") ), MINHADPT ( iConfig.getUntrackedParameter<double>("HadpT") ), MAXB0PREMASS ( iConfig.getUntrackedParameter<double>("MaxB0RoughMass") ), printMsg ( iConfig.getUntrackedParameter<bool>("printMsg", false) ), theTree(0) { std::cout << "\n@@@ Ntuplizer configuration parameters @@@" << std::endl; std::cout << __LINE__ << " : hltTriggerResults = " << hltTriggerResults_ << std::endl; std::cout << __LINE__ << " : doGenReco = " << doGenReco_ << std::endl; std::cout << __LINE__ << " : printMsg = " << printMsg << std::endl; for (auto itrig : TrigTable_ ) std::cout << __LINE__ << " : HLT paths = " << itrig << std::endl; NTuple = new B0KstMuMuTreeContent(); NTuple->Init(); NTuple->ClearNTuple(); Utility = new Utils(); } B0KstMuMu::~B0KstMuMu () { delete NTuple; delete Utility; } void B0KstMuMu::analyze (const edm::Event& iEvent, const edm::EventSetup& iSetup) { // ###################### // # Internal Variables # // ###################### std::stringstream myString; std::string tmpString1, tmpString2, tmpString3, tmpString4; std::string MuMCat; std::string MuPCat; const ParticleMass muonMass = Utility->muonMass; const ParticleMass pionMass = Utility->pionMass; const ParticleMass kaonMass = Utility->kaonMass; float muonMassErr = Utility->muonMassErr; float pionMassErr = Utility->pionMassErr; float kaonMassErr = Utility->kaonMassErr; double chi; double ndf; double LSVtx; double LSVtxErr; double LSBS; double LSBSErr; double cosAlphaVtx; double cosAlphaVtxErr; double cosAlphaBS; double cosAlphaBSErr; double deltaEtaPhi; double pT; double eta; KinematicParticleFactoryFromTransientTrack partFactory; AdaptiveVertexFitter theVtxFitter; // Vertex fitter in nominal reconstruction KinematicParticleVertexFitter PartVtxFitter; // Vertex fit with vtx constraint ClosestApproachInRPhi ClosestApp; GlobalPoint XingPoint; reco::TrackRef muTrackTmp; reco::TrackRef muTrackm; reco::TrackRef muTrackp; reco::TrackRef Trackm; reco::TrackRef Trackp; std::pair <bool,Measurement1D> theDCAXVtx; TrajectoryStateClosestToPoint theDCAXBS; TrajectoryStateClosestToPoint traj; double mumMind0 = 100; double mupMind0 = 100; double TrkmMind0 = 100; double TrkpMind0 = 100; double mumMind0E, mupMind0E, TrkmMind0E, TrkpMind0E; double mumMinIP = 100; double mupMinIP = 100; double TrkmMinIP = 100; double TrkpMinIP = 100; double mumMinIPE, mupMinIPE, TrkmMinIPE, TrkpMinIPE; GlobalPoint vert; TLorentzVector mum_lv; TLorentzVector mup_lv; TLorentzVector jpsi_lv; TLorentzVector tkm_lv; TLorentzVector tkp_lv; TLorentzVector kst_lv; TLorentzVector kstbar_lv; std::vector<float> mum_isovec, mup_isovec, trkm_isovec, trkp_isovec; std::vector<float> mum_isopts, mup_isopts, trkm_isopts, trkp_isopts; std::vector<float> mum_isomom, mup_isomom, trkm_isomom, trkp_isomom; std::vector<float> mum_isodr, mup_isodr, trkm_isodr, trkp_isodr; if (printMsg) std::cout << "\n\n" << __LINE__ << " : @@@@@@ Start Analyzer @@@@@@" << std::endl; // Get Gen-Particles edm::Handle<reco::GenParticleCollection> genParticles; if ((doGenReco_ == 2) || (doGenReco_ == 3)) iEvent.getByToken(genParticlesToken_, genParticles); // Get magnetic field edm::ESHandle<MagneticField> bFieldHandle; iSetup.get<IdealMagneticFieldRecord>().get(bFieldHandle); // Get HLT results edm::Handle<edm::TriggerResults> hltTriggerResults; try { iEvent.getByToken(triggerResultToken_, hltTriggerResults); } catch ( ... ) { if (printMsg) std::cout << __LINE__ << " : couldn't get handle on HLT Trigger" << std::endl; } // ############################ // # Save trigger information # // ############################ HLTConfigProvider hltConfig_; bool changed = true; if (((hltTriggerResults.isValid() == false) || (hltConfig_.init(iEvent.getRun(), iSetup, hltTriggerResults_, changed) == false)) && (printMsg)) std::cout << __LINE__ << " : no trigger results" << std::endl; else { // Get hold of trigger names - based on TriggerResults object const edm::TriggerNames& triggerNames_ = iEvent.triggerNames(*hltTriggerResults); for (unsigned int itrig = 0; itrig < hltTriggerResults->size(); itrig++) { if ((*hltTriggerResults)[itrig].accept() == 1) { std::string trigName = triggerNames_.triggerName(itrig); int trigPrescale = hltConfig_.prescaleValue(itrig, trigName); if (printMsg) std::cout << __LINE__ << " : Trigger name in the event: " << trigName << "\twith prescale: " << trigPrescale << std::endl; // ################################ // # Save HLT trigger information # // ################################ for (unsigned int it = 0; it < TrigTable_.size(); it++){ if (trigName.find(TrigTable_[it]) != std::string::npos) { NTuple->TrigTable->push_back(trigName); NTuple->TrigPrescales->push_back(trigPrescale); break; } } } } if (NTuple->TrigTable->size() == 0) { NTuple->TrigTable->push_back("NotInTable"); NTuple->TrigPrescales->push_back(-1); } } if ((doGenReco_ == 1) || (doGenReco_ == 2)) { // Get BeamSpot edm::Handle<reco::BeamSpot> beamSpotH; iEvent.getByToken(beamSpotToken_, beamSpotH); reco::BeamSpot beamSpot = *beamSpotH; // Get primary vertex with BeamSpot constraint: ordered by the scalar sum of the |pT|^2 of the tracks that compose the vertex edm::Handle<reco::VertexCollection> recVtx; iEvent.getByToken(vtxSampleToken_, recVtx); if (recVtx->empty()) return; // skip the event if no PV found reco::Vertex bestVtx; reco::Vertex bestVtxReFit; for (std::vector<reco::Vertex>::const_iterator iVertex = recVtx->begin(); iVertex != recVtx->end(); iVertex++) { bestVtx = *(iVertex); if (bestVtx.isValid() == true) break; } // Get PAT Muons edm::Handle< std::vector<pat::Muon> > thePATMuonHandle; iEvent.getByToken(muonTypeToken_, thePATMuonHandle); // Get PAT Tracks edm::Handle< std::vector<pat::GenericParticle> > thePATTrackHandle; iEvent.getByToken(trackTypeToken_, thePATTrackHandle); if (printMsg) std::cout << __LINE__ << " : the event has: " << thePATMuonHandle->size() << " muons AND " << thePATTrackHandle->size() << " tracks" << std::endl; // ########### // # Get mu- # // ########### for (std::vector<pat::Muon>::const_iterator iMuonM = thePATMuonHandle->begin(); iMuonM != thePATMuonHandle->end(); iMuonM++) { bool skip = false; // ######################## // # Check mu- kinematics # // ######################## muTrackm = iMuonM->innerTrack(); if ((muTrackm.isNull() == true) || (muTrackm->charge() != -1)) continue; if (muTrackm->hitPattern().trackerLayersWithMeasurement() < 6) continue; if (muTrackm->hitPattern().pixelLayersWithMeasurement() < 1) continue; // ######################### // # Muon- pT and eta cuts # // ######################### pT = muTrackm -> pt(); eta = muTrackm -> eta(); if ((pT < (MUMINPT*(1.0-MUVARTOLE))) || (fabs(eta) > (MUMAXETA*(1.0+MUVARTOLE)))) { if (printMsg) std::cout << __LINE__ << " : break --> too low pT of mu- : " << pT << " or too high eta : " << eta << std::endl; break; } const reco::TransientTrack muTrackmTT(muTrackm, &(*bFieldHandle)); // ############################### // # Compute mu- DCA to BeamSpot # // ############################### theDCAXBS = muTrackmTT.trajectoryStateClosestToPoint(GlobalPoint(beamSpot.position().x(),beamSpot.position().y(),beamSpot.position().z())); if (theDCAXBS.isValid() == false) { if (printMsg) std::cout << __LINE__ << " : continue --> invalid absolute impact parameter 2D for mu-" << std::endl; continue; } double DCAmumBS = theDCAXBS.perigeeParameters().transverseImpactParameter(); double DCAmumBSErr = theDCAXBS.perigeeError().transverseImpactParameterError(); if (fabs(DCAmumBS) > DCAMUBS) { if (printMsg) std::cout << __LINE__ << " : continue --> bad absolute impact parameter 2D for mu- : " << DCAmumBS << std::endl; continue; } // ########### // # Get mu+ # // ########### for (std::vector<pat::Muon>::const_iterator iMuonP = thePATMuonHandle->begin(); iMuonP != thePATMuonHandle->end(); iMuonP++) { // ######################## // # Check mu+ kinematics # // ######################## muTrackp = iMuonP->innerTrack(); if ((muTrackp.isNull() == true) || (muTrackp->charge() != 1)) continue; if (muTrackp->hitPattern().trackerLayersWithMeasurement() < 6) continue; if (muTrackp->hitPattern().pixelLayersWithMeasurement() < 1) continue; // ######################### // # Muon+ pT and eta cuts # // ######################### pT = muTrackp->pt(); eta = muTrackp->eta(); if ((pT < (MUMINPT*(1.0-MUVARTOLE))) || (fabs(eta) > (MUMAXETA*(1.0+MUVARTOLE)))) { if (printMsg) std::cout << __LINE__ << " : break --> too low pT of mu+ : " << pT << " or too high eta : " << eta << std::endl; break; } const reco::TransientTrack muTrackpTT(muTrackp, &(*bFieldHandle)); // ############################### // # Compute mu+ DCA to BeamSpot # // ############################### theDCAXBS = muTrackpTT.trajectoryStateClosestToPoint(GlobalPoint(beamSpot.position().x(),beamSpot.position().y(),beamSpot.position().z())); if (theDCAXBS.isValid() == false) { if (printMsg) std::cout << __LINE__ << " : continue --> invalid absolute impact parameter 2D for mu+" << std::endl; continue; } double DCAmupBS = theDCAXBS.perigeeParameters().transverseImpactParameter(); double DCAmupBSErr = theDCAXBS.perigeeError().transverseImpactParameterError(); if (fabs(DCAmupBS) > DCAMUBS) { if (printMsg) std::cout << __LINE__ << " : continue --> bad absolute impact parameter 2D for mu+: " << DCAmupBS << std::endl; continue; } // ############################################ // # Check goodness of muons closest approach # // ############################################ ClosestApp.calculate(muTrackpTT.initialFreeState(),muTrackmTT.initialFreeState()); if (ClosestApp.status() == false) { if (printMsg) std::cout << __LINE__ << " : continue --> bad status of closest approach" << std::endl; continue; } XingPoint = ClosestApp.crossingPoint(); if ((sqrt(XingPoint.x()*XingPoint.x() + XingPoint.y()*XingPoint.y()) > TRKMAXR) || (fabs(XingPoint.z()) > TRKMAXZ)) { if (printMsg) std::cout << __LINE__ << " : continue --> closest approach crossing point outside the tracker volume" << std::endl; continue; } // ##################################################### // # Cut on the mumu 3D-DCA with respect to each other # // ##################################################### double mumuDCA = ClosestApp.distance(); if (mumuDCA > DCAMUMU) { if (printMsg) std::cout << __LINE__ << " : continue --> bad 3D-DCA of mu+(-) with respect to mu-(+): " << mumuDCA << std::endl; continue; } // ############################################ // # Cut on the dimuon inviariant mass and pT # // ############################################ mum_lv.SetPxPyPzE( muTrackmTT.track().px(), muTrackmTT.track().py(), muTrackmTT.track().pz(), sqrt( pow(muTrackmTT.track().p(),2) + pow(Utility->muonMass,2) )); mup_lv.SetPxPyPzE( muTrackpTT.track().px(), muTrackpTT.track().py(), muTrackpTT.track().pz(), sqrt( pow(muTrackpTT.track().p(),2) + pow(Utility->muonMass,2) )); jpsi_lv = mup_lv + mum_lv; if ((jpsi_lv.Pt() < (MINMUMUPT*(1.0-MUVARTOLE))) || (jpsi_lv.M() < (MINMUMUINVMASS*(1.0-MUVARTOLE))) || (jpsi_lv.M() > (MAXMUMUINVMASS*(1.0+MUVARTOLE)))) { if (printMsg) std::cout << __LINE__ << " : continue --> no good mumu pair pT: " << jpsi_lv.Pt() << "\tinv. mass: " << jpsi_lv.M() << std::endl; continue; } // ####################################################### // # @@@ Make mu-mu and implement pre-selection cuts @@@ # // ####################################################### if (printMsg) std::cout << "\n" << __LINE__ << " : @@@ I have 2 good oppositely-charged muons. I'm trying to vertex them @@@" << std::endl; chi = 0.; ndf = 0.; // #################################################### // # Try to vertex the two muons to get dimuon vertex # // #################################################### std::vector<RefCountedKinematicParticle> muonParticles; muonParticles.push_back(partFactory.particle(muTrackmTT,muonMass,chi,ndf,muonMassErr)); muonParticles.push_back(partFactory.particle(muTrackpTT,muonMass,chi,ndf,muonMassErr)); RefCountedKinematicTree mumuVertexFitTree = PartVtxFitter.fit(muonParticles); if (mumuVertexFitTree->isValid() == false) { if (printMsg) std::cout << __LINE__ << " : continue --> invalid vertex from the mu+ mu- vertex fit" << std::endl; continue; } mumuVertexFitTree->movePointerToTheTop(); RefCountedKinematicVertex mumu_KV = mumuVertexFitTree->currentDecayVertex(); if (mumu_KV->vertexIsValid() == false) { if (printMsg) std::cout << __LINE__ << " : continue --> invalid vertex from the mu+ mu- vertex fit" << std::endl; continue; } if (TMath::Prob(static_cast<double>(mumu_KV->chiSquared()), static_cast<int>(rint(mumu_KV->degreesOfFreedom()))) < CLMUMUVTX) { if (printMsg) std::cout << __LINE__ << " : continue --> bad vtx CL from mu+ mu- fit: " << TMath::Prob(static_cast<double>(mumu_KV->chiSquared()), static_cast<int>(rint(mumu_KV->degreesOfFreedom()))) << std::endl; continue; } RefCountedKinematicParticle mumu_KP = mumuVertexFitTree->currentParticle(); // ###################################################### // # Compute the distance between mumu vtx and BeamSpot # // ###################################################### double MuMuLSBS; double MuMuLSBSErr; Utility->computeLS (mumu_KV->position().x(),mumu_KV->position().y(),0.0, beamSpot.position().x(),beamSpot.position().y(),0.0, mumu_KV->error().cxx(),mumu_KV->error().cyy(),0.0, mumu_KV->error().matrix()(0,1),0.0,0.0, beamSpot.covariance()(0,0),beamSpot.covariance()(1,1),0.0, beamSpot.covariance()(0,1),0.0,0.0, &MuMuLSBS,&MuMuLSBSErr); if (MuMuLSBS/MuMuLSBSErr < LSMUMUBS) { if (printMsg) std::cout << __LINE__ << " : continue --> bad mumu L/sigma with respect to BeamSpot: " << MuMuLSBS << "+/-" << MuMuLSBSErr << std::endl; continue; } // ################################################################### // # Compute cos(alpha) between mumu momentum and mumuVtx - BeamSpot # // ################################################################### double MuMuCosAlphaBS; double MuMuCosAlphaBSErr; Utility->computeCosAlpha (mumu_KP->currentState().globalMomentum().x(),mumu_KP->currentState().globalMomentum().y(),0.0, mumu_KV->position().x() - beamSpot.position().x(),mumu_KV->position().y() - beamSpot.position().y(),0.0, mumu_KP->currentState().kinematicParametersError().matrix()(3,3),mumu_KP->currentState().kinematicParametersError().matrix()(4,4),0.0, mumu_KP->currentState().kinematicParametersError().matrix()(3,4),0.0,0.0, mumu_KV->error().cxx() + beamSpot.covariance()(0,0),mumu_KV->error().cyy() + beamSpot.covariance()(1,1),0.0, mumu_KV->error().matrix()(0,1) + beamSpot.covariance()(0,1),0.0,0.0, &MuMuCosAlphaBS,&MuMuCosAlphaBSErr); if (MuMuCosAlphaBS < COSALPHAMUMUBS) { if (printMsg) std::cout << __LINE__ << " : continue --> bad mumu cos(alpha) with respect to BeamSpot: " << MuMuCosAlphaBS << "+/-" << MuMuCosAlphaBSErr << std::endl; continue; } // ########################### convert KinFit vertex to reco Vertex (needed only to calculate pion IP from this vtx) // reco::Vertex::Point mumu_GP = reco::Vertex::Point(mumu_KV->position().x(), mumu_KV->position().y(), mumu_KV->position().z()); // const reco::Vertex::Error mumu_error = mumu_KV->vertexState().error().matrix(); // float mumu_chi2 = mumu_KV -> chiSquared(); // float mumu_ndof = mumu_KV -> degreesOfFreedom(); // reco::Vertex mumu_rv = reco::Vertex( mumu_GP, mumu_error, mumu_chi2, mumu_ndof, 2 ); // ############## // # Get Track- # // ############## for (std::vector<pat::GenericParticle>::const_iterator iTrackM = thePATTrackHandle->begin(); iTrackM != thePATTrackHandle->end(); iTrackM++) { bool skip = false; // ########################### // # Check Track- kinematics # // ########################### Trackm = iTrackM->track(); // if ((Trackm.isNull() == true) ) continue; if ((Trackm.isNull() == true) || (Trackm->charge() != -1)) continue; if (! Trackm->quality(reco::Track::highPurity)) continue; const reco::TransientTrack TrackmTT(Trackm, &(*bFieldHandle)); // ########################## // # Track- pT and eta cuts # // ########################## pT = TrackmTT.track().pt(); if (pT < (MINHADPT*(1.0-HADVARTOLE))) { if (printMsg) std::cout << __LINE__ << " : break --> too low pT of track- : " << pT << std::endl; break; } // ###################################### // # Compute K*0 track- DCA to BeamSpot # // ###################################### theDCAXBS = TrackmTT.trajectoryStateClosestToPoint(GlobalPoint(beamSpot.position().x(),beamSpot.position().y(),beamSpot.position().z())); if (theDCAXBS.isValid() == false) { if (printMsg) std::cout << __LINE__ << " : continue --> invalid absolute impact parameter 2D for track-" << std::endl; continue; } double DCAKstTrkmBS = theDCAXBS.perigeeParameters().transverseImpactParameter(); double DCAKstTrkmBSErr = theDCAXBS.perigeeError().transverseImpactParameterError(); if (fabs(DCAKstTrkmBS/DCAKstTrkmBSErr) < HADDCASBS) { if (printMsg) std::cout << __LINE__ << " : continue --> track- DCA/sigma with respect to BeamSpot is too small: " << DCAKstTrkmBS << "+/-" << DCAKstTrkmBSErr << std::endl; continue; } // ############## // # Get Track+ # // ############## for (std::vector<pat::GenericParticle>::const_iterator iTrackP = thePATTrackHandle->begin(); iTrackP != thePATTrackHandle->end(); iTrackP++) { // ########################### // # Check Track+ kinematics # // ########################### Trackp = iTrackP->track(); // if ((Trackp.isNull() == true) ) continue; if ((Trackp.isNull() == true) || (Trackp->charge() != 1)) continue; if (! Trackp->quality(reco::Track::highPurity)) continue; // same sign requirement for checks! // if (Trackp->charge()* Trackm->charge() != 1) continue; const reco::TransientTrack TrackpTT(Trackp, &(*bFieldHandle)); // ########################## // # Track+ pT and eta cuts # // ########################## pT = TrackpTT.track().pt(); if (pT < (MINHADPT*(1.0-HADVARTOLE))) { if (printMsg) std::cout << __LINE__ << " : break --> too low pT of track+ : " << pT << std::endl; break; } // ###################################### // # Compute K*0 track+ DCA to BeamSpot # // ###################################### theDCAXBS = TrackpTT.trajectoryStateClosestToPoint(GlobalPoint(beamSpot.position().x(),beamSpot.position().y(),beamSpot.position().z())); if (theDCAXBS.isValid() == false) { if (printMsg) std::cout << __LINE__ << " : continue --> invalid absolute impact parameter 2D for track+" << std::endl; continue; } double DCAKstTrkpBS = theDCAXBS.perigeeParameters().transverseImpactParameter(); double DCAKstTrkpBSErr = theDCAXBS.perigeeError().transverseImpactParameterError(); if (fabs(DCAKstTrkpBS/DCAKstTrkpBSErr) < HADDCASBS) { if (printMsg) std::cout << __LINE__ << " : continue --> track+ DCA/sigma with respect to BeamSpot is too small: " << DCAKstTrkpBS << "+/-" << DCAKstTrkpBSErr << std::endl; continue; } // ############################################## // # Check goodness of hadrons closest approach # // ############################################## ClosestApp.calculate(TrackpTT.initialFreeState(),TrackmTT.initialFreeState()); if (ClosestApp.status() == false) { if (printMsg) std::cout << __LINE__ << " : continue --> bad status of closest approach" << std::endl; continue; } XingPoint = ClosestApp.crossingPoint(); if ((sqrt(XingPoint.x()*XingPoint.x() + XingPoint.y()*XingPoint.y()) > TRKMAXR) || (fabs(XingPoint.z()) > TRKMAXZ)) { if (printMsg) std::cout << __LINE__ << " : continue --> closest approach crossing point outside the tracker volume" << std::endl; continue; } // ###################################################### // # Check if K*0 (OR K*0bar) mass is within acceptance # // ###################################################### tkm_lv.SetPxPyPzE(TrackmTT.track().momentum().x(), TrackmTT.track().momentum().y(), TrackmTT.track().momentum().z(), sqrt( pow(TrackmTT.track().p(),2) + pow(Utility->pionMass,2) )); tkp_lv.SetPxPyPzE(TrackpTT.track().momentum().x(), TrackpTT.track().momentum().y(), TrackpTT.track().momentum().z(), sqrt( pow(TrackpTT.track().p(),2) + pow(Utility->kaonMass,2) ) ); double kstInvMass = (tkm_lv + tkp_lv).M(); tkm_lv.SetE(sqrt( pow(TrackmTT.track().p(),2) + pow(Utility->kaonMass,2) )); tkp_lv.SetE(sqrt( pow(TrackpTT.track().p(),2) + pow(Utility->pionMass,2) )); double kstBarInvMass = (tkm_lv + tkp_lv).M(); if ((fabs(kstInvMass - Utility->kstMass) > (KSTMASSWINDOW*Utility->kstSigma*(1.0+HADVARTOLE))) && (fabs(kstBarInvMass - Utility->kstMass) > (KSTMASSWINDOW*Utility->kstSigma*(1.0+HADVARTOLE)))) { if (printMsg) std::cout << __LINE__ << " : continue --> bad K*0 mass: " << kstInvMass << " AND K*0bar mass: " << kstBarInvMass << std::endl; continue; } // #################################################### // # @@@ Make K* and implement pre-selection cuts @@@ # // #################################################### if (printMsg) std::cout << "\n" << __LINE__ << " : @@@ I have 2 good oppositely-charged tracks. I'm trying to vertex them @@@" << std::endl; chi = 0.; ndf = 0.; // ############################################################################## // # Try to vertex the two Tracks to get K*0 vertex: pion = track- | k = track+ # // ############################################################################## std::vector<RefCountedKinematicParticle> kstParticles; kstParticles.push_back(partFactory.particle(TrackmTT,pionMass,chi,ndf,pionMassErr)); kstParticles.push_back(partFactory.particle(TrackpTT,kaonMass,chi,ndf,kaonMassErr)); RefCountedKinematicTree kstVertexFitTree = PartVtxFitter.fit(kstParticles); if (kstVertexFitTree->isValid() == false) { if (printMsg) std::cout << __LINE__ << " : continue --> invalid vertex from the K*0 vertex fit" << std::endl; continue; } kstVertexFitTree->movePointerToTheTop(); RefCountedKinematicParticle kst_KP = kstVertexFitTree->currentParticle(); RefCountedKinematicVertex kst_KV = kstVertexFitTree->currentDecayVertex(); if (kst_KV->vertexIsValid() == false) { if (printMsg) std::cout << __LINE__ << " : continue --> invalid vertex from the K*0 vertex fit" << std::endl; continue; } chi = 0.; ndf = 0.; // ################################################################################# // # Try to vertex the two Tracks to get K*0bar vertex: pion = track+ | k = track- # // ################################################################################# std::vector<RefCountedKinematicParticle> kstBarParticles; kstBarParticles.push_back(partFactory.particle(TrackmTT,kaonMass,chi,ndf,kaonMassErr)); kstBarParticles.push_back(partFactory.particle(TrackpTT,pionMass,chi,ndf,pionMassErr)); RefCountedKinematicTree kstBarVertexFitTree = PartVtxFitter.fit(kstBarParticles); if (kstBarVertexFitTree->isValid() == false) { if (printMsg) std::cout << __LINE__ << " : continue --> invalid vertex from the K*0bar vertex fit" << std::endl; continue; } kstBarVertexFitTree->movePointerToTheTop(); RefCountedKinematicParticle kstBar_KP = kstBarVertexFitTree->currentParticle(); RefCountedKinematicVertex kstBar_KV = kstBarVertexFitTree->currentDecayVertex(); if (kstBar_KV->vertexIsValid() == false) { if (printMsg) std::cout << __LINE__ << " : continue --> invalid vertex from the K*0bar vertex fit" << std::endl; continue; } // ###################################################### // # Check if K*0 (OR K*0bar) mass is within acceptance # // ###################################################### kstInvMass = kst_KP->currentState().mass(); kstBarInvMass = kstBar_KP->currentState().mass(); if ((fabs(kstInvMass - Utility->kstMass) > KSTMASSWINDOW*Utility->kstSigma) && (fabs(kstBarInvMass - Utility->kstMass) > KSTMASSWINDOW*Utility->kstSigma)) { if (printMsg) std::cout << __LINE__ << " : continue --> bad K*0 mass: " << kstInvMass << " AND K*0bar mass: " << kstBarInvMass << std::endl; continue; } // #################################################### // # @@@ Make B0 and implement pre-selection cuts @@@ # // #################################################### if (printMsg) std::cout << "\n" << __LINE__ << " : @@@ I have 4 good charged tracks. I'm trying to vertex them @@@" << std::endl; TLorentzVector a_lv, b_lv, c_lv, d_lv, tot_lv; a_lv.SetPxPyPzE(muTrackmTT.track().momentum().x(), muTrackmTT.track().momentum().y(), muTrackmTT.track().momentum().z(), sqrt( pow(muTrackmTT.track().p(),2) + pow(Utility->muonMass,2) )); b_lv.SetPxPyPzE(muTrackpTT.track().momentum().x(), muTrackpTT.track().momentum().y(), muTrackpTT.track().momentum().z(), sqrt( pow(muTrackpTT.track().p(),2) + pow(Utility->muonMass,2) )); c_lv.SetPxPyPzE(TrackmTT.track().momentum().x(), TrackmTT.track().momentum().y(), TrackmTT.track().momentum().z(), sqrt( pow(TrackmTT.track().p(),2) + pow(Utility->pionMass,2) )); d_lv.SetPxPyPzE(TrackpTT.track().momentum().x(), TrackpTT.track().momentum().y(), TrackpTT.track().momentum().z(), sqrt( pow(TrackpTT.track().p(),2) + pow(Utility->kaonMass,2) )); tot_lv = a_lv + b_lv + c_lv + d_lv; if (tot_lv.M() > MAXB0PREMASS) { if (printMsg) std::cout << __LINE__ << " : continue --> b0 mass before fit is > max value" << std::endl; continue; } // ################################################# // # Check if the hadron Track- is actually a muon # // ################################################# MuMCat.clear(); MuMCat = "NotMatched"; for (std::vector<pat::Muon>::const_iterator iMuon = thePATMuonHandle->begin(); iMuon != thePATMuonHandle->end(); iMuon++) { muTrackTmp = iMuon->innerTrack(); // same sign check // if ((muTrackTmp.isNull() == true)) continue; if ((muTrackTmp.isNull() == true) || (muTrackTmp->charge() != -1)) continue; if (Trackm == muTrackTmp) { MuMCat.clear(); MuMCat.append(getMuCat(*iMuon)); if (printMsg) std::cout << __LINE__ << " : negative charged hadron is actually a muon (momentum: " << Trackm->p() << ") whose category is: " << MuMCat.c_str() << std::endl; break; } } // ################################################# // # Check if the hadron Track+ is actually a muon # // ################################################# MuPCat.clear(); MuPCat = "NotMatched"; for (std::vector<pat::Muon>::const_iterator iMuon = thePATMuonHandle->begin(); iMuon != thePATMuonHandle->end(); iMuon++) { muTrackTmp = iMuon->innerTrack(); // if ((muTrackTmp.isNull() == true) ) continue; if ((muTrackTmp.isNull() == true) || (muTrackTmp->charge() != 1)) continue; if (Trackp == muTrackTmp) { MuPCat.clear(); MuPCat.append(getMuCat(*iMuon)); if (printMsg) std::cout << __LINE__ << " : positive charged hadron is actually a muon (momentum: " << Trackp->p() << ") whose category is: " << MuPCat.c_str() << std::endl; break; } } chi = 0.; ndf = 0.; // ##################################### // # B0 vertex fit with vtx constraint # // ##################################### std::vector<RefCountedKinematicParticle> bParticles; bParticles.push_back(partFactory.particle(muTrackmTT,muonMass,chi,ndf,muonMassErr)); bParticles.push_back(partFactory.particle(muTrackpTT,muonMass,chi,ndf,muonMassErr)); bParticles.push_back(partFactory.particle(TrackmTT,pionMass,chi,ndf,pionMassErr)); bParticles.push_back(partFactory.particle(TrackpTT,kaonMass,chi,ndf,kaonMassErr)); RefCountedKinematicTree bVertexFitTree = PartVtxFitter.fit(bParticles); if (bVertexFitTree->isValid() == false) { if (printMsg) std::cout << __LINE__ << " : continue --> invalid vertex from the B0 vertex fit" << std::endl; continue; } bVertexFitTree->movePointerToTheTop(); RefCountedKinematicParticle b_KP = bVertexFitTree->currentParticle(); RefCountedKinematicVertex b_KV = bVertexFitTree->currentDecayVertex(); if (b_KV->vertexIsValid() == false) { if (printMsg) std::cout << __LINE__ << " : continue --> invalid vertex from the B0 vertex fit" << std::endl; continue; } chi = 0.; ndf = 0.; // ######################################## // # B0bar vertex fit with vtx constraint # // ######################################## std::vector<RefCountedKinematicParticle> bBarParticles; bBarParticles.push_back(partFactory.particle(muTrackmTT,muonMass,chi,ndf,muonMassErr)); bBarParticles.push_back(partFactory.particle(muTrackpTT,muonMass,chi,ndf,muonMassErr)); bBarParticles.push_back(partFactory.particle(TrackmTT,kaonMass,chi,ndf,kaonMassErr)); bBarParticles.push_back(partFactory.particle(TrackpTT,pionMass,chi,ndf,pionMassErr)); RefCountedKinematicTree bBarVertexFitTree = PartVtxFitter.fit(bBarParticles); if (bBarVertexFitTree->isValid() == false) { if (printMsg) std::cout << __LINE__ << " : continue --> invalid vertex from the B0bar vertex fit" << std::endl; continue; } bBarVertexFitTree->movePointerToTheTop(); RefCountedKinematicParticle bBar_KP = bBarVertexFitTree->currentParticle(); RefCountedKinematicVertex bBar_KV = bBarVertexFitTree->currentDecayVertex(); if (bBar_KV->vertexIsValid() == false) { if (printMsg) std::cout << __LINE__ << " : continue --> invalid vertex from the B0bar vertex fit" << std::endl; continue; } // ########################################################### // # Extract the re-fitted tracks after the dihadron vtx fit # // ########################################################### bVertexFitTree->movePointerToTheTop(); bVertexFitTree->movePointerToTheFirstChild(); RefCountedKinematicParticle refitMum = bVertexFitTree->currentParticle(); const reco::TransientTrack refitMumTT = refitMum->refittedTransientTrack(); bVertexFitTree->movePointerToTheNextChild(); RefCountedKinematicParticle refitMup = bVertexFitTree->currentParticle(); const reco::TransientTrack refitMupTT = refitMup->refittedTransientTrack(); bVertexFitTree->movePointerToTheNextChild(); RefCountedKinematicParticle refitTrkm = bVertexFitTree->currentParticle(); const reco::TransientTrack refitTrkmTT = refitTrkm->refittedTransientTrack(); bVertexFitTree->movePointerToTheNextChild(); RefCountedKinematicParticle refitTrkp = bVertexFitTree->currentParticle(); const reco::TransientTrack refitTrkpTT = refitTrkp->refittedTransientTrack(); // ######################## // # Muon pT and eta cuts # // ######################## pT = refitMupTT.track().pt(); eta = refitMupTT.track().eta(); if ((pT < MUMINPT) || (fabs(eta) > MUMAXETA)) { if (printMsg) std::cout << __LINE__ << " : continue --> too low pT of mu+ : " << pT << " or too high eta : " << eta << std::endl; continue; } pT = refitMumTT.track().pt(); eta = refitMumTT.track().eta(); if ((pT < MUMINPT) || (fabs(eta) > MUMAXETA)) { if (printMsg) std::cout << __LINE__ << " : continue --> too low pT of mu- : " << pT << " or too high eta : " << eta << std::endl; skip = true; continue; } // ############################################ // # Cut on the dimuon invariant mass and pT # // ############################################ pT = sqrt((refitMumTT.track().momentum().x() + refitMupTT.track().momentum().x()) * (refitMumTT.track().momentum().x() + refitMupTT.track().momentum().x()) + (refitMumTT.track().momentum().y() + refitMupTT.track().momentum().y()) * (refitMumTT.track().momentum().y() + refitMupTT.track().momentum().y())); double MuMuInvMass = mumu_KP->currentState().mass(); if ((pT < MINMUMUPT) || (MuMuInvMass < MINMUMUINVMASS) || (MuMuInvMass > MAXMUMUINVMASS)) { if (printMsg) std::cout << __LINE__ << " : continue --> no good mumu pair pT: " << pT << "\tinv. mass: " << MuMuInvMass << std::endl; continue; } // ########################## // # Hadron pT and eta cuts # // ########################## pT = refitTrkpTT.track().pt(); if (pT < MINHADPT) { if (printMsg) std::cout << __LINE__ << " : break --> too low pT of track+ : " << pT << std::endl; continue; } pT = refitTrkmTT.track().pt(); if (pT < MINHADPT) { if (printMsg) std::cout << __LINE__ << " : break --> too low pT of track- : " << pT << std::endl; skip = true; continue; } // ######################## // # Cuts on B0 AND B0bar # // ######################## if (((b_KP->currentState().mass() < B0MASSLOWLIMIT) || (b_KP->currentState().mass() > B0MASSUPLIMIT)) && ((bBar_KP->currentState().mass() < B0MASSLOWLIMIT) || (bBar_KP->currentState().mass() > B0MASSUPLIMIT))) { if (printMsg) std::cout << __LINE__ << " : continue --> bad B0 mass: " << b_KP->currentState().mass() << " AND B0bar mass: " << bBar_KP->currentState().mass() << std::endl; continue; } if ((TMath::Prob(static_cast<double>(b_KV->chiSquared()), static_cast<int>(rint(b_KV->degreesOfFreedom()))) < CLB0VTX) && (TMath::Prob(static_cast<double>(bBar_KV->chiSquared()), static_cast<int>(rint(bBar_KV->degreesOfFreedom()))) < CLB0VTX)) { if (printMsg) { std::cout << __LINE__ << " : continue --> bad vtx CL from B0 fit: " << TMath::Prob(static_cast<double>(b_KV->chiSquared()), static_cast<int>(rint(b_KV->degreesOfFreedom()))); std::cout << " AND bad vtx CL from B0bar fit: " << TMath::Prob(static_cast<double>(bBar_KV->chiSquared()), static_cast<int>(rint(bBar_KV->degreesOfFreedom()))) << std::endl; } continue; } // ############################### // # Cuts on B0 L/sigma BeamSpot # // ############################### Utility->computeLS (b_KV->position().x(), b_KV->position().y(), 0.0, beamSpot.position().x(),beamSpot.position().y(),0.0, b_KV->error().cxx(),b_KV->error().cyy(),0.0, b_KV->error().matrix()(0,1),0.0,0.0, beamSpot.covariance()(0,0),beamSpot.covariance()(1,1),0.0, beamSpot.covariance()(0,1),0.0,0.0, &LSBS,&LSBSErr); // ############################## // # Compute B0 DCA to BeamSpot # // ############################## theDCAXBS = b_KP->refittedTransientTrack().trajectoryStateClosestToPoint(GlobalPoint(beamSpot.position().x(),beamSpot.position().y(),beamSpot.position().z())); if (theDCAXBS.isValid() == false) { if (printMsg) std::cout << __LINE__ << " : continue --> invalid absolute impact parameter 2D for B0" << std::endl; continue; } double DCAB0BS = theDCAXBS.perigeeParameters().transverseImpactParameter(); double DCAB0BSErr = theDCAXBS.perigeeError().transverseImpactParameterError(); // ##################################### // # Compute B0 cos(alpha) to BeamSpot # // ##################################### Utility->computeCosAlpha (b_KP->currentState().globalMomentum().x(),b_KP->currentState().globalMomentum().y(),0.0, b_KV->position().x() - beamSpot.position().x(),b_KV->position().y() - beamSpot.position().y(),0.0, b_KP->currentState().kinematicParametersError().matrix()(3,3),b_KP->currentState().kinematicParametersError().matrix()(4,4),0.0, b_KP->currentState().kinematicParametersError().matrix()(3,4),0.0,0.0, b_KV->error().cxx() + beamSpot.covariance()(0,0),b_KV->error().cyy() + beamSpot.covariance()(1,1),0.0, b_KV->error().matrix()(0,1) + beamSpot.covariance()(0,1),0.0,0.0, &cosAlphaBS,&cosAlphaBSErr); // ############################################################################################################# // # If the tracks in the B reco candidate belongs to the primary vertex, then remove them and redo the Vertex # // ############################################################################################################# std::vector<reco::TransientTrack> vertexTracks; for (std::vector<reco::TrackBaseRef>::const_iterator iTrack = bestVtx.tracks_begin(); iTrack != bestVtx.tracks_end(); iTrack++) { // Compare primary tracks to check for matches with B candidate reco::TrackRef trackRef = iTrack->castTo<reco::TrackRef>(); if ((Trackm != trackRef) && (Trackp != trackRef) && (muTrackm != trackRef) && (muTrackp != trackRef)) { reco::TransientTrack TT(trackRef, &(*bFieldHandle)); vertexTracks.push_back(TT); } else if (printMsg) std::cout << __LINE__ << " : some of the B0 reco candidate tracks belong to the Pri.Vtx" << std::endl; } if (vertexTracks.size() < 2) { if (printMsg) std::cout << __LINE__ << " : continue --> number of tracks of the new Pri.Vtx is too small: " << vertexTracks.size() << std::endl; continue; } TransientVertex bestTransVtx = theVtxFitter.vertex(vertexTracks); if (bestTransVtx.isValid() == false) { if (printMsg) std::cout << __LINE__ << " : continue --> invalid new Pri.Vtx" << std::endl; continue; } bestVtxReFit = (reco::Vertex)bestTransVtx; // ########################## // # Compute mu- DCA to Vtx # // ########################## theDCAXVtx = pionImpactParameter(muTrackmTT, bestVtxReFit); double DCAmumVtx = theDCAXVtx.second.value(); double DCAmumVtxErr = theDCAXVtx.second.error(); // ########################## // # Compute mu+ DCA to Vtx # // ########################## theDCAXVtx = pionImpactParameter(muTrackpTT, bestVtxReFit); double DCAmupVtx = theDCAXVtx.second.value(); double DCAmupVtxErr = theDCAXVtx.second.error(); // ################################# // # Compute K*0 track- DCA to Vtx # // ################################# theDCAXVtx = pionImpactParameter(TrackmTT, bestVtxReFit); double DCAKstTrkmVtx = theDCAXVtx.second.value(); double DCAKstTrkmVtxErr = theDCAXVtx.second.error(); // ################################# // # Compute K*0 track+ DCA to Vtx # // ################################# theDCAXVtx = pionImpactParameter(TrackpTT, bestVtxReFit); double DCAKstTrkpVtx = theDCAXVtx.second.value(); double DCAKstTrkpVtxErr = theDCAXVtx.second.error(); // ######################### // # Compute B0 DCA to Vtx # // ######################### theDCAXVtx = IPTools::absoluteImpactParameter3D(b_KP->refittedTransientTrack(), bestVtxReFit); if (theDCAXVtx.first == false) { if (printMsg) std::cout << __LINE__ << " : continue --> invalid absolute impact parameter 3D for B0" << std::endl; continue; } double DCAB0Vtx = theDCAXVtx.second.value(); double DCAB0VtxErr = theDCAXVtx.second.error(); // ################################ // # Compute B0 cos(alpha) to Vtx # // ################################ Utility->computeCosAlpha (b_KP->currentState().globalMomentum().x(),b_KP->currentState().globalMomentum().y(),b_KP->currentState().globalMomentum().z(), b_KV->position().x() - bestVtxReFit.x(),b_KV->position().y() - bestVtxReFit.y(), b_KV->position().z() - bestVtxReFit.z(), b_KP->currentState().kinematicParametersError().matrix()(3,3),b_KP->currentState().kinematicParametersError().matrix()(4,4),b_KP->currentState().kinematicParametersError().matrix()(5,5), b_KP->currentState().kinematicParametersError().matrix()(3,4),b_KP->currentState().kinematicParametersError().matrix()(3,5),b_KP->currentState().kinematicParametersError().matrix()(4,5), b_KV->error().cxx() + bestVtxReFit.error()(0,0),b_KV->error().cyy() + bestVtxReFit.error()(1,1),b_KV->error().czz() + bestVtxReFit.error()(2,2), b_KV->error().matrix()(0,1) + bestVtxReFit.error()(0,1),b_KV->error().matrix()(0,2) + bestVtxReFit.error()(0,2),b_KV->error().matrix()(1,2) + bestVtxReFit.error()(1,2), &cosAlphaVtx,&cosAlphaVtxErr); // ############################# // # Compute B0 L/sigma to Vtx # // ############################# Utility->computeLS (b_KV->position().x(),b_KV->position().y(),b_KV->position().z(), bestVtxReFit.x(),bestVtxReFit.y(),bestVtxReFit.z(), b_KV->error().cxx(),b_KV->error().cyy(),b_KV->error().czz(), b_KV->error().matrix()(0,1),b_KV->error().matrix()(0,2),b_KV->error().matrix()(1,2), bestVtxReFit.error()(0,0),bestVtxReFit.error()(1,1),bestVtxReFit.error()(2,2), bestVtxReFit.error()(0,1),bestVtxReFit.error()(0,2),bestVtxReFit.error()(1,2), &LSVtx,&LSVtxErr); // ##################################################### // # Compute ctau = mB * (BVtx - PVtx) dot pB / |pB|^2 # // ##################################################### GlobalVector Bmomentum = b_KP->currentState().globalMomentum(); double Bmomentum2 = Bmomentum.dot(Bmomentum); AlgebraicSymMatrix33 BmomentumErr2; BmomentumErr2(0,0) = b_KP->currentState().kinematicParametersError().matrix()(3,3); BmomentumErr2(0,1) = b_KP->currentState().kinematicParametersError().matrix()(3,4); BmomentumErr2(0,2) = b_KP->currentState().kinematicParametersError().matrix()(3,5); BmomentumErr2(1,0) = b_KP->currentState().kinematicParametersError().matrix()(4,3); BmomentumErr2(1,1) = b_KP->currentState().kinematicParametersError().matrix()(4,4); BmomentumErr2(1,2) = b_KP->currentState().kinematicParametersError().matrix()(4,5); BmomentumErr2(2,0) = b_KP->currentState().kinematicParametersError().matrix()(5,3); BmomentumErr2(2,1) = b_KP->currentState().kinematicParametersError().matrix()(5,4); BmomentumErr2(2,2) = b_KP->currentState().kinematicParametersError().matrix()(5,5); GlobalVector BVtxPVtxSep = GlobalPoint(b_KV->position()) - GlobalPoint(bestVtxReFit.position().x(), bestVtxReFit.position().y(), bestVtxReFit.position().z()); double BVtxPVtxSepDOTBmomentum = BVtxPVtxSep.dot(Bmomentum); double bctauPVBS = Utility->B0Mass * BVtxPVtxSepDOTBmomentum / Bmomentum2; double bctauPVBSErr = sqrt(Utility->B0Mass * Utility->B0Mass / (Bmomentum2 * Bmomentum2) * (Bmomentum.x() * Bmomentum.x() * bestVtxReFit.error()(0,0) + Bmomentum.y() * Bmomentum.y() * bestVtxReFit.error()(1,1) + Bmomentum.z() * Bmomentum.z() * bestVtxReFit.error()(2,2) + ((BVtxPVtxSep.x()*Bmomentum2 - 2.*BVtxPVtxSepDOTBmomentum*Bmomentum.x()) * (BVtxPVtxSep.x()*Bmomentum2 - 2.*BVtxPVtxSepDOTBmomentum*Bmomentum.x()) * BmomentumErr2(0,0) + (BVtxPVtxSep.y()*Bmomentum2 - 2.*BVtxPVtxSepDOTBmomentum*Bmomentum.y()) * (BVtxPVtxSep.y()*Bmomentum2 - 2.*BVtxPVtxSepDOTBmomentum*Bmomentum.y()) * BmomentumErr2(1,1) + (BVtxPVtxSep.z()*Bmomentum2 - 2.*BVtxPVtxSepDOTBmomentum*Bmomentum.z()) * (BVtxPVtxSep.z()*Bmomentum2 - 2.*BVtxPVtxSepDOTBmomentum*Bmomentum.z()) * BmomentumErr2(2,2) + (BVtxPVtxSep.x()*Bmomentum2 - 2.*BVtxPVtxSepDOTBmomentum*Bmomentum.x()) * (BVtxPVtxSep.y()*Bmomentum2 - 2.*BVtxPVtxSepDOTBmomentum*Bmomentum.y()) * 2.*BmomentumErr2(0,1) + (BVtxPVtxSep.x()*Bmomentum2 - 2.*BVtxPVtxSepDOTBmomentum*Bmomentum.x()) * (BVtxPVtxSep.z()*Bmomentum2 - 2.*BVtxPVtxSepDOTBmomentum*Bmomentum.z()) * 2.*BmomentumErr2(0,2) + (BVtxPVtxSep.y()*Bmomentum2 - 2.*BVtxPVtxSepDOTBmomentum*Bmomentum.y()) * (BVtxPVtxSep.z()*Bmomentum2 - 2.*BVtxPVtxSepDOTBmomentum*Bmomentum.z()) * 2.*BmomentumErr2(1,2)) / (Bmomentum2 * Bmomentum2))); // ####################################### // # @@@ Fill B0-candidate variables @@@ # // ####################################### // ############ // # Save: B0 # // ############ NTuple->nB++; NTuple->bMass->push_back(b_KP->currentState().mass()); NTuple->bMassE->push_back(sqrt(b_KP->currentState().kinematicParametersError().matrix()(6,6))); NTuple->bBarMass->push_back(bBar_KP->currentState().mass()); NTuple->bBarMassE->push_back(sqrt(bBar_KP->currentState().kinematicParametersError().matrix()(6,6))); NTuple->bPx->push_back(b_KP->currentState().globalMomentum().x()); NTuple->bPy->push_back(b_KP->currentState().globalMomentum().y()); NTuple->bPz->push_back(b_KP->currentState().globalMomentum().z()); NTuple->bVtxCL->push_back(TMath::Prob(static_cast<double>(b_KV->chiSquared()), static_cast<int>(rint(b_KV->degreesOfFreedom())))); NTuple->bVtxX->push_back(b_KV->position().x()); NTuple->bVtxY->push_back(b_KV->position().y()); NTuple->bVtxZ->push_back(b_KV->position().z()); NTuple->bCosAlphaVtx->push_back(cosAlphaVtx); NTuple->bCosAlphaVtxE->push_back(cosAlphaVtxErr); NTuple->bCosAlphaBS->push_back(cosAlphaBS); NTuple->bCosAlphaBSE->push_back(cosAlphaBSErr); NTuple->bLVtx->push_back(LSVtx); NTuple->bLVtxE->push_back(LSVtxErr); NTuple->bLBS->push_back(LSBS); NTuple->bLBSE->push_back(LSBSErr); NTuple->bDCAVtx->push_back(DCAB0Vtx); NTuple->bDCAVtxE->push_back(DCAB0VtxErr); NTuple->bDCABS->push_back(DCAB0BS); NTuple->bDCABSE->push_back(DCAB0BSErr); NTuple->bctauPVBS->push_back(bctauPVBS); NTuple->bctauPVBSE->push_back(bctauPVBSErr); // ############# // # Save: K*0 # // ############# NTuple->kstMass->push_back(kstInvMass); NTuple->kstMassE->push_back(sqrt(kst_KP->currentState().kinematicParametersError().matrix()(6,6))); NTuple->kstBarMass->push_back(kstBarInvMass); NTuple->kstBarMassE->push_back(sqrt(kstBar_KP->currentState().kinematicParametersError().matrix()(6,6))); NTuple->kstPx->push_back(kst_KP->currentState().globalMomentum().x()); NTuple->kstPy->push_back(kst_KP->currentState().globalMomentum().y()); NTuple->kstPz->push_back(kst_KP->currentState().globalMomentum().z()); NTuple->kstPxxE->push_back(kst_KP->currentState().kinematicParametersError().matrix()(3,3)); NTuple->kstPyyE->push_back(kst_KP->currentState().kinematicParametersError().matrix()(4,4)); NTuple->kstPzzE->push_back(kst_KP->currentState().kinematicParametersError().matrix()(5,5)); NTuple->kstPxyE->push_back(kst_KP->currentState().kinematicParametersError().matrix()(3,4)); NTuple->kstPxzE->push_back(kst_KP->currentState().kinematicParametersError().matrix()(3,5)); NTuple->kstPyzE->push_back(kst_KP->currentState().kinematicParametersError().matrix()(4,5)); NTuple->kstVtxCL->push_back(TMath::Prob(static_cast<double>(kst_KV->chiSquared()), static_cast<int>(rint(kst_KV->degreesOfFreedom())))); NTuple->kstVtxX->push_back(kst_KV->position().x()); NTuple->kstVtxY->push_back(kst_KV->position().y()); NTuple->kstVtxZ->push_back(kst_KV->position().z()); // ################# // # Save: mu+ mu- # // ################# NTuple->mumuMass->push_back(MuMuInvMass); NTuple->mumuMassE->push_back(sqrt(mumu_KP->currentState().kinematicParametersError().matrix()(6,6))); NTuple->mumuPx->push_back(mumu_KP->currentState().globalMomentum().x()); NTuple->mumuPy->push_back(mumu_KP->currentState().globalMomentum().y()); NTuple->mumuPz->push_back(mumu_KP->currentState().globalMomentum().z()); NTuple->mumuVtxCL->push_back(TMath::Prob(static_cast<double>(mumu_KV->chiSquared()), static_cast<int>(rint(mumu_KV->degreesOfFreedom())))); NTuple->mumuVtxX->push_back(mumu_KV->position().x()); NTuple->mumuVtxY->push_back(mumu_KV->position().y()); NTuple->mumuVtxZ->push_back(mumu_KV->position().z()); NTuple->mumuCosAlphaBS->push_back(MuMuCosAlphaBS); NTuple->mumuCosAlphaBSE->push_back(MuMuCosAlphaBSErr); NTuple->mumuLBS->push_back(MuMuLSBS); NTuple->mumuLBSE->push_back(MuMuLSBSErr); NTuple->mumuDCA->push_back(mumuDCA); // ############# // # Save: mu- # // ############# NTuple->mumHighPurity->push_back( (int)muTrackm->quality(reco::Track::highPurity)); NTuple->mumCL->push_back(TMath::Prob(muTrackmTT.chi2(), static_cast<int>(rint(muTrackmTT.ndof())))); NTuple->mumNormChi2->push_back(muTrackm->normalizedChi2()); NTuple->mumPx->push_back(refitMumTT.track().momentum().x()); NTuple->mumPy->push_back(refitMumTT.track().momentum().y()); NTuple->mumPz->push_back(refitMumTT.track().momentum().z()); NTuple->mumDCAVtx->push_back(DCAmumVtx); NTuple->mumDCAVtxE->push_back(DCAmumVtxErr); NTuple->mumDCABS->push_back(DCAmumBS); NTuple->mumDCABSE->push_back(DCAmumBSErr); NTuple->mumKinkChi2->push_back(iMuonM->combinedQuality().trkKink); NTuple->mumFracHits->push_back(static_cast<double>(muTrackm->hitPattern().numberOfValidHits()) / static_cast<double>(muTrackm->hitPattern().numberOfValidHits() + muTrackm->hitPattern().numberOfLostHits(reco::HitPattern::TRACK_HITS) + muTrackm->hitPattern().numberOfLostHits(reco::HitPattern::MISSING_INNER_HITS) + muTrackm->hitPattern().numberOfLostHits(reco::HitPattern::MISSING_OUTER_HITS))); theDCAXVtx = IPTools::absoluteTransverseImpactParameter(muTrackmTT, bestVtxReFit); NTuple->mumdxyVtx-> push_back(theDCAXVtx.second.value()); NTuple->mumdzVtx -> push_back(muTrackmTT.track().dz(bestVtxReFit.position())); NTuple->mumCat -> push_back(getMuCat(*iMuonM)); NTuple->mumNPixHits->push_back(muTrackm->hitPattern().numberOfValidPixelHits()); NTuple->mumNPixLayers->push_back(muTrackm->hitPattern().pixelLayersWithMeasurement()); NTuple->mumNTrkHits->push_back(muTrackm->hitPattern().numberOfValidTrackerHits()); NTuple->mumNTrkLayers->push_back(muTrackm->hitPattern().trackerLayersWithMeasurement()); if (iMuonM->isGlobalMuon() == true) NTuple->mumNMuonHits->push_back(iMuonM->globalTrack()->hitPattern().numberOfValidMuonHits()); else NTuple->mumNMuonHits->push_back(0); NTuple->mumNMatchStation->push_back(iMuonM->numberOfMatchedStations()); // ############# // # Save: mu+ # // ############# NTuple->mupHighPurity->push_back( (int) muTrackp->quality(reco::Track::highPurity)); NTuple->mupCL->push_back(TMath::Prob(muTrackpTT.chi2(), static_cast<int>(rint(muTrackpTT.ndof())))); NTuple->mupNormChi2->push_back(muTrackp->normalizedChi2()); NTuple->mupPx->push_back(refitMupTT.track().momentum().x()); NTuple->mupPy->push_back(refitMupTT.track().momentum().y()); NTuple->mupPz->push_back(refitMupTT.track().momentum().z()); NTuple->mupDCAVtx->push_back(DCAmupVtx); NTuple->mupDCAVtxE->push_back(DCAmupVtxErr); NTuple->mupDCABS->push_back(DCAmupBS); NTuple->mupDCABSE->push_back(DCAmupBSErr); NTuple->mupKinkChi2->push_back(iMuonP->combinedQuality().trkKink); NTuple->mupFracHits->push_back(static_cast<double>(muTrackp->hitPattern().numberOfValidHits()) / static_cast<double>(muTrackp->hitPattern().numberOfValidHits() + muTrackp->hitPattern().numberOfLostHits(reco::HitPattern::TRACK_HITS) + muTrackp->hitPattern().numberOfLostHits(reco::HitPattern::MISSING_INNER_HITS) + muTrackp->hitPattern().numberOfLostHits(reco::HitPattern::MISSING_OUTER_HITS))); theDCAXVtx = IPTools::absoluteTransverseImpactParameter(muTrackpTT, bestVtxReFit); NTuple->mupdxyVtx->push_back(theDCAXVtx.second.value()); NTuple->mupdzVtx ->push_back(muTrackpTT.track().dz(bestVtxReFit.position())); NTuple->mupCat->push_back(getMuCat(*iMuonP)); NTuple->mupNPixHits->push_back(muTrackp->hitPattern().numberOfValidPixelHits()); NTuple->mupNPixLayers->push_back(muTrackp->hitPattern().pixelLayersWithMeasurement()); NTuple->mupNTrkHits->push_back(muTrackp->hitPattern().numberOfValidTrackerHits()); NTuple->mupNTrkLayers->push_back(muTrackp->hitPattern().trackerLayersWithMeasurement()); if (iMuonP->isGlobalMuon() == true) NTuple->mupNMuonHits->push_back(iMuonP->globalTrack()->hitPattern().numberOfValidMuonHits()); else NTuple->mupNMuonHits->push_back(0); NTuple->mupNMatchStation->push_back(iMuonP->numberOfMatchedStations()); // ################ // # Save: Track- # // ################ NTuple->kstTrkmHighPurity->push_back( (int)Trackm->quality(reco::Track::highPurity)); NTuple->kstTrkmCL->push_back(TMath::Prob(TrackmTT.chi2(), static_cast<int>(rint(TrackmTT.ndof())))); NTuple->kstTrkmNormChi2->push_back(Trackm->normalizedChi2()); NTuple->kstTrkmPx->push_back(refitTrkmTT.track().momentum().x()); NTuple->kstTrkmPy->push_back(refitTrkmTT.track().momentum().y()); NTuple->kstTrkmPz->push_back(refitTrkmTT.track().momentum().z()); NTuple->kstTrkmPxxE->push_back( refitTrkm ->currentState().kinematicParametersError().matrix()(3,3) ); NTuple->kstTrkmPyyE->push_back( refitTrkm ->currentState().kinematicParametersError().matrix()(4,4) ); NTuple->kstTrkmPzzE->push_back( refitTrkm ->currentState().kinematicParametersError().matrix()(5,5) ); NTuple->kstTrkmPxyE->push_back( refitTrkm ->currentState().kinematicParametersError().matrix()(3,4) ); NTuple->kstTrkmPxzE->push_back( refitTrkm ->currentState().kinematicParametersError().matrix()(3,5) ); NTuple->kstTrkmPyzE->push_back( refitTrkm ->currentState().kinematicParametersError().matrix()(4,5) ); NTuple->kstTrkmDCAVtx->push_back(DCAKstTrkmVtx); NTuple->kstTrkmDCAVtxE->push_back(DCAKstTrkmVtxErr); NTuple->kstTrkmDCABS->push_back(DCAKstTrkmBS); NTuple->kstTrkmDCABSE->push_back(DCAKstTrkmBSErr); NTuple->kstTrkmFracHits->push_back(static_cast<double>(Trackm->hitPattern().numberOfValidHits()) / static_cast<double>(Trackm->hitPattern().numberOfValidHits() + Trackm->hitPattern().numberOfLostHits(reco::HitPattern::TRACK_HITS) + Trackm->hitPattern().numberOfLostHits(reco::HitPattern::MISSING_INNER_HITS))); theDCAXVtx = IPTools::absoluteTransverseImpactParameter(TrackmTT, bestVtxReFit); NTuple->kstTrkmdxyVtx->push_back(theDCAXVtx.second.value()); NTuple->kstTrkmdzVtx->push_back(TrackmTT.track().dz(bestVtxReFit.position())); NTuple->kstTrkmMuMatch->push_back(MuMCat); // I do NOT include the number of missing outer hits because the hadron might interact NTuple->kstTrkmNPixHits->push_back(Trackm->hitPattern().numberOfValidPixelHits()); NTuple->kstTrkmNPixLayers->push_back(Trackm->hitPattern().pixelLayersWithMeasurement()); NTuple->kstTrkmNTrkHits->push_back(Trackm->hitPattern().numberOfValidTrackerHits()); NTuple->kstTrkmNTrkLayers->push_back(Trackm->hitPattern().trackerLayersWithMeasurement()); // ################ // # Save: Track+ # // ################ NTuple->kstTrkpHighPurity->push_back((int)Trackp->quality(reco::Track::highPurity)); NTuple->kstTrkpCL->push_back(TMath::Prob(TrackpTT.chi2(), static_cast<int>(rint(TrackpTT.ndof())))); NTuple->kstTrkpNormChi2->push_back(Trackp->normalizedChi2()); NTuple->kstTrkpPx->push_back(refitTrkpTT.track().momentum().x()); NTuple->kstTrkpPy->push_back(refitTrkpTT.track().momentum().y()); NTuple->kstTrkpPz->push_back(refitTrkpTT.track().momentum().z()); NTuple->kstTrkpPxxE->push_back( refitTrkp ->currentState().kinematicParametersError().matrix()(3,3) ); NTuple->kstTrkpPyyE->push_back( refitTrkp ->currentState().kinematicParametersError().matrix()(4,4) ); NTuple->kstTrkpPzzE->push_back( refitTrkp ->currentState().kinematicParametersError().matrix()(5,5) ); NTuple->kstTrkpPxyE->push_back( refitTrkp ->currentState().kinematicParametersError().matrix()(3,4) ); NTuple->kstTrkpPxzE->push_back( refitTrkp ->currentState().kinematicParametersError().matrix()(3,5) ); NTuple->kstTrkpPyzE->push_back( refitTrkp ->currentState().kinematicParametersError().matrix()(4,5) ); NTuple->kstTrkpDCAVtx->push_back(DCAKstTrkpVtx); NTuple->kstTrkpDCAVtxE->push_back(DCAKstTrkpVtxErr); NTuple->kstTrkpDCABS->push_back(DCAKstTrkpBS); NTuple->kstTrkpDCABSE->push_back(DCAKstTrkpBSErr); NTuple->kstTrkpFracHits->push_back(static_cast<double>(Trackp->hitPattern().numberOfValidHits()) / static_cast<double>(Trackp->hitPattern().numberOfValidHits() + Trackp->hitPattern().numberOfLostHits(reco::HitPattern::TRACK_HITS) + Trackp->hitPattern().numberOfLostHits(reco::HitPattern::MISSING_INNER_HITS))); theDCAXVtx = IPTools::absoluteTransverseImpactParameter(TrackpTT, bestVtxReFit); NTuple->kstTrkpdxyVtx->push_back(theDCAXVtx.second.value()); NTuple->kstTrkpdzVtx->push_back(TrackpTT.track().dz(bestVtxReFit.position())); NTuple->kstTrkpMuMatch->push_back(MuPCat); // I do NOT include the number of missing outer hits because the hadron might interact NTuple->kstTrkpNPixHits -> push_back(Trackp->hitPattern().numberOfValidPixelHits()); NTuple->kstTrkpNPixLayers-> push_back(Trackp->hitPattern().pixelLayersWithMeasurement()); NTuple->kstTrkpNTrkHits -> push_back(Trackp->hitPattern().numberOfValidTrackerHits()); NTuple->kstTrkpNTrkLayers-> push_back(Trackp->hitPattern().trackerLayersWithMeasurement()); // Save trigger matching for the 4 tracks tmpString1.clear(); tmpString2.clear(); tmpString3.clear(); tmpString4.clear(); const pat::Muon* patMuonM = &(*iMuonM); const pat::Muon* patMuonP = &(*iMuonP); const pat::GenericParticle* patTrkm = &(*iTrackM); const pat::GenericParticle* patTrkp = &(*iTrackP); for (unsigned int i = 0; i < TrigTable_.size(); i++) { myString.clear(); myString.str(""); myString << TrigTable_[i].c_str() << "*"; if (patMuonM->triggerObjectMatchesByPath(myString.str().c_str()).empty() == false) tmpString1.append(TrigTable_[i]+" "); if (patMuonP->triggerObjectMatchesByPath(myString.str().c_str()).empty() == false) tmpString2.append(TrigTable_[i]+" "); if (patTrkm ->triggerObjectMatchesByPath(myString.str().c_str()).empty() == false) tmpString3.append(TrigTable_[i]+" "); if (patTrkp ->triggerObjectMatchesByPath(myString.str().c_str()).empty() == false) tmpString4.append(TrigTable_[i]+" "); } if (tmpString1.size() == 0) tmpString1.append("NotInTable"); if (tmpString2.size() == 0) tmpString2.append("NotInTable"); if (tmpString3.size() == 0) tmpString3.append("NotInTable"); if (tmpString4.size() == 0) tmpString4.append("NotInTable"); NTuple->mumTrig ->push_back(tmpString1); NTuple->mupTrig ->push_back(tmpString2); NTuple->kstTrkmTrig->push_back(tmpString3); NTuple->kstTrkpTrig->push_back(tmpString4); // save minimum IP from any PV (2D and 3D) mumMind0 = mupMind0 = 100; TrkmMind0 = TrkpMind0 = 100; mumMinIP = mupMinIP = 100; TrkmMinIP = TrkpMinIP = 100; std::pair<double,double> IPPair; for (std::vector<reco::Vertex>::const_iterator ipv = recVtx->begin(); ipv != recVtx->end(); ipv++) { if (! ipv->isValid() ) continue; vert = GlobalPoint(ipv->x(), ipv->y(), ipv->z()); traj = muTrackmTT.trajectoryStateClosestToPoint(vert ); if (fabs(traj.perigeeParameters().transverseImpactParameter()) < mumMind0){ mumMind0 = fabs(traj.perigeeParameters().transverseImpactParameter()); mumMind0E = traj.perigeeError().transverseImpactParameterError(); } traj = muTrackpTT.trajectoryStateClosestToPoint(vert ); if (fabs(traj.perigeeParameters().transverseImpactParameter()) < mupMind0){ mupMind0 = fabs(traj.perigeeParameters().transverseImpactParameter()); mupMind0E = traj.perigeeError().transverseImpactParameterError(); } traj = TrackmTT.trajectoryStateClosestToPoint(vert ); if (fabs(traj.perigeeParameters().transverseImpactParameter()) < TrkmMind0){ TrkmMind0 = fabs(traj.perigeeParameters().transverseImpactParameter()); TrkmMind0E = traj.perigeeError().transverseImpactParameterError(); } traj = TrackpTT.trajectoryStateClosestToPoint(vert ); if (fabs(traj.perigeeParameters().transverseImpactParameter()) < TrkpMind0){ TrkpMind0 = fabs(traj.perigeeParameters().transverseImpactParameter()); TrkpMind0E = traj.perigeeError().transverseImpactParameterError(); } IPPair = pionImpactParameter(muTrackmTT,*ipv); if (IPPair.first < mumMinIP){ mumMinIP = IPPair.first; mumMinIPE = IPPair.second; } IPPair = pionImpactParameter(muTrackpTT,*ipv); if (IPPair.first < mupMinIP){ mupMinIP = IPPair.first; mupMinIPE = IPPair.second; } IPPair = pionImpactParameter(TrackmTT,*ipv); if (IPPair.first < TrkmMinIP){ TrkmMinIP = IPPair.first; TrkmMinIPE = IPPair.second; } IPPair = pionImpactParameter(TrackpTT,*ipv); if (IPPair.first < TrkpMinIP){ TrkpMinIP = IPPair.first; TrkpMinIPE = IPPair.second; } } // isolation double iso; chi = 0; ndf = 0; mum_isovec.clear(); mup_isovec.clear(); trkm_isovec.clear(); trkp_isovec.clear(); mum_isopts.clear(); mup_isopts.clear(); trkm_isopts.clear(); trkp_isopts.clear(); mum_isomom.clear(); mup_isomom.clear(); trkm_isomom.clear(); trkp_isomom.clear(); mum_isodr.clear(); mup_isodr.clear(); trkm_isodr.clear(); trkp_isodr.clear(); float bestVtx_x = bestVtxReFit.x(); float bestVtx_y = bestVtxReFit.y(); float bestVtx_z = bestVtxReFit.z(); const reco::VertexCollection *recVtxColl = recVtx.product() ; int trk_index = -1; for (std::vector<pat::GenericParticle>::const_iterator iTrackIso = thePATTrackHandle->begin(); iTrackIso != thePATTrackHandle->end(); iTrackIso++) { trk_index++; if (iTrackIso == iTrackM || iTrackIso == iTrackP) continue; if (muTrackm == iTrackIso->track() || muTrackp == iTrackIso->track()) continue; if (! iTrackIso->track()->quality(reco::Track::highPurity)) continue; if ( iTrackIso->track()->pt() < 0.8) continue; // requirement that the track is not associated to any PV if (findPV(trk_index, recVtxColl) == 1 ) continue; const reco::TransientTrack TrackIsoTT(iTrackIso->track(), &(*bFieldHandle)); iso = calculateIsolation(ClosestApp, muTrackmTT, TrackIsoTT, muonMass, bestVtx_x, bestVtx_y, bestVtx_z); if (iso > 0 ) mum_isovec.push_back(iso); iso = calculateIsolation(ClosestApp, muTrackpTT, TrackIsoTT, muonMass, bestVtx_x, bestVtx_y, bestVtx_z); if (iso > 0 ) mup_isovec.push_back(iso); iso = calculateIsolation(ClosestApp, TrackmTT, TrackIsoTT, muonMass, bestVtx_x, bestVtx_y, bestVtx_z); if (iso > 0 ) trkm_isovec.push_back(iso); iso = calculateIsolation(ClosestApp, TrackpTT, TrackIsoTT, muonMass, bestVtx_x, bestVtx_y, bestVtx_z); if (iso > 0 ) trkp_isovec.push_back(iso); // add new iso ClosestApp.calculate(TrackIsoTT.initialFreeState(), muTrackmTT.initialFreeState()); if (ClosestApp.status() != false) { if ( ClosestApp.distance() < 0.1 ) { mum_isopts.push_back( iTrackIso->track()->pt() ); mum_isomom.push_back( iTrackIso->track()->p() ); mum_isodr.push_back ( deltaR(iTrackIso->track() ->eta(), iTrackIso->track()->phi(), refitMumTT.track().eta(), refitMumTT.track().phi() )); } } ClosestApp.calculate(TrackIsoTT.initialFreeState(), muTrackpTT.initialFreeState()); if (ClosestApp.status() != false) { if ( ClosestApp.distance() < 0.1 ) { mup_isopts.push_back( iTrackIso->track()->pt() ); mup_isomom.push_back( iTrackIso->track()->p() ); mup_isodr.push_back ( deltaR(iTrackIso->track() ->eta(), iTrackIso->track()->phi(), refitMupTT.track().eta(), refitMupTT.track().phi() )); } } ClosestApp.calculate(TrackIsoTT.initialFreeState(), TrackmTT.initialFreeState()); if (ClosestApp.status() != false) { if ( ClosestApp.distance() < 0.1 ) { trkm_isopts.push_back( iTrackIso->track()->pt() ); trkm_isomom.push_back( iTrackIso->track()->p() ); trkm_isodr.push_back ( deltaR(iTrackIso->track() ->eta(), iTrackIso->track()->phi(), refitTrkmTT.track().eta(), refitTrkmTT.track().phi() )); } } ClosestApp.calculate(TrackIsoTT.initialFreeState(), TrackpTT.initialFreeState()); if (ClosestApp.status() != false) { if ( ClosestApp.distance() < 0.1 ) { trkp_isopts.push_back( iTrackIso->track()->pt() ); trkp_isomom.push_back( iTrackIso->track()->p() ); trkp_isodr.push_back ( deltaR(iTrackIso->track() ->eta(), iTrackIso->track()->phi(), refitTrkpTT.track().eta(), refitTrkpTT.track().phi() )); } } } NTuple->mumIso -> push_back(mum_isovec); NTuple->mupIso -> push_back(mup_isovec); NTuple->kstTrkmIso -> push_back(trkm_isovec); NTuple->kstTrkpIso -> push_back(trkp_isovec); NTuple->mumIsoPt -> push_back(mum_isopts); NTuple->mupIsoPt -> push_back(mup_isopts); NTuple->kstTrkmIsoPt -> push_back(trkm_isopts); NTuple->kstTrkpIsoPt -> push_back(trkp_isopts); NTuple->mumIsoMom -> push_back(mum_isomom); NTuple->mupIsoMom -> push_back(mup_isomom); NTuple->kstTrkmIsoMom -> push_back(trkm_isomom); NTuple->kstTrkpIsoMom -> push_back(trkp_isomom); NTuple->mumIsodR -> push_back(mum_isodr); NTuple->mupIsodR -> push_back(mup_isodr); NTuple->kstTrkmIsodR -> push_back(trkm_isodr); NTuple->kstTrkpIsodR -> push_back(trkp_isodr); NTuple->mumMinIP2D -> push_back(mumMind0); NTuple->mumMinIP2DE -> push_back(mumMind0E); NTuple->mupMinIP2D -> push_back(mupMind0); NTuple->mupMinIP2DE -> push_back(mupMind0E); NTuple->kstTrkmMinIP2D -> push_back(TrkmMind0); NTuple->kstTrkmMinIP2DE -> push_back(TrkmMind0E); NTuple->kstTrkpMinIP2D -> push_back(TrkpMind0); NTuple->kstTrkpMinIP2DE -> push_back(TrkpMind0E); NTuple->mumMinIP -> push_back(mumMinIP); NTuple->mumMinIPE -> push_back(mumMinIPE); NTuple->mupMinIP -> push_back(mupMinIP); NTuple->mupMinIPE -> push_back(mupMinIPE); NTuple->kstTrkmMinIP -> push_back(TrkmMinIP); NTuple->kstTrkmMinIPE -> push_back(TrkmMinIPE); NTuple->kstTrkpMinIP -> push_back(TrkpMinIP); NTuple->kstTrkpMinIPE -> push_back(TrkpMinIPE); // ##################### // # Clear all vectors # // ##################### vertexTracks.clear(); bParticles.clear(); bBarParticles.clear(); kstParticles.clear(); kstBarParticles.clear(); } // End for Track+ if (skip == true) continue; } // End for Track- muonParticles.clear(); } // End for mu+ if (skip == true) continue; } // End for mu- NTuple->runN = iEvent.id().run(); NTuple->eventN = iEvent.id().event(); if (NTuple->nB > 0) { for (std::vector<reco::Vertex>::const_iterator iVertex = recVtx->begin(); iVertex != recVtx->end(); iVertex++) { if(iVertex->ndof() < PRIVTXNDOF) continue; if(fabs(iVertex->z()) > PRIVTXMAXZ) continue; if(fabs(iVertex->position().rho()) > PRIVTXMAXR) continue; NTuple->recoVtxN++; } // ##################################### // # Save: Primary Vertex and BeamSpot # // ##################################### NTuple->priVtxCL = TMath::Prob(bestVtx.chi2(), static_cast<int>(rint(bestVtx.ndof()))); NTuple->priVtxX = bestVtx.x(); NTuple->priVtxY = bestVtx.y(); NTuple->priVtxZ = bestVtx.z(); NTuple->bsX = beamSpot.position().x(); NTuple->bsY = beamSpot.position().y(); } else if (printMsg) std::cout << __LINE__ << " : @@@ No B0 --> K*0 (K pi) mu+ mu- candidate were found in the event @@@" << std::endl; } // End if doGenReco_ == 1 || doGenReco_ == 2 // ########################################### // # Get truth information from genParticles # // ########################################### // Particle IDs: // 11 = e- // 12 = nu_e // 13 = mu- // 14 = nu_mu // 16 = nu_tau // 22 = gamma // 130 = KL // 211 = pi+ // 310 = Ks // 311 = K0 // 313 = K*0 // 321 = K+ // 443 = J/psi; 100443 psi(2S) // 511 = B0 // 521 = B+ // 531 = Bs // 2212 = p // 5122 = Lambda_b if (doGenReco_ == 2) { // ################################# // # Save pileup information in MC # // ################################# edm::Handle< std::vector<PileupSummaryInfo> > PupInfo; iEvent.getByToken(puToken_, PupInfo); for (std::vector<PileupSummaryInfo>::const_iterator PVI = PupInfo->begin(); PVI != PupInfo->end(); PVI++) { NTuple->bunchXingMC->push_back(PVI->getBunchCrossing()); NTuple->numInteractionsMC->push_back(PVI->getPU_NumInteractions()); NTuple->trueNumInteractionsMC->push_back(PVI->getTrueNumInteractions()); } } if ((doGenReco_ == 2) || (doGenReco_ == 3)) { std::vector<std::vector<unsigned int>* > posDau; std::vector<std::vector<unsigned int>* > negDau; for (unsigned int itGen = 0; itGen < genParticles->size(); itGen++) { const reco::Candidate* FirstPart = &(*genParticles)[itGen]; // ########################## // # Check for: # // # B0 / B0bar # // # Bs / Bsbar # // # Lambda_b / Lambda_bbar # // # B+ / B- # // ########################## if ((abs(FirstPart->pdgId()) == 511) || (abs(FirstPart->pdgId()) == 531) || (abs(FirstPart->pdgId()) == 5122) || (abs(FirstPart->pdgId()) == 521)) { if (printMsg) std::cout << "\n" << __LINE__ << " : @@@ Found B0/B0bar OR Bs/Bsbar OR Lambda_b/Lambda_bbar OR B+/B- in MC @@@" << std::endl; // ######################################################## // # Search for oscillations # // # If there are, then move to the non oscillating stage # // ######################################################## FirstPart = skipOscillations(FirstPart); int imum = -1; int imup = -1; int ikst = -1; int ikst_trkm = -1; int ikst_trkp = -1; int ipsi = -1; int ipsi_mum = -1; int ipsi_mup = -1; bool PhotonB0 = false; bool PhotonKst = false; bool PhotonPsi = false; bool isSignal = true; bool isPsi2SnotJPsi = false; if (abs(FirstPart->pdgId()) == 511) { for (unsigned int i = 0; i < FirstPart->numberOfDaughters(); i++) { if (isSignal == false) break; const reco::Candidate* genDau = FirstPart->daughter(i); if (genDau->pdgId() == 22) { PhotonB0 = true; if (printMsg) std::cout << __LINE__ << " : found B0/B0bar photon" << std::endl; continue; } if (genDau->pdgId() == 13) { imum = i; if (printMsg) std::cout << __LINE__ << " : found mu-" << std::endl; continue; } if (genDau->pdgId() == -13) { imup = i; if (printMsg) std::cout << __LINE__ << " : found mu+" << std::endl; continue; } if (abs(genDau->pdgId()) == 313) { ikst = i; if (printMsg) std::cout << __LINE__ << " : found K*0/K*0bar" << std::endl; for (unsigned int j = 0; j < genDau->numberOfDaughters(); j++) { const reco::Candidate* genDau2 = genDau->daughter(j); if (genDau2->pdgId() == 22) { PhotonKst = true; if (printMsg) std::cout << __LINE__ << " : found K*0/K*0bar photon" << std::endl; continue; } if ((genDau2->pdgId() == -211) || (genDau2->pdgId() == -321)) { ikst_trkm = j; if (printMsg) std::cout << __LINE__ << " : found K*0/K*0bar track-" << std::endl; continue; } if ((genDau2->pdgId() == 211) || (genDau2->pdgId() == 321)) { ikst_trkp = j; if (printMsg) std::cout << __LINE__ << " : found K*0/K*0bar track+" << std::endl; continue; } isSignal = false; break; } continue; } if (abs(genDau->pdgId() == 443) || abs(genDau->pdgId() == 100443)) { if (abs(genDau->pdgId() == 443)) isPsi2SnotJPsi = false; else isPsi2SnotJPsi = true; ipsi = i; if (printMsg) std::cout << __LINE__ << " : found J/psi or psi(2S)" << std::endl; for (unsigned int j = 0; j < genDau->numberOfDaughters(); j++) { const reco::Candidate* genDau2 = genDau->daughter(j); if (genDau2->pdgId() == 22) { PhotonPsi = true; if (printMsg) std::cout << __LINE__ << " : found J/psi or psi(2S) photon" << std::endl; continue; } if (genDau2->pdgId() == 13) { ipsi_mum = j; if (printMsg) std::cout << __LINE__ << " : found J/psi or psi(2S) mu-" << std::endl; continue; } if (genDau2->pdgId() == -13) { ipsi_mup = j; if (printMsg) std::cout << __LINE__ << " : found J/psi or psi(2S) mu+" << std::endl; continue; } isSignal = false; break; } continue; } isSignal = false; break; } // End for B0 / B0bar daughters } // End if B0 / B0bar const reco::Candidate* genPsi = NULL; const reco::Candidate* genMum = NULL; const reco::Candidate* genMup = NULL; const reco::Candidate* genKst = NULL; const reco::Candidate* genKst_trkm = NULL; const reco::Candidate* genKst_trkp = NULL; bool foundSomething = false; if ((abs(FirstPart->pdgId()) == 511) && (isSignal == true) && (((imum != -1) && (imup != -1) && (ikst != -1) && (ikst_trkm != -1) && (ikst_trkp != -1)) || ((NTuple->genSignal != 1) && (NTuple->genSignal != 2) && (ikst != -1) && (ikst_trkm != -1) && (ikst_trkp != -1) && (ipsi != -1) && (ipsi_mum != -1) && (ipsi_mup != -1)))) { // ################################################################ // # Found Signal B0/B0bar --> K*0/K*0bar (K pi) mu+ mu- # // # Found Signal B0/B0bar --> K*0/K*0bar (K pi) J/psi (mu+mu-) # // # Found Signal B0/B0bar --> K*0/K*0bar (K pi) psi(2S) (mu+mu-) # // ################################################################ NTuple->ClearMonteCarlo(); if ((imum != -1) && (imup != -1) && (ikst != -1) && (ikst_trkm != -1) && (ikst_trkp != -1)) { if (printMsg) std::cout << __LINE__ << " : @@@ Found B0/B0bar --> K*0/K*0bar (K pi) mu+ mu- @@@" << std::endl; if (FirstPart->daughter(ikst)->pdgId() == 313) NTuple->genSignal = 1; else if (FirstPart->daughter(ikst)->pdgId() == -313) NTuple->genSignal = 2; genMum = FirstPart->daughter(imum); genMup = FirstPart->daughter(imup); } else { if (isPsi2SnotJPsi == false) { if (printMsg) std::cout << __LINE__ << " : @@@ Found B0/B0bar --> K*0/K*0bar (K pi) J/psi (mu+mu-) @@@" << std::endl; if (FirstPart->daughter(ikst)->pdgId() == 313) NTuple->genSignal = 3; else if (FirstPart->daughter(ikst)->pdgId() == -313) NTuple->genSignal = 4; } else { if (printMsg) std::cout << __LINE__ << " : @@@ Found B0/B0bar --> K*0/K*0bar (K pi) psi(2S) (mu+mu-) @@@" << std::endl; if (FirstPart->daughter(ikst)->pdgId() == 313) NTuple->genSignal = 5; else if (FirstPart->daughter(ikst)->pdgId() == -313) NTuple->genSignal = 6; } genPsi = FirstPart->daughter(ipsi); genMum = genPsi->daughter(ipsi_mum); genMup = genPsi->daughter(ipsi_mup); NTuple->genSignPsiHasFSR = PhotonPsi; } genKst = FirstPart->daughter(ikst); genKst_trkm = FirstPart->daughter(ikst)->daughter(ikst_trkm); genKst_trkp = FirstPart->daughter(ikst)->daughter(ikst_trkp); // ################## // # Save info. FSR # // ################## NTuple->genSignHasFSR = PhotonB0; NTuple->genSignKstHasFSR = PhotonKst; foundSomething = true; } // End if B0/B0bar signal else { if (printMsg) std::cout << __LINE__ << " : @@@ Start particle decay-tree scan for opposite charged stable particles for background search @@@" << std::endl; searchForStableChargedDaughters (FirstPart, itGen, &posDau, &negDau); if ((NTuple->genSignal == 0) && (posDau.size() != 0) && (negDau.size() != 0)) { // ############################### // # Search for Background from: # // # B0 / B0bar # // # Bs / Bsbar # // # Lambda_b / Lambda_bbar # // # B+ / B- # // ############################### for (unsigned int i = 0; i < negDau.size(); i++) { genMum = findDaughter (genParticles, &negDau, i); if (genMum->pdgId() == 13) { for (unsigned int j = 0; j < posDau.size(); j++) { genMup = findDaughter (genParticles, &posDau, j); if (genMup->pdgId() == -13) { if (printMsg) std::cout << __LINE__ << " : found dimuons for possible background" << std::endl; foundSomething = true; break; } } if (foundSomething == true) break; } } if ((foundSomething == true) && (posDau.size() == 2) && (negDau.size() == 1)) { foundSomething = false; for (unsigned int i = 0; i < posDau.size(); i++) { genKst_trkp = findDaughter (genParticles, &posDau, i); if (genKst_trkp != genMup) { NTuple->ClearMonteCarlo(); NTuple->genMuMuBG = FirstPart->pdgId(); NTuple->genMuMuBGnTrksp = 1; foundSomething = true; if (printMsg) std::cout << __LINE__ << " : get background positive track: " << genKst_trkp->pdgId() << "\tfrom mother: " << genKst_trkp->mother()->pdgId() << std::endl; } } } else if ((foundSomething == true) && (posDau.size() == 1) && (negDau.size() == 2)) { foundSomething = false; for (unsigned int i = 0; i < negDau.size(); i++) { genKst_trkm = findDaughter (genParticles, &negDau, i); if (genKst_trkm != genMum) { NTuple->ClearMonteCarlo(); NTuple->genMuMuBG = FirstPart->pdgId(); NTuple->genMuMuBGnTrksm = 1; foundSomething = true; if (printMsg) std::cout << __LINE__ << " : get background negative track: " << genKst_trkm->pdgId() << "\tfrom mother: " << genKst_trkm->mother()->pdgId() << std::endl; } } } else if ((foundSomething == true) && (posDau.size() == 2) && (negDau.size() == 2)) { foundSomething = false; for (unsigned int i = 0; i < negDau.size(); i++) { genKst_trkm = findDaughter (genParticles, &negDau, i); if (genKst_trkm != genMum) { for (unsigned int j = 0; j < posDau.size(); j++) { genKst_trkp = findDaughter (genParticles, &posDau, j); if (genKst_trkp != genMup) { NTuple->ClearMonteCarlo(); NTuple->genMuMuBG = FirstPart->pdgId(); NTuple->genMuMuBGnTrksp = 1; NTuple->genMuMuBGnTrksm = 1; foundSomething = true; if (printMsg) { std::cout << __LINE__ << " : get background negative track: " << genKst_trkm->pdgId() << "\tfrom mother: " << genKst_trkm->mother()->pdgId(); std::cout << "\tand positive track: " << genKst_trkp->pdgId() << "\tfrom mother: " << genKst_trkp->mother()->pdgId() << std::endl; } } } } } } else if ((foundSomething == true) && (posDau.size() >= 2) && (negDau.size() >= 2)) { foundSomething = false; double bestMass = 0.; unsigned int negDauIndx = 0; unsigned int posDauIndx = 0; for (unsigned int i = 0; i < negDau.size(); i++) { genKst_trkm = findDaughter (genParticles, &negDau, i); if (genKst_trkm != genMum) { for (unsigned int j = 0; j < posDau.size(); j++) { genKst_trkp = findDaughter (genParticles, &posDau, j); if (genKst_trkp != genMup) { double invMass = Utility->computeInvMass (genKst_trkm->px(),genKst_trkm->py(),genKst_trkm->pz(),genKst_trkm->mass(), genKst_trkp->px(),genKst_trkp->py(),genKst_trkp->pz(),genKst_trkp->mass()); if (fabs(invMass - Utility->kstMass) < fabs(bestMass - Utility->kstMass)) { bestMass = invMass; negDauIndx = i; posDauIndx = j; } } } } } if (bestMass > 0.) { genKst_trkm = findDaughter (genParticles, &negDau, negDauIndx); genKst_trkp = findDaughter (genParticles, &posDau, posDauIndx); NTuple->ClearMonteCarlo(); NTuple->genMuMuBG = FirstPart->pdgId(); NTuple->genMuMuBGnTrksp = 1; NTuple->genMuMuBGnTrksm = 1; foundSomething = true; if (printMsg) { std::cout << __LINE__ << " : get background negative track: " << genKst_trkm->pdgId() << "\tfrom mother: " << genKst_trkm->mother()->pdgId(); std::cout << "\tand positive track: " << genKst_trkp->pdgId() << "\tfrom mother: " << genKst_trkp->mother()->pdgId() << std::endl; } } } else { foundSomething = false; if (printMsg) std::cout << __LINE__ << " : @@@ No background found @@@" << std::endl; } } else if (printMsg) std::cout << __LINE__ << " : @@@ No possible background found @@@" << std::endl; } // End else background // ######################## // # Save gen information # // ######################## if (foundSomething == true) { if (printMsg) std::cout << __LINE__ << " : @@@ Saving signal OR background compatible with signal @@@" << std::endl; // ############################# // # Search for primary vertex # // ############################# const reco::Candidate* PVtx = FirstPart; while (PVtx->numberOfMothers() > 0) PVtx = PVtx->mother(0); // ############################ // # Generated Primary Vertex # // ############################ NTuple->genPriVtxX = PVtx->vx(); NTuple->genPriVtxY = PVtx->vy(); NTuple->genPriVtxZ = PVtx->vz(); // ##################### // # Generated B0 Mass # // ##################### NTuple->genB0Mass = FirstPart->mass(); NTuple->genB0Px = FirstPart->px(); NTuple->genB0Py = FirstPart->py(); NTuple->genB0Pz = FirstPart->pz(); // #################### // # Generated B0 Vtx # // #################### NTuple->genB0VtxX = FirstPart->vx(); NTuple->genB0VtxY = FirstPart->vy(); NTuple->genB0VtxZ = FirstPart->vz(); if (NTuple->genSignal != 0) { // ###################### // # Generated K*0 Mass # // ###################### NTuple->genKstMass = genKst->mass(); NTuple->genKstPx = genKst->px(); NTuple->genKstPy = genKst->py(); NTuple->genKstPz = genKst->pz(); // ##################### // # Generated K*0 Vtx # // ##################### NTuple->genKstVtxX = genKst->vx(); NTuple->genKstVtxY = genKst->vy(); NTuple->genKstVtxZ = genKst->vz(); } else if ((NTuple->genMuMuBGnTrksm != 0) && (NTuple->genMuMuBGnTrksp != 0) && (genKst_trkm->vx() == genKst_trkp->vx()) && (genKst_trkm->vy() == genKst_trkp->vy()) && (genKst_trkm->vz() == genKst_trkp->vz())) { double invMass = Utility->computeInvMass (genKst_trkm->momentum().x(),genKst_trkm->momentum().y(),genKst_trkm->momentum().z(),genKst_trkm->mass(), genKst_trkp->momentum().x(),genKst_trkp->momentum().y(),genKst_trkp->momentum().z(),genKst_trkp->mass()); // ###################### // # Generated K*0 Mass # // ###################### NTuple->genKstMass = invMass; NTuple->genKstPx = genKst_trkm->momentum().x() + genKst_trkp->momentum().x(); NTuple->genKstPy = genKst_trkm->momentum().y() + genKst_trkp->momentum().y(); NTuple->genKstPz = genKst_trkm->momentum().z() + genKst_trkp->momentum().z(); // ##################### // # Generated K*0 Vtx # // ##################### NTuple->genKstVtxX = genKst_trkm->vx(); NTuple->genKstVtxY = genKst_trkm->vy(); NTuple->genKstVtxZ = genKst_trkm->vz(); } // ########################################### // # Generated J/psi or psi(2S) Mass and Vtx # // ########################################### if ((NTuple->genSignal == 3) || (NTuple->genSignal == 4) || (NTuple->genSignal == 5) || (NTuple->genSignal == 6)) { NTuple->genPsiMass = genPsi->mass(); NTuple->genPsiVtxX = genPsi->vx(); NTuple->genPsiVtxY = genPsi->vy(); NTuple->genPsiVtxZ = genPsi->vz(); } else if ((NTuple->genSignal == 0) && (genMum->vx() == genMup->vx()) && (genMum->vy() == genMup->vy()) && (genMum->vz() == genMup->vz())) { double invMass = Utility->computeInvMass (genMum->momentum().x(),genMum->momentum().y(),genMum->momentum().z(),genMum->mass(), genMup->momentum().x(),genMup->momentum().y(),genMup->momentum().z(),genMup->mass()); NTuple->genPsiMass = invMass; NTuple->genPsiVtxX = genMum->vx(); NTuple->genPsiVtxY = genMum->vy(); NTuple->genPsiVtxZ = genMum->vz(); } // ################# // # Generated mu- # // ################# NTuple->genMumMother = genMum->mother()->pdgId(); NTuple->genMumPx = genMum->px(); NTuple->genMumPy = genMum->py(); NTuple->genMumPz = genMum->pz(); // ################# // # Generated mu+ # // ################# NTuple->genMupMother = genMup->mother()->pdgId(); NTuple->genMupPx = genMup->px(); NTuple->genMupPy = genMup->py(); NTuple->genMupPz = genMup->pz(); // ######################## // # Generated K*0 track- # // ######################## if ((NTuple->genSignal != 0) || (NTuple->genMuMuBGnTrksm != 0)) { NTuple->genKstTrkmMother = genKst_trkm->mother()->pdgId(); NTuple->genKstTrkmID = genKst_trkm->pdgId(); NTuple->genKstTrkmPx = genKst_trkm->px(); NTuple->genKstTrkmPy = genKst_trkm->py(); NTuple->genKstTrkmPz = genKst_trkm->pz(); } // ######################## // # Generated K*0 track+ # // ######################## if ((NTuple->genSignal != 0) || (NTuple->genMuMuBGnTrksp != 0)) { NTuple->genKstTrkpMother = genKst_trkp->mother()->pdgId(); NTuple->genKstTrkpID = genKst_trkp->pdgId(); NTuple->genKstTrkpPx = genKst_trkp->px(); NTuple->genKstTrkpPy = genKst_trkp->py(); NTuple->genKstTrkpPz = genKst_trkp->pz(); } } // End if foundSomething } // End if B0/B0bar OR Bs/Bsbar OR Lambda_b/Lambda_bbar OR B+/B- // ############################################## // # Check to see if J/psi or psi(2S) is prompt # // ############################################## bool isPrompt = false; const reco::Candidate& PsiCand = (*genParticles)[itGen]; if ((abs(PsiCand.pdgId()) == 443) || (abs(PsiCand.pdgId()) == 100443)) { isPrompt = true; for (unsigned int i = 0; i < PsiCand.numberOfMothers(); i++) { const reco::Candidate* psiMom = PsiCand.mother(i); if (((abs(psiMom->pdgId()) < 600) && (abs(psiMom->pdgId()) > 500)) || ((abs(psiMom->pdgId()) < 6000) && (abs(psiMom->pdgId()) > 5000))) { isPrompt = false; continue; } else { for (unsigned int i = 0; i < psiMom->numberOfMothers(); i++) { const reco::Candidate* psiMom2 = psiMom->mother(i); if (((abs(psiMom2->pdgId()) < 600) && (abs(psiMom2->pdgId()) > 500)) || ((abs(psiMom2->pdgId()) < 6000) && (abs(psiMom2->pdgId()) > 5000))) { isPrompt = false; continue; } else { for (unsigned int i = 0; i < psiMom2->numberOfMothers(); i++) { const reco::Candidate* psiMom3 = psiMom2->mother(i); if (((abs(psiMom3->pdgId()) < 600) && (abs(psiMom3->pdgId()) > 500)) || ((abs(psiMom3->pdgId()) < 6000) && (abs(psiMom3->pdgId()) > 5000))) { isPrompt = false; continue; } } } } } } if (isPrompt == true) { NTuple->genPsiPrompt = 1; if (printMsg) std::cout << __LINE__ << " : found prompt J/psi or psi(2S)" << std::endl; } continue; } for (unsigned int i = 0; i < posDau.size(); i++) { posDau[i]->clear(); delete posDau[i]; } posDau.clear(); for (unsigned int i = 0; i < negDau.size(); i++) { negDau[i]->clear(); delete negDau[i]; } negDau.clear(); } // End for genParticles } // End if doGenReco_ == 2 || doGenReco_ == 3 // #################################### // # Perform matching with candidates # // #################################### if ((NTuple->genSignal != 0) || (NTuple->genMuMuBG != 0)) for (unsigned int i = 0; i < NTuple->nB; i++) { // ########################### // # Check matching with mu- # // ########################### deltaEtaPhi = Utility->computeEtaPhiDistance (NTuple->genMumPx,NTuple->genMumPy,NTuple->genMumPz, NTuple->mumPx->at(i),NTuple->mumPy->at(i),NTuple->mumPz->at(i)); NTuple->mumDeltaRwithMC->push_back(deltaEtaPhi); if (deltaEtaPhi < RCUTMU) { NTuple->truthMatchMum->push_back(1); if (printMsg) std::cout << __LINE__ << " : found matched mu-" << std::endl; } else NTuple->truthMatchMum->push_back(0); // ########################### // # Check matching with mu+ # // ########################### deltaEtaPhi = Utility->computeEtaPhiDistance (NTuple->genMupPx,NTuple->genMupPy,NTuple->genMupPz, NTuple->mupPx->at(i),NTuple->mupPy->at(i),NTuple->mupPz->at(i)); NTuple->mupDeltaRwithMC->push_back(deltaEtaPhi); if (deltaEtaPhi < RCUTMU) { NTuple->truthMatchMup->push_back(1); if (printMsg) std::cout << __LINE__ << " : found matched mu+" << std::endl; } else NTuple->truthMatchMup->push_back(0); // ################################## // # Check matching with K*0 track- # // ################################## if ((NTuple->genSignal != 0) || (NTuple->genMuMuBGnTrksm != 0)) { deltaEtaPhi = Utility->computeEtaPhiDistance (NTuple->genKstTrkmPx,NTuple->genKstTrkmPy,NTuple->genKstTrkmPz, NTuple->kstTrkmPx->at(i),NTuple->kstTrkmPy->at(i),NTuple->kstTrkmPz->at(i)); NTuple->kstTrkmDeltaRwithMC->push_back(deltaEtaPhi); if (deltaEtaPhi < RCUTTRK) { NTuple->truthMatchTrkm->push_back(1); if (printMsg) std::cout << __LINE__ << " : found matched track-" << std::endl; } else NTuple->truthMatchTrkm->push_back(0); } else { NTuple->truthMatchTrkm->push_back(0); NTuple->kstTrkmDeltaRwithMC->push_back(-1.0); } // ################################## // # Check matching with K*0 track+ # // ################################## if ((NTuple->genSignal != 0) || (NTuple->genMuMuBGnTrksp != 0)) { deltaEtaPhi = Utility->computeEtaPhiDistance (NTuple->genKstTrkpPx,NTuple->genKstTrkpPy,NTuple->genKstTrkpPz, NTuple->kstTrkpPx->at(i),NTuple->kstTrkpPy->at(i),NTuple->kstTrkpPz->at(i)); NTuple->kstTrkpDeltaRwithMC->push_back(deltaEtaPhi); if (deltaEtaPhi < RCUTTRK) { NTuple->truthMatchTrkp->push_back(1); if (printMsg) std::cout << __LINE__ << " : found matched track+" << std::endl; } else NTuple->truthMatchTrkp->push_back(0); } else { NTuple->truthMatchTrkp->push_back(0); NTuple->kstTrkpDeltaRwithMC->push_back(-1.0); } // #################################################### // # Check matching with B0 --> track+ track- mu+ mu- # // #################################################### if ((NTuple->truthMatchTrkm->back() == 1) && (NTuple->truthMatchTrkp->back() == 1) && (NTuple->truthMatchMum->back() == 1) && (NTuple->truthMatchMup->back() == 1)) { NTuple->truthMatchSignal->push_back(1); if (printMsg) std::cout << __LINE__ << " : @@@ Found matched B0 --> track+ track- mu+ mu- @@@" << std::endl; } else NTuple->truthMatchSignal->push_back(0); } else for (unsigned int i = 0; i < NTuple->nB; i++) { NTuple->mumDeltaRwithMC->push_back(-1.0); NTuple->mupDeltaRwithMC->push_back(-1.0); NTuple->kstTrkmDeltaRwithMC->push_back(-1.0); NTuple->kstTrkpDeltaRwithMC->push_back(-1.0); NTuple->truthMatchMum->push_back(0); NTuple->truthMatchMup->push_back(0); NTuple->truthMatchTrkm->push_back(0); NTuple->truthMatchTrkp->push_back(0); NTuple->truthMatchSignal->push_back(0); } // ################### // # Fill the ntuple # // ################### if (printMsg) std::cout << __LINE__ << " : @@@ Filling the tree @@@" << std::endl; theTree->Fill(); NTuple->ClearNTuple(); } std::string B0KstMuMu::getMuCat (reco::Muon const& muon) { std::stringstream muCat; muCat.str(""); if (muon.isGlobalMuon() == true) { muCat << " GlobalMuon"; if (muon::isGoodMuon(muon, muon::GlobalMuonPromptTight) == true) muCat << " GlobalMuonPromptTight"; } if (muon.isTrackerMuon() == true) { muCat << " TrackerMuon"; if (muon::isGoodMuon(muon, muon::TrackerMuonArbitrated) == true) muCat << " TrackerMuonArbitrated"; if (muon::isGoodMuon(muon, muon::TMLastStationTight) == true) muCat << " TMLastStationTight"; if (muon::isGoodMuon(muon, muon::TMLastStationLoose) == true) muCat << " TMLastStationLoose"; if (muon::isGoodMuon(muon, muon::TM2DCompatibilityTight) == true) muCat << " TM2DCompatibilityTight"; if (muon::isGoodMuon(muon, muon::TM2DCompatibilityLoose) == true) muCat << " TM2DCompatibilityLoose"; if (muon::isGoodMuon(muon, muon::TMOneStationTight) == true) muCat << " TMOneStationTight"; if (muon::isGoodMuon(muon, muon::TMOneStationLoose) == true) muCat << " TMOneStationLoose"; if (muon::isGoodMuon(muon, muon::TMLastStationAngTight) == true) muCat << " TMLastStationAngTight"; if (muon::isGoodMuon(muon, muon::TMLastStationAngLoose) == true) muCat << " TMLastStationAngLoose"; if (muon::isGoodMuon(muon, muon::TMOneStationAngTight) == true) muCat << " TMOneStationAngTight"; if (muon::isGoodMuon(muon, muon::TMOneStationAngLoose) == true) muCat << " TMOneStationAngLoose"; } if (muon.isStandAloneMuon() == true) muCat << " StandAloneMuon"; if (muon.isCaloMuon() == true) muCat << " CaloMuon"; if ((muon.isGlobalMuon() == false) && (muon.isTrackerMuon() == false) && (muon.isStandAloneMuon() == false) && (muon.isCaloMuon() == false)) muCat << " NotInTable"; return muCat.str(); } const reco::Candidate* B0KstMuMu::skipOscillations (const reco::Candidate* Mother) { if (abs(Mother->pdgId()) != 521) for (unsigned int i = 0; i < Mother->numberOfDaughters(); i++) if ((abs(Mother->daughter(i)->pdgId()) == 511) || (abs(Mother->daughter(i)->pdgId()) == 531) || (abs(Mother->daughter(i)->pdgId()) == 5122)) { if (printMsg) std::cout << __LINE__ << " : @@@ Found oscillating B0/B0bar OR Bs/Bsbar OR Lambda_b/Lambda_bbar @@@" << std::endl; Mother = Mother->daughter(i); } return Mother; } const reco::Candidate* B0KstMuMu::findDaughter (edm::Handle<reco::GenParticleCollection> genParticles, std::vector<std::vector<unsigned int>* >* Dau, unsigned int it) { const reco::Candidate* gen; if (Dau != NULL) { gen = skipOscillations(&(*genParticles)[(*Dau)[it]->operator[](0)]); for (unsigned int i = 1; i < (*Dau)[it]->size(); i++) gen = gen->daughter((*Dau)[it]->operator[](i)); return gen; } else return NULL; } void B0KstMuMu::searchForStableChargedDaughters (const reco::Candidate* Mother, unsigned int motherIndex, std::vector<std::vector<unsigned int>* >* posDau, std::vector<std::vector<unsigned int>* >* negDau) { const reco::Candidate* genDau; unsigned int sizeNegVec = negDau->size(); unsigned int sizePosVec = posDau->size(); for (unsigned int i = 0; i < Mother->numberOfDaughters(); i++) { genDau = Mother->daughter(i); if (printMsg) std::cout << __LINE__ << " : start exploring daughter: " << genDau->pdgId() << "\tindex: " << i << "\tof mother: " << Mother->pdgId() << std::endl; if ((genDau->pdgId() == 11) || (genDau->pdgId() == 13) || (genDau->pdgId() == -211) || (genDau->pdgId() == -321) || (genDau->pdgId() == -2212)) { std::vector<unsigned int>* vecDau = new std::vector<unsigned int>; vecDau->push_back(i); negDau->push_back(vecDau); if (printMsg) std::cout << __LINE__ << " : found possible background negative track: " << genDau->pdgId() << "\tfrom mother: " << genDau->mother()->pdgId() << std::endl; } else if ((genDau->pdgId() == -11) || (genDau->pdgId() == -13) || (genDau->pdgId() == 211) || (genDau->pdgId() == 321) || (genDau->pdgId() == 2212)) { std::vector<unsigned int>* vecDau = new std::vector<unsigned int>; vecDau->push_back(i); posDau->push_back(vecDau); if (printMsg) std::cout << __LINE__ << " : found possible background positive track: " << genDau->pdgId() << "\tfrom mother: " << genDau->mother()->pdgId() << std::endl; } else if ((abs(genDau->pdgId()) != 311) && (abs(genDau->pdgId()) != 310) && (abs(genDau->pdgId()) != 130) && (abs(genDau->pdgId()) != 22) && (abs(genDau->pdgId()) != 12) && (abs(genDau->pdgId()) != 14) && (abs(genDau->pdgId()) != 16)) searchForStableChargedDaughters (genDau, i, posDau, negDau); else if (printMsg) std::cout << __LINE__ << " : found long living neutral particle: " << genDau->pdgId() << std::endl; } for (unsigned int it = negDau->size(); it > sizeNegVec; it--) negDau->operator[](it-1)->insert(negDau->operator[](it-1)->begin(), motherIndex); for (unsigned int it = posDau->size(); it > sizePosVec; it--) posDau->operator[](it-1)->insert(posDau->operator[](it-1)->begin(), motherIndex); } void B0KstMuMu::beginJob () { edm::Service<TFileService> fs; theTree = fs->make<TTree>("B0KstMuMuNTuple","B0KstMuMuNTuple"); NTuple->MakeTreeBranches(theTree); // ############################ // # Print out HLT-trigger cuts # // ############################ std::cout << "\n@@@ Pre-selection cuts @@@" << std::endl; std::cout << __LINE__ << " : CLMUMUVTX = " << CLMUMUVTX << std::endl; std::cout << __LINE__ << " : LSMUMUBS = " << LSMUMUBS << std::endl; std::cout << __LINE__ << " : DCAMUMU = " << DCAMUMU << std::endl; std::cout << __LINE__ << " : DCAMUBS = " << DCAMUBS << std::endl; std::cout << __LINE__ << " : COSALPHAMUMUBS = " << COSALPHAMUMUBS << std::endl; std::cout << __LINE__ << " : MUMINPT = " << MUMINPT << std::endl; std::cout << __LINE__ << " : MUMAXETA = " << MUMAXETA << std::endl; std::cout << __LINE__ << " : MINMUMUPT = " << MINMUMUPT << std::endl; std::cout << __LINE__ << " : MINMUMUINVMASS = " << MINMUMUINVMASS << std::endl; std::cout << __LINE__ << " : MAXMUMUINVMASS = " << MAXMUMUINVMASS << std::endl; // ############################## // # Print out pre-selection cuts # // ############################## std::cout << __LINE__ << " : B0MASSLOWLIMIT = " << B0MASSLOWLIMIT << std::endl; std::cout << __LINE__ << " : B0MASSUPLIMIT = " << B0MASSUPLIMIT << std::endl; std::cout << __LINE__ << " : CLB0VTX = " << CLB0VTX << std::endl; std::cout << __LINE__ << " : KSTMASSWINDOW = " << KSTMASSWINDOW << std::endl; std::cout << __LINE__ << " : HADDCASBS = " << HADDCASBS << std::endl; std::cout << __LINE__ << " : MINHADPT = " << MINHADPT << std::endl; std::cout << "\n@@@ Global constants @@@" << std::endl; std::cout << __LINE__ << " : TRKMAXR = " << TRKMAXR << std::endl; std::cout << __LINE__ << " : PRIVTXNDOF = " << PRIVTXNDOF << std::endl; std::cout << __LINE__ << " : PRIVTXMAXZ = " << PRIVTXMAXZ << std::endl; std::cout << __LINE__ << " : PRIVTXMAXR = " << PRIVTXMAXR << std::endl; std::cout << __LINE__ << " : MUVARTOLE = " << MUVARTOLE << std::endl; std::cout << __LINE__ << " : HADVARTOLE = " << HADVARTOLE << std::endl; std::cout << __LINE__ << " : RCUTMU = " << RCUTMU << std::endl; std::cout << __LINE__ << " : RCUTTRK = " << RCUTTRK << std::endl; } void B0KstMuMu::endJob () { theTree->GetDirectory()->cd(); theTree->Write(); } void B0KstMuMu::endLuminosityBlock(const edm::LuminosityBlock& lumiBlock, const edm::EventSetup& iSetup) { if ((doGenReco_ == 2) || (doGenReco_ == 3)) { edm::Handle<GenFilterInfo> genFilter; lumiBlock.getByToken(genFilterToken_, genFilter); NTuple->numEventsTried = genFilter->numEventsTried(); NTuple->numEventsPassed = genFilter->numEventsPassed(); if (printMsg) { std::cout << "\n@@@ End of a luminosity block @@@" << std::endl; std::cout << __LINE__ << " : number of events tried = " << NTuple->numEventsTried << std::endl; std::cout << __LINE__ << " : number of events passed = " << NTuple->numEventsPassed << std::endl; } } } float B0KstMuMu::calculateIsolation( ClosestApproachInRPhi ClosestApp, reco::TransientTrack muTrackmTT, reco::TransientTrack TrackIsoTT, const ParticleMass muonMass, float vtx_x, float vtx_y, float vtx_z ) { float iso = 0; KinematicParticleVertexFitter KPVtxFitter; KinematicParticleFactoryFromTransientTrack partFactory; float chi, ndf, alpha; TLorentzVector tmp_trk_lv, tmp_cand_lv, tmp_lv; ClosestApp.calculate(TrackIsoTT.initialFreeState(), muTrackmTT.initialFreeState()); if (ClosestApp.status() == false) { if (printMsg) std::cout << __LINE__ << " : continue --> bad status of closest approach" << std::endl; return 0; } GlobalPoint XingPoint = ClosestApp.crossingPoint(); if ((sqrt(XingPoint.x()*XingPoint.x() + XingPoint.y()*XingPoint.y()) > TRKMAXR) || (fabs(XingPoint.z()) > TRKMAXZ)) { if (printMsg) std::cout << __LINE__ << " : continue --> closest approach crossing point outside the tracker volume" << std::endl; return 0; } if ( ClosestApp.distance() < 0.1 ) { chi = 0.; ndf = 0.; std::vector<RefCountedKinematicParticle> tmpParticles; tmpParticles.push_back(partFactory.particle(muTrackmTT, muonMass,chi,ndf, mumasserr) ); tmpParticles.push_back(partFactory.particle(TrackIsoTT, muonMass,chi,ndf, mumasserr) ); RefCountedKinematicTree tmpVertexFitTree = KPVtxFitter.fit(tmpParticles); if ( ! tmpVertexFitTree->isValid()) return 0; tmpVertexFitTree->movePointerToTheTop(); RefCountedKinematicVertex tmpVertex = tmpVertexFitTree->currentDecayVertex(); if (tmpVertexFitTree->isValid() && tmpVertex -> vertexIsValid() ) { tmp_trk_lv .SetPtEtaPhiM( TrackIsoTT.track().pt(), TrackIsoTT.track().eta(), TrackIsoTT.track().phi(), Utility -> kaonMass); tmp_cand_lv.SetPtEtaPhiM( muTrackmTT.track().pt(), muTrackmTT.track().eta(), muTrackmTT.track().phi(), Utility -> kaonMass); tmp_lv = tmp_trk_lv + tmp_cand_lv; alpha = tmp_lv.Angle(TVector3 ( tmpVertex->position().x() - vtx_x, tmpVertex->position().y() - vtx_y, tmpVertex->position().z() - vtx_z ) ); iso = (tmp_lv).P() * alpha / ( (tmp_lv).P()*alpha + tmp_cand_lv.Pt() + tmp_trk_lv.Pt() ); } } return iso; } int B0KstMuMu::findPV(int tk_index, const reco::VertexCollection *vtx) { for (unsigned int i = 0; i < vtx->size(); ++i) { if (! vtx->at(i).isValid() ) continue; for (std::vector<reco::TrackBaseRef>::const_iterator iTrack = vtx->at(i).tracks_begin(); iTrack != vtx->at(i).tracks_end(); iTrack++) { if (static_cast<unsigned int>(tk_index) == iTrack->key()) return 1; } } return -1; } // Compute impact parameter 3D wrt Reco Vtx std::pair<double,double> B0KstMuMu::pionImpactParameter(reco::TransientTrack piTT, reco::Vertex myVtx) { std::pair<double,double> measure; std::pair<bool,Measurement1D> piIP_pair = IPTools::absoluteImpactParameter3D(piTT, myVtx); if (piIP_pair.first) { measure.first = piIP_pair.second.value(); measure.second = piIP_pair.second.significance(); } else { if (printMsg) std::cout << __LINE__ << " : continue --> invalid absolute impact parameter 3D" << std::endl; measure.first = 0; measure.second = 0; } return measure; } // Compute impact parameter 3D wrt Transient Vtx // std::pair<double,double> Utils::pionImpactParameter(reco::TransientTrack piTT, TransientVertex jpsiVtx) // { // std::pair<double,double> measure; // std::pair<bool,Measurement1D> piIP_pair = IPTools::absoluteImpactParameter3D(piTT, jpsiVtx); // if (piIP_pair.first) // { // measure.first = piIP_pair.second.value(); // measure.second = piIP_pair.second.significance(); // } // else // { // measure.first = 0; // measure.second = 0; // } // return measure; // } // Define this as a plug-in DEFINE_FWK_MODULE(B0KstMuMu);
9a0d1a47bc6229099b42e7ea4774685c9a9dede6
5dde665a05fc7ac8284f4a63cdbfd58d8365e24f
/interview/meituan/ma1.cpp
c291e265cfc61760f4665e3e2c54bb2c74ca7c9f
[]
no_license
chen-huicheng/cpp-coder
e6613544db89c94b12e465986e60c851e908f7d6
de318edbdadff6fc31087be280228e32aae08147
refs/heads/master
2023-08-05T07:04:14.784018
2021-09-22T08:52:27
2021-09-22T08:52:27
359,787,922
1
0
null
null
null
null
UTF-8
C++
false
false
960
cpp
#include<bits/stdc++.h> using namespace std; int res=0; set<string> ss; void dfs(vector<vector<int>>& graph,vector<int> &vis,int idx,int k){ if(k==0){ string str; for(int i=0;i<vis.size();i++){ if(vis[i]==1){ str+=to_string(i)+","; } } if(ss.find(str)==ss.end()){ res++; ss.insert(str); } return; } for(auto next:graph[idx]){ if(vis[next]==1)continue; vis[next]=1; dfs(graph,vis,next,k-1); vis[next]=0; } } int main(){ int n,m; cin>>n>>m; vector<vector<int>> graph(n+1); int a,b; for(int i=0;i<m;i++){ cin>>a>>b; graph[a].push_back(b); graph[b].push_back(a); } vector<int> vis(n+1,0); for(int i=1;i<=n;i++){ vis[i]=1; dfs(graph,vis,1,4); vis[i]=0; // cout<<res<<endl; } cout<<res<<endl; return 0; }
8468a4c7887e10c519428b2a0f79cf0cc72746d0
6d9b1a3f3f46e3767ccaf972b925b4a9cc4862cd
/.local/share/Trash/files/c5.2.cpp
dcbdb385cac8540e3f9ad67cca1f1ea5010e7281
[]
no_license
cool1314520dog/ACM
011b78a7f3be9b458963ff0539582e08294c6523
554f20e834a39ab5a100e0b818f33547127ddc3c
refs/heads/master
2021-01-25T08:54:41.347832
2013-08-25T09:03:19
2013-08-25T09:03:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
418
cpp
#include<cstdio> #include<cstring> #include<algorithm> using namespace std; #define MAXN 100 char str[MAXN]; int main() { while(gets(str)) { if(str[0]=='#') break; int ok=0; int len=strlen(str); if(next_permutation(str,str+len)) { ok=1; puts(str); } if(!ok) printf("No Successor\n"); } return 0; }
[ "cooldog@cooldog-SVE14A16ECB.(none)" ]
cooldog@cooldog-SVE14A16ECB.(none)
d9adafa3613a26422d64ff8b5bc64d1ea28060e9
ac1e5473cbf31b0dfa1b654dd7885bc1a4656be7
/SUB_IQA_2.cpp
65e82c9cfc6dc2df59f306efeeca7029ce27d4d7
[]
no_license
lppop6/lppop6_1
5ceb1c827f4379aff843a3083f4ee9626876e8b6
2560ff4f0400c029c4cb46cd6ff2a6dc1898e4f7
refs/heads/master
2022-04-21T07:12:29.571083
2020-04-16T07:23:31
2020-04-16T07:23:31
256,243,265
0
0
null
null
null
null
GB18030
C++
false
false
1,544
cpp
#include "SUB_IQA_2.h" SUB_IQA_2::SUB_IQA_2(QWidget* parent) :QMainWindow(parent) { ui.setupUi(this); connect(ui.btn_Submit, &QPushButton::clicked, this, &SUB_IQA_2::get_Result); } //获得从SUB_IQA_1传来的QImage,显示在lbl上 void SUB_IQA_2::get_Pic_IQA(QImage pic) { ui.lbl_Pic->setPixmap(QPixmap::fromImage(pic)); } //从界面的radiobutton获得对图片的评分 double SUB_IQA_2::evaluate() { double score; //判断是否基础得分 if (ui.rdb_1->isChecked()) { score = 1; } else if (ui.rdb_2->isChecked()) { score = 2; } else if(ui.rdb_3->isChecked()){ score = 3; } else if (ui.rdb_4->isChecked()) { score = 4; } else if (ui.rdb_5->isChecked()) { score = 5; } else { score = 0; } //附加分,通过SUB_IQA_1对全局变量的结果进行判断 if (Pic_1 && Pic_2 && (!Pic_3)) { score *= 1.2; } else if (Pic_1 && Pic_3 && (!Pic_2)) { score *= 0.8; } return score; } //显示结果,由MessageBox显示 void SUB_IQA_2::get_Result() { double result = evaluate(); QString s; QString y; if (result >= 5) { y = y.fromLocal8Bit("质量非常好!"); } else if (result >= 4) { y = y.fromLocal8Bit("质量一般。"); } else if (result > 3) { y = y.fromLocal8Bit("质量相当一般。"); } else { y = y.fromLocal8Bit("没有质量。"); } s = "该图片质量评分为:" + QString::number(result) + "/n" + y; QMessageBox::information(NULL, QString::fromLocal8Bit("分析结果") , QString::fromLocal8Bit("该图片质量评分为:%1\n").arg(result).append(y) ); }
0956bf9ce12f627402414db17d204a3fa4348ca5
1c42215c5558211f02557ef1edd711d067ec78b6
/src/Union_AlterDamage/ZenGin/Gothic_II_Addon/API/zArchiverGeneric.h
9f91615945942429d607447c425668777b386fb6
[]
no_license
UnresolvedExternal/Union_AlterDamage
fd5891c3a62896a3e2049e9fea2b3da9721c57c9
88b1ae773ea8e5c3762d2a5fd23b3ca7fae5c3b2
refs/heads/master
2023-07-26T13:52:00.230498
2023-07-11T17:49:13
2023-07-11T17:49:13
200,260,609
5
1
null
null
null
null
UTF-8
C++
false
false
12,744
h
// Supported with union (c) 2018 Union team #ifndef __ZARCHIVER_GENERIC_H__VER3__ #define __ZARCHIVER_GENERIC_H__VER3__ #include "zArchiver.h" namespace Gothic_II_Addon { class zCArchiverGeneric : public zCArchiver { public: zCLASS_DECLARATION( zCArchiverGeneric ) struct zTWriteObjectEntry { zCObject* object; int objectIndex; zTWriteObjectEntry() {} }; zFILE* file; zCBuffer* cbuffer; int owningMedium; int inSaveGame; int binaryMode; zTAccessMode accessMode; zCArray<zTChunkRecord> chunkStack; zCArray<zCObject*> objectList; unsigned long posNumObjects; unsigned long posChecksum; unsigned long posHeaderEnd; int checksumEnabled; int flags; int debugMessagesOn; int noReadSearchCycles; zSTRING tmpResultValue; int deleteFileOnClose; zCSparseArray<zCObject*, zTWriteObjectEntry> writeObjectList; int warnEntrysNotRead; int warnEntryNotFound; int warnWrongEntryOrder; void zCArchiverGeneric_OnInit() zCall( 0x00521E30 ); zCArchiverGeneric() zInit( zCArchiverGeneric_OnInit() ); void DebugMessage( zSTRING const& ) zCall( 0x005222F0 ); void CheckObjectListSize( int ) zCall( 0x00525A50 ); static zCObject* _CreateNewInstance() zCall( 0x00521CC0 ); static void TestClassIntegrity( void( __cdecl* )( zCObject*, int, zCClassDef*, int& )) zCall( 0x00527DE0 ); virtual zCClassDef* _GetClassDef() const zCall( 0x00521F50 ); virtual ~zCArchiverGeneric() zCall( 0x005221E0 ); virtual void __fastcall WriteInt( char const*, int ) zCall( 0x00522E30 ); virtual void __fastcall WriteByte( char const*, unsigned char ) zCall( 0x00522FD0 ); virtual void __fastcall WriteWord( char const*, unsigned short ) zCall( 0x00523170 ); virtual void __fastcall WriteFloat( char const*, float ) zCall( 0x00523310 ); virtual void __fastcall WriteBool( char const*, int ) zCall( 0x005234D0 ); virtual void __fastcall WriteString( char const*, zSTRING const& ) zCall( 0x00523670 ); virtual void __fastcall WriteVec3( char const*, zVEC3 const& ) zCall( 0x005236D0 ); virtual void __fastcall WriteColor( char const*, zCOLOR const& ) zCall( 0x00523A10 ); virtual void __fastcall WriteRaw( char const*, void*, unsigned long ) zCall( 0x00523D80 ); virtual void __fastcall WriteRawFloat( char const*, void*, unsigned long ) zCall( 0x00523F50 ); virtual void __fastcall WriteEnum( char const*, char const*, int ) zCall( 0x00524220 ); virtual void __fastcall WriteObject( zCObject* ) zCall( 0x00524EC0 ); virtual void __fastcall WriteObject( char const*, zCObject* ) zCall( 0x00524E20 ); virtual void __fastcall WriteObject( char const*, zCObject& ) zCall( 0x00524C10 ); virtual void __fastcall WriteChunkStart( char const*, unsigned short ) zCall( 0x00524950 ); virtual void __fastcall WriteChunkStart( char const*, char const*, unsigned short, unsigned long ) zCall( 0x00524490 ); virtual void __fastcall WriteChunkEnd() zCall( 0x00524970 ); virtual void __fastcall WriteGroupBegin( char const* ) zCall( 0x00524ED0 ); virtual void __fastcall WriteGroupEnd( char const* ) zCall( 0x00524FB0 ); virtual void __fastcall ReadInt( char const*, int& ) zCall( 0x00527B80 ); virtual int __fastcall ReadInt( char const* ) zCall( 0x005274C0 ); virtual void __fastcall ReadByte( char const*, unsigned char& ) zCall( 0x00527BD0 ); virtual unsigned char __fastcall ReadByte( char const* ) zCall( 0x005274E0 ); virtual void __fastcall ReadWord( char const*, unsigned short& ) zCall( 0x00527C20 ); virtual unsigned short __fastcall ReadWord( char const* ) zCall( 0x00527500 ); virtual void __fastcall ReadFloat( char const*, float& ) zCall( 0x00527AD0 ); virtual float __fastcall ReadFloat( char const* ) zCall( 0x00527460 ); virtual void __fastcall ReadBool( char const*, int& ) zCall( 0x00527C70 ); virtual int __fastcall ReadBool( char const* ) zCall( 0x00527520 ); virtual void __fastcall ReadString( char const*, zSTRING& ) zCall( 0x00527CD0 ); virtual zSTRING __fastcall ReadString( char const* ) zCall( 0x00527540 ); virtual void __fastcall ReadVec3( char const*, zVEC3& ) zCall( 0x00527B20 ); virtual zVEC3 __fastcall ReadVec3( char const* ) zCall( 0x00527480 ); virtual void __fastcall ReadColor( char const*, zCOLOR& ) zCall( 0x00527D00 ); virtual zCOLOR __fastcall ReadColor( char const* ) zCall( 0x00527600 ); virtual void __fastcall ReadEnum( char const*, int& ) zCall( 0x00527D90 ); virtual int __fastcall ReadEnum( char const* ) zCall( 0x00527620 ); virtual void __fastcall ReadRaw( char const*, void*, unsigned long ) zCall( 0x00527640 ); virtual void __fastcall ReadRawFloat( char const*, void*, unsigned long ) zCall( 0x005278D0 ); virtual zCObject* __fastcall ReadObject( zCObject* ) zCall( 0x00526DF0 ); virtual zCObject* __fastcall ReadObject( char const*, zCObject* ) zCall( 0x00526560 ); virtual int __fastcall ReadChunkStart( zSTRING&, unsigned short& ) zCall( 0x005263E0 ); virtual int __fastcall ReadChunkStart( char const* ) zCall( 0x00525FB0 ); virtual int __fastcall ReadChunkStartNamed( char const*, unsigned short& ) zCall( 0x00526500 ); virtual void __fastcall SkipOpenChunk() zCall( 0x00521F60 ); virtual unsigned short __fastcall GetCurrentChunkVersion() zCall( 0x00526530 ); virtual zFILE* GetFile() const zCall( 0x00521F70 ); virtual void __fastcall GetBufferString( zSTRING& ) zCall( 0x005226E0 ); virtual zCBuffer* __fastcall GetBuffer() zCall( 0x00522850 ); virtual int __fastcall EndOfArchive() zCall( 0x00522650 ); virtual void Close() zCall( 0x00522470 ); virtual void SetStringEOL( zSTRING const& ) zCall( 0x00521F80 ); virtual zSTRING GetStringEOL() const zCall( 0x00522100 ); virtual int IsStringValid( char const* ) zCall( 0x00522C00 ); virtual int GetChecksumEnabled() const zCall( 0x00522140 ); virtual void SetChecksumEnabled( int ) zCall( 0x00522150 ); virtual void SetNoReadSearchCycles( int ) zCall( 0x00522160 ); virtual int InProperties() const zCall( 0x00522170 ); virtual int InSaveGame() const zCall( 0x00522180 ); virtual int InBinaryMode() const zCall( 0x00522190 ); virtual zCObject* __fastcall GetParentObject() zCall( 0x00528800 ); virtual int OpenWriteBuffer( zCBuffer*, zTArchiveMode, int, int, int ) zCall( 0x00522860 ); virtual void OpenWriteFile( zFILE*, zTArchiveMode, int, int, int ) zCall( 0x00522A30 ); virtual void __fastcall WriteHeader( int ) zCall( 0x00522B90 ); virtual void __fastcall WriteHeaderNumObj() zCall( 0x00522310 ); virtual void __fastcall WriteASCIILine( char const*, char const*, zSTRING const& ) zCall( 0x00522C40 ); virtual void __fastcall StoreBuffer( void*, unsigned long ) zCall( 0x00522AA0 ); virtual void __fastcall StoreString( char const* ) zCall( 0x00522AD0 ); virtual void __fastcall StoreStringEOL( char const* ) zCall( 0x00522B60 ); virtual unsigned long __fastcall StoreGetPos() zCall( 0x00522B10 ); virtual void __fastcall StoreSeek( unsigned long ) zCall( 0x00522B30 ); virtual int OpenReadBuffer( zCBuffer&, zTArchiveMode, int, int ) zCall( 0x00525090 ); virtual void OpenReadFile( zFILE*, zTArchiveMode, int, int, int ) zCall( 0x00525260 ); virtual zCClassDef* __fastcall GetClassDefByString( zSTRING const& ) zCall( 0x00525BC0 ); virtual zCObject* __fastcall CreateObject( zSTRING const& ) zCall( 0x00525AF0 ); virtual void __fastcall SkipChunk( int ) zCall( 0x00526E00 ); virtual void __fastcall ReadChunkStartASCII( char const*, zSTRING& ) zCall( 0x00525D60 ); virtual void __fastcall ReadChunkEnd() zCall( 0x00526550 ); virtual int __fastcall ReadEntryASCII( char const*, zSTRING& ) zCall( 0x00527000 ); virtual void __fastcall ReadHeader() zCall( 0x00525750 ); virtual void __fastcall RestoreBuffer( void*, unsigned long ) zCall( 0x005252D0 ); virtual void __fastcall RestoreStringEOL( zSTRING& ) zCall( 0x00525300 ); virtual void __fastcall RestoreString0( zSTRING& ) zCall( 0x005256E0 ); virtual unsigned long __fastcall RestoreGetPos() zCall( 0x005256F0 ); virtual void __fastcall RestoreSeek( unsigned long ) zCall( 0x00525710 ); virtual void __fastcall DeleteBuffer() zCall( 0x005226C0 ); }; } // namespace Gothic_II_Addon #endif // __ZARCHIVER_GENERIC_H__VER3__
c4d7656d69ba8035e9d7a623f3df07151d1f96c0
ce7c24ecd08d1ff537d11e296a5cc8fcad3e4ed6
/C++/WavFile.h
ec84148a013e5f638d8346c4a6ce8edd3cc1b19c
[]
no_license
inspiralpatterns/programming
5396015afa13c2aceb158f2c0784f0600deaddf9
c80697c638fc372971183cb87afb03c071658908
refs/heads/master
2021-01-11T20:34:28.965858
2020-07-16T19:06:10
2020-07-16T19:06:10
79,137,670
3
0
null
null
null
null
UTF-8
C++
false
false
16,865
h
// WavFile.h // #ifndef WAVFILE_H #define WAVFILE_H #include <stdexcept> #include <string> #include <cstdlib> #include <cstdio> #include <cassert> #include <cstring> #include <limits.h> #ifndef uint typedef unsigned int uint; #endif const static char riffStr[] = "RIFF"; const static char waveStr[] = "WAVE"; const static char fmtStr[] = "fmt "; const static char dataStr[] = "data"; typedef struct { char riff_char[4]; int package_len; char wave[4]; } WavRiff; typedef struct { char fmt[4]; int format_len; short fixed; short channel_number; int sample_rate; int byte_rate; short byte_per_sample; short bits_per_sample; } WavFormat; typedef struct { char data_field[4]; uint data_len; } WavData; typedef struct { WavRiff riff; WavFormat format; WavData data; } WavHeader; #ifdef BYTE_ORDER #if BYTE_ORDER == BIG_ENDIAN #define _BIG_ENDIAN_ #endif #endif #ifdef _BIG_ENDIAN_ static inline void _swap32 (unsigned int &dwData) { dwData = ((dwData >> 24) & 0x000000FF) | ((dwData >> 8) & 0x0000FF00) | ((dwData << 8) & 0x00FF0000) | ((dwData << 24) & 0xFF000000); } static inline void _swap16 (unsigned short &wData) { wData = ((wData >> 8) & 0x00FF) | ((wData << 8) & 0xFF00); } static inline void _swap16Buffer (unsigned short *pData, unsigned int dwNumWords) { unsigned long i; for (i = 0; i < dwNumWords; i ++) { _swap16 (pData[i]); } } #else // BIG_ENDIAN static inline void _swap32 (unsigned int &dwData) { // do nothing } static inline void _swap16 (unsigned short &wData) { // do nothing } static inline void _swap16Buffer (unsigned short *pData, unsigned int dwNumBytes) { // do nothing } #endif // BIG_ENDIAN // test if character code is between a white space ' ' and little 'z' static int isAlpha (char c) { return (c >= ' ' && c <= 'z') ? 1 : 0; } // test if all characters are between a white space ' ' and little 'z' static int isAlphaStr (char *str) { int c; c = str[0]; while (c) { if (isAlpha(c) == 0) return 0; str ++; c = str[0]; } return 1; } class WavInFile { public: WavInFile (const char *fileName) { int hdrsOk; // Try to open the file for reading fptr = fopen(fileName, "rb"); if (fptr == NULL) { // didn't succeed std::string msg = "Error : Unable to open file \""; msg += fileName; msg += "\" for reading."; throw std::runtime_error(msg); } // Read the file headers hdrsOk = readWavHeaders(); if (hdrsOk != 0) { // Something didn't match in the wav file headers std::string msg = "File \""; msg += fileName; msg += "\" is corrupt or not a WAV file"; throw std::runtime_error(msg); } if (header.format.fixed != 1) { std::string msg = "File \""; msg += fileName; msg += "\" uses unsupported encoding."; throw std::runtime_error(msg); } dataRead = 0; } ~WavInFile() { close(); } void rewind() { int hdrsOk; fseek(fptr, 0, SEEK_SET); hdrsOk = readWavHeaders(); assert(hdrsOk == 0); dataRead = 0; } int checkCharTags() { // header.format.fmt should equal to 'fmt ' if (memcmp(fmtStr, header.format.fmt, 4) != 0) return -1; // header.data.data_field should equal to 'data' if (memcmp(dataStr, header.data.data_field, 4) != 0) return -1; return 0; } int read(char *buffer, int maxElems) { int numBytes; uint afterDataRead; // ensure it's 8 bit format if (header.format.bits_per_sample != 8) { throw std::runtime_error("Error: read(char*, int) works only with 8bit samples."); } assert(sizeof(char) == 1); numBytes = maxElems; afterDataRead = dataRead + numBytes; if (afterDataRead > header.data.data_len) { // Don't read more samples than are marked available in header numBytes = header.data.data_len - dataRead; assert(numBytes >= 0); } numBytes = fread(buffer, 1, numBytes, fptr); dataRead += numBytes; return numBytes; } int read(short *buffer, int maxElems) { unsigned int afterDataRead; int numBytes; int numElems; if (header.format.bits_per_sample == 8) { // 8 bit format char *temp = new char[maxElems]; int i; numElems = read(temp, maxElems); // convert from 8 to 16 bit for (i = 0; i < numElems; i ++) { buffer[i] = temp[i] << 8; } delete[] temp; } else { // 16 bit format assert(header.format.bits_per_sample == 16); assert(sizeof(short) == 2); numBytes = maxElems * 2; afterDataRead = dataRead + numBytes; if (afterDataRead > header.data.data_len) { // Don't read more samples than are marked available in header numBytes = header.data.data_len - dataRead; assert(numBytes >= 0); } numBytes = fread(buffer, 1, numBytes, fptr); dataRead += numBytes; numElems = numBytes / 2; // 16bit samples, swap byte order if necessary _swap16Buffer((unsigned short *)buffer, numElems); } return numElems; } int read(float *buffer, int maxElems) { short *temp = new short[maxElems]; int num; int i; double fscale; num = read(temp, maxElems); fscale = 1.0 / 32768.0; // convert to floats, scale to range [-1..+1[ for (i = 0; i < num; i ++) { buffer[i] = (float)(fscale * (double)temp[i]); } delete[] temp; return num; } int read(double *buffer, int maxElems) { short *temp = new short[maxElems]; int num; int i; double fscale; num = read(temp, maxElems); fscale = 1.0 / 32768.0; // convert to doubles, scale to range [-1..+1[ for (i = 0; i < num; i ++) { buffer[i] = (double)(fscale * (double)temp[i]); } delete[] temp; return num; } int eof() const { // return true if all data has been read or file eof has reached return (dataRead == header.data.data_len || feof(fptr)); } void close() { fclose(fptr); fptr = NULL; } int readRIFFBlock() { fread(&(header.riff), sizeof(WavRiff), 1, fptr); // swap 32bit data byte order if necessary _swap32((unsigned int &)header.riff.package_len); // header.riff.riff_char should equal to 'RIFF'); if (memcmp(riffStr, header.riff.riff_char, 4) != 0) return -1; // header.riff.wave should equal to 'WAVE' if (memcmp(waveStr, header.riff.wave, 4) != 0) return -1; return 0; } int readHeaderBlock() { char label[5]; std::string sLabel; // lead label std::string fread(label, 1, 4, fptr); label[4] = 0; if (isAlphaStr(label) == 0) return -1; // not a valid label // Decode blocks according to their label if (strcmp(label, fmtStr) == 0) { int nLen, nDump; // 'fmt ' block memcpy(header.format.fmt, fmtStr, 4); // read length of the format field fread(&nLen, sizeof(int), 1, fptr); // swap byte order if necessary _swap32((unsigned int &)nLen); // int format_len; header.format.format_len = nLen; // calculate how much length differs from expected nDump = nLen - (sizeof(header.format) - 8); // if format_len is larger than expected, read only as much data as we've space for if (nDump > 0) { nLen = sizeof(header.format) - 8; } // read data fread(&(header.format.fixed), nLen, 1, fptr); // swap byte order if necessary _swap16((unsigned short &)header.format.fixed); // short int fixed; _swap16((unsigned short &)header.format.channel_number); // short int channel_number; _swap32((unsigned int &)header.format.sample_rate); // int sample_rate; _swap32((unsigned int &)header.format.byte_rate); // int byte_rate; _swap16((unsigned short &)header.format.byte_per_sample); // short int byte_per_sample; _swap16((unsigned short &)header.format.bits_per_sample); // short int bits_per_sample; // if format_len is larger than expected, skip the extra data if (nDump > 0) { fseek(fptr, nDump, SEEK_CUR); } return 0; } else if (strcmp(label, dataStr) == 0) { // 'data' block memcpy(header.data.data_field, dataStr, 4); fread(&(header.data.data_len), sizeof(uint), 1, fptr); // swap byte order if necessary _swap32((unsigned int &)header.data.data_len); return 1; } else { uint len, i; uint temp; // unknown block // read length fread(&len, sizeof(len), 1, fptr); // scan through the block for (i = 0; i < len; i ++) { fread(&temp, 1, 1, fptr); if (feof(fptr)) return -1; // unexpected eof } } return 0; } int readWavHeaders() { int res; memset(&header, 0, sizeof(header)); res = readRIFFBlock(); if (res) return 1; // read header blocks until data block is found do { // read header blocks res = readHeaderBlock(); if (res < 0) return 1; // error in file structure } while (res == 0); // check that all required tags are legal return checkCharTags(); } uint getNumChannels() const { return header.format.channel_number; } uint getNumBits() const { return header.format.bits_per_sample; } uint getBytesPerSample() const { return getNumChannels() * getNumBits() / 8; } uint getSampleRate() const { return header.format.sample_rate; } uint getDataSizeInBytes() const { return header.data.data_len; } uint getNumSamples() const { return header.data.data_len / header.format.byte_per_sample; } uint getLengthMS() const { uint numSamples; uint sampleRate; numSamples = getNumSamples(); sampleRate = getSampleRate(); assert(numSamples < UINT_MAX / 1000); return (1000 * numSamples / sampleRate); } private: FILE *fptr; uint dataRead; WavHeader header; }; /// Class for writing WAV audio files. class WavOutFile { private: /// Pointer to the WAV file FILE *fptr; /// WAV file header data. WavHeader header; /// Counter of how many bytes have been written to the file so far. int bytesWritten; public: ////////////////////////////////////////////////////////////////////////////// // // Class WavOutFile // WavOutFile(const char *fileName, int sampleRate, int bits, int channels) { bytesWritten = 0; fptr = fopen(fileName, "wb"); if (fptr == NULL) { std::string msg = "Error : Unable to open file \""; msg += fileName; msg += "\" for writing."; //pmsg = msg.c_str; throw std::runtime_error(msg); } fillInHeader(sampleRate, bits, channels); writeHeader(); } ~WavOutFile() { close(); } void fillInHeader(uint sampleRate, uint bits, uint channels) { // fill in the 'riff' part.. // copy std::string 'RIFF' to riff_char memcpy(&(header.riff.riff_char), riffStr, 4); // package_len unknown so far header.riff.package_len = 0; // copy std::string 'WAVE' to wave memcpy(&(header.riff.wave), waveStr, 4); // fill in the 'format' part.. // copy std::string 'fmt ' to fmt memcpy(&(header.format.fmt), fmtStr, 4); header.format.format_len = 0x10; header.format.fixed = 1; header.format.channel_number = (short)channels; header.format.sample_rate = sampleRate; header.format.bits_per_sample = (short)bits; header.format.byte_per_sample = (short)(bits * channels / 8); header.format.byte_rate = header.format.byte_per_sample * sampleRate; header.format.sample_rate = sampleRate; // fill in the 'data' part.. // copy std::string 'data' to data_field memcpy(&(header.data.data_field), dataStr, 4); // data_len unknown so far header.data.data_len = 0; } void finishHeader() { // supplement the file length into the header structure header.riff.package_len = bytesWritten + 36; header.data.data_len = bytesWritten; writeHeader(); } void writeHeader() { WavHeader hdrTemp; // swap byte order if necessary hdrTemp = header; _swap32((unsigned int &)hdrTemp.riff.package_len); _swap32((unsigned int &)hdrTemp.format.format_len); _swap16((unsigned short &)hdrTemp.format.fixed); _swap16((unsigned short &)hdrTemp.format.channel_number); _swap32((unsigned int &)hdrTemp.format.sample_rate); _swap32((unsigned int &)hdrTemp.format.byte_rate); _swap16((unsigned short &)hdrTemp.format.byte_per_sample); _swap16((unsigned short &)hdrTemp.format.bits_per_sample); _swap32((unsigned int &)hdrTemp.data.data_len); // write the supplemented header in the beginning of the file fseek(fptr, 0, SEEK_SET); fwrite(&hdrTemp, sizeof(hdrTemp), 1, fptr); // jump back to the end of the file fseek(fptr, 0, SEEK_END); } void close() { finishHeader(); fclose(fptr); fptr = NULL; } void write(const char *buffer, int numElems) { int res; if (header.format.bits_per_sample != 8) { throw std::runtime_error("Error: write(const char*, int) accepts only 8bit samples."); } assert(sizeof(char) == 1); res = fwrite(buffer, 1, numElems, fptr); if (res != numElems) { throw std::runtime_error("Error while writing to a wav file."); } bytesWritten += numElems; } void write(const short *buffer, int numElems) { int res; // 16 bit samples if (numElems < 1) return; // nothing to do if (header.format.bits_per_sample == 8) { int i; char *temp = new char[numElems]; // convert from 16bit format to 8bit format for (i = 0; i < numElems; i ++) { temp[i] = buffer[i] >> 8; } // write in 8bit format write(temp, numElems); delete[] temp; } else { // 16bit format unsigned short *pTemp = new unsigned short[numElems]; assert(header.format.bits_per_sample == 16); // allocate temp buffer to swap byte order if necessary memcpy(pTemp, buffer, numElems * 2); _swap16Buffer(pTemp, numElems); res = fwrite(pTemp, 2, numElems, fptr); delete[] pTemp; if (res != numElems) { throw std::runtime_error("Error while writing to a wav file."); } bytesWritten += 2 * numElems; } } void write(const float *buffer, int numElems) { int i; short *temp = new short[numElems]; int iTemp; // convert to 16 bit integer for (i = 0; i < numElems; i ++) { // convert to integer iTemp = (int)(32768.0f * buffer[i]); // saturate if (iTemp < -32768) iTemp = -32768; if (iTemp > 32767) iTemp = 32767; temp[i] = (short)iTemp; } write(temp, numElems); delete[] temp; } void write(const double *buffer, int numElems) { int i; short *temp = new short[numElems]; int iTemp; // convert to 16 bit integer for (i = 0; i < numElems; i ++) { // convert to integer iTemp = (int)(32768.0f * buffer[i]); // saturate if (iTemp < -32768) iTemp = -32768; if (iTemp > 32767) iTemp = 32767; temp[i] = (short)iTemp; } write(temp, numElems); delete[] temp; } }; #endif
f24aadf4f2342cdd9cfbbb7781e0bab64f39d2a1
e1ad8df32760159d8d48112cb733ca52e917339b
/Source/Figures/DurationProtocolControllers/DurationProtocolController.h
385a46cb8bdda4ba00d7ab0e9d701fbbc2a0d3a3
[]
no_license
joncode/Montage
b3e2c17194b2863ba2ea2e2b3fb3486faa58e134
189f1c4119aeba03ed73c1385d4cfcc3a6c1b662
refs/heads/master
2023-04-05T10:54:17.551077
2021-03-24T09:37:27
2021-03-24T09:37:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
710
h
#pragma once // NB: forward declaration to avoid circular dependency. Including // DurationProtoolParams.h here results in a compilation error class DurationProtocolParams; #include <DurationsProducer.hpp> #include <juce_gui_basics/juce_gui_basics.h> #include <memory> class DurationProtocolController : public juce::Component { public: virtual ~DurationProtocolController() = default; enum class Type { geometric, multiples, prescribed }; // Factory static std::unique_ptr<DurationProtocolController> create(Type type, DurationProtocolParams &params, std::shared_ptr<aleatoric::DurationsProducer> producer); private: virtual void setProtocol() = 0; };
9e73f0eb5ac652bd245c5a9ad205d55374a13582
8dc84558f0058d90dfc4955e905dab1b22d12c08
/third_party/blink/renderer/core/css/css_selector.h
b709e69feac94f250bfea6f0585fcf0017bd0add
[ "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause", "LGPL-2.0-only", "BSD-2-Clause", "LGPL-2.1-only" ]
permissive
meniossin/src
42a95cc6c4a9c71d43d62bc4311224ca1fd61e03
44f73f7e76119e5ab415d4593ac66485e65d700a
refs/heads/master
2022-12-16T20:17:03.747113
2020-09-03T10:43:12
2020-09-03T10:43:12
263,710,168
1
0
BSD-3-Clause
2020-05-13T18:20:09
2020-05-13T18:20:08
null
UTF-8
C++
false
false
19,902
h
/* * Copyright (C) 1999-2003 Lars Knoll ([email protected]) * 1999 Waldo Bastian ([email protected]) * Copyright (C) 2004, 2006, 2007, 2008, 2009, 2010, 2013 Apple Inc. 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 THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_SELECTOR_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_SELECTOR_H_ #include <memory> #include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/core/css/parser/css_parser_context.h" #include "third_party/blink/renderer/core/css/parser/css_parser_mode.h" #include "third_party/blink/renderer/core/dom/qualified_name.h" #include "third_party/blink/renderer/core/style/computed_style_constants.h" #include "third_party/blink/renderer/platform/wtf/ref_counted.h" namespace blink { class CSSSelectorList; // This class represents a simple selector for a StyleRule. // CSS selector representation is somewhat complicated and subtle. A // representative list of selectors is in CSSSelectorTest; run it in a debug // build to see useful debugging output. // // ** TagHistory() and Relation(): // // Selectors are represented as an array of simple selectors (defined more // or less according to // http://www.w3.org/TR/css3-selectors/#simple-selectors-dfn). The tagHistory() // method returns the next simple selector in the list. The relation() method // returns the relationship of the current simple selector to the one in // tagHistory(). For example, the CSS selector .a.b #c is represented as: // // SelectorText(): .a.b #c // --> (relation == kDescendant) // SelectorText(): .a.b // --> (relation == kSubSelector) // SelectorText(): .b // // The order of tagHistory() varies depending on the situation. // * Relations using combinators // (http://www.w3.org/TR/css3-selectors/#combinators), such as descendant, // sibling, etc., are parsed right-to-left (in the example above, this is why // #c is earlier in the tagHistory() chain than .a.b). // * SubSelector relations are parsed left-to-right in most cases (such as the // .a.b example above); a counter-example is the // ::content pseudo-element. Most (all?) other pseudo elements and pseudo // classes are parsed left-to-right. // * ShadowPseudo relations are parsed right-to-left. Example: // summary::-webkit-details-marker is parsed as: selectorText(): // summary::-webkit-details-marker --> (relation == ShadowPseudo) // selectorText(): summary // // ** match(): // // The match of the current simple selector tells us the type of selector, such // as class, id, tagname, or pseudo-class. Inline comments in the Match enum // give examples of when each type would occur. // // ** value(), attribute(): // // value() tells you the value of the simple selector. For example, for class // selectors, value() will tell you the class string, and for id selectors it // will tell you the id(). See below for the special case of attribute // selectors. // // ** Attribute selectors. // // Attribute selectors return the attribute name in the attribute() method. The // value() method returns the value matched against in case of selectors like // [attr="value"]. // class CORE_EXPORT CSSSelector { USING_FAST_MALLOC_WITH_TYPE_NAME(blink::CSSSelector); public: CSSSelector(); CSSSelector(const CSSSelector&); explicit CSSSelector(const QualifiedName&, bool tag_is_implicit = false); ~CSSSelector(); String SelectorText() const; bool operator==(const CSSSelector&) const; // http://www.w3.org/TR/css3-selectors/#specificity // We use 256 as the base of the specificity number system. unsigned Specificity() const; /* how the attribute value has to match.... Default is Exact */ enum MatchType { kUnknown, kTag, // Example: div kId, // Example: #id kClass, // example: .class kPseudoClass, // Example: :nth-child(2) kPseudoElement, // Example: ::first-line kPagePseudoClass, // ?? kAttributeExact, // Example: E[foo="bar"] kAttributeSet, // Example: E[foo] kAttributeHyphen, // Example: E[foo|="bar"] kAttributeList, // Example: E[foo~="bar"] kAttributeContain, // css3: E[foo*="bar"] kAttributeBegin, // css3: E[foo^="bar"] kAttributeEnd, // css3: E[foo$="bar"] kFirstAttributeSelectorMatch = kAttributeExact, }; enum RelationType { kSubSelector, // No combinator kDescendant, // "Space" combinator kChild, // > combinator kDirectAdjacent, // + combinator kIndirectAdjacent, // ~ combinator // Special cases for shadow DOM related selectors. kShadowPiercingDescendant, // >>> combinator kShadowDeep, // /deep/ combinator kShadowDeepAsDescendant, // /deep/ as an alias for descendant kShadowPseudo, // ::shadow pseudo element kShadowSlot, // ::slotted() pseudo element kShadowPart, // ::part() pseudo element }; enum PseudoType { kPseudoUnknown, kPseudoEmpty, kPseudoFirstChild, kPseudoFirstOfType, kPseudoLastChild, kPseudoLastOfType, kPseudoOnlyChild, kPseudoOnlyOfType, kPseudoFirstLine, kPseudoFirstLetter, kPseudoNthChild, kPseudoNthOfType, kPseudoNthLastChild, kPseudoNthLastOfType, kPseudoPart, kPseudoLink, kPseudoVisited, kPseudoAny, kPseudoMatches, kPseudoIS, kPseudoAnyLink, kPseudoWebkitAnyLink, kPseudoAutofill, kPseudoHover, kPseudoDrag, kPseudoFocus, kPseudoFocusVisible, kPseudoFocusWithin, kPseudoActive, kPseudoChecked, kPseudoEnabled, kPseudoFullPageMedia, kPseudoDefault, kPseudoDisabled, kPseudoOptional, kPseudoPlaceholderShown, kPseudoRequired, kPseudoReadOnly, kPseudoReadWrite, kPseudoValid, kPseudoInvalid, kPseudoIndeterminate, kPseudoTarget, kPseudoBefore, kPseudoAfter, kPseudoBackdrop, kPseudoLang, kPseudoNot, kPseudoPlaceholder, kPseudoResizer, kPseudoRoot, kPseudoScope, kPseudoScrollbar, kPseudoScrollbarButton, kPseudoScrollbarCorner, kPseudoScrollbarThumb, kPseudoScrollbarTrack, kPseudoScrollbarTrackPiece, kPseudoWindowInactive, kPseudoCornerPresent, kPseudoDecrement, kPseudoIncrement, kPseudoHorizontal, kPseudoVertical, kPseudoStart, kPseudoEnd, kPseudoDoubleButton, kPseudoSingleButton, kPseudoNoButton, kPseudoSelection, kPseudoLeftPage, kPseudoRightPage, kPseudoFirstPage, // TODO(foolip): When the unprefixed Fullscreen API is enabled, merge // kPseudoFullScreen and kPseudoFullscreen into one. (kPseudoFullscreen is // controlled by the FullscreenUnprefixed REF, but is otherwise an alias.) kPseudoFullScreen, kPseudoFullScreenAncestor, kPseudoFullscreen, kPseudoInRange, kPseudoOutOfRange, // Pseudo elements in UA ShadowRoots. Available in any stylesheets. kPseudoWebKitCustomElement, // Pseudo elements in UA ShadowRoots. Availble only in UA stylesheets. kPseudoBlinkInternalElement, kPseudoCue, kPseudoFutureCue, kPseudoPastCue, kPseudoUnresolved, kPseudoDefined, kPseudoContent, kPseudoHost, kPseudoHostContext, kPseudoShadow, kPseudoSpatialNavigationFocus, kPseudoListBox, kPseudoHostHasAppearance, kPseudoSlotted, kPseudoVideoPersistent, kPseudoVideoPersistentAncestor, }; enum AttributeMatchType { kCaseSensitive, kCaseInsensitive, }; PseudoType GetPseudoType() const { return static_cast<PseudoType>(pseudo_type_); } void UpdatePseudoType(const AtomicString&, const CSSParserContext&, bool has_arguments, CSSParserMode); void UpdatePseudoPage(const AtomicString&); static PseudoType ParsePseudoType(const AtomicString&, bool has_arguments); static PseudoId ParsePseudoId(const String&); static PseudoId GetPseudoId(PseudoType); // Selectors are kept in an array by CSSSelectorList. The next component of // the selector is the next item in the array. const CSSSelector* TagHistory() const { return is_last_in_tag_history_ ? nullptr : this + 1; } static const AtomicString& UniversalSelectorAtom() { return g_null_atom; } const QualifiedName& TagQName() const; const AtomicString& Value() const; const AtomicString& SerializingValue() const; // WARNING: Use of QualifiedName by attribute() is a lie. // attribute() will return a QualifiedName with prefix and namespaceURI // set to g_star_atom to mean "matches any namespace". Be very careful // how you use the returned QualifiedName. // http://www.w3.org/TR/css3-selectors/#attrnmsp const QualifiedName& Attribute() const; AttributeMatchType AttributeMatch() const; // Returns the argument of a parameterized selector. For example, :lang(en-US) // would have an argument of en-US. // Note that :nth-* selectors don't store an argument and just store the // numbers. const AtomicString& Argument() const { return has_rare_data_ ? data_.rare_data_->argument_ : g_null_atom; } const CSSSelectorList* SelectorList() const { return has_rare_data_ ? data_.rare_data_->selector_list_.get() : nullptr; } #ifndef NDEBUG void Show() const; void Show(int indent) const; #endif bool IsASCIILower(const AtomicString& value); void SetValue(const AtomicString&, bool match_lower_case); void SetAttribute(const QualifiedName&, AttributeMatchType); void SetArgument(const AtomicString&); void SetSelectorList(std::unique_ptr<CSSSelectorList>); void SetNth(int a, int b); bool MatchNth(unsigned count) const; bool IsAdjacentSelector() const { return relation_ == kDirectAdjacent || relation_ == kIndirectAdjacent; } bool IsShadowSelector() const { return relation_ == kShadowPseudo || relation_ == kShadowDeep; } bool IsAttributeSelector() const { return match_ >= kFirstAttributeSelectorMatch; } bool IsHostPseudoClass() const { return pseudo_type_ == kPseudoHost || pseudo_type_ == kPseudoHostContext; } bool IsUserActionPseudoClass() const; bool IsV0InsertionPointCrossing() const { return pseudo_type_ == kPseudoHostContext || pseudo_type_ == kPseudoContent; } bool IsIdClassOrAttributeSelector() const; RelationType Relation() const { return static_cast<RelationType>(relation_); } void SetRelation(RelationType relation) { relation_ = relation; DCHECK_EQ(static_cast<RelationType>(relation_), relation); // using a bitfield. } MatchType Match() const { return static_cast<MatchType>(match_); } void SetMatch(MatchType match) { match_ = match; DCHECK_EQ(static_cast<MatchType>(match_), match); // using a bitfield. } bool IsLastInSelectorList() const { return is_last_in_selector_list_; } void SetLastInSelectorList(bool is_last) { is_last_in_selector_list_ = is_last; } bool IsLastInOriginalList() const { return is_last_in_original_list_; } void SetLastInOriginalList(bool is_last) { is_last_in_original_list_ = is_last; } bool IsLastInTagHistory() const { return is_last_in_tag_history_; } void SetLastInTagHistory(bool is_last) { is_last_in_tag_history_ = is_last; } bool IgnoreSpecificity() const { return ignore_specificity_; } void SetIgnoreSpecificity(bool ignore) { ignore_specificity_ = ignore; } // https://drafts.csswg.org/selectors/#compound bool IsCompound() const; enum LinkMatchMask { kMatchLink = 1, kMatchVisited = 2, kMatchAll = kMatchLink | kMatchVisited }; unsigned ComputeLinkMatchType(unsigned link_match_type) const; bool IsForPage() const { return is_for_page_; } void SetForPage() { is_for_page_ = true; } bool RelationIsAffectedByPseudoContent() const { return relation_is_affected_by_pseudo_content_; } void SetRelationIsAffectedByPseudoContent() { relation_is_affected_by_pseudo_content_ = true; } bool MatchesPseudoElement() const; bool HasContentPseudo() const; bool HasSlottedPseudo() const; bool HasDeepCombinatorOrShadowPseudo() const; bool NeedsUpdatedDistribution() const; bool HasPseudoMatches() const; bool HasPseudoIS() const; private: unsigned relation_ : 4; // enum RelationType unsigned match_ : 4; // enum MatchType unsigned pseudo_type_ : 8; // enum PseudoType unsigned is_last_in_selector_list_ : 1; unsigned is_last_in_tag_history_ : 1; unsigned has_rare_data_ : 1; unsigned is_for_page_ : 1; unsigned tag_is_implicit_ : 1; unsigned relation_is_affected_by_pseudo_content_ : 1; unsigned is_last_in_original_list_ : 1; unsigned ignore_specificity_ : 1; void SetPseudoType(PseudoType pseudo_type) { pseudo_type_ = pseudo_type; DCHECK_EQ(static_cast<PseudoType>(pseudo_type_), pseudo_type); // using a bitfield. } unsigned SpecificityForOneSelector() const; unsigned SpecificityForPage() const; const CSSSelector* SerializeCompound(StringBuilder&) const; // Hide. CSSSelector& operator=(const CSSSelector&) = delete; struct RareData : public RefCounted<RareData> { static scoped_refptr<RareData> Create(const AtomicString& value) { return base::AdoptRef(new RareData(value)); } ~RareData(); bool MatchNth(unsigned count); int NthAValue() const { return bits_.nth_.a_; } int NthBValue() const { return bits_.nth_.b_; } AtomicString matching_value_; AtomicString serializing_value_; union { struct { int a_; // Used for :nth-* int b_; // Used for :nth-* } nth_; AttributeMatchType attribute_match_; // used for attribute selector (with value) } bits_; QualifiedName attribute_; // used for attribute selector AtomicString argument_; // Used for :contains, :lang, :nth-* std::unique_ptr<CSSSelectorList> selector_list_; // Used for :-webkit-any and :not private: RareData(const AtomicString& value); }; void CreateRareData(); union DataUnion { DataUnion() : value_(nullptr) {} StringImpl* value_; QualifiedName::QualifiedNameImpl* tag_q_name_; RareData* rare_data_; } data_; }; inline const QualifiedName& CSSSelector::Attribute() const { DCHECK(IsAttributeSelector()); DCHECK(has_rare_data_); return data_.rare_data_->attribute_; } inline CSSSelector::AttributeMatchType CSSSelector::AttributeMatch() const { DCHECK(IsAttributeSelector()); DCHECK(has_rare_data_); return data_.rare_data_->bits_.attribute_match_; } inline bool CSSSelector::IsASCIILower(const AtomicString& value) { for (size_t i = 0; i < value.length(); ++i) { if (IsASCIIUpper(value[i])) return false; } return true; } inline void CSSSelector::SetValue(const AtomicString& value, bool match_lower_case = false) { DCHECK_NE(match_, static_cast<unsigned>(kTag)); if (match_lower_case && !has_rare_data_ && !IsASCIILower(value)) { CreateRareData(); } // Need to do ref counting manually for the union. if (!has_rare_data_) { if (data_.value_) data_.value_->Release(); data_.value_ = value.Impl(); data_.value_->AddRef(); return; } data_.rare_data_->matching_value_ = match_lower_case ? value.LowerASCII() : value; data_.rare_data_->serializing_value_ = value; } inline CSSSelector::CSSSelector() : relation_(kSubSelector), match_(kUnknown), pseudo_type_(kPseudoUnknown), is_last_in_selector_list_(false), is_last_in_tag_history_(true), has_rare_data_(false), is_for_page_(false), tag_is_implicit_(false), relation_is_affected_by_pseudo_content_(false), is_last_in_original_list_(false), ignore_specificity_(false) {} inline CSSSelector::CSSSelector(const QualifiedName& tag_q_name, bool tag_is_implicit) : relation_(kSubSelector), match_(kTag), pseudo_type_(kPseudoUnknown), is_last_in_selector_list_(false), is_last_in_tag_history_(true), has_rare_data_(false), is_for_page_(false), tag_is_implicit_(tag_is_implicit), relation_is_affected_by_pseudo_content_(false), is_last_in_original_list_(false), ignore_specificity_(false) { data_.tag_q_name_ = tag_q_name.Impl(); data_.tag_q_name_->AddRef(); } inline CSSSelector::CSSSelector(const CSSSelector& o) : relation_(o.relation_), match_(o.match_), pseudo_type_(o.pseudo_type_), is_last_in_selector_list_(o.is_last_in_selector_list_), is_last_in_tag_history_(o.is_last_in_tag_history_), has_rare_data_(o.has_rare_data_), is_for_page_(o.is_for_page_), tag_is_implicit_(o.tag_is_implicit_), relation_is_affected_by_pseudo_content_( o.relation_is_affected_by_pseudo_content_), is_last_in_original_list_(o.is_last_in_original_list_), ignore_specificity_(o.ignore_specificity_) { if (o.match_ == kTag) { data_.tag_q_name_ = o.data_.tag_q_name_; data_.tag_q_name_->AddRef(); } else if (o.has_rare_data_) { data_.rare_data_ = o.data_.rare_data_; data_.rare_data_->AddRef(); } else if (o.data_.value_) { data_.value_ = o.data_.value_; data_.value_->AddRef(); } } inline CSSSelector::~CSSSelector() { if (match_ == kTag) data_.tag_q_name_->Release(); else if (has_rare_data_) data_.rare_data_->Release(); else if (data_.value_) data_.value_->Release(); } inline const QualifiedName& CSSSelector::TagQName() const { DCHECK_EQ(match_, static_cast<unsigned>(kTag)); return *reinterpret_cast<const QualifiedName*>(&data_.tag_q_name_); } inline const AtomicString& CSSSelector::Value() const { DCHECK_NE(match_, static_cast<unsigned>(kTag)); if (has_rare_data_) return data_.rare_data_->matching_value_; // AtomicString is really just a StringImpl* so the cast below is safe. // FIXME: Perhaps call sites could be changed to accept StringImpl? return *reinterpret_cast<const AtomicString*>(&data_.value_); } inline const AtomicString& CSSSelector::SerializingValue() const { DCHECK_NE(match_, static_cast<unsigned>(kTag)); if (has_rare_data_) return data_.rare_data_->serializing_value_; // AtomicString is really just a StringImpl* so the cast below is safe. // FIXME: Perhaps call sites could be changed to accept StringImpl? return *reinterpret_cast<const AtomicString*>(&data_.value_); } inline bool CSSSelector::IsUserActionPseudoClass() const { return pseudo_type_ == kPseudoHover || pseudo_type_ == kPseudoActive || pseudo_type_ == kPseudoFocus || pseudo_type_ == kPseudoDrag || pseudo_type_ == kPseudoFocusWithin || pseudo_type_ == kPseudoFocusVisible; } inline bool CSSSelector::IsIdClassOrAttributeSelector() const { return IsAttributeSelector() || Match() == CSSSelector::kId || Match() == CSSSelector::kClass; } } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_SELECTOR_H_
ab858223eff8ac7fbae6a5e27cf43c174a2ba364
828e8b01eca57df4048e63ffc858e5c568b42eee
/Online-Judges/Neps-Academy/cpp/Riemann_Ataca_Novamente.cpp
0d039aa24fab683212dafbb1b24a05e877c44d85
[]
no_license
RogerEC/CP-ICPC-Training
2b1b2cc08006727418a8eee972e6e38afc97d825
52d0e6d0a585e719f3df8f30e3be2afc166fcdd4
refs/heads/master
2022-12-08T15:16:45.911993
2020-09-04T16:41:46
2020-09-04T16:41:46
280,004,582
1
0
null
null
null
null
UTF-8
C++
false
false
1,027
cpp
#include<bits/stdc++.h> using namespace std; const int MAXN = 2e5+5; #define mdc(a, b) (__gcd((a), (b))) #define mmc(a, b) (((a)*(b))/__gcd((a), (b))) #define pb push_back #define mp make_pair #define f first #define s second #define fastin ios_base::sync_with_stdio(0); cin.tie(0) typedef long long int ll; typedef unsigned int ui; typedef unsigned long long int ull; typedef pair<int, int> pii; typedef pair<ll, ll> pll; int main(){ fastin; vector<int> primos; vector<bool> flag; vector<int>::iterator pos; int p, q, tam=1300000; for(int i=0; i<tam; i++) flag.pb(true); for(int i=2; i<tam; i++){ if(flag[i]){ for(int j=2; i*j<tam; j++) flag[i*j]=false; } } for(int i=2; i<tam; i++){ if(flag[i]){ primos.pb(i); } } cin>>q; for(int i=0; i<q; i++){ cin>>p; pos=lower_bound(primos.begin(), primos.end(), p); cout<<pos-primos.begin()+1<<endl; } return 0; }
5cc170474f1d5ace61be317befec6bea4e4ba561
2e51c1543ee18399ff210c60d3adc2ddd9ab562b
/자료구조/generic_stack/testmain.cpp
0adf0df6daa70832c5177b61db2f9176057fdf35
[]
no_license
5dddddo/C-language
15f9879058334ff0cc48b67f6a5171151c8ad8dd
79684ed882529ec9a9a0aff6347d38a57e27eecb
refs/heads/master
2020-07-25T22:23:20.807931
2019-09-28T12:55:35
2019-09-28T12:55:35
208,439,838
0
0
null
null
null
null
UHC
C++
false
false
1,927
cpp
#include "stack.h" #include <stdio.h> #include "person.h" #pragma warning (disable: 4996) int menu(char **, int); void myFlush(); void input(Stack *); void myDelete(Stack *); int main() { Stack stk; char *menuList[] = { "입력하기", "삭제하기", "출력하기", "종료" }; int menuCnt; int menuNum; initStack(&stk, 5, sizeof(Person)); menuCnt = sizeof(menuList) / sizeof(menuList[0]); while (1) { menuNum = menu(menuList, menuCnt); if (menuNum == menuCnt) break; switch (menuNum) { case 1: input(&stk); break; case 2: myDelete(&stk); break; case 3: printStack(&stk, sizeof(Person), personPrint); printf("\n"); break; } } destroyStack(&stk, sizeof(Person), personClear); return 0; } void input(Stack *sPtr) { Person temp = { NULL, 0, "" }; char name[20]; while (1) { temp.name = (char *)calloc(1, sizeof(name)); printf("이름 : "); scanf("%s", temp.name); if (strcmp(temp.name, "끝") == 0) break; printf("나이 : "); scanf("%d", &temp.age); printf("번호 : "); scanf("%s", temp.phoneNumber); push(sPtr, &temp, sizeof(Person), personMemCpy); free(temp.name); } } void myDelete(Stack *sPtr) { int i; int cnt; Person temp = { NULL, 0, "" }; int res; printf("Stack에서 데이터를 pop할 횟수를 입력하시오 : "); scanf("%d", &cnt); for (i = 0; i < cnt; i++) { res = pop(sPtr, &temp, sizeof(Person), personMemCpy, personClear); if (res == 1) printf("pop 데이터\n 이름 : %s 나이 : %d 번호 : %s\n", temp.name, temp.age, temp.phoneNumber); } } int menu(char **menuList, int menuCnt) { int i; int menuNum = 0; int res; for (i = 0; i < menuCnt; i++) { printf("%d. %s\n", i + 1, menuList[i]); } while (menuNum<1 || menuNum > menuCnt) { printf("# 메뉴번호를 입력하세요 : "); res = scanf("%d", &menuNum); if (res != 1) myFlush(); } return menuNum; } void myFlush() { while (getchar() != '\n') { ; } }
1fd90519efa9e823a05de4446e0c632c2a59ec28
886a2807cc2fc92945fc35e6e6202f5e9feefe24
/697_数组的度.cpp
a2346bbcfd8b23bd2b09c4eca8b7616606fb0037
[]
no_license
ZhuJiaqi9905/my_leetcode
b0292f29aa6adf9cc934aa53af9329d8213aae43
80d3b3562e8111075e1d45a3e166e3c0dd2e8022
refs/heads/main
2023-06-25T00:02:28.120225
2021-07-29T03:23:07
2021-07-29T03:23:07
390,587,094
0
0
null
null
null
null
UTF-8
C++
false
false
979
cpp
class Solution { public: const int kLen = 50000; int findShortestSubArray(vector<int>& nums) { int n = nums.size(); int cnt[kLen]; int max_val = 0; memset(cnt, 0, sizeof(cnt)); for(auto& ele: nums){ cnt[ele]++; } max_val = *std::max_element(cnt, cnt + kLen);//求出最大的度 //滑动窗口 int s = 0; int e = 0; int ans = kLen + 1; int *freq = new int[kLen]();//记录窗口中的每个数的频数 while(e < n){ freq[nums[e]]++; while(freq[nums[e]] == max_val){ ans = std::min(ans, e - s + 1);//这里不要在while循环外更新, //否则需要有一个变量来告诉它是从这个while中跳出来的 freq[nums[s]]--; s++; } e++; } delete []freq; return ans; } };
e73f14b87052b6db5f548258fc6c2e78f036ddd8
cf81c5fdbde58a1fb1809735e189a85b1c2cb11d
/WiFiHandler/WiFiHandler.h
2f791fd08132ce5a3909dc1efd5f4ff15e648d74
[]
no_license
pxds/nodemcu-libs
00dae8f5a4be0ccbf5c801f319edfb146e9a0513
d173041552af04dd400ff467e1e28e3fe3304ab9
refs/heads/master
2020-03-21T06:27:21.933055
2018-08-02T20:55:17
2018-08-02T20:55:17
138,221,026
1
0
null
null
null
null
UTF-8
C++
false
false
1,614
h
/* Simple WiFi handler to decouple WiFi complexity from main */ #ifndef WIFIHANDLER_H #define WIFIHANDLER_H #include "IPAddress.h" #include <ESP8266mDNS.h> #include <WiFiUdp.h> #include <ArduinoOTA.h> inline void OTAsetup() { ArduinoOTA.onStart([]() { Serial.println("Start"); }); ArduinoOTA.onEnd([]() { Serial.println("\nEnd"); }); ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { Serial.printf("Progress: %u%%\r", (progress / (total / 100))); }); ArduinoOTA.onError([](ota_error_t error) { Serial.printf("Error[%u]: ", error); if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed"); else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed"); else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed"); else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed"); else if (error == OTA_END_ERROR) Serial.println("End Failed"); }); ArduinoOTA.begin(); } inline void OTAloop() { ArduinoOTA.handle(); } class WiFiHandler { private: IPAddress staticIP; IPAddress gateway; IPAddress subnet; const char* ssid; const char* password; bool OTAenabled; int connectTryoutMax; public: WiFiHandler(); ~WiFiHandler(); bool Connect(const char* ssid, const char* password); void StaticIPConfig(const char* ip, const char* gateway, const char* subnet); IPAddress GetIP(); IPAddress GetSubnetMask(); IPAddress GetGatewayIP(); void EnableOTA(); void OTAsetPort(int port); void OTAsetHostName(const char* hostName); void OTAsetPassword(const char* password); void OTAbootloader(); }; #endif
c8153560ba9fe6da5297aa1602ceb43b8db58bd4
8e1a06887b85b4fd6d830a6d583953fc5c3bff66
/src/core/environ/ui/XP3RepackForm.cpp
9b0e10a0074654bb4bca1825826b6c7e40d16fdb
[ "LicenseRef-scancode-warranty-disclaimer", "Zlib", "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "Libpng", "BSD-2-Clause-Views", "FTL", "Apache-2.0", "BSD-2-Clause" ]
permissive
yangyu52009/Kirikiroid2
0462c3273e0353c67368b73ebed329026e9f8c9c
9b232c674b9a2b10c45d28a86679a743d5a79f65
refs/heads/master
2021-01-20T05:14:05.745038
2017-04-23T17:55:39
2017-04-23T17:59:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,663
cpp
#include "XP3RepackForm.h" #include "StorageImpl.h" #include "cocos2d/MainScene.h" #include "PreferenceForm.h" #include "ConfigManager/LocaleConfigManager.h" #include "XP3ArchiveRepack.h" #include "ui/UIListView.h" #include "ui/UILoadingBar.h" #include "ui/UIText.h" #include "ui/UIButton.h" #include "ui/UICheckBox.h" #include "Platform.h" #include "MessageBox.h" #include "base/CCDirector.h" #include "base/CCScheduler.h" #include "TickCount.h" #include "2d/CCLayer.h" #include "2d/CCActionInterval.h" #include "platform/CCFileUtils.h" #include "platform/CCDevice.h" using namespace cocos2d; using namespace cocos2d::ui; bool TVPGetXP3ArchiveOffset(tTJSBinaryStream *st, const ttstr name, tjs_uint64 & offset, bool raise); static void WalkDir(const ttstr &dir, const std::function<void(const ttstr&, tjs_uint64)>& cb) { std::vector<ttstr> subdirs; std::vector<std::pair<std::string, tjs_uint64> > files; TVPGetLocalFileListAt(dir, [&](const ttstr& path, tTVPLocalFileInfo* info) { if (info->Mode & S_IFDIR) { subdirs.emplace_back(path); } else { files.emplace_back(info->NativeName, info->Size); } }); ttstr prefix = dir + TJS_W("/"); for (std::pair<std::string, tjs_uint64> &it : files) { cb(prefix + it.first, it.second); } for (ttstr &path : subdirs) { WalkDir(prefix + path, cb); } } class TVPXP3Repacker { const int UpdateMS = 100; // update rate 10 fps public: TVPXP3Repacker(const std::string &rootdir) : RootDir(rootdir) {} ~TVPXP3Repacker(); void Start(std::vector<std::string> &filelist, const std::string &xp3filter); void SetOption(const std::string &name, bool v) { ArcRepacker.SetOption(name, v); } private: void OnNewFile(int idx, uint64_t size, const std::string &filename); void OnNewArchive(int idx, uint64_t size, const std::string &filename); void OnProgress(uint64_t total_size, uint64_t arc_size, uint64_t file_size); void OnError(int errcode, const std::string &errmsg); void OnEnded(); TVPSimpleProgressForm *ProgressForm = nullptr; XP3ArchiveRepackAsync ArcRepacker; std::string RootDir; std::string CurrentFileName, CurrentArcName; uint64_t TotalSize, CurrentFileSize, CurrentArcSize; int CurrentFileIndex; tjs_uint32 LastUpdate = 0; }; TVPXP3Repacker::~TVPXP3Repacker() { if (ProgressForm) { TVPMainScene::GetInstance()->popUIForm(ProgressForm, TVPMainScene::eLeaveAniNone); ProgressForm = nullptr; } cocos2d::Device::setKeepScreenOn(false); } void TVPXP3Repacker::Start(std::vector<std::string> &filelist, const std::string &xp3filter) { if (!ProgressForm) { ProgressForm = TVPSimpleProgressForm::create(); TVPMainScene::GetInstance()->pushUIForm(ProgressForm, TVPMainScene::eEnterAniNone); std::vector<std::pair<std::string, std::function<void(cocos2d::Ref*)> > > vecButtons; LocaleConfigManager *locmgr = LocaleConfigManager::GetInstance(); vecButtons.emplace_back(locmgr->GetText("stop"), [this](Ref*) { ArcRepacker.Stop(); }); ProgressForm->initButtons(vecButtons); ProgressForm->setTitle(locmgr->GetText("archive_repack_proc_title")); ProgressForm->setPercentOnly(0); ProgressForm->setPercentOnly2(0); ProgressForm->setPercentText(""); ProgressForm->setPercentText2(""); ProgressForm->setContent(""); } ArcRepacker.SetCallback( std::bind(&TVPXP3Repacker::OnNewFile, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3), std::bind(&TVPXP3Repacker::OnNewArchive, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3), std::bind(&TVPXP3Repacker::OnProgress, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3), std::bind(&TVPXP3Repacker::OnError, this, std::placeholders::_1, std::placeholders::_2), std::bind(&TVPXP3Repacker::OnEnded, this)); if (cocos2d::FileUtils::getInstance()->isFileExist(xp3filter)) { ArcRepacker.SetXP3Filter(xp3filter); } TotalSize = 0; for (const std::string &name : filelist) { TotalSize += ArcRepacker.AddTask(name); } cocos2d::Device::setKeepScreenOn(true); ArcRepacker.Start(); } void TVPXP3Repacker::OnNewFile(int idx, uint64_t size, const std::string &filename) { tjs_uint32 tick = TVPGetRoughTickCount32(); if ((int)(tick - LastUpdate) < UpdateMS && size < 1024 * 1024) { return; } CurrentFileIndex = idx; Director::getInstance()->getScheduler()->performFunctionInCocosThread([this, size, filename] { CurrentFileSize = size; ProgressForm->setContent(CurrentArcName + ">" + filename); }); } void TVPXP3Repacker::OnNewArchive(int idx, uint64_t size, const std::string &filename) { int prefixlen = RootDir.length() + 1; std::string name = filename.substr(prefixlen); Director::getInstance()->getScheduler()->performFunctionInCocosThread([this, name, size] { CurrentArcSize = size; CurrentArcName = name; }); } void TVPXP3Repacker::OnProgress(uint64_t total_size, uint64_t arc_size, uint64_t file_size) { tjs_uint32 tick = TVPGetRoughTickCount32(); if ((int)(tick - LastUpdate) < UpdateMS) { return; } LastUpdate = tick; Director::getInstance()->getScheduler()->performFunctionInCocosThread([this, total_size, arc_size] { ProgressForm->setPercentOnly((float)total_size / TotalSize); ProgressForm->setPercentOnly2((float)arc_size / CurrentArcSize); char buf[64]; int sizeMB = static_cast<int>(total_size / (1024 * 1024)), totalMB = static_cast<int>(TotalSize / (1024 * 1024)); sprintf(buf, "%d / %dMB", sizeMB, totalMB); ProgressForm->setPercentText(buf); sizeMB = static_cast<int>(arc_size / (1024 * 1024)); totalMB = static_cast<int>(CurrentArcSize / (1024 * 1024)); sprintf(buf, "%d / %dMB", sizeMB, totalMB); ProgressForm->setPercentText2(buf); }); } void TVPXP3Repacker::OnError(int errcode, const std::string &errmsg) { if (errcode < 0) { Director::getInstance()->getScheduler()->performFunctionInCocosThread([this, errcode, errmsg] { char buf[64]; sprintf(buf, "Error %d\n", errcode); ttstr strmsg(buf); strmsg += errmsg; TVPShowSimpleMessageBox(strmsg, TJS_W("XP3Repack Error")); }); } } void TVPXP3Repacker::OnEnded() { Director::getInstance()->getScheduler()->performFunctionInCocosThread([this] { delete this; }); } class TVPXP3RepackFileListForm : public iTVPBaseForm { public: virtual ~TVPXP3RepackFileListForm(); virtual void bindBodyController(const NodeMap &allNodes); static TVPXP3RepackFileListForm* show(std::vector<std::string> &filelist, const std::string &dir); void initData(std::vector<std::string> &filelist, const std::string &dir); void close(); private: void onOkClicked(Ref*); cocos2d::ui::ListView *ListViewFiles, *ListViewPref; std::string RootDir; std::vector<std::string> FileList; TVPXP3Repacker *m_pRepacker = nullptr; }; TVPXP3RepackFileListForm::~TVPXP3RepackFileListForm() { if (m_pRepacker) delete m_pRepacker; } void TVPXP3RepackFileListForm::bindBodyController(const NodeMap &allNodes) { LocaleConfigManager *locmgr = LocaleConfigManager::GetInstance(); ui::ScrollView *btnList = allNodes.findController<ui::ScrollView>("btn_list"); Size containerSize = btnList->getContentSize(); btnList->setInnerContainerSize(containerSize); Widget *btnCell = allNodes.findWidget("btn_cell"); Button *btn = allNodes.findController<Button>("btn"); int nButton = 2; locmgr->initText(allNodes.findController<Text>("title"), "XP3 Repack"); btn->setTitleText(locmgr->GetText("start")); btn->addClickEventListener(std::bind(&TVPXP3RepackFileListForm::onOkClicked, this, std::placeholders::_1)); btnCell->setPositionX(containerSize.width / (nButton + 1) * 1); btnList->addChild(btnCell->clone()); btn->setTitleText(locmgr->GetText("cancel")); btn->addClickEventListener([this](Ref*) { close(); }); btnCell->setPositionX(containerSize.width / (nButton + 1) * 2); btnList->addChild(btnCell->clone()); btn->removeFromParent(); ListViewFiles = allNodes.findController<ListView>("list_2"); ListViewPref = allNodes.findController<ListView>("list_1"); } TVPXP3RepackFileListForm* TVPXP3RepackFileListForm::show(std::vector<std::string> &filelist, const std::string &dir) { TVPXP3RepackFileListForm *form = new TVPXP3RepackFileListForm; form->initFromFile("ui/CheckListDialog.csb"); form->initData(filelist, dir); TVPMainScene::GetInstance()->pushUIForm(form, TVPMainScene::eEnterAniNone); return form; } void TVPXP3RepackFileListForm::initData(std::vector<std::string> &filelist, const std::string &dir) { LocaleConfigManager *locmgr = LocaleConfigManager::GetInstance(); RootDir = dir; FileList.swap(filelist); int tag = 256; Size size = ListViewFiles->getContentSize(); int prefixlen = dir.length() + 1; for (size_t i = 0; i < FileList.size(); ++i) { std::string filename = FileList[i].substr(prefixlen); tPreferenceItemCheckBox *cell = CreatePreferenceItem<tPreferenceItemCheckBox>(i, size, filename, [](tPreferenceItemCheckBox* p) { p->_getter = []()->bool { return true; }; p->_setter = [](bool v) {}; }); cell->setTag(tag++); ListViewFiles->pushBackCustomItem(cell); } m_pRepacker = new TVPXP3Repacker(RootDir); size = ListViewPref->getContentSize(); ListViewPref->pushBackCustomItem(CreatePreferenceItem <tPreferenceItemConstant>(0, size, locmgr->GetText("archive_repack_desc"))); ListViewPref->pushBackCustomItem(CreatePreferenceItem <tPreferenceItemCheckBox>(1, size, locmgr->GetText("archive_repack_merge_img"), [this](tPreferenceItemCheckBox* p) { p->_getter = []()->bool { return true; }; p->_setter = [this](bool v) { m_pRepacker->SetOption("merge_mask_img", v); }; })); ListViewPref->pushBackCustomItem(CreatePreferenceItem <tPreferenceItemCheckBox>(2, size, locmgr->GetText("archive_repack_conv_etc2"), [this](tPreferenceItemCheckBox* p) { p->_getter = []()->bool { return false; }; p->_setter = [this](bool v) { m_pRepacker->SetOption("conv_etc2", v); }; })); } void TVPXP3RepackFileListForm::close() { // TVPMainScene::GetInstance()->popUIForm(this, TVPMainScene::eLeaveAniNone); removeFromParent(); } void TVPXP3RepackFileListForm::onOkClicked(Ref*) { class HackPreferenceItemCheckBox : public tPreferenceItemCheckBox { public: bool getCheckBoxState() { return checkbox->isSelected(); } }; std::vector<std::string> filelist; filelist.reserve(FileList.size()); auto &allCell = ListViewFiles->getItems(); for (int i = 0; i < allCell.size(); ++i) { Widget *cell = allCell.at(i); if (static_cast<HackPreferenceItemCheckBox*>(cell)->getCheckBoxState()) { filelist.push_back(FileList[cell->getTag() - 256]); } } if (filelist.empty()) return; m_pRepacker->Start(filelist, RootDir + "/xp3filter.tjs"); m_pRepacker = nullptr; close(); } void TVPProcessXP3Repack(const std::string &dir) { std::vector<std::string> filelist; bool hasXp3Filter = false; TVPGetLocalFileListAt(dir, [&](const ttstr& path, tTVPLocalFileInfo* info) { if (info->Mode & S_IFDIR) { } else if(path == TJS_W("xp3filter.tjs")) { hasXp3Filter = true; } }); LocaleConfigManager *locmgr = LocaleConfigManager::GetInstance(); if (!hasXp3Filter) { if (TVPShowSimpleMessageBoxYesNo(locmgr->GetText("archive_repack_no_xp3filter"), locmgr->GetText("notice")) != 0) { return; } } WalkDir(dir, [&](const ttstr& strpath, tjs_uint64 size) { if (size < 32) return; tjs_uint64 offset; tTVPLocalFileStream *st = new tTVPLocalFileStream(strpath, strpath, TJS_BS_READ); if (TVPGetXP3ArchiveOffset(st, strpath, offset, false)) { filelist.emplace_back(strpath.AsStdString()); } delete st; }); if (filelist.empty()) { TVPShowSimpleMessageBox(locmgr->GetText("archive_repack_no_xp3").c_str(), "XP3Repack", 0, nullptr); } else { TVPXP3RepackFileListForm::show(filelist, dir); } }
97951f8b2ec868cb93a8bf64b76d53d7b7d8cab0
5f5fcbc4128e8c23419596c242c7fffdf0e53e98
/src/ca/jsoncons/detail/number_printers.hpp
c8ca9431f87482bd7fc63b667beb6c1ab2064b8d
[ "Apache-2.0" ]
permissive
NerdyDuck/WixJsonExtension
4029ae1d0c2203d039b7acb7571c75fd1ad79cc5
e70523f8deb21ec69e55069ad2386f115c6bcf82
refs/heads/master
2022-11-24T17:05:49.404554
2018-04-23T10:23:27
2018-04-23T10:23:27
129,555,941
1
8
Apache-2.0
2020-11-10T15:24:22
2018-04-14T21:31:37
C++
UTF-8
C++
false
false
9,141
hpp
// Copyright 2013 Daniel Parker // Distributed under the Boost license, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // See https://github.com/danielaparker/jsoncons for latest version #ifndef JSONCONS_DETAIL_NUMBERPRINTERS_HPP #define JSONCONS_DETAIL_NUMBERPRINTERS_HPP #include <stdexcept> #include <string> #include <sstream> #include <vector> #include <istream> #include <ostream> #include <iomanip> #include <cstdlib> #include <cmath> #include <cstdarg> #include <locale> #include <limits> #include <algorithm> #include <exception> #include "jsoncons/jsoncons_config.hpp" #include "jsoncons/detail/obufferedstream.hpp" namespace jsoncons { namespace detail { // print_integer template<class Writer> void print_integer(int64_t value, Writer& os) { typedef typename Writer::char_type char_type; char_type buf[255]; uint64_t u = (value < 0) ? static_cast<uint64_t>(-value) : static_cast<uint64_t>(value); char_type* p = buf; do { *p++ = static_cast<char_type>(48 + u%10); } while (u /= 10); if (value < 0) { os.put('-'); } while (--p >= buf) { os.put(*p); } } // print_uinteger template<class Writer> void print_uinteger(uint64_t value, Writer& os) { typedef typename Writer::char_type char_type; char_type buf[255]; char_type* p = buf; do { *p++ = static_cast<char_type>(48 + value % 10); } while (value /= 10); while (--p >= buf) { os.put(*p); } } // print_double #if defined(JSONCONS_HAS__ECVT_S) class print_double { private: uint8_t precision_override_; public: print_double(uint8_t precision) : precision_override_(precision) { } template <class Writer> void operator()(double val, uint8_t precision, Writer& writer) { typedef typename Writer::char_type char_type; char buf[_CVTBUFSIZE]; int decimal_point = 0; int sign = 0; int prec; if (precision_override_ != 0) { prec = precision_override_; } else if (precision != 0) { prec = precision; } else { prec = std::numeric_limits<double>::digits10; } int err = _ecvt_s(buf, _CVTBUFSIZE, val, prec, &decimal_point, &sign); if (err != 0) { JSONCONS_THROW(json_exception_impl<std::runtime_error>("Failed attempting double to string conversion")); } //std::cout << "prec:" << prec << ", buf:" << buf << std::endl; char* s = buf; char* se = s + prec; int i, k; int j; if (sign) { writer.put('-'); } if (decimal_point <= -4 || decimal_point > se - s + 5) { writer.put(*s++); if (s < se) { writer.put('.'); while ((se-1) > s && *(se-1) == '0') { --se; } while(s < se) { writer.put(*s++); } } writer.put('e'); /* sprintf(b, "%+.2d", decimal_point - 1); */ if (--decimal_point < 0) { writer.put('-'); decimal_point = -decimal_point; } else writer.put('+'); for(j = 2, k = 10; 10*k <= decimal_point; j++, k *= 10); for(;;) { i = decimal_point / k; writer.put(static_cast<char_type>(i) + '0'); if (--j <= 0) break; decimal_point -= i*k; decimal_point *= 10; } } else if (decimal_point <= 0) { writer.put('0'); writer.put('.'); while ((se-1) > s && *(se-1) == '0') { --se; } for(; decimal_point < 0; decimal_point++) { writer.put('0'); } while(s < se) { writer.put(*s++); } } else { while(s < se) { writer.put(*s++); if ((--decimal_point == 0) && s < se) { writer.put('.'); while ((se-1) > s && *(se-1) == '0') { --se; } } } for(; decimal_point > 0; decimal_point--) { writer.put('0'); } } } }; #elif defined(JSONCONS_NO_LOCALECONV) class print_double { private: uint8_t precision_override_; basic_obufferedstream<char> os_; public: print_double(uint8_t precision) : precision_override_(precision) { os_.imbue(std::locale::classic()); os_.precision(precision); } template <class Writer> void operator()(double val, uint8_t precision, Writer& writer) { typedef typename Writer::char_type char_type; int prec; if (precision_override_ != 0) { prec = precision_override_; } else if (precision != 0) { prec = precision; } else { prec = std::numeric_limits<double>::digits10; } os_.clear_sequence(); os_.precision(prec); os_ << val; //std::cout << "precision_override_:" << (int)precision_override_ << ", precision:" << (int)precision << ", buf:" << os_.data() << std::endl; const char_type* sbeg = os_.data(); const char_type* send = sbeg + os_.length(); const char_type* pexp = send; if (sbeg != send) { bool dot = false; for (pexp = sbeg; *pexp != 'e' && *pexp != 'E' && pexp < send; ++pexp) { } const char_type* qend = pexp; while (qend >= sbeg+2 && *(qend-1) == '0' && *(qend-2) != '.') { --qend; } if (pexp == send) { qend = ((qend >= sbeg+2) && *(qend-2) == '.') ? qend : send; } for (const char_type* q = sbeg; q < qend; ++q) { if (*q == '.') { dot = true; } writer.put(*q); } if (!dot) { writer.put('.'); writer.put('0'); dot = true; } for (const char_type* q = pexp; q < send; ++q) { writer.put(*q); } } } }; #else class print_double { private: uint8_t precision_override_; char decimal_point_; public: print_double(uint8_t precision) : precision_override_(precision) { struct lconv * lc = localeconv(); if (lc != nullptr && lc->decimal_point[0] != 0) { decimal_point_ = lc->decimal_point[0]; } else { decimal_point_ = '.'; } } template <class Writer> void operator()(double val, uint8_t precision, Writer& writer) { typedef typename Writer::char_type char_type; int prec; if (precision_override_ != 0) { prec = precision_override_; } else if (precision != 0) { prec = precision; } else { prec = std::numeric_limits<double>::digits10; } char number_buffer[100]; int length = snprintf(number_buffer, 100, "%1.*g", prec, val); if (length < 0) { JSONCONS_THROW(json_exception_impl<std::invalid_argument>("print_double failed.")); } const char* sbeg = number_buffer; const char* send = sbeg + length; const char* pexp = send; if (sbeg != send) { bool dot = false; for (pexp = sbeg; *pexp != 'e' && *pexp != 'E' && pexp < send; ++pexp) { } for (const char* q = sbeg; q < pexp; ++q) { switch (*q) { case '-':case '0':case '1':case '2':case '3':case '4':case '5':case '6':case '7':case '8':case '9': writer.put(*q); break; default: if (*q == decimal_point_) { dot = true; writer.put('.'); } break; } } if (!dot) { writer.put('.'); writer.put('0'); dot = true; } for (const char* q = pexp; q < send; ++q) { writer.put(*q); } } } }; #endif }} #endif
2e06b4b324f2a0715a64b0a6d13bb56115bc2552
73cfd700522885a3fec41127e1f87e1b78acd4d3
/_Include/boost/fusion/support/pair.hpp
4059ea649082d15b74d2ff1cab6a8a27e58635a7
[ "BSL-1.0" ]
permissive
pu2oqa/muServerDeps
88e8e92fa2053960671f9f57f4c85e062c188319
92fcbe082556e11587887ab9d2abc93ec40c41e4
refs/heads/master
2023-03-15T12:37:13.995934
2019-02-04T10:07:14
2019-02-04T10:07:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,440
hpp
//////////////////////////////////////////////////////////////////////////////// // pair.hpp /*============================================================================= Copyright (c) 2001-2011 Joel de Guzman Copyright (c) 2006 Tobias Schwinger Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) ==============================================================================*/ #if !defined(FUSION_PAIR_07222005_1203) #define FUSION_PAIR_07222005_1203 #include <boost/fusion/support/config.hpp> #include <iosfwd> #include <boost/fusion/support/detail/access.hpp> #include <boost/fusion/support/detail/as_fusion_element.hpp> #include <boost/config.hpp> #include <boost/utility/enable_if.hpp> #include <boost/type_traits/is_convertible.hpp> #include <boost/type_traits/is_lvalue_reference.hpp> #if defined (BOOST_MSVC) # pragma warning(push) # pragma warning (disable: 4512) // assignment operator could not be generated. #endif namespace boost { namespace fusion { // A half runtime pair where the first type does not have data template <typename First, typename Second> struct pair { BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED pair() : second() {} BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED pair(pair const& rhs) : second(rhs.second) {} #if !defined(BOOST_NO_CXX11_RVALUE_REFERENCES) BOOST_CXX14_CONSTEXPR BOOST_FUSION_GPU_ENABLED pair(pair&& rhs) : second(BOOST_FUSION_FWD_ELEM(Second, rhs.second)) {} #endif BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED pair(typename detail::call_param<Second>::type val) : second(val) {} #if !defined(BOOST_NO_CXX11_RVALUE_REFERENCES) template <typename Second2> BOOST_FUSION_GPU_ENABLED pair(Second2&& val , typename boost::disable_if<is_lvalue_reference<Second2> >::type* /* dummy */ = 0 , typename boost::enable_if<is_convertible<Second2, Second> >::type* /*dummy*/ = 0 ) : second(BOOST_FUSION_FWD_ELEM(Second, val)) {} #endif template <typename Second2> BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED pair(pair<First, Second2> const& rhs) : second(rhs.second) {} template <typename Second2> BOOST_CXX14_CONSTEXPR BOOST_FUSION_GPU_ENABLED pair& operator=(pair<First, Second2> const& rhs) { second = rhs.second; return *this; } BOOST_CXX14_CONSTEXPR BOOST_FUSION_GPU_ENABLED pair& operator=(pair const& rhs) { second = rhs.second; return *this; } #if !defined(BOOST_NO_CXX11_RVALUE_REFERENCES) BOOST_CXX14_CONSTEXPR BOOST_FUSION_GPU_ENABLED pair& operator=(pair&& rhs) { second = BOOST_FUSION_FWD_ELEM(Second, rhs.second); return *this; } #endif typedef First first_type; typedef Second second_type; Second second; }; namespace result_of { template<typename First, typename Second> struct make_pair { typedef fusion::pair<First, typename detail::as_fusion_element<Second>::type> type; }; template<class Pair> struct first { typedef typename Pair::first_type type; }; template<class Pair> struct second { typedef typename Pair::second_type type; }; } template <typename First, typename Second> BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED inline typename result_of::make_pair<First,Second>::type make_pair(Second const& val) { return pair<First, typename detail::as_fusion_element<Second>::type>(val); } template <typename First, typename Second> inline std::ostream& operator<<(std::ostream& os, pair<First, Second> const& p) { os << p.second; return os; } template <typename First, typename Second> inline std::istream& operator>>(std::istream& is, pair<First, Second>& p) { is >> p.second; return is; } template <typename First, typename SecondL, typename SecondR> BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED inline bool operator==(pair<First, SecondL> const& l, pair<First, SecondR> const& r) { return l.second == r.second; } template <typename First, typename SecondL, typename SecondR> BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED inline bool operator!=(pair<First, SecondL> const& l, pair<First, SecondR> const& r) { return l.second != r.second; } template <typename First, typename SecondL, typename SecondR> BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED inline bool operator<(pair<First, SecondL> const& l, pair<First, SecondR> const& r) { return l.second < r.second; } }} #if defined (BOOST_MSVC) # pragma warning(pop) #endif #endif ///////////////////////////////////////////////// // vnDev.Games - Trong.LIVE - DAO VAN TRONG // ////////////////////////////////////////////////////////////////////////////////
38bafe4ac9435cae5f3444b5e64001456ab79bff
b5768158857cd041380c3a19bf85bf080856aa09
/src/Engine/Tools/Input/InputManager.cpp
9a159b83cceda3454a380abbf8337a12aeb43ae4
[]
no_license
Compiler/RTX-Practice
7119db92baf17b84bfabd47f6d7d4b5328cc7123
8d5ddac3b7285e18141aa10118cdad0c049ba472
refs/heads/master
2023-01-15T07:36:16.794745
2020-11-24T13:31:55
2020-11-24T13:31:55
306,980,222
0
0
null
null
null
null
UTF-8
C++
false
false
397
cpp
#include "InputManager.h" namespace reach { glm::vec2 InputManager::_mousePosition; std::vector<glm::vec2> InputManager::_mouseMovedEvents; std::vector<uint16_t> InputManager::_mousePressEvents; std::vector<uint16_t> InputManager::_keyPressedEvents; std::vector<uint16_t> InputManager::_keyReleasedEvents; std::vector<uint16_t> InputManager::_mouseReleaseEvents; }
745b8d17e9a43b1921bc4d7b8ca0185305a59cb5
551da0619b15a6365678a6a02498e377fdaedd12
/HelloSocket/HelloSocket/Test.cpp
724243bd2fce4267e4e339553e3f326c7f3b61f9
[]
no_license
Latias94/CppGameServerFromScratch
4846f797d4c6130de11e2fbed4d13b999b6d0cfc
dda57a3e3807b559c0d8574a7ffd1893da0869aa
refs/heads/master
2020-06-12T20:00:25.548271
2019-07-02T07:13:47
2019-07-02T07:13:47
194,409,293
4
0
null
null
null
null
UTF-8
C++
false
false
1,334
cpp
#define WIN32_LEAN_AND_MEAN #include <windows.h> #include <winsock2.h> // 静态链接库 // #pragma comment(lib, "ws2_32.lib") // 只在 windows 有效 // 或者在 项目->属性->配置属性->链接器->输入->附加依赖项 中添加 int main() { // 在 POSIX 平台,socket 库在默认下就是激活状态,不需要特意启动 socket 功能。 // 但是 Winsock2 需要显式地启动和关闭,并允许用户指定使用什么版本 // WORD 两个字节,低字节表示主版本号,高字节表示所需要的 Winsock 实现的最低版本 WORD ver = MAKEWORD(2, 2); // lpWSAData 指向 Windows 特定的数据结构 WSADATA data; // 返回值 成功为0,或者错误代码 WSAStartup(ver, &data); // 关闭库需要调用 Cleanup,返回的是错误代码。 // 当一个进程调用 WSACleanup 时,会结束所有未完成的 socket 操作,释放所有 socket 资源。 // 所以关闭 socket 之前,最好确保所有 socket 都已经关闭并且没有在使用。 // WSAStartup 时引用计数的,所以调用 WSACleanup 的次数与调用 WSAStartup 的次数必须一致,保证清理了一切东西。 WSACleanup(); return 0; } // 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单 // 调试程序: F5 或调试 >“开始调试”菜单
52e8b54774075dbf75f14100f55a069acfd63725
7a00a2a8161b2f356c964b583eeb739e2ce9182f
/Source/Common/Core/_Test/CoreTests/SerializationTest/SerializationTest.cpp
039510641853dd11be08dad77cd9876c2f9d0e0e
[]
no_license
TamasSzep/Framework
064000b5b3e0b2b9834e30b7c8df08e583bc3b57
6194acd881cfec4d083bd8d1c962df23af541bce
refs/heads/main
2023-03-02T13:55:21.506624
2021-02-14T18:20:03
2021-02-14T18:20:03
326,766,086
2
0
null
null
null
null
UTF-8
C++
false
false
1,664
cpp
// SerializationTest.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <Core/SimpleBinarySerialization.hpp> #include <vector> #include <string> struct A { int I; std::string Str; void Serialize(Core::SimpleBinarySerializer& serializer) const { serializer.Serialize(I); serializer.Serialize(Str); } void Deserialize(Core::SimpleBinaryDeserializer& deserializer) { deserializer.Deserialize(I); deserializer.Deserialize(Str); } }; struct B { std::vector<A> As; std::string Str2; void Serialize(Core::SimpleBinarySerializer& serializer) const { serializer.Serialize(As); serializer.Serialize(Str2); } void Deserialize(Core::SimpleBinaryDeserializer& deserializer) { deserializer.Deserialize(As); deserializer.Deserialize(Str2); } }; struct C { std::vector<A> As2; std::vector<B> Bs; int I2; void Serialize(Core::SimpleBinarySerializer& serializer) const { serializer.Serialize(As2); serializer.Serialize(Bs); serializer.Serialize(I2); } void Deserialize(Core::SimpleBinaryDeserializer& deserializer) { deserializer.Deserialize(As2); deserializer.Deserialize(Bs); deserializer.Deserialize(I2); } }; int main() { C c; c.I2 = 42; c.As2.push_back({ 0, "zero" }); c.Bs.push_back({}); c.Bs.push_back({}); c.Bs[0].Str2 = "B0"; c.Bs[0].As.push_back({ 1, "one" }); c.Bs[1].Str2 = "B1"; c.Bs[1].As.push_back({ 2, "two" }); C c2; c2.As2.push_back({}); Core::SimpleBinarySerializer serializer; serializer.Start(); serializer.Serialize(c); Core::SimpleBinaryDeserializer deserializer; deserializer.Deserialize(c2, serializer.GetBytes()); return 0; }
6730f430d7960a6e8b199165a8294b7f79867180
4946879981bcda5df68000e6820b309129b94266
/Random/devskill-easy11-3.cpp
b6f73e4debcc431092b6fe87b833ff87c9d11883
[]
no_license
NazmulHasanMoon/OJ
b567a231eb2dd7f4dd20f17026c6845ffe969c20
399d6fdf5e65cd49c5a00072b820bcda66e4676e
refs/heads/master
2021-07-16T00:13:03.228187
2020-06-25T06:41:09
2020-06-25T06:41:09
178,351,786
0
0
null
null
null
null
UTF-8
C++
false
false
418
cpp
#include<bits/stdc++.h> using namespace std; int main() { int t,i(1); scanf("%d",&t); while(i<=t) { int x; scanf("%d",&x); long long s; s=(long long)pow(2.0,x); //cout<<s<<endl; while(s>=10){ s/=10; } if(x%2==0) printf("+%lld\n",s); else printf("-%lld\n",s); i++; } return 0; }
e5b3eec58d4afabbfdf675d558a4c9fcd2ef89ad
b9cd09bf5c88e1a11284d27e2e2b91842424a743
/Visual_C++_MFC_examples/Part 3 고급 사용자 인터페이스/23장 GDI+/GdiplusLine/GdiplusLine/GdiplusLineView.h
557c6b5eb7affec1c9f8a227c661478503ea19a2
[]
no_license
uki0327/book_source
4bab68f90b4ec3d2e3aad72ec53877f6cc19a895
a55750464e75e3a9b586dded1f99c3c67ff1e8c9
refs/heads/master
2023-02-21T07:13:11.213967
2021-01-29T06:16:31
2021-01-29T06:16:31
330,401,135
0
0
null
null
null
null
UHC
C++
false
false
1,163
h
// GdiplusLineView.h : CGdiplusLineView 클래스의 인터페이스 // #pragma once class CGdiplusLineView : public CView { protected: // serialization에서만 만들어집니다. CGdiplusLineView(); DECLARE_DYNCREATE(CGdiplusLineView) // 특성입니다. public: CGdiplusLineDoc* GetDocument() const; // 작업입니다. public: // 재정의입니다. public: virtual void OnDraw(CDC* pDC); // 이 뷰를 그리기 위해 재정의되었습니다. virtual BOOL PreCreateWindow(CREATESTRUCT& cs); protected: virtual BOOL OnPreparePrinting(CPrintInfo* pInfo); virtual void OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo); virtual void OnEndPrinting(CDC* pDC, CPrintInfo* pInfo); // 구현입니다. public: virtual ~CGdiplusLineView(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: // 생성된 메시지 맵 함수 protected: DECLARE_MESSAGE_MAP() public: afx_msg void OnPaint(); }; #ifndef _DEBUG // GdiplusLineView.cpp의 디버그 버전 inline CGdiplusLineDoc* CGdiplusLineView::GetDocument() const { return reinterpret_cast<CGdiplusLineDoc*>(m_pDocument); } #endif
26dc796fc9f011db0b3bee54be4b0cc787b3b7dc
1fe7ec2a90bf84df6643ca6ac42a6015f323aa71
/Bank Program/manager.cpp
3f43245256cec7fd67122a99da86eeb990f7a806
[]
no_license
ShwetaDixit/QureshiRepo
d0071b6f98abdc7bce604fe15957f4a9a901c0f7
7a81667c0c183fa781dcb388e6dd23e2221dfa14
refs/heads/master
2020-03-21T13:27:33.662083
2018-06-25T04:35:06
2018-06-25T04:35:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,552
cpp
#include "bank.h" /* has managerial powers to open and close an account and see the critical details of a particular, or all (at once), customers in a formatted display. Manager IS A Person */ class Manager: public Person { public: //will close accounts of customerAccount highlighted in Parameter //will only close account if account has balance 0 bool accountClose(Customer* cust, string account){ //CHECKING if(!account.compare("check")){ if(cust->getCheck() == -1){ cout << "account is already closed!"; return false; } else if(cust->getCheck() != 0){ cout << "Account does not have 0 balance" << endl; return false; } else{ cust->setCheck(-1); cout << "Checking Account closed" << endl; return true; } } //SAVING if(!account.compare("saving")){ if(cust->getSave() == -1){ cout << "account is already closed!"; return false; } else if(cust->getSave() != 0){ cout << "Account does not have 0 balance" << endl; return false; } else{ cust->setSave(-1); cout << "Savings Account closed" << endl; return true; } } return false; } bool accountOpen(Customer* cust, string account){ if(!account.compare("check")){ if(cust->getCheck() == -1){ cust->setCheck(0); cout << "Checking Account Opened!" << endl; return true; } else{ cout << "Account is already open!" << endl; return false; } } else if(!account.compare("saving")){ if(cust->getSave() == -1){ cust->setSave(0); cout << "Savings Account Opened!" << endl; return true; } else{ cout << "Account is already open!" << endl; return false; } } else{ cout << "Entered Wrong Account Type" << endl; return false; } } //will printout balances of customer void printbalance(Customer* cust){ cout << "\n Checking: " << cust->getCheck(); cout << "\n Savings: " << cust->getSave() << endl; } };
02a763689b72a99d8987e2a4fd1505c5d1186824
43260c9add09e83c4f36c694f473b79fdf60cf6b
/remote_ui/trunk/remote_ui/QT/fieldparsers/xml2fields.h
f2729bf967730fb2a3066960531725fcce14fe2b
[]
no_license
tompipen/aubit4gl_code
63d31e10e329831f95f9e839a0f1bf312c056164
ea632477f2653dd97f024eb6a54abfdf5a892153
refs/heads/master
2020-04-11T14:52:49.192757
2018-11-12T10:21:42
2018-11-12T10:21:42
161,871,995
0
0
null
null
null
null
UTF-8
C++
false
false
1,939
h
//--------------------------------------------------------- (C) VENTAS AG 2009 - // Project : VENTAS Desktop Client for A4gl // Filename : xml2fields.h // Description : parses an XMLForm and returns a layout // with the avilabe fields //------------------------------------------------------------------------------ // // This file may be used under the terms of the GNU General Public // License version 2.0 as published by the Free Software Foundation // (http://www.gnu.org/licenses/gpl-2.0.html) // // This file is provided AS IT IS with NO WARRANTY OF ANY KIND, INCLUDING THE // WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. // If you need professional Support please contact us at www.ventas.de // Enjoy using it! // //------------------------------------------------------------------------------ #ifndef XML2FIELDS_H #define XML2FIELDS_H #include <QObject> #include <QWidget> #include <QLayout> #include <QHBoxLayout> #include <QVBoxLayout> #include <QGridLayout> #include <QGroupBox> #include <QDomDocument> #include <QDomNode> #include <QDomElement> #include <QMainWindow> #include <models/table.h> class XML2Fields : public QWidget { Q_OBJECT public: XML2Fields(); void parseForm(QDomDocument); void parseElement(QDomNode); TableView *p_screenRecord; QList<QObject*> ql_formFields; QList<QObject*> getFieldList(); QObject* getLayout(); private: //FglForm* p_fglform; QObject *currObject; QObject *parentObject; QLayout *layout; QColor qcol_BaseColor; void addToForm(QObject*, bool add=false, int x=0, int y=0, int w=0); void handleField(const QDomNode&); void handleFormField(const QDomNode&); void handleTableColumn(const QDomNode&); bool hidden; int widthFactor; int heightFactor; QList<QObject*> ql_objectList; }; #endif
[ "siverly@ccff5c2d-aaaf-4f61-a5bd-d7f44fd75822" ]
siverly@ccff5c2d-aaaf-4f61-a5bd-d7f44fd75822
2d3f9492f9f6c44398fccedfa64569096098bf77
bfc88c2fd382ea99175de00dce4adafcdd3550a0
/cylinder/discont/kode/obscure/oldcylinder.cpp
adcd3b6e2f8e27efefb11dec0654c94651d11243
[]
no_license
archqua/mitosis
0c1f0c1835eeaeb8da16c66a51dd5de5c2c78530
2c688d96733994870b54d2551166816d02704b65
refs/heads/main
2023-06-17T12:13:18.614398
2021-07-15T12:57:47
2021-07-15T12:57:47
334,888,652
0
2
null
2021-05-08T16:29:24
2021-02-01T08:59:50
C++
UTF-8
C++
false
false
10,583
cpp
#include "parameters.h" #include<armadillo> #include <boost/program_options.hpp> #include<iostream> #include<fstream> #include<sstream> #include<algorithm> #include<string> #include<vector> #include<array> // time-independent arma::vec::fixed<6> u_ij[I+2][J+2]; //u_ij[i][j] stands for u_i-0.5,j-0.5 //arma::vec::fixed<6> ukiter_ij[I][J]; //k-th Newton iteration arma::sp_mat dbulk_mx=arma::sp_mat(6,6); arma::sp_mat dmt_mx=arma::sp_mat(6,6); arma::sp_mat dav_mx=arma::sp_mat(6,6); arma::sp_mat dzer_mx=arma::sp_mat(6,6); arma::sp_mat C_i[I];//these 4 matrices will have function(i,j) interfaces arma::sp_mat A_i[I]; arma::sp_mat F_i[3]; arma::sp_mat G_i[3]; //jacobianless arma::sp_mat BJL_ij[I][J]; arma::sp_mat E_mx(6,6); // time-dependent // jacobianful arma::mat::fixed<6,6> BJF_ij[I][J]; arma::mat::fixed<6,6> B_ij[I][J]; arma::mat::fixed<6,6> Binv_ij[I][J]; //initialize time-independent and initial condition auto astest(const int& i, const int& j){//toRemove return u_ij[i+1][j+1][1]; } void set_init_cond_from_file(const std::string& path){ //JxI.csv std::ifstream istream(path); std::string line; int i=0; int j=0; int k=0; if (istream.is_open()){ while (getline(istream,line)){ if (j>=J){throw "J value exceeded";} std::stringstream ss(line); std::vector<std::vector<double>> us; //std::string sus; std::vector<double> u; std::string su; std::string _su; while (getline(ss, su, ';')){ if (i>=I){throw "I value exceeded";} std::stringstream _ss(su); while (getline(_ss, _su, ',')){ if (k>=6){throw "vector of dimension gt 6";} u.push_back(stod(_su)); ++k; } arma::vec _u(u); u_ij[i+1][j+1] = _u; //astest = _u(1); //toRemove //us.push_back(u); u.clear(); k=0; ++i; } /* for (arma::vec _u : us){ u_ij[i+1][j+1] = _u; //astest = _u(1); //toRemove } */ i=0; ++j; } } } void initializeDiffusion(){ for (int i=0; i<3; ++i){ //should zeros be initialized??? dav_mx(i,i)=dav; dmt_mx(i,i)=dmt; dbulk_mx(i,i)=dbulk; } } //1D->2D bool r_in_mt(const int& i, const int& j){ return i < rmti && i > 0; } bool r_in_bulk(const int& i, const int& j){ return i > rmti && i < I; //was <= } bool r_in_av(const int& i, const int& j){//is incorrect and not called return i == rmti; } bool r_in_vanish(const int& i, const int& j){ return i==0 || i==I; // was I+1 } arma::sp_mat& diffr_coeff(const int& i, const int& j){ if (r_in_bulk(i,j)) {return dbulk_mx;} if (r_in_mt(i,j)) {return dmt_mx;} if (r_in_vanish(i,j)) {return dzer_mx;} return dav_mx; } // diffr_coeff(i,j) stands for d_i,j+0.5 bool z_in_mt(const int& i, const int& j){ return i < rmti && j > 0 && j < J; //was <= } bool z_in_bulk(const int& i, const int& j){ return i >= rmti && j > 0 && j < J; //was <= } bool z_in_av(const int& i, const int& j); bool z_in_vanish(const int& i, const int& j){ return j == 0 || j == J; // was J+1 } arma::sp_mat& diffz_coeff(const int& i, const int& j){//??? if (z_in_bulk(i,j)) {return dbulk_mx;} if (z_in_mt(i,j)) {return dmt_mx;} if (z_in_vanish(i,j)) {return dzer_mx;} return dav_mx; /* if (j > 0 && j <= J){ if (i >= rmti) {return dbulk_mx;} return dmt_mx; } return dzer_mx; */ } // diffz_coeff(i,j) stands for d_i+0.5,j void initializeCAFGEBJL(){ for (int i=0; i<I; ++i){ C_i[i] = (ht*(i + 1.) / (hr*hr*(i + 0.5))) * diffr_coeff(i+1,0); A_i[i] = (ht*i / (hr*hr*(i+0.5))) * diffr_coeff(i,0); } F_i[0] = dzer_mx; F_i[1] =(ht / (hz*hz)) * dbulk_mx; F_i[2] =(ht / (hz*hz)) * dmt_mx; G_i[0] = dzer_mx; G_i[1] =(ht / (hz*hz)) * dbulk_mx; G_i[2] =(ht / (hz*hz)) * dmt_mx; for (int i=0; i<6; ++i){ E_mx(i,i)=1; } for (int i=0; i<I; ++i){ for (int j=0; j<J; ++j){ BJL_ij[i][j] = E_mx + (ht / (hr*hr*(i+0.5))) * ((i + 1.)*diffr_coeff(i+1,j) + i*diffr_coeff(i,j)) + (ht / (hz*hz)) * (diffz_coeff(i,j+1) + diffz_coeff(i,j)); } } } //1D->2D arma::sp_mat& C_ij(const int& i, const int& j){ return C_i[i]; } arma::sp_mat& A_ij(const int& i, const int& j){ return A_i[i]; } arma::sp_mat F_ij(const int& i, const int& j){ /* question is what return type should be (to & or not to &)? * another question is who optimizes better -- me or compiler? if (j < J-1){ if (i > rmti) { return F_i[1]; } return F_i[2]; } return F_i[0]; */ return (j < J-1)*((i >= rmti) ? F_i[1] : F_i[2]) + dzer_mx; //was i> } arma::sp_mat G_ij(const int& i, const int& j){ /* same questions here if (j > 0){ if (i > rmti){ return G_i[1]; } return G_i[2]; } return G_i[0]; */ return (j > 0)*((i >= rmti) ? G_i[1] : G_i[2]) + dzer_mx; //was i> } //TODO bool satisfied=false; void update(const int& i, const int& j, arma::vec::fixed<6>& uij_prev, double& shift, double& worstshift, const arma::vec::fixed<6> dt_phi[I][J]){ //arrays are passed by reference by default, I think uij_prev=u_ij[i+1][j+1]; //u_ij[i+1][j+1] = Binv_ij[i][j] //* (dt_phi[i][j] //- altomg*BJL_ij[i][j]*u_ij[i+1][j+1] //sign? //+ C_ij(i,j)*u_ij[i+2][j+1] //+ A_ij(i,j)*u_ij[i][j+1] //+ F_ij(i,j)*u_ij[i+1][j+2] //+ G_ij(i,j)*u_ij[i+1][j]); u_ij[i+1][j+1] = (1 - omega)*u_ij[i+1][j+1] + omega*Binv_ij[i][j] * (dt_phi[i][j] + C_ij(i,j)*u_ij[i+2][j+1] + A_ij(i,j)*u_ij[i][j+1] + F_ij(i,j)*u_ij[i+1][j+2] + G_ij(i,j)*u_ij[i+1][j]); shift = norm(u_ij[i+1][j+1] - uij_prev, "inf") / std::max(1., norm(uij_prev, "inf")); worstshift = std::max(worstshift, shift); } arma::vec::fixed<6> dt_phi[I][J]; void newtonStep(){ //arrays are passed by reference by default, I think int jinit=0; double worstshift=0; double shift=0; arma::vec::fixed<6> uij_prev; /* auto update = [&](const int& i, const int& j){ uij_prev=u_ij[i+1][j+1]; u_ij[i+1][j+1]=Binv_ij[i][j] * (dt_phi[i][j] + C_ij(i,j)*u_ij[i+2][j+1] + A_ij(i,j)*u_ij[i][j+1] + F_ij(i,j)*u_ij[i+1][j+2] + G_ij(i,j)*u_ij[i+1][j]); shift = norm(u_ij[i+1][j+1] - uij_prev, "inf") / std::max(1., norm(uij_prev, "inf")); worstshift = std::max(worstshift, shift); }; */ for (int i=0; i<I; ++i){ for (int j=jinit; j<J; j+=2){ update(i, j, uij_prev, shift, worstshift, dt_phi); } jinit = (jinit + 1) % 2; } jinit=1; for (int i=0; i<I; ++i){ for (int j=jinit; j<J; j+=2){ update(i, j, uij_prev, shift, worstshift, dt_phi); } jinit = (jinit + 1) % 2; } satisfied = worstshift < nepsilon; } //TODO int max_newton_steps=0; int newton_steps=0; arma::vec::fixed<6> u11; //toRemove double _u11; void impEuler(){ for (int i=0; i<I; ++i){ for (int j=0; j<J; ++j){ const arma::vec::fixed<6> uij = u_ij[i+1][j+1]; BJF_ij[i][j] = - ht*ourJac(uij,i,j); //mind the sign //B_ij[i][j] = invomg*BJL_ij[i][j] + BJF_ij[i][j];//omega or invomg??? B_ij[i][j] = BJL_ij[i][j] + BJF_ij[i][j]; Binv_ij[i][j] = B_ij[i][j].i(); dt_phi[i][j] = ht*rhs(uij,i,j) + BJF_ij[i][j]*uij + uij; //SIGN!!! //u_ij[i+1][j+1] = uij; // I forgot what I meant } } newton_steps=0; do{ newtonStep(); ++newton_steps; u11 = u_ij[1][1]; //toRemove _u11 = u11[1]; } while (!satisfied); //satisfied=false; max_newton_steps = (newton_steps > max_newton_steps)?newton_steps:max_newton_steps; //std::cout << "newton_steps: " << newton_steps << std::endl; } //TODO //don't forget B_ij and Binv_ij stepwise initialization void stamp(std::ostream& csv_stream){ //was ofstream))) for (int j=1; j <= J; ++j){ for (int i=1; i<I; ++i){ csv_stream << u_ij[i][j][1] << ","; } csv_stream << u_ij[I][j][1] << std::endl; } } void timeStep(std::ostream& csv_stream){ // i wonder if ofstream should better be reopened at each call stamp(csv_stream); impEuler(); } void saveinfo(const std::string& save_path, int argc, char* argv[]){ std::ofstream infostream(save_path + ".info"); /* std::vector<std::string> args; std::for_each(std::begin(argv),std::end(argv), [&](const std::string& word){args.push_back(word);}); */ std::string word; if (infostream.is_open()){ for (int i=0; i<argc-1; ++i){ word = argv[i]; infostream << argv[argc-1] << " "; } infostream << word << std::endl; } else {std::cout << "Can't save " << save_path << ".info" << std::endl;} } class NullBuffer : public std::streambuf{ public: int overflow(int c) {return c;} }; //stackoverflow))) int main(int argc, char* argv[]){ std::string help_msg = std::string("`-ic init_cond.csv` for initial condition\n") +std::string("`-t time` for time of simulation\n") +std::string("`-o save_path` for main output file\n") +std::string("-o option creates save_path.csv and save_path.info\n") +std::string("w/ u_ijs and other information respectively") +std::string("\n`-omg omega` for omega\n") +std::string("`-eps relax_crit` for nepsilon\n") +std::string("`-ht ht` for ht\n"); std::string init_cond_path="cylinder_ic.scv"; double time=10; int each = 1; std::string save_path="out"; std::string comment="none"; for (int i=1; i<argc; ++i){ std::string strarg(argv[i]); if (strarg=="-ic"){ init_cond_path=argv[i+1]; } if (strarg=="-t"){ time=std::stod(argv[i+1]); } if (strarg=="-o"){ save_path=argv[i+1]; } if (strarg=="-m"){ //m for message comment=argv[i+1]; } if (strarg=="-e"){ each=std::stod(argv[i+1]); } if (strarg=="-omg"){ omega=std::stod(argv[i+1]); } if (strarg=="-ht"){ ht=std::stod(argv[i+1]); } if (strarg=="-eps"){ nepsilon=std::stod(argv[i+1]); } if (strarg=="-h"){ std::cout << help_msg; return 0; } } unsigned long long timesteps = time/ht; initializeDiffusion(); initializeCAFGEBJL(); set_init_cond_from_file(init_cond_path); // larmadillo usage /* arma::vec v({1,2,3}); arma::mat m({{0,1,0},{1,0,0},{0,0,1}}); arma::sp_mat sm(3,3); sm(0,0)=0.333; sm(1,1)=0.5; sm(2,2)=1; std::cout << m*v << std::endl; std::cout << sm*v << std::endl; */ //actual execution finally starts std::ofstream csv_stream(save_path + ".csv"); NullBuffer nullBuf; std::ostream nullStr(&nullBuf); //stackoverflow))) if (csv_stream.is_open()){ unsigned long long t=0; for (t=0; t<timesteps; ++t){ if (t % each == 0) timeStep(csv_stream); else timeStep(nullStr); //stackoverflow))) } if (t % each == 0) stamp(csv_stream); csv_stream.close(); } else {std::cout << "Can't save " << save_path << ".csv" << std::endl;} saveinfo(save_path, argc, argv); std::cout << "max Newton steps: " << max_newton_steps << std::endl; std::cout << "number of timesteps: " << timesteps << std::endl; return 0; }
0f59c8a56bfe510fc0e22ec01a4ae1fc21c53000
1ae133cea27a76e21d6ed8385315abe39dbd7d75
/src/rs_add_dialog.h
27176663088108a3d8972c8d691db8b8d2f40ae2
[]
no_license
chukago/RelayStore
bbb24c2751b3df29d3e483b122dba3bbcaed1e81
7a28cbbada2ac641c9eda1f6fc024cf2a3b57d0d
refs/heads/master
2020-06-08T17:43:52.922034
2019-06-22T20:48:33
2019-06-22T20:48:33
193,275,397
0
0
null
null
null
null
UTF-8
C++
false
false
2,289
h
#ifndef RS_ADD_DIALOG_H #define RS_ADD_DIALOG_H #include <QDialog> #include <QWidget> #include <QLabel> #include <QLineEdit> #include <QGridLayout> #include <QPushButton> #include <QComboBox> #include <QDateEdit> #include <QtSql/QSqlDatabase> #include <QtSql/QSqlQuery> #include <QMessageBox> #include <QVector> #include <QKeyEvent> #include "../src/servers.h" class rs_add_dialog : public QDialog { Q_OBJECT private: dbQueryServer *_req_server; struct rs_relay *_relay; QLabel *_type_lb; QLabel *_period_lb; QLabel *_ser_num_lb; QLabel *_manufactured_lb; QLabel *_station_lb; QLabel *_relay_rack_lb; QLabel *_device_number_lb; QLabel *_last_check_lb; QLabel *_next_check_lb; QLabel *_status_lb; QLabel *_comment_lb; QComboBox *_type_ed; QLineEdit *_period_ed; QLineEdit *_ser_num_ed; QDateEdit *_manufactured_ed; QComboBox *_station_ed; QLineEdit *_relay_rack_ed; QLineEdit *_device_number_ed; QDateEdit *_last_check_ed; QLineEdit *_next_check_ed; QComboBox *_status_ed; QLineEdit *_comment_ed; QPushButton *_ok; QPushButton *_cancel; QGridLayout *_gl; void setConnections(void); /* bool check_input(void); // Проверка ввода bool check_data(void); // Проверка введённых данных bool check_database(void); // Проверка в базе данных QString gen_query(void); // Генерация запроса */ public: rs_add_dialog(QWidget *parent, dbQueryServer *req_server); public slots: void check_errors(void); // Проверка введённых данных void check_type(QString); // Проверка введённых данных в поле типа реле //void check_period(QString); // Проверка введённого периода проверки void check_status(QString); // Проверка статуса void check_manufactured(QDate); // Проверка даты производства void check_last_check(QDate); // Проверка даты последней проверки protected: void keyPressEvent(QKeyEvent* key_event); }; #endif /*RS_ADD_DIALOG_H*/
ffd81362cc91ecca877bb67c1c8ac126ebb6db7a
e76ea38dbe5774fccaf14e1a0090d9275cdaee08
/src/net/disk_cache/cache_creator.cc
ccdab1ff626fc16c6b941a26256adfa79c13a37d
[ "BSD-3-Clause" ]
permissive
eurogiciel-oss/Tizen_Crosswalk
efc424807a5434df1d5c9e8ed51364974643707d
a68aed6e29bd157c95564e7af2e3a26191813e51
refs/heads/master
2021-01-18T19:19:04.527505
2014-02-06T13:43:21
2014-02-06T13:43:21
16,070,101
1
3
null
null
null
null
UTF-8
C++
false
false
5,341
cc
// 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 "base/files/file_path.h" #include "base/metrics/field_trial.h" #include "base/strings/stringprintf.h" #include "net/base/cache_type.h" #include "net/base/net_errors.h" #include "net/disk_cache/backend_impl.h" #include "net/disk_cache/cache_util.h" #include "net/disk_cache/disk_cache.h" #include "net/disk_cache/mem_backend_impl.h" #include "net/disk_cache/simple/simple_backend_impl.h" #ifdef USE_TRACING_CACHE_BACKEND #include "net/disk_cache/tracing_cache_backend.h" #endif namespace { // Builds an instance of the backend depending on platform, type, experiments // etc. Takes care of the retry state. This object will self-destroy when // finished. class CacheCreator { public: CacheCreator(const base::FilePath& path, bool force, int max_bytes, net::CacheType type, net::BackendType backend_type, uint32 flags, base::MessageLoopProxy* thread, net::NetLog* net_log, scoped_ptr<disk_cache::Backend>* backend, const net::CompletionCallback& callback); // Creates the backend. int Run(); private: ~CacheCreator(); void DoCallback(int result); void OnIOComplete(int result); const base::FilePath path_; bool force_; bool retry_; int max_bytes_; net::CacheType type_; net::BackendType backend_type_; uint32 flags_; scoped_refptr<base::MessageLoopProxy> thread_; scoped_ptr<disk_cache::Backend>* backend_; net::CompletionCallback callback_; scoped_ptr<disk_cache::Backend> created_cache_; net::NetLog* net_log_; DISALLOW_COPY_AND_ASSIGN(CacheCreator); }; CacheCreator::CacheCreator( const base::FilePath& path, bool force, int max_bytes, net::CacheType type, net::BackendType backend_type, uint32 flags, base::MessageLoopProxy* thread, net::NetLog* net_log, scoped_ptr<disk_cache::Backend>* backend, const net::CompletionCallback& callback) : path_(path), force_(force), retry_(false), max_bytes_(max_bytes), type_(type), backend_type_(backend_type), flags_(flags), thread_(thread), backend_(backend), callback_(callback), net_log_(net_log) { } CacheCreator::~CacheCreator() { } int CacheCreator::Run() { // TODO(gavinp,pasko): Turn Simple Cache on for more cache types as // appropriate. if (backend_type_ == net::CACHE_BACKEND_SIMPLE && (type_ == net::DISK_CACHE || type_ == net::APP_CACHE)) { disk_cache::SimpleBackendImpl* simple_cache = new disk_cache::SimpleBackendImpl(path_, max_bytes_, type_, thread_.get(), net_log_); created_cache_.reset(simple_cache); return simple_cache->Init( base::Bind(&CacheCreator::OnIOComplete, base::Unretained(this))); } disk_cache::BackendImpl* new_cache = new disk_cache::BackendImpl(path_, thread_.get(), net_log_); created_cache_.reset(new_cache); new_cache->SetMaxSize(max_bytes_); new_cache->SetType(type_); new_cache->SetFlags(flags_); int rv = new_cache->Init( base::Bind(&CacheCreator::OnIOComplete, base::Unretained(this))); DCHECK_EQ(net::ERR_IO_PENDING, rv); return rv; } void CacheCreator::DoCallback(int result) { DCHECK_NE(net::ERR_IO_PENDING, result); if (result == net::OK) { #ifndef USE_TRACING_CACHE_BACKEND *backend_ = created_cache_.Pass(); #else *backend_.reset( new disk_cache::TracingCacheBackend(created_cache_.Pass())); #endif } else { LOG(ERROR) << "Unable to create cache"; created_cache_.reset(); } callback_.Run(result); delete this; } // If the initialization of the cache fails, and |force| is true, we will // discard the whole cache and create a new one. void CacheCreator::OnIOComplete(int result) { if (result == net::OK || !force_ || retry_) return DoCallback(result); // This is a failure and we are supposed to try again, so delete the object, // delete all the files, and try again. retry_ = true; created_cache_.reset(); if (!disk_cache::DelayedCacheCleanup(path_)) return DoCallback(result); // The worker thread will start deleting files soon, but the original folder // is not there anymore... let's create a new set of files. int rv = Run(); DCHECK_EQ(net::ERR_IO_PENDING, rv); } } // namespace namespace disk_cache { int CreateCacheBackend(net::CacheType type, net::BackendType backend_type, const base::FilePath& path, int max_bytes, bool force, base::MessageLoopProxy* thread, net::NetLog* net_log, scoped_ptr<Backend>* backend, const net::CompletionCallback& callback) { DCHECK(!callback.is_null()); if (type == net::MEMORY_CACHE) { *backend = disk_cache::MemBackendImpl::CreateBackend(max_bytes, net_log); return *backend ? net::OK : net::ERR_FAILED; } DCHECK(thread); CacheCreator* creator = new CacheCreator(path, force, max_bytes, type, backend_type, kNone, thread, net_log, backend, callback); return creator->Run(); } } // namespace disk_cache
cef110e7d16db67a085d50979e310c26c7ad9c50
b7f3edb5b7c62174bed808079c3b21fb9ea51d52
/services/data_decoder/web_bundler.h
36be21410482f12ab44a2ead248ca42e27f58207
[ "BSD-3-Clause" ]
permissive
otcshare/chromium-src
26a7372773b53b236784c51677c566dc0ad839e4
64bee65c921db7e78e25d08f1e98da2668b57be5
refs/heads/webml
2023-03-21T03:20:15.377034
2020-11-16T01:40:14
2020-11-16T01:40:14
209,262,645
18
21
BSD-3-Clause
2023-03-23T06:20:07
2019-09-18T08:52:07
null
UTF-8
C++
false
false
1,108
h
// Copyright 2020 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 SERVICES_DATA_DECODER_WEB_BUNDLER_H_ #define SERVICES_DATA_DECODER_WEB_BUNDLER_H_ #include <vector> #include "base/files/file.h" #include "mojo/public/cpp/base/big_buffer.h" #include "mojo/public/cpp/bindings/pending_remote.h" #include "services/data_decoder/public/mojom/resource_snapshot_for_web_bundle.mojom.h" #include "services/data_decoder/public/mojom/web_bundler.mojom.h" namespace data_decoder { class WebBundler : public mojom::WebBundler { public: WebBundler() = default; ~WebBundler() override = default; WebBundler(const WebBundler&) = delete; WebBundler& operator=(const WebBundler&) = delete; private: // mojom::WebBundler implementation. void Generate( std::vector<mojo::PendingRemote<mojom::ResourceSnapshotForWebBundle>> snapshots, base::File file, GenerateCallback callback) override; }; } // namespace data_decoder #endif // SERVICES_DATA_DECODER_WEB_BUNDLER_H_
1a7fc989b239b183c790717b48f2efeca49a9a54
e46e6a6e1a14edb3011be5a5355a7805e39e8d96
/jni/Utils/UtilsMemoryPool.cpp
5ef01bd698b9c629d3524c3f5a032b62ebaacc43
[]
no_license
vim1993/SoftwareProb
42383a81b2a8a746fbfd420278d8fff8c074f8bd
cee1a9ee5b018fa0e151ab5282041ea5dc446a83
refs/heads/master
2020-03-28T10:14:37.138249
2018-09-12T10:11:20
2018-09-12T10:11:20
148,093,747
0
0
null
null
null
null
UTF-8
C++
false
false
713
cpp
#include "UtilsMemoryPool.h" int memory_pool::sdk_mem_init(void) { buf_mem = (char *)malloc( 1024*1024*5 ); if(buf_mem == NULL) { return 0; } alloc = yy_f_alloc_nfp_create2( 1024*1024*5, buf_mem, NULL ); if( alloc == NULL ) { return 0; } return 1; } void * memory_pool::sdk_mem_malloc(size_t len) { if(buf_mem == NULL) { sdk_mem_init(); } return YY_F_ALLOC_MALLOC( alloc, len ); } void memory_pool::sdk_mem_free(char *buf) { YY_F_ALLOC_FREE(alloc,buf); } void memory_pool::sdk_mem_deinit(void) { YY_F_ALLOC_RELEASE( alloc ); free( buf_mem ); }
cfec7d16ec9879ff1ab8dc714150d4dfaa19305e
1417e7f4386a1952d8efd3ad550bd760b5bcc068
/teste/teste.ino
0834f57e42b8a8867adf8ea97c6bbd29be28a6b7
[]
no_license
jopedrosilva/Projetos-Arduino
82621d5ae2caefbbdadf0ba32477e9487e7d2df6
27109eb781477aa0998734786316e811d6238b13
refs/heads/master
2022-12-03T21:52:29.236304
2020-08-25T11:36:12
2020-08-25T11:36:12
290,197,790
0
0
null
null
null
null
UTF-8
C++
false
false
136
ino
void setup() { pinMode(7, OUTPUT); } void loop() { digitalWrite(7, HIGH); delay(2000); digitalWrite(7, LOW); delay(2000); }
50f42b372e85fedfd7abaae4e0786609521ed757
83e81c25b1f74f88ed0f723afc5d3f83e7d05da8
/native/android/system_fonts.cpp
9a2f55f3c88120291fa98d62192dbeb39eb5e1fb
[ "Apache-2.0", "LicenseRef-scancode-unicode" ]
permissive
Ankits-lab/frameworks_base
8a63f39a79965c87a84e80550926327dcafb40b7
150a9240e5a11cd5ebc9bb0832ce30e9c23f376a
refs/heads/main
2023-02-06T03:57:44.893590
2020-11-14T09:13:40
2020-11-14T09:13:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
13,779
cpp
/* * Copyright (C) 2018 The Android Open Source Project * * 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 <jni.h> #define LOG_TAG "SystemFont" #include <android/font.h> #include <android/font_matcher.h> #include <android/system_fonts.h> #include <memory> #include <string> #include <vector> #include <errno.h> #include <fcntl.h> #include <libxml/tree.h> #include <log/log.h> #include <sys/stat.h> #include <unistd.h> #include <hwui/MinikinSkia.h> #include <minikin/FontCollection.h> #include <minikin/LocaleList.h> #include <minikin/SystemFonts.h> struct XmlCharDeleter { void operator()(xmlChar* b) { xmlFree(b); } }; struct XmlDocDeleter { void operator()(xmlDoc* d) { xmlFreeDoc(d); } }; using XmlCharUniquePtr = std::unique_ptr<xmlChar, XmlCharDeleter>; using XmlDocUniquePtr = std::unique_ptr<xmlDoc, XmlDocDeleter>; struct ParserState { xmlNode* mFontNode = nullptr; XmlCharUniquePtr mLocale; }; struct ASystemFontIterator { XmlDocUniquePtr mXmlDoc; ParserState state; // The OEM customization XML. XmlDocUniquePtr mCustomizationXmlDoc; }; struct AFont { std::string mFilePath; std::unique_ptr<std::string> mLocale; uint16_t mWeight; bool mItalic; uint32_t mCollectionIndex; std::vector<std::pair<uint32_t, float>> mAxes; }; struct AFontMatcher { minikin::FontStyle mFontStyle; uint32_t mLocaleListId = 0; // 0 is reserved for empty locale ID. bool mFamilyVariant = AFAMILY_VARIANT_DEFAULT; }; static_assert(static_cast<uint32_t>(AFAMILY_VARIANT_DEFAULT) == static_cast<uint32_t>(minikin::FamilyVariant::DEFAULT)); static_assert(static_cast<uint32_t>(AFAMILY_VARIANT_COMPACT) == static_cast<uint32_t>(minikin::FamilyVariant::COMPACT)); static_assert(static_cast<uint32_t>(AFAMILY_VARIANT_ELEGANT) == static_cast<uint32_t>(minikin::FamilyVariant::ELEGANT)); namespace { std::string xmlTrim(const std::string& in) { if (in.empty()) { return in; } const char XML_SPACES[] = "\u0020\u000D\u000A\u0009"; const size_t start = in.find_first_not_of(XML_SPACES); // inclusive if (start == std::string::npos) { return ""; } const size_t end = in.find_last_not_of(XML_SPACES); // inclusive if (end == std::string::npos) { return ""; } return in.substr(start, end - start + 1 /* +1 since end is inclusive */); } const xmlChar* FAMILY_TAG = BAD_CAST("family"); const xmlChar* FONT_TAG = BAD_CAST("font"); const xmlChar* LOCALE_ATTR_NAME = BAD_CAST("lang"); xmlNode* firstElement(xmlNode* node, const xmlChar* tag) { for (xmlNode* child = node->children; child; child = child->next) { if (xmlStrEqual(child->name, tag)) { return child; } } return nullptr; } xmlNode* nextSibling(xmlNode* node, const xmlChar* tag) { while ((node = node->next) != nullptr) { if (xmlStrEqual(node->name, tag)) { return node; } } return nullptr; } void copyFont(const XmlDocUniquePtr& xmlDoc, const ParserState& state, AFont* out, const std::string& pathPrefix) { xmlNode* fontNode = state.mFontNode; XmlCharUniquePtr filePathStr( xmlNodeListGetString(xmlDoc.get(), fontNode->xmlChildrenNode, 1)); out->mFilePath = pathPrefix + xmlTrim( std::string(filePathStr.get(), filePathStr.get() + xmlStrlen(filePathStr.get()))); const xmlChar* WEIGHT_ATTR_NAME = BAD_CAST("weight"); XmlCharUniquePtr weightStr(xmlGetProp(fontNode, WEIGHT_ATTR_NAME)); out->mWeight = weightStr ? strtol(reinterpret_cast<const char*>(weightStr.get()), nullptr, 10) : 400; const xmlChar* STYLE_ATTR_NAME = BAD_CAST("style"); const xmlChar* ITALIC_ATTR_VALUE = BAD_CAST("italic"); XmlCharUniquePtr styleStr(xmlGetProp(fontNode, STYLE_ATTR_NAME)); out->mItalic = styleStr ? xmlStrEqual(styleStr.get(), ITALIC_ATTR_VALUE) : false; const xmlChar* INDEX_ATTR_NAME = BAD_CAST("index"); XmlCharUniquePtr indexStr(xmlGetProp(fontNode, INDEX_ATTR_NAME)); out->mCollectionIndex = indexStr ? strtol(reinterpret_cast<const char*>(indexStr.get()), nullptr, 10) : 0; out->mLocale.reset( state.mLocale ? new std::string(reinterpret_cast<const char*>(state.mLocale.get())) : nullptr); const xmlChar* TAG_ATTR_NAME = BAD_CAST("tag"); const xmlChar* STYLEVALUE_ATTR_NAME = BAD_CAST("stylevalue"); const xmlChar* AXIS_TAG = BAD_CAST("axis"); out->mAxes.clear(); for (xmlNode* axis = firstElement(fontNode, AXIS_TAG); axis; axis = nextSibling(axis, AXIS_TAG)) { XmlCharUniquePtr tagStr(xmlGetProp(axis, TAG_ATTR_NAME)); if (!tagStr || xmlStrlen(tagStr.get()) != 4) { continue; // Tag value must be 4 char string } XmlCharUniquePtr styleValueStr(xmlGetProp(axis, STYLEVALUE_ATTR_NAME)); if (!styleValueStr) { continue; } uint32_t tag = static_cast<uint32_t>(tagStr.get()[0] << 24) | static_cast<uint32_t>(tagStr.get()[1] << 16) | static_cast<uint32_t>(tagStr.get()[2] << 8) | static_cast<uint32_t>(tagStr.get()[3]); float styleValue = strtod(reinterpret_cast<const char*>(styleValueStr.get()), nullptr); out->mAxes.push_back(std::make_pair(tag, styleValue)); } } bool isFontFileAvailable(const std::string& filePath) { std::string fullPath = filePath; struct stat st = {}; if (stat(fullPath.c_str(), &st) != 0) { return false; } return S_ISREG(st.st_mode); } bool findFirstFontNode(const XmlDocUniquePtr& doc, ParserState* state) { xmlNode* familySet = xmlDocGetRootElement(doc.get()); if (familySet == nullptr) { return false; } xmlNode* family = firstElement(familySet, FAMILY_TAG); if (family == nullptr) { return false; } state->mLocale.reset(xmlGetProp(family, LOCALE_ATTR_NAME)); xmlNode* font = firstElement(family, FONT_TAG); while (font == nullptr) { family = nextSibling(family, FAMILY_TAG); if (family == nullptr) { return false; } font = firstElement(family, FONT_TAG); } state->mFontNode = font; return font != nullptr; } } // namespace ASystemFontIterator* ASystemFontIterator_open() { std::unique_ptr<ASystemFontIterator> ite(new ASystemFontIterator()); ite->mXmlDoc.reset(xmlReadFile("/system/etc/fonts.xml", nullptr, 0)); ite->mCustomizationXmlDoc.reset(xmlReadFile("/product/etc/fonts_customization.xml", nullptr, 0)); return ite.release(); } void ASystemFontIterator_close(ASystemFontIterator* ite) { delete ite; } AFontMatcher* _Nonnull AFontMatcher_create() { return new AFontMatcher(); } void AFontMatcher_destroy(AFontMatcher* matcher) { delete matcher; } void AFontMatcher_setStyle( AFontMatcher* _Nonnull matcher, uint16_t weight, bool italic) { matcher->mFontStyle = minikin::FontStyle( weight, static_cast<minikin::FontStyle::Slant>(italic)); } void AFontMatcher_setLocales( AFontMatcher* _Nonnull matcher, const char* _Nonnull languageTags) { matcher->mLocaleListId = minikin::registerLocaleList(languageTags); } void AFontMatcher_setFamilyVariant(AFontMatcher* _Nonnull matcher, uint32_t familyVariant) { matcher->mFamilyVariant = familyVariant; } AFont* _Nonnull AFontMatcher_match( const AFontMatcher* _Nonnull matcher, const char* _Nonnull familyName, const uint16_t* _Nonnull text, const uint32_t textLength, uint32_t* _Nullable runLength) { std::shared_ptr<minikin::FontCollection> fc = minikin::SystemFonts::findFontCollection(familyName); std::vector<minikin::FontCollection::Run> runs = fc->itemize( minikin::U16StringPiece(text, textLength), matcher->mFontStyle, matcher->mLocaleListId, static_cast<minikin::FamilyVariant>(matcher->mFamilyVariant), 1 /* maxRun */); const minikin::Font* font = runs[0].fakedFont.font; std::unique_ptr<AFont> result = std::make_unique<AFont>(); const android::MinikinFontSkia* minikinFontSkia = reinterpret_cast<android::MinikinFontSkia*>(font->typeface().get()); result->mFilePath = minikinFontSkia->getFilePath(); result->mWeight = font->style().weight(); result->mItalic = font->style().slant() == minikin::FontStyle::Slant::ITALIC; result->mCollectionIndex = minikinFontSkia->GetFontIndex(); const std::vector<minikin::FontVariation>& axes = minikinFontSkia->GetAxes(); result->mAxes.reserve(axes.size()); for (auto axis : axes) { result->mAxes.push_back(std::make_pair(axis.axisTag, axis.value)); } if (runLength != nullptr) { *runLength = runs[0].end; } return result.release(); } bool findNextFontNode(const XmlDocUniquePtr& xmlDoc, ParserState* state) { if (state->mFontNode == nullptr) { if (!xmlDoc) { return false; // Already at the end. } else { // First time to query font. return findFirstFontNode(xmlDoc, state); } } else { xmlNode* nextNode = nextSibling(state->mFontNode, FONT_TAG); while (nextNode == nullptr) { xmlNode* family = nextSibling(state->mFontNode->parent, FAMILY_TAG); if (family == nullptr) { break; } state->mLocale.reset(xmlGetProp(family, LOCALE_ATTR_NAME)); nextNode = firstElement(family, FONT_TAG); } state->mFontNode = nextNode; return nextNode != nullptr; } } AFont* ASystemFontIterator_next(ASystemFontIterator* ite) { LOG_ALWAYS_FATAL_IF(ite == nullptr, "nullptr has passed as iterator argument"); if (ite->mXmlDoc) { if (!findNextFontNode(ite->mXmlDoc, &ite->state)) { // Reached end of the XML file. Continue OEM customization. ite->mXmlDoc.reset(); } else { std::unique_ptr<AFont> font = std::make_unique<AFont>(); copyFont(ite->mXmlDoc, ite->state, font.get(), "/system/fonts/"); if (!isFontFileAvailable(font->mFilePath)) { return ASystemFontIterator_next(ite); } return font.release(); } } if (ite->mCustomizationXmlDoc) { // TODO: Filter only customizationType="new-named-family" if (!findNextFontNode(ite->mCustomizationXmlDoc, &ite->state)) { // Reached end of the XML file. Finishing ite->mCustomizationXmlDoc.reset(); return nullptr; } else { std::unique_ptr<AFont> font = std::make_unique<AFont>(); copyFont(ite->mCustomizationXmlDoc, ite->state, font.get(), "/product/fonts/"); if (!isFontFileAvailable(font->mFilePath)) { return ASystemFontIterator_next(ite); } return font.release(); } } return nullptr; } void AFont_close(AFont* font) { delete font; } const char* AFont_getFontFilePath(const AFont* font) { LOG_ALWAYS_FATAL_IF(font == nullptr, "nullptr has passed as font argument"); return font->mFilePath.c_str(); } uint16_t AFont_getWeight(const AFont* font) { LOG_ALWAYS_FATAL_IF(font == nullptr, "nullptr has passed as font argument"); return font->mWeight; } bool AFont_isItalic(const AFont* font) { LOG_ALWAYS_FATAL_IF(font == nullptr, "nullptr has passed as font argument"); return font->mItalic; } const char* AFont_getLocale(const AFont* font) { LOG_ALWAYS_FATAL_IF(font == nullptr, "nullptr has passed to font argument"); return font->mLocale ? font->mLocale->c_str() : nullptr; } size_t AFont_getCollectionIndex(const AFont* font) { LOG_ALWAYS_FATAL_IF(font == nullptr, "nullptr has passed to font argument"); return font->mCollectionIndex; } size_t AFont_getAxisCount(const AFont* font) { LOG_ALWAYS_FATAL_IF(font == nullptr, "nullptr has passed to font argument"); return font->mAxes.size(); } uint32_t AFont_getAxisTag(const AFont* font, uint32_t axisIndex) { LOG_ALWAYS_FATAL_IF(font == nullptr, "nullptr has passed to font argument"); LOG_ALWAYS_FATAL_IF(axisIndex >= font->mAxes.size(), "given axis index is out of bounds. (< %zd", font->mAxes.size()); return font->mAxes[axisIndex].first; } float AFont_getAxisValue(const AFont* font, uint32_t axisIndex) { LOG_ALWAYS_FATAL_IF(font == nullptr, "nullptr has passed to font argument"); LOG_ALWAYS_FATAL_IF(axisIndex >= font->mAxes.size(), "given axis index is out of bounds. (< %zd", font->mAxes.size()); return font->mAxes[axisIndex].second; }
e97104057747005cf458f269cc77bd6b81253e12
2e70cefba49cb743363b0b284295d981c9582f0a
/src/qt/optionsdialog.cpp
642754d2d7c1d4efec6d7a26f348de3f6bf9d1a5
[ "MIT" ]
permissive
aarigs/tune
e7ded144a100b15982f988270c5d787d998468d7
20405781b17d972cc06843c0fa53ec05d40179d4
refs/heads/master
2020-03-20T15:16:19.030033
2018-03-10T16:34:57
2018-03-10T16:34:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
13,327
cpp
// Copyright (c) 2011-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include "config/tune-config.h" #endif #include "optionsdialog.h" #include "ui_optionsdialog.h" #include "bitcoinunits.h" #include "guiutil.h" #include "optionsmodel.h" #include "main.h" // for DEFAULT_SCRIPTCHECK_THREADS and MAX_SCRIPTCHECK_THREADS #include "netbase.h" #include "txdb.h" // for -dbcache defaults #ifdef ENABLE_WALLET #include "wallet/wallet.h" // for CWallet::GetRequiredFee() #endif #include "darksend.h" #include <boost/thread.hpp> #include <QDataWidgetMapper> #include <QDir> #include <QIntValidator> #include <QLocale> #include <QMessageBox> #include <QTimer> extern CWallet* pwalletMain; OptionsDialog::OptionsDialog(QWidget *parent, bool enableWallet) : QDialog(parent), ui(new Ui::OptionsDialog), model(0), mapper(0) { ui->setupUi(this); /* Main elements init */ ui->databaseCache->setMinimum(nMinDbCache); ui->databaseCache->setMaximum(nMaxDbCache); ui->threadsScriptVerif->setMinimum(-GetNumCores()); ui->threadsScriptVerif->setMaximum(MAX_SCRIPTCHECK_THREADS); /* Network elements init */ #ifndef USE_UPNP ui->mapPortUpnp->setEnabled(false); #endif ui->proxyIp->setEnabled(false); ui->proxyPort->setEnabled(false); ui->proxyPort->setValidator(new QIntValidator(1, 65535, this)); ui->proxyIpTor->setEnabled(false); ui->proxyPortTor->setEnabled(false); ui->proxyPortTor->setValidator(new QIntValidator(1, 65535, this)); connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyIp, SLOT(setEnabled(bool))); connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyPort, SLOT(setEnabled(bool))); connect(ui->connectSocks, SIGNAL(toggled(bool)), this, SLOT(updateProxyValidationState())); connect(ui->connectSocksTor, SIGNAL(toggled(bool)), ui->proxyIpTor, SLOT(setEnabled(bool))); connect(ui->connectSocksTor, SIGNAL(toggled(bool)), ui->proxyPortTor, SLOT(setEnabled(bool))); connect(ui->connectSocksTor, SIGNAL(toggled(bool)), this, SLOT(updateProxyValidationState())); /* Window elements init */ #ifdef Q_OS_MAC /* remove Window tab on Mac */ ui->tabWidget->removeTab(ui->tabWidget->indexOf(ui->tabWindow)); #endif /* remove Wallet tab in case of -disablewallet */ if (!enableWallet) { ui->tabWidget->removeTab(ui->tabWidget->indexOf(ui->tabWallet)); } /* Display elements init */ /* Number of displayed decimal digits selector */ QString digits; for(int index = 2; index <=8; index++){ digits.setNum(index); ui->digits->addItem(digits, digits); } /* Theme selector */ ui->theme->addItem(QString("TUN-light"), QVariant("light")); ui->theme->addItem(QString("TUN-blue"), QVariant("drkblue")); ui->theme->addItem(QString("TUN-Crownium"), QVariant("crownium")); ui->theme->addItem(QString("TUN-traditional"), QVariant("trad")); /* Language selector */ QDir translations(":translations"); ui->lang->addItem(QString("(") + tr("default") + QString(")"), QVariant("")); Q_FOREACH(const QString &langStr, translations.entryList()) { QLocale locale(langStr); /** check if the locale name consists of 2 parts (language_country) */ if(langStr.contains("_")) { #if QT_VERSION >= 0x040800 /** display language strings as "native language - native country (locale name)", e.g. "Deutsch - Deutschland (de)" */ ui->lang->addItem(locale.nativeLanguageName() + QString(" - ") + locale.nativeCountryName() + QString(" (") + langStr + QString(")"), QVariant(langStr)); #else /** display language strings as "language - country (locale name)", e.g. "German - Germany (de)" */ ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" - ") + QLocale::countryToString(locale.country()) + QString(" (") + langStr + QString(")"), QVariant(langStr)); #endif } else { #if QT_VERSION >= 0x040800 /** display language strings as "native language (locale name)", e.g. "Deutsch (de)" */ ui->lang->addItem(locale.nativeLanguageName() + QString(" (") + langStr + QString(")"), QVariant(langStr)); #else /** display language strings as "language (locale name)", e.g. "German (de)" */ ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" (") + langStr + QString(")"), QVariant(langStr)); #endif } } #if QT_VERSION >= 0x040700 ui->thirdPartyTxUrls->setPlaceholderText("https://example.com/tx/%s"); #endif ui->unit->setModel(new BitcoinUnits(this)); /* Widget-to-option mapper */ mapper = new QDataWidgetMapper(this); mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit); mapper->setOrientation(Qt::Vertical); /* setup/change UI elements when proxy IPs are invalid/valid */ ui->proxyIp->setCheckValidator(new ProxyAddressValidator(parent)); ui->proxyIpTor->setCheckValidator(new ProxyAddressValidator(parent)); connect(ui->proxyIp, SIGNAL(validationDidChange(QValidatedLineEdit *)), this, SLOT(updateProxyValidationState())); connect(ui->proxyIpTor, SIGNAL(validationDidChange(QValidatedLineEdit *)), this, SLOT(updateProxyValidationState())); connect(ui->proxyPort, SIGNAL(textChanged(const QString&)), this, SLOT(updateProxyValidationState())); connect(ui->proxyPortTor, SIGNAL(textChanged(const QString&)), this, SLOT(updateProxyValidationState())); } OptionsDialog::~OptionsDialog() { delete ui; } void OptionsDialog::setModel(OptionsModel *model) { this->model = model; if(model) { /* check if client restart is needed and show persistent message */ if (model->isRestartRequired()) showRestartWarning(true); QString strLabel = model->getOverriddenByCommandLine(); if (strLabel.isEmpty()) strLabel = tr("none"); ui->overriddenByCommandLineLabel->setText(strLabel); mapper->setModel(model); setMapper(); mapper->toFirst(); updateDefaultProxyNets(); } /* warn when one of the following settings changes by user action (placed here so init via mapper doesn't trigger them) */ /* Main */ connect(ui->databaseCache, SIGNAL(valueChanged(int)), this, SLOT(showRestartWarning())); connect(ui->threadsScriptVerif, SIGNAL(valueChanged(int)), this, SLOT(showRestartWarning())); /* Wallet */ connect(ui->showMasternodesTab, SIGNAL(clicked(bool)), this, SLOT(showRestartWarning())); connect(ui->spendZeroConfChange, SIGNAL(clicked(bool)), this, SLOT(showRestartWarning())); /* Network */ connect(ui->allowIncoming, SIGNAL(clicked(bool)), this, SLOT(showRestartWarning())); connect(ui->connectSocks, SIGNAL(clicked(bool)), this, SLOT(showRestartWarning())); connect(ui->connectSocksTor, SIGNAL(clicked(bool)), this, SLOT(showRestartWarning())); /* Display */ connect(ui->digits, SIGNAL(valueChanged()), this, SLOT(showRestartWarning())); connect(ui->theme, SIGNAL(valueChanged()), this, SLOT(showRestartWarning())); connect(ui->lang, SIGNAL(valueChanged()), this, SLOT(showRestartWarning())); connect(ui->thirdPartyTxUrls, SIGNAL(textChanged(const QString &)), this, SLOT(showRestartWarning())); } void OptionsDialog::setMapper() { /* Main */ mapper->addMapping(ui->bitcoinAtStartup, OptionsModel::StartAtStartup); mapper->addMapping(ui->threadsScriptVerif, OptionsModel::ThreadsScriptVerif); mapper->addMapping(ui->databaseCache, OptionsModel::DatabaseCache); /* Wallet */ mapper->addMapping(ui->coinControlFeatures, OptionsModel::CoinControlFeatures); mapper->addMapping(ui->showMasternodesTab, OptionsModel::ShowMasternodesTab); mapper->addMapping(ui->showAdvancedPSUI, OptionsModel::ShowAdvancedPSUI); mapper->addMapping(ui->lowKeysWarning, OptionsModel::LowKeysWarning); mapper->addMapping(ui->privateSendMultiSession, OptionsModel::PrivateSendMultiSession); mapper->addMapping(ui->spendZeroConfChange, OptionsModel::SpendZeroConfChange); mapper->addMapping(ui->privateSendRounds, OptionsModel::PrivateSendRounds); mapper->addMapping(ui->privateSendAmount, OptionsModel::PrivateSendAmount); /* Network */ mapper->addMapping(ui->mapPortUpnp, OptionsModel::MapPortUPnP); mapper->addMapping(ui->allowIncoming, OptionsModel::Listen); mapper->addMapping(ui->connectSocks, OptionsModel::ProxyUse); mapper->addMapping(ui->proxyIp, OptionsModel::ProxyIP); mapper->addMapping(ui->proxyPort, OptionsModel::ProxyPort); mapper->addMapping(ui->connectSocksTor, OptionsModel::ProxyUseTor); mapper->addMapping(ui->proxyIpTor, OptionsModel::ProxyIPTor); mapper->addMapping(ui->proxyPortTor, OptionsModel::ProxyPortTor); /* Window */ #ifndef Q_OS_MAC mapper->addMapping(ui->minimizeToTray, OptionsModel::MinimizeToTray); mapper->addMapping(ui->minimizeOnClose, OptionsModel::MinimizeOnClose); #endif /* Display */ mapper->addMapping(ui->digits, OptionsModel::Digits); mapper->addMapping(ui->theme, OptionsModel::Theme); mapper->addMapping(ui->lang, OptionsModel::Language); mapper->addMapping(ui->unit, OptionsModel::DisplayUnit); mapper->addMapping(ui->thirdPartyTxUrls, OptionsModel::ThirdPartyTxUrls); } void OptionsDialog::setOkButtonState(bool fState) { ui->okButton->setEnabled(fState); } void OptionsDialog::on_resetButton_clicked() { if(model) { // confirmation dialog QMessageBox::StandardButton btnRetVal = QMessageBox::question(this, tr("Confirm options reset"), tr("Client restart required to activate changes.") + "<br><br>" + tr("Client will be shut down. Do you want to proceed?"), QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel); if(btnRetVal == QMessageBox::Cancel) return; /* reset all options and close GUI */ model->Reset(); QApplication::quit(); } } void OptionsDialog::on_okButton_clicked() { mapper->submit(); darkSendPool.nCachedNumBlocks = std::numeric_limits<int>::max(); pwalletMain->MarkDirty(); accept(); updateDefaultProxyNets(); } void OptionsDialog::on_cancelButton_clicked() { reject(); } void OptionsDialog::showRestartWarning(bool fPersistent) { ui->statusLabel->setStyleSheet("QLabel { color: red; }"); if(fPersistent) { ui->statusLabel->setText(tr("Client restart required to activate changes.")); } else { ui->statusLabel->setText(tr("This change would require a client restart.")); // clear non-persistent status label after 10 seconds // Todo: should perhaps be a class attribute, if we extend the use of statusLabel QTimer::singleShot(10000, this, SLOT(clearStatusLabel())); } } void OptionsDialog::clearStatusLabel() { ui->statusLabel->clear(); } void OptionsDialog::updateProxyValidationState() { QValidatedLineEdit *pUiProxyIp = ui->proxyIp; QValidatedLineEdit *otherProxyWidget = (pUiProxyIp == ui->proxyIpTor) ? ui->proxyIp : ui->proxyIpTor; if (pUiProxyIp->isValid() && (!ui->proxyPort->isEnabled() || ui->proxyPort->text().toInt() > 0) && (!ui->proxyPortTor->isEnabled() || ui->proxyPortTor->text().toInt() > 0)) { setOkButtonState(otherProxyWidget->isValid()); //only enable ok button if both proxys are valid ui->statusLabel->clear(); } else { setOkButtonState(false); ui->statusLabel->setStyleSheet("QLabel { color: red; }"); ui->statusLabel->setText(tr("The supplied proxy address is invalid.")); } } void OptionsDialog::updateDefaultProxyNets() { proxyType proxy; std::string strProxy; QString strDefaultProxyGUI; GetProxy(NET_IPV4, proxy); strProxy = proxy.proxy.ToStringIP() + ":" + proxy.proxy.ToStringPort(); strDefaultProxyGUI = ui->proxyIp->text() + ":" + ui->proxyPort->text(); (strProxy == strDefaultProxyGUI.toStdString()) ? ui->proxyReachIPv4->setChecked(true) : ui->proxyReachIPv4->setChecked(false); GetProxy(NET_IPV6, proxy); strProxy = proxy.proxy.ToStringIP() + ":" + proxy.proxy.ToStringPort(); strDefaultProxyGUI = ui->proxyIp->text() + ":" + ui->proxyPort->text(); (strProxy == strDefaultProxyGUI.toStdString()) ? ui->proxyReachIPv6->setChecked(true) : ui->proxyReachIPv6->setChecked(false); GetProxy(NET_TOR, proxy); strProxy = proxy.proxy.ToStringIP() + ":" + proxy.proxy.ToStringPort(); strDefaultProxyGUI = ui->proxyIp->text() + ":" + ui->proxyPort->text(); (strProxy == strDefaultProxyGUI.toStdString()) ? ui->proxyReachTor->setChecked(true) : ui->proxyReachTor->setChecked(false); } ProxyAddressValidator::ProxyAddressValidator(QObject *parent) : QValidator(parent) { } QValidator::State ProxyAddressValidator::validate(QString &input, int &pos) const { Q_UNUSED(pos); // Validate the proxy proxyType addrProxy = proxyType(CService(input.toStdString(), 9050), true); if (addrProxy.IsValid()) return QValidator::Acceptable; return QValidator::Invalid; }
b02972158c374967de0cd5ebcfeb8881f4a934cc
30bdd8ab897e056f0fb2f9937dcf2f608c1fd06a
/contest/1542581268.cpp
cb3523b08e97db29735227a417d72ce601d809a6
[]
no_license
thegamer1907/Code_Analysis
0a2bb97a9fb5faf01d983c223d9715eb419b7519
48079e399321b585efc8a2c6a84c25e2e7a22a61
refs/heads/master
2020-05-27T01:20:55.921937
2019-11-20T11:15:11
2019-11-20T11:15:11
188,403,594
2
1
null
null
null
null
UTF-8
C++
false
false
1,455
cpp
#include <bits/stdc++.h> using namespace std; #define MAXN 100010 #define X first #define Y second typedef long long ll; int a[MAXN], c[20]; int b[4]; int main() { //freopen("input", "r", stdin); //freopen("output", "w", stdout); int n, k; cin >> n >> k; for (int i = 0; i < n; ++i) { int x; for (int j = 0; j < k; ++j) { scanf("%d", &x); a[i] = (a[i] << 1) | x; } ++c[a[i]]; //cout << a[i] << endl; } bool flag = false; if (c[0]) flag = true; for (int mask = 1; mask < (1 << (1 << k)); ++mask) { bool ff = true; for (int i = 0; i < (1 << k); ++i) if ((mask & (1 << i)) && !c[i]) ff = false; if (!ff) continue; int cnt = 0; memset(b, 0, sizeof(b)); for (int i = 0; i < (1 << k); ++i) { if (mask & (1 << i)) { if (!c[i]) continue; ++cnt; for (int j = 0; j < k; ++j) if (i & (1 << j)) ++b[j]; } } bool f = true; for (int j = 0; j < k; ++j) if (b[j] > cnt / 2) f = false; if (f) flag = true; } puts(flag? "YES":"NO"); return 0; }
a39b956dbfa2576863a6bcb7d2eb622148354b21
fa274ec4f0c66c61d6acd476e024d8e7bdfdcf54
/Resoluções OJ/uri/1382 - Elementar, meu Caro Watson!.cpp
6b1dfb74c9efc9fde7c99bd76e423bea8e78b783
[]
no_license
luanaamorim04/Competitive-Programming
1c204b9c21e9c22b4d63ad425a98f4453987b879
265ad98ffecb304524ac805612dfb698d0a419d8
refs/heads/master
2023-07-13T03:04:51.447580
2021-08-11T00:28:57
2021-08-11T00:28:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
800
cpp
// Autor: [GAPA] Francisco Arcos Filho<[email protected]> // Nome: Elementar, meu Caro Watson! // Nível: 3 // Categoria: ESTRUTURAS E BIBLIOTECAS // URL: https://www.urionlinejudge.com.br/judge/pt/problems/view/1382 #include<bits/stdc++.h> #define vi vector<int> #define _ ios_base::sync_with_stdio(0); using namespace std; int t,n,i,j,k,ans; vi a; bitset<10009> b; int main(){_ for (cin>>t; t--;){ cin>>n; a = vi(n+1); b.set(), ans=0; for (i=1;i<=n;i++) cin>>a[i]; for (i=1;i<=n;i++){ if (b[i]){ for (j=i; a[j]!=i; j=a[j]){ ans++; b[j]=0; } b[j]=0; } } cout<<ans<<endl; } return 0; }
3aca8f305c0b9f88801b2e9a897163954108b3e4
89745ce3c5c7eb424f3237b9d1fb9d4afafa545c
/functions.cpp
833e2a37c4a90732b2fcac06bf43578f88c98460
[]
no_license
Xen-R/RC5
42b32ec7251b28eb506908ace9d7a68a1583036a
9abd4c129c1a7f02d0b29c55bed7a4890d0433c4
refs/heads/main
2023-08-25T01:03:56.217412
2021-10-20T19:39:43
2021-10-20T19:39:43
419,465,314
0
0
null
null
null
null
UTF-8
C++
false
false
15,292
cpp
#include "Header.h" uint32_t cycle_shift_right(uint32_t to_be_shifted, int shift) { uint32_t tmp = to_be_shifted >> shift%32; uint32_t res = to_be_shifted << (32 - shift%32); uint32_t fulres = tmp | res; return fulres; } vector<uint32_t> cycle_shift_left(vector<uint32_t> data, int shift) { vector<uint32_t> result = data; /*while (shift >= 32) { uint32_t tmp = result[data.size()-1]; for (int i = 1; i < data.size() - 1; i++) { result[i] = result[i-1] >> shift; } result[0] = tmp; shift -= 32; } if (shift > 0) { vector<uint32_t> tmp = result; for (int i = 0; i < data.size() - 1; i++) { tmp[i] = tmp[i] << (32 - shift); result[i] = result[i] >> shift; } for (int i = 0; i < data.size() - 2; i++) { result[i] = result[i] | tmp[i + 1] >> shift; } result[data.size() - 1] = result[data.size() - 1] | tmp[0]; }*/ if (shift < 32 && shift !=0) { uint32_t tmp0 = data[0]; uint32_t tmp1 = data[1]; result[0] = result[0] << shift; tmp0 = tmp0 >> (32 - shift); result[1] = result[1] << shift; tmp1 = tmp1 >> (32 - shift); result[0] = result[0] | tmp1; result[1] = result[1] | tmp0; } if (shift == 32) { result[0] = data[1]; result[1] = data[0]; } if (shift > 32 && shift !=64) { result[0] = data[1]; result[1] = data[0]; uint32_t tmp0 = data[1]; uint32_t tmp1 = data[0]; result[0] = result[0] << (shift-32); tmp0 = tmp0 >> (32 - (shift - 32)); result[1] = result[1] << (shift-32); tmp1 = tmp1 >> (32 - (shift-32)); result[0] = result[0] | tmp1; result[1] = result[1] | tmp0; } return result; } int get_bit(vector<uint32_t> data, int idx, int num) { uint32_t tmp = data[idx] >> (32 - num); tmp = tmp & 1; return tmp; } int get_bit(uint32_t data, int num) { uint32_t tmp = data >> (32 - num); tmp = tmp & 1; return tmp; } int max_ind(vector<int> arr1) { int ind = 0; for (int i = 0; i < arr1.size(); i++) { if (arr1[i] > 0) { ind = i; } } return ind; } string random_key(int len) { std::string str("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"); std::random_device rd; std::mt19937 generator(rd()); std::shuffle(str.begin(), str.end(), generator); return str.substr(0, len); } uint32_t cycle_shift_left(uint32_t to_be_shifted, int shift) { uint32_t tmp = to_be_shifted << (shift%32); uint32_t res = to_be_shifted >> (32 - (shift%32)); uint32_t fulres = tmp | res; return fulres; } vector<uint32_t> string_to_words(string &key) { int len = key.length(); if (len != 0) { vector<unsigned char> buffer; for (int i = 0; i < key.length(); i++) { buffer.push_back(key.at(i)); } int words_number = len/4, tail = 4 - len % 4; if (tail != 4) { words_number++; } vector<uint32_t> key_words(words_number); for (int i = 0; i < words_number; i++) { for (int j = 0; j < 4; j++) { if (!(i == words_number - 1 && tail != 4 && j >= 4 - tail)) { key_words[i] = key_words[i] | (uint32_t)buffer[i*4 + j]; } key_words[i] = key_words[i] << 8; } } return key_words; } vector<uint32_t> kk; kk.push_back(0); return kk; } vector<uint32_t> txt_to_words(string &key) { int len = key.length(); if (len != 0) { vector<unsigned char> buffer; for (int i = 0; i < key.length(); i++) { buffer.push_back(key.at(i)); } int words_number = len / 4, tail = 4 - len % 4; if (tail != 4) { words_number++; } vector<uint32_t> key_words(words_number); for (int i = 0; i < words_number; i++) { for (int j = 0; j < 4; j++) { if (!(i == words_number - 1 && tail != 4 && j >= 4 - tail)) { uint32_t tmp = (uint32_t)buffer[i * 4 + j] << 8 * j; key_words[i] = key_words[i] | tmp; } } } return key_words; } vector<uint32_t> kk; return kk; } vector<uint32_t> char_to_words(vector<char>& data) { int len = data.size(); if (len != 0) { vector<unsigned char> buffer; for (int i = 0; i < data.size(); i++) { buffer.push_back(data[i]); } int words_number = len / 4, tail = 4 - len % 4; if (tail != 4) { words_number++; } vector<uint32_t> key_words(words_number); for (int i = 0; i < words_number; i++) { for (int j = 0; j < 4; j++) { if (!(i == words_number - 1 && tail != 0 && j >= 4 - tail)) { key_words[i] = key_words[i] | (uint32_t)buffer[i * 4 + j]; } key_words[i] = key_words[i] << 8; } } return key_words; } return vector<uint32_t>(); } string words_to_string(vector<uint32_t>& data) { vector<char> buffer; for (int i = 0; i < data.size(); i++) { uint32_t tmp = data[i]; for(int j = 0; j < 4; j++){ char tmp2 = ((unsigned char *)(&data[i]))[j]; buffer.push_back((char)tmp); tmp = tmp >> 8; } } string newstr; for (int i = 0; i < buffer.size(); i++) { //cout << buffer[i] << endl; newstr+=buffer[i]; } return newstr; } vector<char> words_to_char(vector<uint32_t>& data) { vector<char> buffer; for (int i = 0; i < data.size(); i++) { uint32_t tmp = data[i]; for (int j = 0; j < 4; j++) { //char tmp2 = ((unsigned char *)(&data[i]))[j]; buffer.push_back((char)tmp); tmp = tmp >> 8; } } return buffer; } vector<uint32_t> expanded_keys(int r) { uint32_t p = 3084996963, q= 2654435769; vector<uint32_t> key_exp; key_exp.push_back(p); for (int i = 1; i < 2*(r + 1) - 1; i++) { uint32_t tmp = key_exp[i - 1] + q; key_exp.push_back(tmp); } return key_exp; } void mix_key(vector<uint32_t> &s, vector<uint32_t> &l) { uint32_t a = 0, b = 0; int i = 0, j = 0; int c = l.size(); int sr = s.size(); int n = 3*c; if (sr > c) { n = 3*sr; } for (int k = 0; k < n; k++) { uint32_t tmp = s[i] + a + b, tmp2 = l[j] + a + b, ab = a+b; s[i] = cycle_shift_left(tmp, 3); a = s[i]; ab = a + b; tmp2 = l[j] + a + b; l[j] = cycle_shift_left(tmp2, ab%32); b = l[j]; i = (i + 1) % sr; j = (j + 1) % c; } } void encode(vector<uint32_t> &data, string key, int r) { vector<uint32_t> s = expanded_keys(r); vector<uint32_t> kw = string_to_words(key); //while (kw.size() % 4 != 0) { // kw.push_back(0); //} //cout << words_to_string(kw) << endl; mix_key(s, kw); //cout << words_to_string(s) << endl; for (int j = 0; j <data.size()- 1;) { data[j] += s[0];//a+s0 data[j+1] += s[1];//b+s1 for (int i = 1; i < r; i++) { uint32_t tmp = data[j] ^ data[j + 1];//a xor b data[j] = cycle_shift_left(tmp, data[j + 1]) + s[2 * i];//a = a xor b <<< b + s2i tmp = data[j + 1] ^ data[j];//b xor a data[j + 1] = cycle_shift_left(tmp, data[j]) + s[2 * i + 1];//b = b xor a <<< a + s2i+1 } j += 2; } } void sencode(vector<uint32_t>& data, int key_type, int r, vector<int>& bitchanges) { vector<uint32_t> kw; if (key_type == 0) { kw.push_back(0); kw.push_back(0); kw.push_back(0); kw.push_back(0); } if (key_type == 1) { kw.push_back(4294967295); kw.push_back(4294967295); kw.push_back(4294967295); kw.push_back(4294967295); } if (key_type == 2) { kw.push_back(4027576335); kw.push_back(4027576335); kw.push_back(4027576335); kw.push_back(4027576335); } if (key_type == 3) { string key = random_key(16); kw = string_to_words(key); } vector<uint32_t> s = expanded_keys(r); mix_key(s, kw); for (int l = 0; l < 2; l++) { uint32_t gf = data[l]; for (int k = 0; k < 32; k++) { cout << (gf & 1) << " "; gf = gf >> 1; } } cout << '\n'; for (int j = 0; j < data.size() - 1;) { uint32_t stat1 = data[j]; uint32_t stat2 = data[j + 1]; data[j] += s[0];//a+s0 data[j + 1] += s[1];//b+s1 for (int k = 0; k < 32; k++) { if (get_bit(data[j], k) != get_bit(stat1, k)) bitchanges[j * 32 + k]++; if (get_bit(data[j + 1], k) != get_bit(stat2, k)) bitchanges[(j + 1) * 32 + k]++; } stat1 = data[j]; stat2 = data[j + 1]; for (int l = 0; l < 2; l++) { uint32_t gf = data[l]; for (int k = 0; k < 32; k++) { cout << (gf & 1)<< " "; gf = gf >> 1; } } cout << '\n'; for (int i = 1; i < r; i++) { uint32_t tmp = data[j] ^ data[j + 1];//a xor b data[j] = cycle_shift_left(tmp, data[j + 1]) + s[2 * i];//a = a xor b <<< b + s2i tmp = data[j + 1] ^ data[j];//b xor a data[j + 1] = cycle_shift_left(tmp, data[j]) + s[2 * i + 1];//b = b xor a <<< a + s2i+1 for (int k = 0; k < 32; k++) { if (get_bit(data[j], k) != get_bit(stat1, k)) bitchanges[j * 32 + k]++; if (get_bit(data[j+1], k) != get_bit(stat2, k)) bitchanges[(j+1) * 32 + k]++; } for (int l = 0; l < 2; l++) { uint32_t gf = data[l]; for (int k = 0; k < 32; k++) { cout << (gf & 1) << " "; gf = gf >> 1; } } cout << '\n'; stat1 = data[j]; stat2 = data[j + 1]; } j += 2; } } void full_encode(vector<uint32_t>& data, string key, int r, bool key_gen) { if (key_gen) { srand(time(0)); int len = 16 * rand(); key = random_key(len); } encode(data, key, r); } void decode(vector<uint32_t> &data, string key, int r) { vector<uint32_t> s = expanded_keys(r); vector<uint32_t> kw = string_to_words(key); mix_key(s, kw); for (int j = 0; j < data.size() - 1;) { for (int i = r-1; i >= 1; i--) { uint32_t tmp = data[j+1] - s[2 * i + 1] ;//b-s2i+1 data[j + 1] = cycle_shift_right(tmp, data[j])^ data[j];//b = b - s2i+1 >>> a xor a tmp = data[j] -s[2 * i];//a - s2i data[j] = cycle_shift_right(tmp, data[j + 1])^ data[j + 1];//a = a - s2i >>> b xor b } data[j + 1] -= s[1];//b - s1 data[j] -= s[0];//a - s0 j += 2; } } vector<uint32_t> ofb(vector<uint32_t> init, vector<uint32_t> &data, string key, int r, bool key_gen, bool encode) { if (encode) { srand(time(0)); int len = rand() % 127 + 129; string str = random_key(len); init = string_to_words(str); } vector<uint32_t>in = init;//to save initializing vector if (key_gen) { srand(time(0)); int len = rand() % 15 + 1; key = random_key(len); } vector<uint32_t> s = expanded_keys(r); vector<uint32_t> kw = string_to_words(key); mix_key(s, kw); for (int j = 0; j < data.size() - 1;) { init[0] += s[0];//a+s0 init[1] += s[1];//b+s1 for (int i = 1; i < r; i++) { uint32_t tmp = init[0] ^ init[ 1];//a xor b init[0] = cycle_shift_left(tmp, init[ 1]) + s[2 * i];//a = a xor b <<< b + s2i tmp = init[1] ^ init[0];//b xor a init[1] = cycle_shift_left(tmp, init[0]) + s[2 * i + 1];//b = b xor a <<< a + s2i+1 } data[j] = data[j] ^ init[0];//first block of text xor a data[j + 1] = data[j + 1] ^ init[1];//second block of text xor b j += 2; } return in;//to save initializing vector } bool frequency_test(vector<uint32_t> data) { double sum = 0; cout << "Frequency test started\n"; for (int i = 0; i < data.size(); i++) { uint32_t tmp = data[i]; for (int j = 0; j < 32; j++) { sum += tmp & 1; tmp = tmp >> 1; } } cout << "sum of x = " << sum << "\n"; sum = sum - ((double)data.size()*32.0 )/ 2; sum = (double)(2 * sum )/ (sqrt((double)(data.size()*32.0))); cout << "f(x) = " << sum << "\n"; if (abs(sum) < 3) { cout << "Frequency test has been succesfully passed\n"; return true; } cout << "Frequency test has been failed\n"; return false; } vector<int> autocorretation_test(vector<uint32_t> data) { vector<int> result; for (int i = 0; i < data.size()*32; i++) { //vector<uint32_t> tmp = cycle_shift_left(data, i); vector<uint32_t> tmp(2); tmp[0] = data[0]; tmp[1] = data[1]; int shift = i; if (shift < 32 && shift != 0) { uint32_t tmp0 = data[0]; uint32_t tmp1 = data[1]; tmp[0] = tmp[0] << shift; tmp0 = tmp0 >> (32 - shift); tmp[1] = tmp[1] << shift; tmp1 = tmp1 >> (32 - shift); tmp[0] = tmp1 | tmp[0]; tmp[1] = tmp0 | tmp[1]; } if (shift == 32) { tmp[0] = data[1]; tmp[1] = data[0]; } if (shift > 32 && shift != 64) { tmp[0] = data[1]; tmp[1] = data[0]; uint32_t tmp0 = data[1]; uint32_t tmp1 = data[0]; tmp[0] = tmp[0] << (shift - 32); tmp0 = tmp0 >> (32 - (shift - 32)); tmp[1] = tmp[1] << (shift - 32); tmp1 = tmp1 >> (32 - (shift - 32)); tmp[0] =tmp1 | tmp[0]; tmp[1] =tmp0 | tmp[1] ; } int sum = 0, tmp1 = 0; for (int j = 0; j < data.size(); j++) { uint32_t cor1 = data[j], cor2 = tmp[j]; for (int k = 0; k < 32; k++) { int last1 = cor1 & 1, last2 = cor2 & 1; if (last1 == last2) { sum++; } else { sum--; } //cout <<( cor2&1 ); cor1 = cor1 >> 1; cor2 = cor2 >> 1; } } //cout <<'\n'; result.push_back((sum)); } return result; } vector<int> runs_test(vector<uint32_t> data) { vector<int> zeroes(data.size()*32), ones(data.size()*32); for (int i = 0; i < data.size() * 32; i++) { zeroes[i] = 0; ones[i] = 0; } int curlen = 1, prev = 0, cur = 0; for (int i = 0; i < data.size() * 32; i++) { cur = get_bit(data, i / 32, 32 - i % 32); // cout << cur; if ((cur == prev) || (i == 0)) { if (i != 0) { curlen++; } prev = cur; } if ((cur != prev) || (i == data.size() * 32 - 1)) { if (prev == 1) { ones[curlen]++; curlen = 1; } else { zeroes[curlen]++; curlen = 1; } if ((cur != prev) && (i == data.size() * 32 - 1)) { if (prev == 1) { zeroes[curlen]++; } else { ones[curlen]++; } } } prev = cur; } double sum1 = 0, sum2 = 0; /* cout << "\n";*/ for (int i = 0; i < data.size() * 32; i++) { // cout << ones[i] << " " << zeroes[i] << "\n"; // sum2 += ones[i]; // sum1 += zeroes[i]; } //cout << "sum " << sum << endl; int l1 = max_ind(zeroes), l2 = max_ind(ones); for (int i = 0; i < l1; i++) { if (zeroes[i] != 0) { double del1 = (double)zeroes.size() / pow(2, i + 2); sum1 += double(pow((zeroes[i] - del1),2)) / del1; } } for (int i = 0; i < l2; i++) { if (ones[i] != 0) { double del2 = (double)zeroes.size() / pow(2, i + 2); sum2 += double(pow((zeroes[i] - del2),2)) / del2; } } sum1 += sum2; double x2[] = { 0, 3.8415, 5.9915, 7.8147, 9.4877, 11.0705, 12.5916, 14.0671, 15.5073, 16.9190, 18.3070, 19.6751, 21.0261, 22.3620, 23.6848 }; //cout << "Enter x2 for k = " << max(l1,l2) << " and needed alpha\n"; //double x2 = 0; //cin >> x2; if (x2[max(l1, l2)] < sum1) { cout << sum1 << " > " << x2[max(l1, l2)] << " =>\n"; cout << "Runs test has been succefully passed\n"; } else { cout << sum1 << " <= " << x2[max(l1, l2)] << " =>\n"; cout << "Runs test has been failed\n"; } return vector<int>(); }
e26719daeb311aa7d5cf2033f6a8302797002bf6
483f3c69e67caf2be48a816a17b997dd3789d621
/geEngine-RTS/geUtility/Include/geRTTIManagedDataBlockField.h
4f9e1e3385a9c5194257b4fc450026312ea56b0d
[]
no_license
Danelo13/IA2RTS
2549b12db36bf4ccc582013e0ddd40b7e3428103
abcdb8c4f0829ce39df48881347cfce6a1119661
refs/heads/master
2020-03-17T19:44:54.314827
2018-06-26T14:18:32
2018-06-26T14:18:32
133,876,044
0
0
null
2018-06-01T03:20:03
2018-05-17T22:50:01
C++
UTF-8
C++
false
false
4,869
h
/*****************************************************************************/ /** * @file geRTTIManagedDataBlockField.h * @author Samuel Prince ([email protected]) * @date 2017/06/11 * @brief Base class with common functionality for a managed data block field * * Base class containing common functionality for a managed data block class * field. Managed data blocks are just blocks of memory that may, or may not be * released automatically when they are no longer referenced. They are useful * when wanting to return some temporary data only for serialization purposes. * * @bug No known bugs. */ /*****************************************************************************/ #pragma once /*****************************************************************************/ /** * Includes */ /*****************************************************************************/ #include "gePrerequisitesUtil.h" #include "geRTTIField.h" namespace geEngineSDK { using std::function; /** * @brief Base class containing common functionality for a managed data block class field. * @note Managed data blocks are just blocks of memory that may, or may not be released * automatically when they are no longer referenced. They are useful when wanting * to return some temporary data only for serialization purposes. */ struct RTTIManagedDataBlockFieldBase : public RTTIField { /** * @brief Retrieves a managed data block from the specified instance. */ virtual SPtr<DataStream> getValue(void* object, uint32& size) = 0; /** * @brief Sets a managed data block on the specified instance. */ virtual void setValue(void* object, const SPtr<DataStream>& data, uint32 size) = 0; }; /** * @brief Class containing a managed data block field containing a specific type. */ template<class DataType, class ObjectType> struct RTTIManagedDataBlockField : public RTTIManagedDataBlockFieldBase { /** * @brief Initializes a field that returns a block of bytes. * Can be used for serializing pretty much anything. * @param[in] name Name of the field. * @param[in] uniqueId Unique identifier for this field. Although name is also a unique * identifier we want a small data type that can be used for efficiently * serializing data to disk and similar. It is primarily used for * compatibility between different versions of serialized data. * @param[in] getter The getter method for the field. Must be a specific signature: * SerializableDataBlock(ObjectType*) * @param[in] setter The setter method for the field. Must be a specific signature: * void(ObjectType*, SerializableDataBlock) * @param[in] flags Various flags you can use to specialize how systems handle this * field. See RTTIFieldFlag. */ void initSingle(const String& name, uint16 uniqueId, Any getter, Any setter, uint64 flags) { initAll(getter, setter, nullptr, nullptr, name, uniqueId, false, SERIALIZABLE_FIELD_TYPE::kDataBlock, flags); } /** * @copydoc RTTIField::getTypeSize */ uint32 getTypeSize() override { return 0; //Data block types don't store size the conventional way } /** * @copydoc RTTIField::hasDynamicSize */ bool hasDynamicSize() override { return true; } /** * @copydoc RTTIField::getArraySize */ uint32 getArraySize(void* /*object*/) override { GE_EXCEPT(InternalErrorException, "Data block types don't support arrays."); return 0; } /** * @copydoc RTTIField::setArraySize */ void setArraySize(void* /*object*/, uint32 /*size*/) override { GE_EXCEPT(InternalErrorException, "Data block types don't support arrays."); } /** * @copydoc RTTIManagedDataBlockFieldBase::getValue */ SPtr<DataStream> getValue(void* object, uint32& size) override { ObjectType* castObj = static_cast<ObjectType*>(object); function<SPtr<DataStream>(ObjectType*, uint32&)> f = any_cast<function<SPtr<DataStream>(ObjectType*, uint32&)>>(m_valueGetter); return f(castObj, size); } /** * @copydoc RTTIManagedDataBlockFieldBase::setValue */ void setValue(void* object, const SPtr<DataStream>& value, uint32 size) override { ObjectType* castObj = static_cast<ObjectType*>(object); function<void(ObjectType*, const SPtr<DataStream>&, uint32)> f = any_cast<function<void(ObjectType*, const SPtr<DataStream>&, uint32)>>(m_valueSetter); f(castObj, value, size); } }; }
1e0a0905c4ed7544762ebab215897a88e90df4e3
00df597b0bb5995a3ef456996168f9dcb8572239
/cpp04/ex01/Character.hpp
ab91162fab575c513de6d7eb9b330a19496c7c99
[]
no_license
federicoorsili/C-plus-plus
251c6d6bf2d55b9a20cd38158a5fd17596b47ece
893e06829ce115f10b118f08ac5b6e47568cca57
refs/heads/main
2023-04-19T10:08:41.003043
2021-05-11T12:20:19
2021-05-11T12:20:19
359,805,794
1
0
null
null
null
null
UTF-8
C++
false
false
1,440
hpp
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* Character.hpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: aduregon <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/05/05 12:36:12 by aduregon #+# #+# */ /* Updated: 2021/05/05 16:17:07 by aduregon ### ########.fr */ /* */ /* ************************************************************************** */ #pragma once #include <iostream> #include "AWeapon.hpp" #include "Enemy.hpp" class Character { private: std::string name; int ap; AWeapon *weapon; Character(/* args */); public: Character(std::string const &name); Character(Character const &copy); Character &operator = (Character const &op); ~Character(); std::string getName() const; int getAp() const; AWeapon *getWeapon() const; void recoverAP(); void equip(AWeapon *w); void attack(Enemy *e); }; std::ostream &operator << (std::ostream &out, Character const &c);
2bb75b18bab639af3f42066efb84ab37c81b6cde
b27ddd2092ac4a3c7d36fbdc0d567f10a6d1179b
/server/src/db_proxy_server/business/AudioModel.h
0ba72abc89b528ca25488d419ab576e1bd556537
[]
no_license
10th-commune/10thspace
312a6beec124cb9325dee74b76e0b27c54c5791e
589ccc0f63ea92bf14867049ea017771fc62cccd
refs/heads/main
2023-03-26T15:58:39.337197
2021-03-25T03:14:14
2021-03-25T03:14:14
351,005,610
2
0
null
null
null
null
UTF-8
C++
false
false
1,166
h
/*================================================================ * Copyright (C) 2014 All rights reserved. * * 文件名称:AudioModel.h * 创 建 者:Zhang Yuanhao * 邮 箱:[email protected] * 创建日期:2014年12月15日 * 描 述: * ================================================================*/ #ifndef AUDIO_MODEL_H_ #define AUDIO_MODEL_H_ #include <list> #include <map> #include "public_define.h" #include "util.h" #include "IM.BaseDefine.pb.h" using namespace std; class CAudioModel { public: virtual ~CAudioModel(); static CAudioModel* getInstance(); void setUrl(string& strFileUrl); bool readAudios(list<IM::BaseDefine::MsgInfo>& lsMsg); int saveAudioInfo(string nFromId, string nToId, uint32_t nCreateTime, const char* pAudioData, uint32_t nAudioLen); private: CAudioModel(); // void GetAudiosInfo(uint32_t nAudioId, IM::BaseDefine::MsgInfo& msg); bool readAudioContent(uint32_t nCostTime, uint32_t nSize, const string& strPath, IM::BaseDefine::MsgInfo& msg); private: static CAudioModel* m_pInstance; string m_strFileSite; }; #endif /* AUDIO_MODEL_H_ */